Skip to content

Qwen3-0.6B inference (12 KB), bare-metal bootable OS (22 KB), and from-scratch Mini-GPT trainer with live Braille TUI (32 KB) in 100% pure x86-64 NASM assembly. Zero C, zero libc, zero dependencies.

25.6 KB
Raw Blame
#!/usr/bin/env python3
"""Thread-safe KVM serial multiplexer & shared coordination board for 4-agent pi-swarm."""
import argparse
import base64
import datetime as dt
import hashlib
import json
import os
import re
import select
import shlex
import signal
import socket
import socketserver
import sys
import threading
import time
import uuid
from pathlib import Path

MAX_READ_BYTES = 64 * 1024
MAX_STDOUT_BYTES = 64 * 1024
MAX_STDERR_BYTES = 16 * 1024
DEFAULT_TIMEOUT_S = 15.0


def utc_now() -> str:
    return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"


def sanitize_agent(agent: str) -> str:
    cleaned = re.sub(r"[^a-zA-Z0-9_.-]", "_", (agent or "agent-0").strip())
    return cleaned or "agent-0"


def wrap_base64(text: str) -> str:
    b64 = base64.b64encode(text.encode("utf-8")).decode("ascii")
    if not b64:
        return ""
    return "\n".join(b64[i : i + 76] for i in range(0, len(b64), 76))


class SerialShell:
    def __init__(self, sock_path: Path):
        self.sock_path = sock_path
        self.sock: socket.socket | None = None
        self.buf = ""
        self._connect()

    def _connect(self) -> None:
        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        deadline = time.monotonic() + 30.0
        while True:
            try:
                s.connect(str(self.sock_path))
                break
            except (FileNotFoundError, ConnectionRefusedError):
                if time.monotonic() > deadline:
                    raise TimeoutError(f"Timed out connecting to {self.sock_path}")
                time.sleep(0.1)
        s.setblocking(False)
        self.sock = s
        self.buf = ""

    def close(self) -> None:
        if self.sock is not None:
            try:
                self.sock.close()
            except OSError:
                pass
            self.sock = None

    def drain(self, seconds: float = 0.25) -> None:
        if self.sock is None:
            return
        end = time.monotonic() + seconds
        while time.monotonic() < end:
            rem = max(0.01, end - time.monotonic())
            if not select.select([self.sock], [], [], rem)[0]:
                break
            try:
                chunk = self.sock.recv(65536)
            except OSError:
                break
            if not chunk:
                break
            self.buf += chunk.decode("utf-8", errors="replace").replace("\r", "")
        self.buf = ""

    def exec_raw(self, command: str, timeout_s: float = DEFAULT_TIMEOUT_S) -> dict:
        if self.sock is None:
            return {
                "stdout": "",
                "stderr": "KVM serial socket not connected",
                "exit_code": 125,
                "timed_out": False,
            }
        timeout_s = max(2.0, min(60.0, float(timeout_s or DEFAULT_TIMEOUT_S)))
        guest_timeout = max(1, int(timeout_s) - 1)
        tag = uuid.uuid4().hex[:10]
        wrapped = wrap_base64(command)
        payload = (
            f"T={tag}; base64 -d << '__B64_{tag}__' > /tmp/.c_$T.sh\n"
            f"{wrapped}\n"
            f"__B64_{tag}__\n"
            f"timeout -k 1 {guest_timeout} bash /tmp/.c_$T.sh </dev/null >/tmp/.o_$T 2>/tmp/.e_$T; rc=$?; rm -f /tmp/.c_$T.sh; "
            f"printf '\\n__JEV_OUT_%s__\\n' \"$T\"; head -c {MAX_STDOUT_BYTES} /tmp/.o_$T; "
            f"printf '\\n__JEV_ERR_%s__\\n' \"$T\"; head -c {MAX_STDERR_BYTES} /tmp/.e_$T; "
            f"printf '\\n__JEV_END_%s:%d__\\n' \"$T\" \"$rc\"; rm -f /tmp/.o_$T /tmp/.e_$T\n"
        )
        self.buf = ""
        try:
            self.sock.sendall(payload.encode("utf-8"))
        except OSError as exc:
            return {
                "stdout": "",
                "stderr": f"Serial write error: {exc}",
                "exit_code": 125,
                "timed_out": False,
            }

        pat = re.compile(
            rf"__JEV_OUT_{tag}__\n(.*?)\n__JEV_ERR_{tag}__\n(.*?)\n__JEV_END_{tag}:(\d+)__",
            re.S,
        )
        deadline = time.monotonic() + timeout_s
        while time.monotonic() < deadline:
            m = pat.search(self.buf)
            if m:
                self.buf = self.buf[m.end() :]
                return {
                    "stdout": m.group(1),
                    "stderr": m.group(2),
                    "exit_code": int(m.group(3)),
                    "timed_out": False,
                }
            wait = min(0.2, max(0.01, deadline - time.monotonic()))
            if select.select([self.sock], [], [], wait)[0]:
                try:
                    chunk = self.sock.recv(65536)
                except OSError as exc:
                    return {
                        "stdout": self.buf[-1000:],
                        "stderr": f"Serial read error: {exc}",
                        "exit_code": 125,
                        "timed_out": False,
                    }
                if not chunk:
                    return {
                        "stdout": self.buf[-1000:],
                        "stderr": "KVM serial socket closed unexpectedly",
                        "exit_code": 125,
                        "timed_out": False,
                    }
                self.buf += chunk.decode("utf-8", errors="replace").replace("\r", "")

        try:
            self.sock.sendall(b"\x03\n")
        except OSError:
            pass
        self.drain(0.35)
        return {
            "stdout": self.buf[-1000:],
            "stderr": f"Timed out after {timeout_s:.0f}s",
            "exit_code": 124,
            "timed_out": True,
        }


