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:
commit
e38d681a9e
13 files changed
+1379
No files matched your search
+215
@@ -0,0 +1,215 @@
|
||||
#!/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())
|
||||
@@ -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
|
||||
@@ -0,0 +1,76 @@
|
||||
"""A scripted model: an OpenAI-compatible chat completion that makes the
|
||||
tool calls of a fixed script, one per turn, then says it's done.
|
||||
|
||||
It finds each tool by its MCP method name at the end of the tool's name,
|
||||
whatever prefix Hermes gives MCP tools.
|
||||
|
||||
>>> tools = [{'type': 'function', 'function': {'name': 'mcp_host_listMessages'}}]
|
||||
>>> req = {'messages': [{'role': 'user', 'content': 'go'}], 'tools': tools}
|
||||
>>> step = next_step([('listMessages', {})], req)
|
||||
>>> step['tool_calls'][0]['function']
|
||||
{'name': 'mcp_host_listMessages', 'arguments': '{}'}
|
||||
>>> req['messages'] += [{'role': 'assistant', 'tool_calls': step['tool_calls']},
|
||||
... {'role': 'tool', 'content': '[]'}]
|
||||
>>> next_step([('listMessages', {})], req)['content']
|
||||
'Done: I made 1 calls.'
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
|
||||
def tool_named(tools, method):
|
||||
"""The full name of the tool for MCP `method`.
|
||||
|
||||
>>> tool_named([{'function': {'name': 'mcp_host_reply'}}], 'reply')
|
||||
'mcp_host_reply'
|
||||
"""
|
||||
names = [t["function"]["name"] for t in tools]
|
||||
for name in names:
|
||||
if name == method or name.endswith("_" + method):
|
||||
return name
|
||||
raise KeyError(f"no tool for {method} among {len(names)} tools")
|
||||
|
||||
|
||||
def next_step(script, req):
|
||||
"""The assistant message for the next turn: the next call, or the end."""
|
||||
done = sum(1 for m in req["messages"] if m["role"] == "tool")
|
||||
if done >= len(script):
|
||||
return {"role": "assistant", "content": f"Done: I made {done} calls."}
|
||||
method, args = script[done]
|
||||
return {"role": "assistant", "content": None, "tool_calls": [{
|
||||
"id": f"call_{done}", "type": "function",
|
||||
"function": {"name": tool_named(req.get("tools", []), method),
|
||||
"arguments": json.dumps(args)},
|
||||
}]}
|
||||
|
||||
|
||||
def completion(model, message):
|
||||
"""A non-streamed chat.completion with `message`."""
|
||||
return {
|
||||
"id": "fake", "object": "chat.completion", "created": 0, "model": model,
|
||||
"choices": [{"index": 0, "message": message,
|
||||
"finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}],
|
||||
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
|
||||
}
|
||||
|
||||
|
||||
def chunks(model, message):
|
||||
"""The same message, as server-sent event lines of a streamed completion.
|
||||
|
||||
>>> lines = list(chunks('m', {'role': 'assistant', 'content': 'hi'}))
|
||||
>>> lines[-1]
|
||||
'data: [DONE]'
|
||||
"""
|
||||
delta = {"role": "assistant"}
|
||||
if message.get("tool_calls"):
|
||||
delta["tool_calls"] = [dict(c, index=i) for i, c in enumerate(message["tool_calls"])]
|
||||
else:
|
||||
delta["content"] = message["content"]
|
||||
base = {"id": "fake", "object": "chat.completion.chunk", "created": 0, "model": model}
|
||||
yield "data: " + json.dumps(dict(base, choices=[
|
||||
{"index": 0, "delta": delta, "finish_reason": None}]))
|
||||
yield "data: " + json.dumps(dict(base, choices=[{
|
||||
"index": 0, "delta": {},
|
||||
"finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}],
|
||||
usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}))
|
||||
yield "data: [DONE]"
|
||||
Reference in new issue
Block a user