WIP: feat: Hermes confined to act only as an Endo guest #1
No files matched your search
+4
-1
@@ -8,6 +8,7 @@ How to check a change, and why the confinement holds. For what this is and how t
|
|||||||
- [nix/linux-host.nix](nix/linux-host.nix), [nix/llm-proxy.nix](nix/llm-proxy.nix): on Linux, the host's systemd serves the unit's two sockets.
|
- [nix/linux-host.nix](nix/linux-host.nix), [nix/llm-proxy.nix](nix/llm-proxy.nix): on Linux, the host's systemd serves the unit's two sockets.
|
||||||
- [nix/vfkit-vm.nix](nix/vfkit-vm.nix), [nix/darwin-host.nix](nix/darwin-host.nix): on macOS, the same unit in a microVM, with its sockets relayed over vsock to launchd.
|
- [nix/vfkit-vm.nix](nix/vfkit-vm.nix), [nix/darwin-host.nix](nix/darwin-host.nix): on macOS, the same unit in a microVM, with its sockets relayed over vsock to launchd.
|
||||||
- [llm-proxy.py](llm-proxy.py): the inference proxy, which holds the API key.
|
- [llm-proxy.py](llm-proxy.py): the inference proxy, which holds the API key.
|
||||||
|
- [guide/endo-guest.md](guide/endo-guest.md): what a guest can do (names, messages, `call`, WebApps, `define`, and moving bytes over `host.sock` from the shell). A host serves it as the MCP resource `endo://guide`, with `HOST_SOCK` filled in.
|
||||||
- [test/](test/demo.py): unmodified Hermes against a fake host and a scripted model.
|
- [test/](test/demo.py): unmodified Hermes against a fake host and a scripted model.
|
||||||
|
|
||||||
## Checking a change
|
## Checking a change
|
||||||
@@ -21,10 +22,12 @@ python3 demo.py path/to/hermes path/to/socat # ends with PASS
|
|||||||
With a model and a proxy command, a real model drives it, through [llm-proxy.py](llm-proxy.py) as deployed. For example, with an [Inference Cooperative](https://docs.inference.coop/guides/api-access/) key:
|
With a model and a proxy command, a real model drives it, through [llm-proxy.py](llm-proxy.py) as deployed. For example, with an [Inference Cooperative](https://docs.inference.coop/guides/api-access/) key:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python3 demo.py path/to/hermes path/to/socat deepseek-flash-tee \
|
python3 demo.py --model deepseek-flash-tee path/to/hermes path/to/socat \
|
||||||
python3 ../llm-proxy.py https://gateway.inference.coop/v1 path/to/key
|
python3 ../llm-proxy.py https://gateway.inference.coop/v1 path/to/key
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Add `--task install` to ask Hermes to install `six` and `ms` with no network but the package-index WebApps its host grants; on macOS it runs under `sandbox-exec` with outbound network denied. It passes when both import from where Hermes put them.
|
||||||
|
|
||||||
The demo leaves Hermes's detached helpers running; look for them with `pgrep -fl hermes_cli`. After a change to `nix/`, evaluate both platforms:
|
The demo leaves Hermes's detached helpers running; look for them with `pgrep -fl hermes_cli`. After a change to `nix/`, evaluate both platforms:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# Being an Endo guest
|
||||||
|
|
||||||
|
You are a guest of one host, in the Endo style of object capabilities. You can affect the world only through the references your host has given you, and only by the tools of the `host` MCP server. You have no network, and no other services.
|
||||||
|
|
||||||
|
## Names, not references
|
||||||
|
|
||||||
|
The references themselves stay with your host, in your pet store. You hold names for them:
|
||||||
|
- `list` shows your names, and `lookup` shows what one refers to: plain data as it is, or an object by its interface, such as `{"interface": "WebApp"}`.
|
||||||
|
- `HOST` is your host.
|
||||||
|
|
||||||
|
## Messages
|
||||||
|
|
||||||
|
`listMessages` shows your inbox. A message has `strings` and `names`, with each named reference sitting between two strings: one more string than names. To send "Here is the pen!" with the reference `pen`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"to": "HOST", "strings": ["Here is the ", "!"], "edgeNames": ["pen"], "petNames": ["pen"]}
|
||||||
|
```
|
||||||
|
|
||||||
|
`edgeNames` are what the recipient sees; `petNames` are your names for the references. `reply` does the same, to a message number. `adopt` keeps a reference from a message under a name of yours, and `dismiss` removes a message.
|
||||||
|
|
||||||
|
## Asking and calling
|
||||||
|
|
||||||
|
- `request(to, description, responseName)` asks your host for something, in words. Its answer is kept under `responseName`.
|
||||||
|
- `call(target, method, args, saveAs)` calls a method of an object you have a name for. In `args`, `{"@name": "n"}` passes the reference `n` names. If the answer is a reference, it's kept under `saveAs`.
|
||||||
|
|
||||||
|
## WebApps
|
||||||
|
|
||||||
|
A WebApp is a handle to one URL, and to nothing outside it.
|
||||||
|
- `pathjoin(path)` narrows it to a path within its URL, and `query(params)` adds query parameters. Both answer a new WebApp, so give `saveAs`.
|
||||||
|
- `get()` and `post(body)` fire the request and answer the body as text.
|
||||||
|
- `getBase64()` answers the body as base64, for bytes such as a tarball or a wheel.
|
||||||
|
|
||||||
|
For example, with a WebApp named `npm` for `https://registry.npmjs.org/`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"target": "npm", "method": "pathjoin", "args": ["ms"], "saveAs": "ms-meta"}
|
||||||
|
{"target": "ms-meta", "method": "get"}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Moving bytes: speak to host.sock from your shell
|
||||||
|
|
||||||
|
What a tool answers comes into your context, not onto your disk. To get a file onto disk, have your code talk to the host directly. The `host` MCP server is the Unix socket `HOST_SOCK`, speaking MCP's stdio framing, one JSON-RPC message per line. For example, in Python:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import base64, json, socket
|
||||||
|
|
||||||
|
def host_call(*calls):
|
||||||
|
"""Make MCP tools/call requests on host.sock; answer each one's text."""
|
||||||
|
s = socket.socket(socket.AF_UNIX)
|
||||||
|
s.connect("HOST_SOCK")
|
||||||
|
f = s.makefile("rw")
|
||||||
|
def rpc(id, method, params):
|
||||||
|
f.write(json.dumps({"jsonrpc": "2.0", "id": id, "method": method, "params": params}) + "\n")
|
||||||
|
f.flush()
|
||||||
|
return json.loads(f.readline())
|
||||||
|
rpc(0, "initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
|
||||||
|
"clientInfo": {"name": "shell", "version": "0"}})
|
||||||
|
f.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")
|
||||||
|
out = []
|
||||||
|
for i, (name, arguments) in enumerate(calls, 1):
|
||||||
|
result = rpc(i, "tools/call", {"name": name, "arguments": arguments})["result"]
|
||||||
|
if result.get("isError"):
|
||||||
|
raise RuntimeError(result["content"][0]["text"])
|
||||||
|
out.append(json.loads(result["content"][0]["text"]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
[b64] = host_call(("call", {"target": "some-file", "method": "getBase64"}))
|
||||||
|
open("some-file", "wb").write(base64.b64decode(b64))
|
||||||
|
```
|
||||||
|
|
||||||
|
It's the same socket, and the same authority, as your `host` tools.
|
||||||
|
|
||||||
|
## Proposing code: define
|
||||||
|
|
||||||
|
To get something done with references you don't hold, propose code to your host with `define(modules, slots)`:
|
||||||
|
- `modules` maps each module's path to its source, which is JavaScript in a vat;
|
||||||
|
- `slots` names the vat's parameters, each with a `label` saying what it should be.
|
||||||
|
|
||||||
|
Your host reads the source and decides. It may endow the definition: fill each slot with a reference it holds, run the vat, and keep its root. The root is your host's, to keep or send to you. So you ask for an attenuation of what your host holds, and your host decides what goes in and who gets what comes out.
|
||||||
|
|
||||||
|
A vat's main module exports `buildRootObject(powers, params)`:
|
||||||
|
- `powers` holds `E` (eventual send: `E(x).method(...)` answers a promise), `Far` (makes a remotable object) and `M` (method guards).
|
||||||
|
- `params` holds your slots, by name.
|
||||||
|
|
||||||
|
For example, a vat that answers the latest version of an npm package, given a WebApp for the registry:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"modules": {
|
||||||
|
"main.js": "export const buildRootObject = ({ E, Far }, { registry }) => Far('Latest', { async of(name) { const meta = JSON.parse(await E(E(registry).pathjoin(name)).get()); return meta['dist-tags'].latest; } });"
|
||||||
|
},
|
||||||
|
"slots": {"registry": {"label": "a WebApp for https://registry.npmjs.org/"}}
|
||||||
|
}
|
||||||
|
```
|
||||||
+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.
|
model, so the run needs no API key and does the same thing every time.
|
||||||
Then it checks what the host received.
|
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
|
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
|
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.
|
the script, so only the outcome is checked: the pen comes back.
|
||||||
|
|
||||||
usage: demo.py HERMES SOCAT [MODEL PROXY...]
|
With --task install, the host asks Hermes to install a Python and an
|
||||||
HERMES the hermes executable
|
npm package, with no network but WebApps for the package indexes, which
|
||||||
SOCAT the socat executable
|
it grants on request. On macOS, Hermes runs under sandbox-exec with
|
||||||
MODEL e.g. deepseek-flash-tee
|
outbound network denied. The check: both import from where Hermes put
|
||||||
PROXY e.g. python3 ../llm-proxy.py https://gateway.inference.coop/v1 KEY_FILE
|
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 json
|
||||||
import logging
|
import logging
|
||||||
import threading
|
import threading
|
||||||
|
from urllib.request import Request
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
from socketserver import (BaseRequestHandler, StreamRequestHandler,
|
from socketserver import (BaseRequestHandler, StreamRequestHandler,
|
||||||
ThreadingTCPServer, ThreadingUnixStreamServer)
|
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
|
from fake_llm import chunks, completion, next_step
|
||||||
|
|
||||||
MODEL = "fake-guest-model"
|
MODEL = "fake-guest-model"
|
||||||
@@ -48,7 +53,8 @@ class McpHandler(StreamRequestHandler):
|
|||||||
for line in self.rfile:
|
for line in self.rfile:
|
||||||
if not line.strip():
|
if not line.strip():
|
||||||
continue
|
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:
|
if reply is not None:
|
||||||
self.wfile.write(json.dumps(reply).encode() + b"\n")
|
self.wfile.write(json.dumps(reply).encode() + b"\n")
|
||||||
self.wfile.flush()
|
self.wfile.flush()
|
||||||
@@ -152,21 +158,109 @@ def check_outcome(host):
|
|||||||
return [what for what, ok in expect.items() if not ok]
|
return [what for what, ok in expect.items() if not ok]
|
||||||
|
|
||||||
|
|
||||||
def main(argv, make_tmpdir, run, popen, timeout_expired, environ):
|
# The install task: no network but what the host grants, as WebApps.
|
||||||
hermes, socat = argv[1:3]
|
INDEXES = ("https://pypi.org/", "https://files.pythonhosted.org/",
|
||||||
live = argv[3:4]
|
"https://registry.npmjs.org/")
|
||||||
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."], [], [])
|
|
||||||
|
|
||||||
|
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")
|
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 = ThreadingUnixStreamServer(host_sock, McpHandler)
|
||||||
mcp.mailbox = mailbox
|
mcp.mailbox = mailbox
|
||||||
|
mcp.resources = {"endo://guide": ("Being an Endo guest", guide)}
|
||||||
if live:
|
if live:
|
||||||
llm = ThreadingTCPServer(("127.0.0.1", 0), InetdHandler)
|
llm = ThreadingTCPServer(("127.0.0.1", 0), InetdHandler)
|
||||||
llm.popen, llm.command = popen, argv[4:]
|
llm.popen, llm.command = popen, args.proxy
|
||||||
else:
|
else:
|
||||||
llm = ThreadingHTTPServer(("127.0.0.1", 0), LlmHandler)
|
llm = ThreadingHTTPServer(("127.0.0.1", 0), LlmHandler)
|
||||||
llm.script, llm.seen, llm.errors = SCRIPT, [], []
|
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 = home / ".hermes"
|
||||||
hermes_home.mkdir(parents=True)
|
hermes_home.mkdir(parents=True)
|
||||||
(hermes_home / "config.yaml").write_text(
|
(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
|
# 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))
|
env = dict(environ, HOME=str(home), HERMES_HOME=str(hermes_home))
|
||||||
# As in the deployed unit, the agent runs in `hermes gateway`, which
|
# As in the deployed unit, the agent runs in `hermes gateway`, which
|
||||||
# owns the MCP servers; `hermes chat` is only its client. Start the
|
# owns the MCP servers; `hermes chat` is only its client. Start the
|
||||||
# gateway ourselves, in the foreground, as systemd would, so chat
|
# gateway ourselves, in the foreground, as systemd would, so chat
|
||||||
# finds it rather than spawning a detached one of its own.
|
# 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_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)
|
stdout=gateway_log, stderr=gateway_log)
|
||||||
try:
|
try:
|
||||||
done = run([hermes, "chat", "--oneshot", "-q",
|
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."],
|
||||||
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
|
stdout = done.stdout
|
||||||
logging.info("hermes exited %s\n--- stdout\n%s\n--- stderr\n%s",
|
logging.info("hermes exited %s\n--- stdout\n%s\n--- stderr\n%s",
|
||||||
done.returncode, done.stdout[-3000:], done.stderr[-3000:])
|
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",
|
logging.info("--- gateway log (tail)\n%s",
|
||||||
(tmp / "gateway.log").read_text()[-2000:])
|
(tmp / "gateway.log").read_text()[-2000:])
|
||||||
|
|
||||||
failures = (check_outcome(host) if live
|
if args.task == "install":
|
||||||
else check(host, mailbox, llm.seen, stdout) + llm.errors)
|
failures = check_install(run, home, environ.get("PATH", "/usr/bin:/bin"))
|
||||||
logging.info("host inbox: %s", json.dumps(host.inbox))
|
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:
|
for what in failures:
|
||||||
logging.error("FAILED: %s", what)
|
logging.error("FAILED: %s", what)
|
||||||
if not failures:
|
if not failures:
|
||||||
@@ -230,20 +333,35 @@ if __name__ == "__main__":
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def make_tmpdir():
|
def make_tmpdir():
|
||||||
# in /tmp: macOS's $TMPDIR is too long for a Unix socket's path
|
# 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)
|
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")
|
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||||
|
from urllib.request import urlopen
|
||||||
|
|
||||||
return main(
|
return main(
|
||||||
argv=list(sys.argv),
|
argv=list(sys.argv),
|
||||||
|
cwd=Path.cwd(),
|
||||||
make_tmpdir=make_tmpdir,
|
make_tmpdir=make_tmpdir,
|
||||||
run=subprocess.run,
|
run=subprocess.run,
|
||||||
popen=subprocess.Popen,
|
popen=subprocess.Popen,
|
||||||
timeout_expired=subprocess.TimeoutExpired,
|
timeout_expired=subprocess.TimeoutExpired,
|
||||||
environ=dict(os.environ),
|
environ=dict(os.environ),
|
||||||
|
urlopen=urlopen,
|
||||||
|
sandbox_exec="/usr/bin/sandbox-exec" if sys.platform == "darwin" else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
raise SystemExit(_script_io())
|
raise SystemExit(_script_io())
|
||||||
+119
-4
@@ -3,7 +3,9 @@
|
|||||||
The methods follow Endo's EndoGuest (listMessages, request, resolve,
|
The methods follow Endo's EndoGuest (listMessages, request, resolve,
|
||||||
lookup, ...), restricted to data: arguments are pet names, strings, and
|
lookup, ...), restricted to data: arguments are pet names, strings, and
|
||||||
message numbers, and references stay here, in the pet store. A guest
|
message numbers, and references stay here, in the pet store. A guest
|
||||||
never holds one; it moves them between messages and names.
|
never holds one; it moves them between messages and names. As in
|
||||||
|
toybox's wallet, it may `call` a named reference's methods, and propose
|
||||||
|
code to its host with `define`.
|
||||||
|
|
||||||
>>> host = HostSide(on_request=lambda description: Ref('Pen'))
|
>>> host = HostSide(on_request=lambda description: Ref('Pen'))
|
||||||
>>> guest = Mailbox(host)
|
>>> guest = Mailbox(host)
|
||||||
@@ -19,12 +21,35 @@ never holds one; it moves them between messages and names.
|
|||||||
(['Thanks for the ', '!'], ['it'])
|
(['Thanks for the ', '!'], ['it'])
|
||||||
>>> host.received['it']
|
>>> host.received['it']
|
||||||
Ref(interface='Pen')
|
Ref(interface='Pen')
|
||||||
|
|
||||||
|
Calling a WebApp, by name; it reaches only within its URL:
|
||||||
|
|
||||||
|
>>> fetch = lambda url, method, body: (200, ('fetched ' + url).encode())
|
||||||
|
>>> host = HostSide(on_request=lambda d: WebApp(fetch, 'https://registry.npmjs.org/'))
|
||||||
|
>>> guest = Mailbox(host)
|
||||||
|
>>> guest.request('HOST', 'https://registry.npmjs.org/', 'npm')
|
||||||
|
{'interface': 'WebApp'}
|
||||||
|
>>> guest.call('npm', 'pathjoin', ['ms'], 'ms')
|
||||||
|
{'@name': 'ms', 'interface': 'WebApp'}
|
||||||
|
>>> guest.call('ms', 'get')
|
||||||
|
'fetched https://registry.npmjs.org/ms'
|
||||||
|
>>> guest.call('npm', 'pathjoin', ['https://elsewhere.example/'])
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
ValueError: pathjoin: https://elsewhere.example/ is not within https://registry.npmjs.org/
|
||||||
|
>>> guest.define({'main.js': 'export const buildRootObject = () => ({});'},
|
||||||
|
... {'site': {'label': 'a WebApp for the site'}})
|
||||||
|
>>> host.definitions[0]['slots']
|
||||||
|
{'site': {'label': 'a WebApp for the site'}}
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import re
|
||||||
import threading
|
import threading
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from urllib.parse import urlencode, urljoin, urlsplit
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -42,7 +67,52 @@ def describe(value):
|
|||||||
>>> describe(3)
|
>>> describe(3)
|
||||||
3
|
3
|
||||||
"""
|
"""
|
||||||
return {"interface": value.interface} if isinstance(value, Ref) else value
|
return {"interface": value.interface} if is_ref(value) else value
|
||||||
|
|
||||||
|
|
||||||
|
def is_ref(value):
|
||||||
|
return hasattr(value, "interface")
|
||||||
|
|
||||||
|
|
||||||
|
class WebApp:
|
||||||
|
"""Toybox's WebApp: an attenuated handle to one URL. Narrow with
|
||||||
|
pathjoin and query, then fire with get or post. getBase64 is this
|
||||||
|
host's addition, for bytes: toybox's fetch device answers text."""
|
||||||
|
|
||||||
|
interface = "WebApp"
|
||||||
|
METHODS = ("pathjoin", "query", "get", "getBase64", "post")
|
||||||
|
|
||||||
|
def __init__(self, fetch, url):
|
||||||
|
self._fetch, self._url = fetch, url
|
||||||
|
|
||||||
|
def pathjoin(self, ref):
|
||||||
|
there, here = urlsplit(urljoin(self._url, ref)), urlsplit(self._url)
|
||||||
|
if (there.scheme, there.netloc) != (here.scheme, here.netloc) or not (
|
||||||
|
there.path.startswith(here.path)):
|
||||||
|
raise ValueError(f"pathjoin: {ref} is not within {self._url}")
|
||||||
|
return WebApp(self._fetch, there.geturl())
|
||||||
|
|
||||||
|
def query(self, params):
|
||||||
|
joiner = "&" if urlsplit(self._url).query else "?"
|
||||||
|
return WebApp(self._fetch, self._url + joiner + urlencode(params))
|
||||||
|
|
||||||
|
def _send(self, method, body=None):
|
||||||
|
status, data = self._fetch(self._url, method, body)
|
||||||
|
if status >= 400:
|
||||||
|
raise ValueError(f"{status} on {self._url}: {data[:200]!r}")
|
||||||
|
return data
|
||||||
|
|
||||||
|
def get(self):
|
||||||
|
return self._send("GET").decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
def getBase64(self):
|
||||||
|
return base64.b64encode(self._send("GET")).decode("ascii")
|
||||||
|
|
||||||
|
def post(self, body):
|
||||||
|
return self._send("POST", body.encode()).decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
|
||||||
|
SLOT = re.compile(r"^[A-Za-z_$][\w$]*$")
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -52,6 +122,7 @@ class HostSide:
|
|||||||
on_request: object # description -> value
|
on_request: object # description -> value
|
||||||
inbox: list = field(default_factory=list)
|
inbox: list = field(default_factory=list)
|
||||||
received: dict = field(default_factory=dict)
|
received: dict = field(default_factory=dict)
|
||||||
|
definitions: list = field(default_factory=list)
|
||||||
|
|
||||||
def send(self, guest, strings, edge_names, values):
|
def send(self, guest, strings, edge_names, values):
|
||||||
guest._deliver("package", "HOST", strings=strings,
|
guest._deliver("package", "HOST", strings=strings,
|
||||||
@@ -122,6 +193,30 @@ class Mailbox:
|
|||||||
record, values = self._message(messageNumber)
|
record, values = self._message(messageNumber)
|
||||||
self._pets[petName] = values[record["names"].index(edgeName)]
|
self._pets[petName] = values[record["names"].index(edgeName)]
|
||||||
|
|
||||||
|
def call(self, target, method, args=None, saveAs=None):
|
||||||
|
"""Call `target`'s `method`; {"@name": n} in args is the reference n names."""
|
||||||
|
obj = self._pets[target]
|
||||||
|
methods = getattr(obj, "METHODS", ())
|
||||||
|
if method not in methods:
|
||||||
|
raise KeyError(f"{target} ({describe(obj)}) has no method {method}; "
|
||||||
|
f"it has {list(methods)}")
|
||||||
|
args = [self._pets[a["@name"]] if isinstance(a, dict) and set(a) == {"@name"}
|
||||||
|
else a for a in (args or [])]
|
||||||
|
answer = getattr(obj, method)(*args)
|
||||||
|
if not is_ref(answer):
|
||||||
|
return answer
|
||||||
|
if not saveAs:
|
||||||
|
raise ValueError(f"{method} answers a reference: give saveAs, a name to keep it under")
|
||||||
|
self._pets[saveAs] = answer
|
||||||
|
return {"@name": saveAs, **describe(answer)}
|
||||||
|
|
||||||
|
def define(self, modules, slots):
|
||||||
|
"""Propose to the host a vat of `modules`, its params named by `slots`."""
|
||||||
|
for name in slots:
|
||||||
|
if not SLOT.match(name):
|
||||||
|
raise ValueError(f"define: not a slot name: {json.dumps(name)}")
|
||||||
|
self._host.definitions.append({"modules": modules, "slots": slots})
|
||||||
|
|
||||||
def dismiss(self, messageNumber):
|
def dismiss(self, messageNumber):
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._messages = [
|
self._messages = [
|
||||||
@@ -152,10 +247,22 @@ TOOLS = {
|
|||||||
"adopt": ("Keep a reference from a message under a pet name.",
|
"adopt": ("Keep a reference from a message under a pet name.",
|
||||||
_schema({"messageNumber": INT, "edgeName": STR, "petName": STR})),
|
_schema({"messageNumber": INT, "edgeName": STR, "petName": STR})),
|
||||||
"dismiss": ("Remove a message from the inbox.", _schema({"messageNumber": INT})),
|
"dismiss": ("Remove a message from the inbox.", _schema({"messageNumber": INT})),
|
||||||
|
"call": ("Call a method of the object a pet name refers to. In args, "
|
||||||
|
'{"@name": n} passes the reference n names. A reference answered '
|
||||||
|
"is kept under saveAs. See the endo://guide resource.",
|
||||||
|
_schema({"target": STR, "method": STR, "args": {"type": "array"},
|
||||||
|
"saveAs": STR}, ["target", "method"])),
|
||||||
|
"define": ("Propose code to your host: a vat's modules (path to source), and its "
|
||||||
|
"params by slot name, each with a label saying what it's for. The host "
|
||||||
|
"reads it and may endow it. See the endo://guide resource.",
|
||||||
|
_schema({"modules": {"type": "object", "additionalProperties": STR},
|
||||||
|
"slots": {"type": "object", "additionalProperties": {
|
||||||
|
"type": "object", "properties": {"label": STR},
|
||||||
|
"required": ["label"]}}})),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def handle_rpc(mailbox, msg):
|
def handle_rpc(mailbox, msg, resources=None):
|
||||||
"""One MCP JSON-RPC message in; the reply out, or None for a notification.
|
"""One MCP JSON-RPC message in; the reply out, or None for a notification.
|
||||||
|
|
||||||
>>> box = Mailbox(HostSide(on_request=lambda d: 1))
|
>>> box = Mailbox(HostSide(on_request=lambda d: 1))
|
||||||
@@ -171,7 +278,7 @@ def handle_rpc(mailbox, msg):
|
|||||||
if method == "initialize":
|
if method == "initialize":
|
||||||
reply["result"] = {
|
reply["result"] = {
|
||||||
"protocolVersion": params.get("protocolVersion", "2025-06-18"),
|
"protocolVersion": params.get("protocolVersion", "2025-06-18"),
|
||||||
"capabilities": {"tools": {}},
|
"capabilities": {"tools": {}, **({"resources": {}} if resources else {})},
|
||||||
"serverInfo": {"name": "fake-endo-host", "version": "0"},
|
"serverInfo": {"name": "fake-endo-host", "version": "0"},
|
||||||
}
|
}
|
||||||
elif method == "ping":
|
elif method == "ping":
|
||||||
@@ -180,6 +287,14 @@ def handle_rpc(mailbox, msg):
|
|||||||
reply["result"] = {"tools": [
|
reply["result"] = {"tools": [
|
||||||
{"name": name, "description": desc, "inputSchema": schema}
|
{"name": name, "description": desc, "inputSchema": schema}
|
||||||
for name, (desc, schema) in TOOLS.items()]}
|
for name, (desc, schema) in TOOLS.items()]}
|
||||||
|
elif method == "resources/list" and resources:
|
||||||
|
reply["result"] = {"resources": [
|
||||||
|
{"uri": uri, "name": name, "mimeType": "text/markdown"}
|
||||||
|
for uri, (name, _) in resources.items()]}
|
||||||
|
elif method == "resources/read" and params.get("uri") in (resources or {}):
|
||||||
|
uri = params["uri"]
|
||||||
|
reply["result"] = {"contents": [
|
||||||
|
{"uri": uri, "mimeType": "text/markdown", "text": resources[uri][1]}]}
|
||||||
elif method == "tools/call" and params.get("name") in TOOLS:
|
elif method == "tools/call" and params.get("name") in TOOLS:
|
||||||
name, args = params["name"], params.get("arguments") or {}
|
name, args = params["name"], params.get("arguments") or {}
|
||||||
logging.info("guest calls %s(%s)", name, json.dumps(args))
|
logging.info("guest calls %s(%s)", name, json.dumps(args))
|
||||||
|
|||||||
Reference in new issue
Block a user