Files
dckc e38d681a9e feat: Hermes confined to act only as an Endo guest
A NixOS module (nix/hermes-guest.nix) layers confinement on upstream's
services.hermes-agent: no network (PrivateNetwork), an empty /run with
two Unix sockets bound back in, and no user manager. Hermes reaches the
world through host.sock, the guest's Endo methods (listMessages,
request, lookup, reply, ...) as MCP, and llm.sock, an inference proxy
that holds the API key.

The same unit runs on a Linux host (nix/linux-host.nix) and in a vfkit
microVM on macOS (nix/vfkit-vm.nix), where systemd relays the two
sockets over vsock to launchd on the host (nix/darwin-host.nix).

test/demo.py runs unmodified Hermes against a fake host and a scripted
model, and checks what the host received.

Generated-by: Claude Opus 5.5
2026-11-29 16:34:39 -06:00

216 lines
8.4 KiB
Python

#!/usr/bin/env python3
"""Hermes as a guest of a fake host: an integration test of the plumbing.
The test plays both of Hermes's counterparts. It serves the guest's
methods as MCP on host.sock, which Hermes reaches as the deployed unit
does (socat STDIO UNIX-CONNECT:host.sock). It also serves a scripted
model, so the run needs no API key and does the same thing every time.
Then it checks what the host received.
usage: demo.py HERMES SOCAT
HERMES the hermes executable
SOCAT the socat executable
"""
import json
import logging
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from socketserver import StreamRequestHandler, ThreadingUnixStreamServer
from fake_host import HostSide, Mailbox, Ref, handle_rpc
from fake_llm import chunks, completion, next_step
MODEL = "fake-guest-model"
SCRIPT = [
("listMessages", {}),
("request", {"to": "HOST", "description": "a pen", "responseName": "pen"}),
("lookup", {"petName": "pen"}),
("reply", {"messageNumber": 0, "strings": ["Thanks for the ", "!"],
"edgeNames": ["pen"], "petNames": ["pen"]}),
("dismiss", {"messageNumber": 0}),
]
class McpHandler(StreamRequestHandler):
"""One MCP connection: newline-delimited JSON-RPC, as MCP's stdio transport frames it."""
def handle(self):
for line in self.rfile:
if not line.strip():
continue
reply = handle_rpc(self.server.mailbox, json.loads(line))
if reply is not None:
self.wfile.write(json.dumps(reply).encode() + b"\n")
self.wfile.flush()
class LlmHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.rstrip("/").endswith("/models"):
self._json({"object": "list", "data": [
{"id": MODEL, "object": "model", "owned_by": "test"}]})
else:
self.send_error(404)
def do_POST(self):
req = json.loads(self.rfile.read(int(self.headers["content-length"])))
if not self.path.endswith("/chat/completions"):
self.send_error(404)
return
self.server.seen.append(req)
try:
message = next_step(self.server.script, req)
except KeyError as err:
# a 400, not a dropped connection: Hermes retries those forever
names = [t["function"]["name"] for t in req.get("tools", [])]
logging.error("fake model: %s; offered: %s", err, names)
self.server.errors.append(str(err))
self._json({"error": {"message": str(err), "type": "invalid_request_error"}},
status=400)
return
logging.info("model says %s", json.dumps(message)[:200])
if req.get("stream"):
self.send_response(200)
self.send_header("content-type", "text/event-stream")
self.end_headers()
for line in chunks(MODEL, message):
self.wfile.write(line.encode() + b"\n\n")
else:
self._json(completion(MODEL, message))
def _json(self, data, status=200):
body = json.dumps(data).encode()
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, format, *args):
logging.debug(format, *args)
def hermes_config(socat, host_sock, llm_port):
"""config.yaml for the run (JSON is YAML): the deployed unit's settings."""
return json.dumps({
"model": {
"provider": "custom",
"default": MODEL,
"base_url": f"http://127.0.0.1:{llm_port}/v1",
"api_key": "held-by-proxy",
},
# the guest's methods are its whole world: offer them to the model
# directly, not behind tool_search/tool_call
"tools": {"tool_search": {"enabled": "off"}},
"mcp_servers": {"host": {
"command": socat,
"args": ["STDIO", f"UNIX-CONNECT:{host_sock}"],
}},
}, indent=2)
def check(host, mailbox, seen, stdout):
"""What should have happened; the failures, if any."""
tool_results = [m for m in (seen[-1]["messages"] if seen else [])
if m["role"] == "tool"]
expect = {
"Hermes made all 5 calls": len(tool_results) == len(SCRIPT),
"it read the host's message": bool(tool_results)
and "ask me for a pen" in str(tool_results[0]["content"]),
"the host got the pen back, as a reference": host.received.get("pen") == Ref("Pen"),
"as a reply to message 0": bool(host.inbox) and host.inbox[-1].get("replyTo") == 0,
"the message was dismissed": mailbox.listMessages() == [],
"Hermes printed the model's last words": "Done: I made 5 calls." in stdout,
}
return [what for what, ok in expect.items() if not ok]
def main(argv, make_tmpdir, run, popen, timeout_expired, environ):
hermes, socat = argv[1:3]
with make_tmpdir() as tmp:
host = HostSide(on_request=lambda description: Ref("Pen"))
mailbox = Mailbox(host)
host.send(mailbox, ["Hello Hermes. Please ask me for a pen, then thank me with it."], [], [])
host_sock = str(tmp / "host.sock")
mcp = ThreadingUnixStreamServer(host_sock, McpHandler)
mcp.mailbox = mailbox
llm = ThreadingHTTPServer(("127.0.0.1", 0), LlmHandler)
llm.script, llm.seen, llm.errors = SCRIPT, [], []
for server in (mcp, llm):
threading.Thread(target=server.serve_forever, daemon=True).start()
home = tmp / "home"
hermes_home = home / ".hermes"
hermes_home.mkdir(parents=True)
(hermes_home / "config.yaml").write_text(
hermes_config(socat, host_sock, llm.server_address[1]))
env = dict(environ, HOME=str(home), HERMES_HOME=str(hermes_home))
# As in the deployed unit, the agent runs in `hermes gateway`, which
# owns the MCP servers; `hermes chat` is only its client. Start the
# gateway ourselves, in the foreground, as systemd would, so chat
# finds it rather than spawning a detached one of its own.
gateway_log = (tmp / "gateway.log").open("w")
gateway = popen([hermes, "gateway", "run"], env=env,
stdout=gateway_log, stderr=gateway_log)
try:
done = run([hermes, "chat", "--oneshot", "-q",
"Check your messages and do what your host asks."],
env=env, capture_output=True, text=True, timeout=120)
stdout = done.stdout
logging.info("hermes exited %s\n--- stdout\n%s\n--- stderr\n%s",
done.returncode, done.stdout[-3000:], done.stderr[-3000:])
except timeout_expired as err:
stdout = err.stdout or ""
logging.error("hermes timed out after %ss", err.timeout)
finally:
gateway.terminate()
try:
gateway.wait(timeout=20)
except timeout_expired:
gateway.kill()
gateway_log.close()
for server in (mcp, llm):
server.shutdown()
logging.info("--- gateway log (tail)\n%s",
(tmp / "gateway.log").read_text()[-2000:])
failures = check(host, mailbox, llm.seen, stdout) + llm.errors
logging.info("host inbox: %s", json.dumps(host.inbox))
for what in failures:
logging.error("FAILED: %s", what)
if not failures:
logging.info("PASS: Hermes acted as a guest, over MCP on host.sock")
return 1 if failures else 0
if __name__ == "__main__":
def _script_io():
import os
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from pathlib import Path
@contextmanager
def make_tmpdir():
# in /tmp: macOS's $TMPDIR is too long for a Unix socket's path
with tempfile.TemporaryDirectory(prefix="hermes-guest-", dir="/tmp") as d:
yield Path(d)
logging.basicConfig(level=logging.INFO, format="%(message)s")
return main(
argv=list(sys.argv),
make_tmpdir=make_tmpdir,
run=subprocess.run,
popen=subprocess.Popen,
timeout_expired=subprocess.TimeoutExpired,
environ=dict(os.environ),
)
raise SystemExit(_script_io())