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
This commit is contained in:
dckc committed 2026-11-29 16:34:39 -06:00
commit e38d681a9e
13 files changed
+1379

No files matched your search

+195
View File
@@ -0,0 +1,195 @@
"""A guest's mailbox and pet store, and its methods as an MCP server.
The methods follow Endo's EndoGuest (listMessages, request, resolve,
lookup, ...), restricted to data: arguments are pet names, strings, and
message numbers, and references stay here, in the pet store. A guest
never holds one; it moves them between messages and names.
>>> host = HostSide(on_request=lambda description: Ref('Pen'))
>>> guest = Mailbox(host)
>>> host.send(guest, ['Hello. Please ask me for a pen.'], [], [])
>>> [m['strings'] for m in guest.listMessages()]
[['Hello. Please ask me for a pen.']]
>>> guest.request('HOST', 'a pen', 'pen')
{'interface': 'Pen'}
>>> guest.list()
['HOST', 'pen']
>>> guest.reply(0, ['Thanks for the ', '!'], ['it'], ['pen'])
>>> host.inbox[-1]['strings'], host.inbox[-1]['names']
(['Thanks for the ', '!'], ['it'])
>>> host.received['it']
Ref(interface='Pen')
"""
import json
import logging
import threading
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Ref:
"""A reference, as the pet store holds it: never sent to the guest."""
interface: str
def describe(value):
"""What the guest may see of a stored value: data as is, a Ref by its interface.
>>> describe(Ref('Counter'))
{'interface': 'Counter'}
>>> describe(3)
3
"""
return {"interface": value.interface} if isinstance(value, Ref) else value
@dataclass
class HostSide:
"""The guest's host: it sends to the guest, answers its requests, and reads its mail."""
on_request: object # description -> value
inbox: list = field(default_factory=list)
received: dict = field(default_factory=dict)
def send(self, guest, strings, edge_names, values):
guest._deliver("package", "HOST", strings=strings,
names=edge_names, values=values)
def _receive(self, message, values):
self.inbox.append(message)
self.received.update(zip(message.get("names", []), values))
class Mailbox:
"""One guest's powers. Method names are EndoGuest's."""
def __init__(self, host):
self._host = host
self._lock = threading.Lock()
self._pets = {"HOST": Ref("Host")}
self._messages = [] # (record, values)
def _deliver(self, type_, sender, values=(), **record):
with self._lock:
number = len(self._messages)
self._messages.append((
{"number": number, "type": type_, "from": sender, **record},
list(values),
))
def _message(self, number):
for record, values in self._messages:
if record["number"] == number:
return record, values
raise KeyError(f"no message {number}")
def _to_host(self, to):
if to != "HOST":
raise KeyError(f"no recipient {to}; this guest can write only to HOST")
def listMessages(self):
with self._lock:
return [dict(record) for record, _ in self._messages]
def list(self):
return sorted(self._pets)
def lookup(self, petName):
return describe(self._pets[petName])
def request(self, to, description, responseName=None):
self._to_host(to)
value = self._host.on_request(description)
if responseName:
self._pets[responseName] = value
return describe(value)
def send(self, to, strings, edgeNames, petNames):
self._to_host(to)
values = [self._pets[n] for n in petNames]
self._host._receive(
{"type": "package", "from": "guest", "strings": strings,
"names": edgeNames}, values)
def reply(self, messageNumber, strings, edgeNames, petNames):
record, _ = self._message(messageNumber)
self.send(record["from"], strings, edgeNames, petNames)
self._host.inbox[-1]["replyTo"] = messageNumber
def adopt(self, messageNumber, edgeName, petName):
record, values = self._message(messageNumber)
self._pets[petName] = values[record["names"].index(edgeName)]
def dismiss(self, messageNumber):
with self._lock:
self._messages = [
(r, v) for r, v in self._messages if r["number"] != messageNumber]
def _schema(props, required=None):
return {"type": "object", "properties": props,
"required": list(props) if required is None else required}
STR, INT = {"type": "string"}, {"type": "integer"}
STRS = {"type": "array", "items": STR}
TOOLS = {
"listMessages": ("The messages in this guest's inbox.", _schema({})),
"list": ("This guest's pet names.", _schema({})),
"lookup": ("What a pet name refers to: data, or an object's interface.",
_schema({"petName": STR})),
"request": ("Ask a recipient for something; the answer is stored under responseName.",
_schema({"to": STR, "description": STR, "responseName": STR},
["to", "description"])),
"send": ("Send a message: strings, with the named references between them.",
_schema({"to": STR, "strings": STRS, "edgeNames": STRS, "petNames": STRS})),
"reply": ("Reply to a message, as send does.",
_schema({"messageNumber": INT, "strings": STRS,
"edgeNames": STRS, "petNames": STRS})),
"adopt": ("Keep a reference from a message under a pet name.",
_schema({"messageNumber": INT, "edgeName": STR, "petName": STR})),
"dismiss": ("Remove a message from the inbox.", _schema({"messageNumber": INT})),
}
def handle_rpc(mailbox, msg):
"""One MCP JSON-RPC message in; the reply out, or None for a notification.
>>> box = Mailbox(HostSide(on_request=lambda d: 1))
>>> handle_rpc(box, {'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call',
... 'params': {'name': 'list', 'arguments': {}}})['result']['content'][0]['text']
'["HOST"]'
>>> handle_rpc(box, {'jsonrpc': '2.0', 'method': 'notifications/initialized'})
"""
method, params = msg.get("method"), msg.get("params") or {}
if "id" not in msg:
return None
reply = {"jsonrpc": "2.0", "id": msg["id"]}
if method == "initialize":
reply["result"] = {
"protocolVersion": params.get("protocolVersion", "2025-06-18"),
"capabilities": {"tools": {}},
"serverInfo": {"name": "fake-endo-host", "version": "0"},
}
elif method == "ping":
reply["result"] = {}
elif method == "tools/list":
reply["result"] = {"tools": [
{"name": name, "description": desc, "inputSchema": schema}
for name, (desc, schema) in TOOLS.items()]}
elif method == "tools/call" and params.get("name") in TOOLS:
name, args = params["name"], params.get("arguments") or {}
logging.info("guest calls %s(%s)", name, json.dumps(args))
try:
result = getattr(mailbox, name)(**args)
reply["result"] = {"content": [
{"type": "text", "text": json.dumps(result)}]}
except (KeyError, ValueError, TypeError) as err:
reply["result"] = {"isError": True, "content": [
{"type": "text", "text": str(err)}]}
else:
reply["error"] = {"code": -32601, "message": f"no method {method}"}
return reply