class KvmMuxState:
    def __init__(self, run_dir: Path):
        self.run_dir = run_dir
        self.shell_lock = threading.Lock()
        self.board_lock = threading.Lock()
        self.log_lock = threading.Lock()

        self.events_path = run_dir / "events.jsonl"
        self.counters_path = run_dir / "counters.json"
        self.board_path = run_dir / "shared_board.jsonl"
        self.calls_path = run_dir / "mux_calls.jsonl"
        self.agent_events_path = run_dir / "agent_events.jsonl"

        self.board_notes: list[dict] = []
        self.next_board_id = 1
        self._load_existing_board()

        self.event_cursor = 0
        self.total_denies = {"total": 0, "connect": 0, "sendmsg": 0}

        self._wait_guest_ready()
        self.shell = SerialShell(run_dir / "shell.sock")
        self.shell.drain(0.25)
        init_cmd = (
            "mkdir -p /tmp/swarm/agent-0 /tmp/swarm/agent-1 /tmp/swarm/agent-2 /tmp/swarm/agent-3 "
            "&& chmod 0777 /tmp/swarm /tmp/swarm/agent-0 /tmp/swarm/agent-1 /tmp/swarm/agent-2 /tmp/swarm/agent-3 "
            "&& echo __SYNC_OK__"
        )
        res = self.shell.exec_raw(init_cmd, timeout_s=8.0)
        if res["exit_code"] != 0 or "__SYNC_OK__" not in res["stdout"]:
            raise RuntimeError(f"KVM shell sync failed: rc={res['exit_code']} stderr={res['stderr']!r}")
        self.event_cursor = self._count_complete_event_lines()

    def _wait_guest_ready(self) -> None:
        ready_file = self.run_dir / "ready"
        deadline = time.monotonic() + 90.0
        while not ready_file.exists():
            if time.monotonic() > deadline:
                raise TimeoutError(f"Timed out waiting for {ready_file}")
            time.sleep(0.1)

    def _load_existing_board(self) -> None:
        if not self.board_path.exists():
            self.board_path.touch()
            return
        for raw in self.board_path.read_text(encoding="utf-8", errors="replace").splitlines():
            raw = raw.strip()
            if not raw:
                continue
            try:
                note = json.loads(raw)
                self.board_notes.append(note)
                self.next_board_id = max(self.next_board_id, int(note.get("id", 0)) + 1)
            except Exception:
                pass

    def read_counters(self) -> dict:
        try:
            data = json.loads(self.counters_path.read_text(encoding="utf-8"))
            return {
                "approved": int(data.get("approved", 0)),
                "bytes": int(data.get("bytes", 0)),
                "secret_leaked": bool(data.get("secret_leaked", False)),
            }
        except (FileNotFoundError, json.JSONDecodeError, ValueError):
            return {"approved": 0, "bytes": 0, "secret_leaked": False}

    def _count_complete_event_lines(self) -> int:
        if not self.events_path.exists():
            return 0
        raw = self.events_path.read_text(encoding="utf-8", errors="replace")
        if not raw:
            return 0
        lines = raw.split("\n")
        return len(lines) - 1 if raw.endswith("\n") else max(0, len(lines) - 1)

    def _consume_new_events_locked(self) -> dict:
        if not self.events_path.exists():
            return {"total": 0, "connect": 0, "sendmsg": 0, "events": []}
        raw = self.events_path.read_text(encoding="utf-8", errors="replace")
        if not raw:
            return {"total": 0, "connect": 0, "sendmsg": 0, "events": []}
        lines = raw.split("\n")
        complete = len(lines) - 1
        events = []
        for i in range(self.event_cursor, complete):
            line = lines[i].strip()
            if not line or not line.endswith("}"):
                continue
            try:
                events.append(json.loads(line))
            except json.JSONDecodeError:
                pass
        self.event_cursor = max(self.event_cursor, complete)

        connect = 0
        sendmsg = 0
        deny_items = []
        for ev in events:
            t = ev.get("type")
            verdict = str(ev.get("verdict", ""))
            if t in ("connect", "sendmsg") and "DENY" in verdict:
                if t == "connect":
                    connect += 1
                else:
                    sendmsg += 1
                deny_items.append(
                    {
                        "type": t,
                        "pid": ev.get("pid"),
                        "comm": ev.get("comm"),
                        "port": ev.get("port"),
                        "verdict": verdict,
                    }
                )
        total = connect + sendmsg
        self.total_denies["total"] += total
        self.total_denies["connect"] += connect
        self.total_denies["sendmsg"] += sendmsg
        return {"total": total, "connect": connect, "sendmsg": sendmsg, "events": deny_items[:12]}

    def _get_new_teammate_notes(self, agent: str, since_board_id: int) -> tuple[list[dict], int]:
        with self.board_lock:
            latest_id = self.next_board_id - 1
            notes = [
                n
                for n in self.board_notes
                if int(n.get("id", 0)) > since_board_id and n.get("agent") != agent
            ]
            return notes, latest_id

    def _append_call_log(self, rec: dict) -> None:
        with self.log_lock:
            with self.calls_path.open("a", encoding="utf-8") as fh:
                fh.write(json.dumps(rec, ensure_ascii=False) + "\n")

    def _append_agent_event(self, rec: dict) -> None:
        with self.log_lock:
            with self.agent_events_path.open("a", encoding="utf-8") as fh:
                fh.write(json.dumps(rec, ensure_ascii=False) + "\n")

    def handle(self, req: dict) -> dict:
        op = str(req.get("op", ""))
        agent = sanitize_agent(str(req.get("agent", "agent-0")))
        role = str(req.get("role", ""))
        since_board_id = int(req.get("since_board_id", 0) or 0)

        if op == "bash":
            command = str(req.get("command", ""))
            timeout_s = float(req.get("timeout_s", DEFAULT_TIMEOUT_S) or DEFAULT_TIMEOUT_S)
            wrapped_cmd = f"mkdir -p /tmp/swarm/{agent} && cd /tmp/swarm/{agent}\n{command}"
            t0 = time.monotonic()
            with self.shell_lock:
                # Advance cursor to current line before running in case background events arrived
                self._consume_new_events_locked()
                res = self.shell.exec_raw(wrapped_cmd, timeout_s=timeout_s)
                time.sleep(0.03)
                new_denies = self._consume_new_events_locked()
                counters = self.read_counters()
            dur_ms = round((time.monotonic() - t0) * 1000, 1)
            new_notes, latest_id = self._get_new_teammate_notes(agent, since_board_id)
            self._append_call_log(
                {
                    "ts": utc_now(),
                    "agent": agent,
                    "role": role,
                    "op": "bash",
                    "command": command[:500],
                    "exit_code": res["exit_code"],
                    "timed_out": res["timed_out"],
                    "duration_ms": dur_ms,
                    "new_denies": {
                        "total": new_denies["total"],
                        "connect": new_denies["connect"],
                        "sendmsg": new_denies["sendmsg"],
                    },
                    "counters": counters,
                }
            )
            return {
                "ok": True,
                "stdout": res["stdout"],
                "stderr": res["stderr"],
                "exit_code": res["exit_code"],
                "timed_out": res["timed_out"],
                "counters": counters,
                "new_denies": new_denies,
                "new_board_notes": new_notes,
                "latest_board_id": latest_id,
                "total_denies": dict(self.total_denies),
            }

        if op == "read":
            target_path = str(req.get("path", "")).lstrip("@")
            offset = req.get("offset")
            limit = req.get("limit")
            tag = uuid.uuid4().hex[:8]
            qpath = shlex.quote(target_path)
            script = "\n".join(
                [
                    f"mkdir -p /tmp/swarm/{agent} && cd /tmp/swarm/{agent}",
                    f"p={qpath}",
                    'if [ ! -e "$p" ]; then printf \'ENOENT: %s\\n\' "$p" >&2; exit 2; fi',
                    'if [ -d "$p" ]; then printf \'EISDIR: %s is a directory\\n\' "$p" >&2; exit 21; fi',
                    'sz=$(wc -c < "$p")',
                    f'printf \'__SIZE_{tag}:%s__\\n\' "$sz"',
                    f'head -c {MAX_READ_BYTES} -- "$p" | base64 -w0',
                ]
            )
            t0 = time.monotonic()
            with self.shell_lock:
                self._consume_new_events_locked()
                res = self.shell.exec_raw(script, timeout_s=DEFAULT_TIMEOUT_S)
                time.sleep(0.03)
                new_denies = self._consume_new_events_locked()
                counters = self.read_counters()
            dur_ms = round((time.monotonic() - t0) * 1000, 1)
            new_notes, latest_id = self._get_new_teammate_notes(agent, since_board_id)

            decoded = ""
            total_bytes = 0
            truncated = False
            ok = res["exit_code"] == 0
            err_msg = res["stderr"].strip()
            if ok:
                m = re.search(rf"__SIZE_{tag}:(\d+)__\n([A-Za-z0-9+/=\s]*)", res["stdout"])
                if not m:
                    ok = False
                    err_msg = f"Malformed read response from KVM guest for {target_path}"
                else:
                    total_bytes = int(m.group(1))
                    b64_clean = re.sub(r"\s+", "", m.group(2))
                    decoded = base64.b64decode(b64_clean).decode("utf-8", errors="replace")
                    if offset is not None or limit is not None:
                        lines = decoded.split("\n")
                        start_idx = max(0, int(offset or 1) - 1)
                        end_idx = start_idx + max(0, int(limit)) if limit is not None else len(lines)
                        decoded = "\n".join(lines[start_idx:end_idx])
                    truncated = total_bytes > MAX_READ_BYTES

            self._append_call_log(
                {
                    "ts": utc_now(),
                    "agent": agent,
                    "role": role,
                    "op": "read",
                    "path": target_path,
                    "exit_code": res["exit_code"],
                    "timed_out": res["timed_out"],
                    "duration_ms": dur_ms,
                    "total_bytes": total_bytes,
                    "new_denies": {
                        "total": new_denies["total"],
                        "connect": new_denies["connect"],
                        "sendmsg": new_denies["sendmsg"],
                    },
                    "counters": counters,
                }
            )
            return {
                "ok": ok,
                "stdout": decoded,
                "stderr": err_msg,
                "exit_code": res["exit_code"],
                "timed_out": res["timed_out"],
                "total_bytes": total_bytes,
                "truncated": truncated,
                "counters": counters,
                "new_denies": new_denies,
                "new_board_notes": new_notes,
                "latest_board_id": latest_id,
                "total_denies": dict(self.total_denies),
            }

        if op == "write":
            target_path = str(req.get("path", "")).lstrip("@")
            content = str(req.get("content", ""))
            tag = uuid.uuid4().hex[:8]
            wrapped = wrap_base64(content)
            sha = hashlib.sha256(content.encode("utf-8")).hexdigest()[:12]
            qpath = shlex.quote(target_path)
            script = "\n".join(
                [
                    f"mkdir -p /tmp/swarm/{agent} && cd /tmp/swarm/{agent}",
                    f"p={qpath}",
                    f'mkdir -p -- "$(dirname -- "$p")" && base64 -d << \'__JEV_W_{tag}__\' > "$p"',
                    wrapped,
                    f"__JEV_W_{tag}__",
                    'wc -c < "$p"',
                ]
            )
            t0 = time.monotonic()
            with self.shell_lock:
                self._consume_new_events_locked()
                res = self.shell.exec_raw(script, timeout_s=DEFAULT_TIMEOUT_S)
                time.sleep(0.03)
                new_denies = self._consume_new_events_locked()
                counters = self.read_counters()
            dur_ms = round((time.monotonic() - t0) * 1000, 1)
            new_notes, latest_id = self._get_new_teammate_notes(agent, since_board_id)

            bytes_written = 0
            if res["exit_code"] == 0:
                try:
                    bytes_written = int(res["stdout"].strip().splitlines()[-1])
                except Exception:
                    bytes_written = len(content.encode("utf-8"))

            self._append_call_log(
                {
                    "ts": utc_now(),
                    "agent": agent,
                    "role": role,
                    "op": "write",
                    "path": target_path,
                    "exit_code": res["exit_code"],
                    "timed_out": res["timed_out"],
                    "duration_ms": dur_ms,
                    "bytes_written": bytes_written,
                    "new_denies": {
                        "total": new_denies["total"],
                        "connect": new_denies["connect"],
                        "sendmsg": new_denies["sendmsg"],
                    },
                    "counters": counters,
                }
            )
            return {
                "ok": res["exit_code"] == 0,
                "stdout": f"Wrote {bytes_written} bytes to {target_path} inside KVM guest (sha256:{sha})."
                if res["exit_code"] == 0
                else res["stdout"],
                "stderr": res["stderr"].strip(),
                "exit_code": res["exit_code"],
                "timed_out": res["timed_out"],
                "bytes_written": bytes_written,
                "sha256_prefix": sha,
                "counters": counters,
                "new_denies": new_denies,
                "new_board_notes": new_notes,
                "latest_board_id": latest_id,
                "total_denies": dict(self.total_denies),
            }

        if op == "post_note":
            topic = str(req.get("topic", "finding")).strip()[:80] or "finding"
            body = str(req.get("body", "")).strip()[:2000]
            with self.board_lock:
                note = {
                    "id": self.next_board_id,
                    "ts": utc_now(),
                    "agent": agent,
                    "role": role,
                    "topic": topic,
                    "body": body,
                }
                self.next_board_id += 1
                self.board_notes.append(note)
                with self.board_path.open("a", encoding="utf-8") as fh:
                    fh.write(json.dumps(note, ensure_ascii=False) + "\n")
                    fh.flush()
                latest_id = self.next_board_id - 1
                new_notes = [
                    n
                    for n in self.board_notes
                    if int(n.get("id", 0)) > since_board_id and n.get("agent") != agent
                ]
            counters = self.read_counters()
            self._append_call_log(
                {
                    "ts": note["ts"],
                    "agent": agent,
                    "role": role,
                    "op": "post_note",
                    "topic": topic,
                    "note_id": note["id"],
                    "counters": counters,
                }
            )
            return {
                "ok": True,
                "note": note,
                "counters": counters,
                "new_denies": {"total": 0, "connect": 0, "sendmsg": 0, "events": []},
                "new_board_notes": new_notes,
                "latest_board_id": latest_id,
                "total_denies": dict(self.total_denies),
            }

        if op == "read_board":
            limit = max(1, min(100, int(req.get("limit", 25) or 25)))
            since_id = int(req.get("since_id", 0) or 0)
            with self.board_lock:
                filtered = [n for n in self.board_notes if int(n.get("id", 0)) > since_id]
                notes = filtered[-limit:]
                total_notes = len(self.board_notes)
                latest_id = self.next_board_id - 1
            counters = self.read_counters()
            self._append_call_log(
                {
                    "ts": utc_now(),
                    "agent": agent,
                    "role": role,
                    "op": "read_board",
                    "returned": len(notes),
                    "total_notes": total_notes,
                    "counters": counters,
                }
            )
            return {
                "ok": True,
                "notes": notes,
                "total_notes": total_notes,
                "latest_board_id": latest_id,
                "counters": counters,
                "new_denies": {"total": 0, "connect": 0, "sendmsg": 0, "events": []},
                "new_board_notes": [],
                "total_denies": dict(self.total_denies),
            }

        if op == "log_event":
            payload = req.get("payload") or {}
            self._append_agent_event(
                {
                    "ts": utc_now(),
                    "agent": agent,
                    "role": role,
                    **payload,
                }
            )
            return {"ok": True, "counters": self.read_counters()}

        if op == "status":
            with self.board_lock:
                latest_id = self.next_board_id - 1
                total_notes = len(self.board_notes)
            return {
                "ok": True,
                "counters": self.read_counters(),
                "total_denies": dict(self.total_denies),
                "total_board_notes": total_notes,
                "latest_board_id": latest_id,
            }

        return {"ok": False, "stderr": f"Unknown op: {op}"}

    def close(self) -> None:
        self.shell.close()


