feat: teach the guest call, WebApps and define; install through the host
- guide/endo-guest.md, served as the MCP resource endo://guide: names and messages, toybox-style call, WebApps, define, and moving bytes over host.sock from the shell. - The fake host gains call, define (toybox's modules-and-slots shape, recorded for the host) and a WebApp narrowed to one URL, with getBase64 for bytes, since toybox's fetch device answers text. - demo.py --task install: with a real model, Hermes installs six and ms with no network but package-index WebApps its host grants; on macOS under sandbox-exec with outbound network denied. Checked by importing both from where Hermes put them. - Temp cleanup logs, rather than fails, when Hermes's detached helpers are still writing. Generated-by: Claude Opus 5.5
This commit is contained in:
1 parent
cfffe56cce
commit
783e4c595f
4 files changed
+361
-31
No files matched your search
+144
-26
@@ -7,26 +7,31 @@ 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.
|
||||
|
||||
With MODEL and PROXY, a real model drives it instead: each connection to
|
||||
With --model and a PROXY command, a real model drives it instead: each connection to
|
||||
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.
|
||||
|
||||
usage: demo.py HERMES SOCAT [MODEL PROXY...]
|
||||
HERMES the hermes executable
|
||||
SOCAT the socat executable
|
||||
MODEL e.g. deepseek-flash-tee
|
||||
PROXY e.g. python3 ../llm-proxy.py https://gateway.inference.coop/v1 KEY_FILE
|
||||
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...]
|
||||
e.g. --model deepseek-flash-tee HERMES SOCAT \\
|
||||
python3 ../llm-proxy.py https://gateway.inference.coop/v1 KEY_FILE
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from urllib.request import Request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from socketserver import (BaseRequestHandler, StreamRequestHandler,
|
||||
ThreadingTCPServer, ThreadingUnixStreamServer)
|
||||
|
||||
from fake_host import HostSide, Mailbox, Ref, handle_rpc
|
||||
from fake_host import HostSide, Mailbox, Ref, WebApp, handle_rpc
|
||||
from fake_llm import chunks, completion, next_step
|
||||
|
||||
MODEL = "fake-guest-model"
|
||||
@@ -48,7 +53,8 @@ class McpHandler(StreamRequestHandler):
|
||||
for line in self.rfile:
|
||||
if not line.strip():
|
||||
continue
|
||||
reply = handle_rpc(self.server.mailbox, json.loads(line))
|
||||
reply = handle_rpc(self.server.mailbox, json.loads(line),
|
||||
getattr(self.server, "resources", None))
|
||||
if reply is not None:
|
||||
self.wfile.write(json.dumps(reply).encode() + b"\n")
|
||||
self.wfile.flush()
|
||||
@@ -152,21 +158,109 @@ def check_outcome(host):
|
||||
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]
|
||||
live = argv[3:4]
|
||||
model = argv[3] if live else MODEL
|
||||
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."], [], [])
|
||||
# The install task: no network but what the host grants, as WebApps.
|
||||
INDEXES = ("https://pypi.org/", "https://files.pythonhosted.org/",
|
||||
"https://registry.npmjs.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."]
|
||||
|
||||
# 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))')
|
||||
|
||||
|
||||
def grant_index(fetch):
|
||||
"""The host's policy: a WebApp for a package index the request names."""
|
||||
def on_request(description):
|
||||
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")
|
||||
return on_request
|
||||
|
||||
|
||||
def check_install(run, home, path):
|
||||
"""Whether six and ms import from where Hermes put them."""
|
||||
pkgs = home / "pkgs"
|
||||
tries = {
|
||||
"six imports from ~/pkgs/py": ["python3", "-c", "import six; print(six.__version__)"],
|
||||
"ms requires from ~/pkgs/node_modules": ["node", "-e", "console.log(require('ms')('2h'))"],
|
||||
}
|
||||
env = {"PYTHONPATH": str(pkgs / "py"), "NODE_PATH": str(pkgs / "node_modules"),
|
||||
"PATH": path}
|
||||
failures = []
|
||||
for what, cmd in tries.items():
|
||||
try:
|
||||
done = run(cmd, env=env, capture_output=True, text=True, timeout=30)
|
||||
ok = done.returncode == 0
|
||||
logging.info("%s: %s", what, (done.stdout or done.stderr).strip()[-200:])
|
||||
except FileNotFoundError as err:
|
||||
ok = False
|
||||
logging.info("%s: %s", what, err)
|
||||
if not ok:
|
||||
failures.append(what)
|
||||
return failures
|
||||
|
||||
|
||||
def parse_args(argv):
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
parser.add_argument("hermes")
|
||||
parser.add_argument("socat")
|
||||
parser.add_argument("proxy", nargs="*",
|
||||
help="with --model: the proxy command, as launchd and systemd run it")
|
||||
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")
|
||||
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)")
|
||||
return args
|
||||
|
||||
|
||||
def main(argv, cwd, make_tmpdir, run, popen, timeout_expired, environ,
|
||||
urlopen, sandbox_exec):
|
||||
args = parse_args(argv)
|
||||
live = bool(args.model)
|
||||
model = args.model or MODEL
|
||||
|
||||
def fetch(url, method, body):
|
||||
"""The host's own fetch, for the WebApps it grants; only to INDEXES."""
|
||||
if not url.startswith(INDEXES):
|
||||
raise ValueError(f"not a package index: {url}")
|
||||
logging.info("host fetches %s %s", method, url)
|
||||
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, [], [])
|
||||
|
||||
mcp = ThreadingUnixStreamServer(host_sock, McpHandler)
|
||||
mcp.mailbox = mailbox
|
||||
mcp.resources = {"endo://guide": ("Being an Endo guest", guide)}
|
||||
if live:
|
||||
llm = ThreadingTCPServer(("127.0.0.1", 0), InetdHandler)
|
||||
llm.popen, llm.command = popen, argv[4:]
|
||||
llm.popen, llm.command = popen, args.proxy
|
||||
else:
|
||||
llm = ThreadingHTTPServer(("127.0.0.1", 0), LlmHandler)
|
||||
llm.script, llm.seen, llm.errors = SCRIPT, [], []
|
||||
@@ -177,22 +271,26 @@ def main(argv, make_tmpdir, run, popen, timeout_expired, environ):
|
||||
hermes_home = home / ".hermes"
|
||||
hermes_home.mkdir(parents=True)
|
||||
(hermes_home / "config.yaml").write_text(
|
||||
hermes_config(socat, host_sock, llm.server_address[1], model,
|
||||
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
|
||||
{"agent": {"reasoning_effort": "low"}} if live else ()))
|
||||
extra={"agent": {"reasoning_effort": "low"}} if live else ()))
|
||||
|
||||
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.
|
||||
confine = [sandbox_exec, "-p", NO_NETWORK] if (
|
||||
args.task == "install" and sandbox_exec) else []
|
||||
gateway_log = (tmp / "gateway.log").open("w")
|
||||
gateway = popen([hermes, "gateway", "run"], env=env,
|
||||
gateway = popen([*confine, args.hermes, "gateway", "run"], env=env,
|
||||
stdout=gateway_log, stderr=gateway_log)
|
||||
try:
|
||||
done = run([hermes, "chat", "--oneshot", "-q",
|
||||
done = run([args.hermes, "chat", "--oneshot", "-q",
|
||||
"Check your messages and do what your host asks."],
|
||||
env=env, capture_output=True, text=True, timeout=300 if live else 120)
|
||||
env=env, capture_output=True, text=True,
|
||||
timeout=900 if args.task == "install" else 300 if live else 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:])
|
||||
@@ -211,9 +309,14 @@ def main(argv, make_tmpdir, run, popen, timeout_expired, environ):
|
||||
logging.info("--- gateway log (tail)\n%s",
|
||||
(tmp / "gateway.log").read_text()[-2000:])
|
||||
|
||||
failures = (check_outcome(host) if live
|
||||
else check(host, mailbox, llm.seen, stdout) + llm.errors)
|
||||
logging.info("host inbox: %s", json.dumps(host.inbox))
|
||||
if args.task == "install":
|
||||
failures = check_install(run, home, environ.get("PATH", "/usr/bin:/bin"))
|
||||
elif live:
|
||||
failures = check_outcome(host)
|
||||
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])
|
||||
for what in failures:
|
||||
logging.error("FAILED: %s", what)
|
||||
if not failures:
|
||||
@@ -230,20 +333,35 @@ if __name__ == "__main__":
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import shutil
|
||||
|
||||
@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:
|
||||
d = tempfile.mkdtemp(prefix="hermes-guest-", dir="/tmp")
|
||||
try:
|
||||
yield Path(d)
|
||||
finally:
|
||||
try:
|
||||
shutil.rmtree(d)
|
||||
except OSError as err:
|
||||
# Hermes's detached helpers may still be writing there
|
||||
logging.warning("left %s in place: %s; look for strays with "
|
||||
"pgrep -fl hermes_cli", d, err)
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
from urllib.request import urlopen
|
||||
|
||||
return main(
|
||||
argv=list(sys.argv),
|
||||
cwd=Path.cwd(),
|
||||
make_tmpdir=make_tmpdir,
|
||||
run=subprocess.run,
|
||||
popen=subprocess.Popen,
|
||||
timeout_expired=subprocess.TimeoutExpired,
|
||||
environ=dict(os.environ),
|
||||
urlopen=urlopen,
|
||||
sandbox_exec="/usr/bin/sandbox-exec" if sys.platform == "darwin" else None,
|
||||
)
|
||||
|
||||
raise SystemExit(_script_io())
|
||||
Reference in new issue
Block a user