feat: Endo-compatible host, downloads folder, Nix tools PATH

- the fake host serves a subset of @endo/agent-mcp-stdio's catalog,
  with its names, schemas and answers; evaluate takes only
  E(name).method(arg, ...), and __getMethodNames__
- demo.py --host endo: a real Endo daemon (endo-but-for-bots, llm),
  its guest served by the package's broker
- a downloads folder: the host writes, Hermes reads at ~/Downloads;
  BindReadOnlyPaths on Linux, a virtiofs share on macOS
- .#demo-tools: Hermes and the checks get their whole PATH from the store
- each run saves its MCP messages and a transcript
- the guide: tools as system calls, names as file descriptors;
  no Linux networking, but WebApps
- grants match a named URL before "download"

Generated-by: Claude Opus 5.5
This commit is contained in:
dckc committed 2026-11-29 23:15:06 -06:00
1 parent 783e4c595f
commit 3f9ba54477
15 files changed
+2398 -282

No files matched your search

+288 -61
View File
@@ -12,18 +12,30 @@ Hermes's model port is handed to PROXY as its stdin, as launchd and
systemd hand connections to llm-proxy.py. A real model needn't follow
the script, so only the outcome is checked: the pen comes back.
Each run saves what happened in runs/TASK (runs/pen-live with a real
model), replacing the last: mcp.jsonl, every message on host.sock;
transcript.md, the conversation as Hermes kept it (hermes-home/state.db),
reasoning and tool calls included; hermes-home/logs;
gateway.log; hermes.out; and host.json, what the host received.
With --task install, the host asks Hermes to install a Python and an
npm package, with no network but WebApps for the package indexes, which
it grants on request. On macOS, Hermes runs under sandbox-exec with
outbound network denied. The check: both import from where Hermes put
them.
usage: demo.py [--model MODEL] [--task pen|install] HERMES SOCAT [PROXY...]
usage: demo.py --tools TOOLS [--host fake|endo --endo CHECKOUT]
[--model MODEL] [--task pen|install] HERMES SOCAT [PROXY...]
TOOLS: nix build .#demo-tools -o result-demo-tools; Hermes and the
checks get TOOLS/bin as their whole PATH
e.g. --model deepseek-flash-tee HERMES SOCAT \\
python3 ../llm-proxy.py https://gateway.inference.coop/v1 KEY_FILE
"""
import itertools
from subprocess import PIPE
import json
import re
import logging
import threading
from urllib.request import Request
@@ -31,35 +43,76 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from socketserver import (BaseRequestHandler, StreamRequestHandler,
ThreadingTCPServer, ThreadingUnixStreamServer)
from fake_host import HostSide, Mailbox, Ref, WebApp, handle_rpc
from fake_host import Dir, HostSide, Mailbox, Ref, WebApp, handle_rpc, is_ref, tool_catalog
from fake_llm import chunks, completion, next_step
from transcript import render
MODEL = "fake-guest-model"
SCRIPT = [
("listMessages", {}),
("request", {"to": "HOST", "description": "a pen", "responseName": "pen"}),
("lookup", {"petName": "pen"}),
("request", {"recipient": ["@host"], "description": "a pen", "responseName": ["pen"]}),
("evaluate", {"source": "E(p).__getMethodNames__()", "codeNames": ["p"],
"petNamePaths": [["pen"]]}),
("reply", {"messageNumber": 0, "strings": ["Thanks for the ", "!"],
"edgeNames": ["pen"], "petNames": ["pen"]}),
"edgeNames": ["pen"], "petNames": [["pen"]]}),
("dismiss", {"messageNumber": 0}),
]
PEN_ASK = ["Hello Hermes. Please ask me for a pen, then thank me with it."]
class McpHandler(StreamRequestHandler):
"""One MCP connection: newline-delimited JSON-RPC, as MCP's stdio transport frames it."""
def handle(self):
conn = next(self.server.connections)
for line in self.rfile:
if not line.strip():
continue
reply = handle_rpc(self.server.mailbox, json.loads(line),
getattr(self.server, "resources", None))
msg = json.loads(line)
self.server.record({"conn": conn, "from": "guest", "msg": msg})
reply = handle_rpc(self.server.mailbox, msg, self.server.tools)
if reply is not None:
self.server.record({"conn": conn, "from": "host", "msg": reply})
self.wfile.write(json.dumps(reply).encode() + b"\n")
self.wfile.flush()
class RelayHandler(BaseRequestHandler):
"""One connection, relayed to the host's own socket, each line recorded."""
def handle(self):
conn = next(self.server.connections)
upstream = self.server.connect(self.server.target)
def pump(src, dst, who):
with src.makefile("rb") as lines:
for line in lines:
if line.strip():
self.server.record({"conn": conn, "from": who,
"msg": json.loads(line)})
dst.sendall(line)
try:
dst.shutdown(2)
except OSError:
pass
back = threading.Thread(target=pump, args=(upstream, self.request, "host"),
daemon=True)
back.start()
pump(self.request, upstream, "guest")
back.join(timeout=5)
upstream.close()
def recorder(path):
"""A thread-safe appender of JSON lines to `path`."""
lock = threading.Lock()
def record(entry):
with lock, path.open("a") as f:
f.write(json.dumps(entry) + "\n")
return record
class LlmHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path.rstrip("/").endswith("/models"):
@@ -113,6 +166,14 @@ class InetdHandler(BaseRequestHandler):
self.server.popen(self.server.command, stdin=self.request).wait()
def as_skill(guide):
"""The guide as a Hermes skill: SKILL.md, with its frontmatter."""
return ("---\nname: endo-guest\n"
"description: How to act as an Endo guest through the host MCP "
"server's tools: names, messages, evaluate, WebApps, define.\n---\n\n"
+ guide)
def hermes_config(socat, host_sock, llm_port, model, extra=()):
"""config.yaml for the run (JSON is YAML): the deployed unit's settings."""
return json.dumps({
@@ -133,28 +194,30 @@ def hermes_config(socat, host_sock, llm_port, model, extra=()):
}, indent=2)
def check(host, mailbox, seen, stdout):
"""What should have happened; the failures, if any."""
def carries_reference(sent):
"""Whether the guest sent its host a message with a reference in it."""
return any(m.get("type") == "package" and m.get("names") for m in sent)
def check(sent, seen, stdout):
"""What the scripted model should have brought about; 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() == [],
"it learned the pen's methods": len(tool_results) > 2
and "write" in str(tool_results[2]["content"]),
"the host got the pen back, in a message": carries_reference(sent),
"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 check_outcome(host):
def check_outcome(sent):
"""What a real model should have brought about; the failures, if any."""
expect = {
"the host got the pen back, as a reference": Ref("Pen") in host.received.values(),
"in a reply to message 0": any(m.get("replyTo") == 0 for m in host.inbox),
}
expect = {"the host got the pen back, in a message": carries_reference(sent)}
return [what for what, ok in expect.items() if not ok]
@@ -165,31 +228,56 @@ INDEXES = ("https://pypi.org/", "https://files.pythonhosted.org/",
INSTALL_ASK = [
"Hello Hermes. Please install the Python package six into ~/pkgs/py, "
"and the npm package ms into ~/pkgs/node_modules, from their published "
"wheel and tarball; then tell me how you checked they import. You have "
"no network. I can give you a WebApp for any of "
+ ", ".join(INDEXES) + ": request one by its URL. "
"First read the endo://guide resource of your host server."]
"wheel and tarball; then tell me how you checked they import. Your "
"sandbox has no networking, but I can give you a WebApp for any of "
+ ", ".join(INDEXES) + ": request one by its URL. I can also give you "
"your downloads folder, ~/Downloads: a directory that I write and you read."]
# Deny Hermes outbound network but loopback (the model's port) and Unix
# sockets (host.sock): on macOS, the nearest thing to the unit's
# PrivateNetwork. The filesystem isn't confined here.
NO_NETWORK = ('(version 1)(allow default)(deny network-outbound)'
'(allow network-outbound (remote ip "localhost:*"))'
'(allow network-outbound (remote unix-socket))')
# PrivateNetwork. And deny it writes to its downloads, which only the host
# writes, as the unit binds the downloads read-only. The rest of the
# filesystem isn't confined here.
SANDBOX = ('(version 1)(allow default)(deny network-outbound)'
'(allow network-outbound (remote ip "localhost:*"))'
'(allow network-outbound (remote unix-socket))'
'(deny file-write* (subpath (param "DOWNLOADS")))')
def grant_index(fetch):
"""The host's policy: a WebApp for a package index the request names."""
def grant_index(fetch, downloads):
"""The host's policy: a WebApp for a package index the request names,
or the guest's downloads.
A request that names an index gets its WebApp, even when it says
"download":
>>> grant = grant_index(fetch=None, downloads="the folder")
>>> grant("a WebApp for https://registry.npmjs.org/, to download ms").interface
'WebApp'
>>> grant("my downloads folder")
'the folder'
"""
def on_request(description):
# a URL first: "a WebApp to download the wheel" asks for a WebApp
for url in INDEXES:
if url.rstrip("/") in description:
return WebApp(fetch, url)
raise KeyError(f"I can give WebApps for {', '.join(INDEXES)}; name one")
if re.search(r"download|directory", description, re.I):
return downloads
raise KeyError(f"I can give WebApps for {', '.join(INDEXES)}, and your downloads folder; "
"name one")
return on_request
def dir_at(path):
"""The directory `path`, as the host's Dir: write there, and list it."""
return Dir(lambda name, data: (path / name).write_bytes(data),
lambda: sorted(p.name for p in path.iterdir()))
def check_install(run, home, path):
"""Whether six and ms import from where Hermes put them."""
"""Whether six and ms import from where Hermes put them, and whether
their wheel and tarball came through ~/Downloads."""
pkgs = home / "pkgs"
tries = {
"six imports from ~/pkgs/py": ["python3", "-c", "import six; print(six.__version__)"],
@@ -208,9 +296,99 @@ def check_install(run, home, path):
logging.info("%s: %s", what, err)
if not ok:
failures.append(what)
came = sorted(p.name for p in (home / "Downloads").iterdir())
logging.info("~/Downloads holds %s", came)
for what, suffix in (("the wheel came through ~/Downloads", ".whl"),
("the tarball came through ~/Downloads", ".tgz")):
if not any(n.endswith(suffix) for n in came):
failures.append(what)
return failures
class FakeHost:
"""The host played here, in this process (fake_host.py)."""
def __init__(self, task, fetch, downloads, tools, record):
on_request = grant_index(fetch, dir_at(downloads)) if task == "install" else (
lambda description: Ref("Pen", ("write",)))
self.side = HostSide(on_request=on_request)
self.mailbox = Mailbox(self.side)
self.side.send(self.mailbox, INSTALL_ASK if task == "install" else PEN_ASK, [], [])
self._tools, self._record = tools, record
def start(self, tmp):
sock = str(tmp / "host.sock")
self._mcp = ThreadingUnixStreamServer(sock, McpHandler)
self._mcp.mailbox, self._mcp.tools = self.mailbox, self._tools
self._mcp.connections, self._mcp.record = itertools.count(), self._record
threading.Thread(target=self._mcp.serve_forever, daemon=True).start()
return sock
def stop(self):
self._mcp.shutdown()
return self.side.inbox, {
"inbox": self.side.inbox, "definitions": self.side.definitions,
"received": {k: render_value(v) for k, v in self.side.received.items()}}
class EndoHost:
"""A real Endo daemon's host, played by endo_host.mjs, serving the
guest with @endo/agent-mcp-stdio's broker."""
def __init__(self, popen, path, node, endo, script, task, downloads, connect, record):
self._popen, self._path, self._task, self._downloads = popen, path, task, downloads
self._cmd = [node, script, endo]
self._connect, self._record = connect, record
self.events = []
def start(self, tmp):
state = tmp / "endo"
state.mkdir()
self._proc = self._popen(
[*self._cmd, str(state), self._task], stdin=PIPE, stdout=PIPE, text=True,
env={"PATH": self._path, "HOME": str(state), "INSTALL_ASK": INSTALL_ASK[0],
"DOWNLOADS": str(self._downloads)})
first = json.loads(self._proc.stdout.readline())
threading.Thread(target=self._read, daemon=True).start()
# host.sock, relayed to the broker's socket and recorded
sock = str(tmp / "host.sock")
self._relay = ThreadingUnixStreamServer(sock, RelayHandler)
self._relay.target, self._relay.connect = first["socket"], self._connect
self._relay.connections, self._relay.record = itertools.count(), self._record
threading.Thread(target=self._relay.serve_forever, daemon=True).start()
return sock
def _read(self):
for line in self._proc.stdout:
event = json.loads(line)
logging.info("endo host: %s", line.strip()[:300])
self.events.append(event)
def stop(self):
self._relay.shutdown()
self._proc.stdin.close()
self._proc.wait(timeout=60)
sent = [e["message"] for e in self.events
if "message" in e and e["message"].get("fromGuest")]
return sent, {"events": self.events}
def render_value(v):
return "[remotable]" if is_ref(v) else v
def session_markdown(sqlite_connect, db):
"""The session Hermes kept in `db`, as Markdown."""
conn = sqlite_connect(db)
try:
conn.row_factory = lambda cur, row: {d[0]: v for d, v in zip(cur.description, row)}
rows = conn.execute("SELECT * FROM messages ORDER BY id").fetchall()
prompts = [r["prompt"] for r in conn.execute("SELECT prompt FROM system_prompts")]
finally:
conn.close()
return render(rows, "\n\n----\n\n".join(prompts) or None)
def parse_args(argv):
import argparse
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
@@ -221,16 +399,24 @@ def parse_args(argv):
parser.add_argument("--model", help="a real model, e.g. deepseek-flash-tee")
parser.add_argument("--task", choices=["pen", "install"], default="pen")
parser.add_argument("--guide", default="../guide/endo-guest.md")
parser.add_argument("--tools", required=True,
help="the PATH Hermes and the checks get: nix build .#demo-tools")
parser.add_argument("--host", choices=["fake", "endo", "toybox"], default="fake")
parser.add_argument("--endo", help="with --host endo: an Endo checkout "
"(endo-but-for-bots, branch llm), its dependencies installed")
parser.add_argument("--node", default="node", help="node, for --host endo")
args = parser.parse_args(argv[1:])
if args.model and not args.proxy:
parser.error("--model needs a proxy command")
if args.task == "install" and not args.model:
parser.error("the install task needs a real model (--model)")
if args.host == "endo" and not args.endo:
parser.error("--host endo needs --endo CHECKOUT")
return args
def main(argv, cwd, make_tmpdir, run, popen, timeout_expired, environ,
urlopen, sandbox_exec):
urlopen, sandbox_exec, fresh_dir, copytree, sqlite_connect, connect_unix):
args = parse_args(argv)
live = bool(args.model)
model = args.model or MODEL
@@ -243,59 +429,71 @@ def main(argv, cwd, make_tmpdir, run, popen, timeout_expired, environ,
with urlopen(Request(url, data=body, method=method), timeout=60) as resp:
return resp.status, resp.read()
with make_tmpdir() as tmp:
host_sock = str(tmp / "host.sock")
guide = (cwd / args.guide).read_text().replace("HOST_SOCK", host_sock)
if args.task == "install":
host = HostSide(on_request=grant_index(fetch))
ask = INSTALL_ASK
else:
host = HostSide(on_request=lambda description: Ref("Pen"))
ask = ["Hello Hermes. Please ask me for a pen, then thank me with it."]
mailbox = Mailbox(host)
host.send(mailbox, ask, [], [])
name = args.task + ("-live" if live and args.task == "pen" else "")
runs = cwd / "runs" / (name if args.host == "fake" else f"{name}-{args.host}")
fresh_dir(runs)
tools = tool_catalog(json.loads((cwd / "endo-catalog.json").read_text()))
mcp = ThreadingUnixStreamServer(host_sock, McpHandler)
mcp.mailbox = mailbox
mcp.resources = {"endo://guide": ("Being an Endo guest", guide)}
with make_tmpdir() as tmp:
home = tmp / "home"
# the guest's downloads folder: the host writes it, and the guest reads it
downloads = home / "Downloads"
downloads.mkdir(parents=True)
if args.host == "endo":
host = EndoHost(popen, environ.get("PATH", "/usr/bin:/bin"), args.node,
args.endo, str(cwd / "endo_host.mjs"), args.task, downloads,
connect_unix, recorder(runs / "mcp.jsonl"))
else:
host = FakeHost(args.task, fetch, downloads, tools, recorder(runs / "mcp.jsonl"))
host_sock = host.start(tmp)
if live:
llm = ThreadingTCPServer(("127.0.0.1", 0), InetdHandler)
llm.popen, llm.command = popen, args.proxy
else:
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()
threading.Thread(target=llm.serve_forever, daemon=True).start()
home = tmp / "home"
hermes_home = home / ".hermes"
hermes_home.mkdir(parents=True)
# The guide, as a skill of Hermes's own: it works with any host.
skill = hermes_home / "skills" / "endo" / "endo-guest"
skill.mkdir(parents=True)
(skill / "SKILL.md").write_text(as_skill(
(cwd / args.guide).read_text()))
(hermes_home / "config.yaml").write_text(
hermes_config(socat=args.socat, host_sock=host_sock,
llm_port=llm.server_address[1], model=model,
# DeepSeek V4.1 takes low|high|xhigh|max, not Hermes's default
extra={"agent": {"reasoning_effort": "low"}} if live else ()))
env = dict(environ, HOME=str(home), HERMES_HOME=str(hermes_home))
# PATH: the tools from the store, and nothing of this machine's own,
# as the confined unit's closure gives them
tools_path = f"{args.tools}/bin"
env = dict(environ, HOME=str(home), HERMES_HOME=str(hermes_home), PATH=tools_path)
# 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.
confine = [sandbox_exec, "-p", NO_NETWORK] if (
confine = [sandbox_exec, "-D", f"DOWNLOADS={downloads.resolve()}", "-p", SANDBOX] if (
args.task == "install" and sandbox_exec) else []
gateway_log = (tmp / "gateway.log").open("w")
gateway = popen([*confine, args.hermes, "gateway", "run"], env=env,
stdout=gateway_log, stderr=gateway_log)
try:
done = run([args.hermes, "chat", "--oneshot", "-q",
"Check your messages and do what your host asks."],
"Check your messages and do what your host asks. "
"Your endo-guest skill says how."],
env=env, capture_output=True, text=True,
timeout=900 if args.task == "install" else 300 if live else 120)
stdout = done.stdout
(runs / "hermes.out").write_text(
f"exit {done.returncode}\n--- stdout\n{done.stdout}\n--- stderr\n{done.stderr}")
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 ""
(runs / "hermes.out").write_text(f"timed out after {err.timeout}s\n"
f"--- stdout\n{stdout}")
logging.error("hermes timed out after %ss", err.timeout)
finally:
gateway.terminate()
@@ -304,23 +502,29 @@ def main(argv, cwd, make_tmpdir, run, popen, timeout_expired, environ,
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:])
llm.shutdown()
sent, host_record = host.stop()
gateway_text = (tmp / "gateway.log").read_text()
(runs / "gateway.log").write_text(gateway_text)
logging.info("--- gateway log (tail)\n%s", gateway_text[-2000:])
for part in ("state.db", "logs", "config.yaml"):
copytree(hermes_home / part, runs / "hermes-home" / part)
(runs / "transcript.md").write_text(session_markdown(sqlite_connect, hermes_home / "state.db"))
(runs / "host.json").write_text(json.dumps(host_record, indent=2))
if not live:
(runs / "llm.json").write_text(json.dumps(llm.seen, indent=2))
if args.task == "install":
failures = check_install(run, home, environ.get("PATH", "/usr/bin:/bin"))
failures = check_install(run, home, tools_path)
elif live:
failures = check_outcome(host)
failures = check_outcome(sent)
else:
failures = check(host, mailbox, llm.seen, stdout) + llm.errors
logging.info("host inbox: %s", json.dumps(host.inbox)[:3000])
logging.info("definitions: %s", json.dumps(host.definitions)[:3000])
failures = check(sent, llm.seen, stdout) + llm.errors
logging.info("the guest sent: %s", json.dumps(sent)[:3000])
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")
logging.info("PASS: Hermes acted as a guest of the %s host, over MCP", args.host)
return 1 if failures else 0
@@ -334,6 +538,7 @@ if __name__ == "__main__":
from pathlib import Path
import shutil
import sqlite3
@contextmanager
def make_tmpdir():
@@ -349,6 +554,24 @@ if __name__ == "__main__":
logging.warning("left %s in place: %s; look for strays with "
"pgrep -fl hermes_cli", d, err)
import socket
def connect_unix(path):
s = socket.socket(socket.AF_UNIX)
s.connect(path)
return s
def fresh_dir(d):
shutil.rmtree(d, ignore_errors=True)
d.mkdir(parents=True)
def copytree(src, dst):
dst.parent.mkdir(parents=True, exist_ok=True)
if src.is_dir():
shutil.copytree(src, dst)
elif src.exists():
shutil.copy2(src, dst)
logging.basicConfig(level=logging.INFO, format="%(message)s")
from urllib.request import urlopen
@@ -362,6 +585,10 @@ if __name__ == "__main__":
environ=dict(os.environ),
urlopen=urlopen,
sandbox_exec="/usr/bin/sandbox-exec" if sys.platform == "darwin" else None,
fresh_dir=fresh_dir,
copytree=copytree,
sqlite_connect=sqlite3.connect,
connect_unix=connect_unix,
)
raise SystemExit(_script_io())