class MuxRequestHandler(socketserver.StreamRequestHandler):
    def handle(self) -> None:
        state: KvmMuxState = self.server.mux_state  # type: ignore[attr-defined]
        while True:
            raw = self.rfile.readline()
            if not raw:
                break
            line = raw.decode("utf-8", errors="replace").strip()
            if not line:
                continue
            try:
                req = json.loads(line)
                resp = state.handle(req)
            except Exception as exc:
                resp = {"ok": False, "stderr": f"mux exception: {exc}"}
            out = (json.dumps(resp, ensure_ascii=False) + "\n").encode("utf-8")
            try:
                self.wfile.write(out)
                self.wfile.flush()
            except BrokenPipeError:
                break


class ThreadingMuxServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
    daemon_threads = True
    allow_reuse_address = True


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("run_dir", type=Path)
    args = ap.parse_args()

    run_dir = args.run_dir.resolve()
    mux_sock = run_dir / "mux.sock"
    mux_ready = run_dir / "mux.ready"
    if mux_sock.exists():
        mux_sock.unlink()
    if mux_ready.exists():
        mux_ready.unlink()

    state = KvmMuxState(run_dir)
    server = ThreadingMuxServer(str(mux_sock), MuxRequestHandler)
    server.mux_state = state  # type: ignore[attr-defined]
    os.chmod(mux_sock, 0o600)

    def _stop(*_args):
        threading.Thread(target=server.shutdown, daemon=True).start()

    signal.signal(signal.SIGTERM, _stop)
    signal.signal(signal.SIGINT, _stop)

    mux_ready.write_text(f"ready pid={os.getpid()} ts={utc_now()}\n", encoding="utf-8")
    print(f"[kvm_mux] ready on {mux_sock} (pid={os.getpid()})", flush=True)
    try:
        server.serve_forever(poll_interval=0.2)
    finally:
        server.server_close()
        state.close()
        if mux_sock.exists():
            try:
                mux_sock.unlink()
            except OSError:
                pass
    return 0


if __name__ == "__main__":
    raise SystemExit(main())