From a4b704a38cd99d5df92da1d9b347474e4a012451 Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Sun, 29 Nov 2026 16:36:13 -0600 Subject: [PATCH 1/7] fix(sandbox): one sandbox for every process running as Hermes's user - The LLM bridge runs as Hermes's user but saw the host's /run. Where same-uid ptrace is allowed, Hermes could take it over and reach any socket there. It now gets Hermes's sandbox, with only llm.sock. - A socket on a read-only mount still accepts connect(), so ProtectSystem=strict doesn't hide sockets under /var/lib. /var/lib is now empty, with the state directory bound back in. - ProtectProc=invisible and ProcSubset=pid: other processes, and their command lines, are out of sight. Generated-by: Claude Opus 5.5 --- nix/hermes-guest.nix | 75 ++++++++++++++++++++++++++------------------ 1 file changed, 45 insertions(+), 30 deletions(-) diff --git a/nix/hermes-guest.nix b/nix/hermes-guest.nix index cf947f7..b2c589e 100644 --- a/nix/hermes-guest.nix +++ b/nix/hermes-guest.nix @@ -20,6 +20,43 @@ let cfg = config.services.hermes-guest; hermes = config.services.hermes-agent; socketDir = "/run/hermes-guest"; + + # The sandbox every process running as Hermes's user gets. See + # CONTRIBUTING.md#confinement for why it confines. + sandbox = { + PrivateNetwork = true; + IPAddressDeny = "any"; + IPAddressAllow = "localhost"; + RestrictAddressFamilies = [ + "AF_UNIX" + "AF_INET" + "AF_INET6" + ]; + # Path-named Unix sockets ignore network namespaces, and a socket on a + # read-only mount still accepts connect(): hide the places sockets + # live, then bind back what each unit may use. (/var/run is a symlink + # to /run, so it's covered too; PrivateTmp and ProtectHome cover /tmp + # and /home.) + TemporaryFileSystem = [ + "/run" + "/var/lib" + ]; + ProtectProc = "invisible"; + ProcSubset = "pid"; + PrivateDevices = true; + PrivateIPC = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectKernelLogs = true; + ProtectControlGroups = true; + ProtectClock = true; + ProtectHostname = true; + RestrictNamespaces = true; + RestrictSUIDSGID = true; + LockPersonality = true; + CapabilityBoundingSet = ""; + SystemCallArchitectures = "native"; + }; in { options.services.hermes-guest = { @@ -79,60 +116,38 @@ in systemd.services.hermes-agent = { after = [ "hermes-llm-bridge.service" ]; requires = [ "hermes-llm-bridge.service" ]; - serviceConfig = { - PrivateNetwork = true; - IPAddressDeny = "any"; - IPAddressAllow = "localhost"; - RestrictAddressFamilies = [ - "AF_UNIX" - "AF_INET" - "AF_INET6" - ]; - # Path-named Unix sockets ignore network namespaces: hide them all, - # then put back the two this service may use. (/var/run is a - # symlink to /run, so it's covered too.) - TemporaryFileSystem = [ "/run" ]; + serviceConfig = sandbox // { BindReadOnlyPaths = [ cfg.hostSocket cfg.llmSocket ]; + # the state directory, back inside the empty /var/lib + BindPaths = [ hermes.stateDir ]; ProtectHome = lib.mkForce true; - PrivateDevices = true; - PrivateIPC = true; - ProtectKernelTunables = true; - ProtectKernelModules = true; - ProtectKernelLogs = true; - ProtectControlGroups = true; - ProtectClock = true; - ProtectHostname = true; - RestrictNamespaces = true; - RestrictSUIDSGID = true; - LockPersonality = true; - CapabilityBoundingSet = ""; - SystemCallArchitectures = "native"; }; }; # Hermes's client wants a TCP base_url. This joins Hermes's network - # namespace and forwards its loopback port to llmSocket. + # namespace and forwards its loopback port to llmSocket. It runs as + # Hermes's user, so it gets the same sandbox: taking it over (ptrace, + # same uid) must gain nothing. systemd.services.hermes-llm-bridge = { description = "Hermes's loopback port to the inference proxy"; unitConfig.JoinsNamespaceOf = "hermes-agent.service"; partOf = [ "hermes-agent.service" ]; - serviceConfig = { + serviceConfig = sandbox // { User = hermes.user; Group = hermes.group; - PrivateNetwork = true; ExecStart = lib.escapeShellArgs [ "${pkgs.socat}/bin/socat" "TCP-LISTEN:${toString cfg.llmPort},bind=127.0.0.1,fork,reuseaddr" "UNIX-CONNECT:${cfg.llmSocket}" ]; + BindReadOnlyPaths = [ cfg.llmSocket ]; ProtectSystem = "strict"; ProtectHome = true; PrivateTmp = true; NoNewPrivileges = true; - CapabilityBoundingSet = ""; }; }; -- 2.53.0 From 052a9dc6402a5783fa63bfa19e4fb868314e5a3d Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Sun, 29 Nov 2026 16:37:03 -0600 Subject: [PATCH 2/7] docs: CONTRIBUTING, with the argument for Hermes's confinement How to check a change (doctests, the demo, evaluation), and a Confinement section: the claim, why it assumes nothing about Hermes or its config, each channel a process could use and what closes it, what the two sockets grant, the VM's added boundary, what's not claimed, and what has and hasn't been checked, with a probe for a running host. Generated-by: Claude Opus 5.5 --- CONTRIBUTING.md | 126 ++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 + 2 files changed, 128 insertions(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..aea3571 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,126 @@ +# Contributing to hermes-guest + +How to check a change, and why the confinement holds. For what this is and how to deploy it, see the [README](README.md). + +## Layout + +- [nix/hermes-guest.nix](nix/hermes-guest.nix): the confined unit, the part that ports. Its `sandbox` attribute set is the confinement this document argues for. +- [nix/linux-host.nix](nix/linux-host.nix), [nix/llm-proxy.nix](nix/llm-proxy.nix): on a Linux host, 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 on the host. +- [llm-proxy.py](llm-proxy.py): the inference proxy, which holds the API key. +- [test/](test/demo.py): unmodified Hermes against a fake host and a scripted model. + +## Checking a change + +Doctests, for the fake host and the scripted model: + +```sh +cd test && python3 -m doctest fake_host.py fake_llm.py +``` + +The demo needs a `hermes` and a `socat`. Hermes's own flake doesn't build on macOS yet (its pnpm dependency hash is wrong there), so install it from a checkout with `uv sync --frozen --extra mcp`: + +```sh +cd test && python3 demo.py path/to/hermes-agent/.venv/bin/hermes "$(nix build --no-link --print-out-paths nixpkgs#socat)/bin/socat" +``` + +It ends with `PASS: Hermes acted as a guest, over MCP on host.sock` in a few seconds. Hermes starts helpers detached from the demo's process tree (`hermes_cli.default_plugins`). Under systemd they stay in the unit's cgroup; after a demo run, look for strays with `pgrep -fl hermes_cli`. + +Evaluate both platforms' configurations after a change to `nix/`: + +```sh +nix eval --impure --expr '(builtins.getFlake (toString ./.)).lib.mkDarwin { + hostDir = "/tmp/h"; model = "m"; upstream = "https://example.com/v1"; keyFile = "/k"; +}.runner.drvPath' +``` + +Python here follows [DisciplinedPython](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/ocap-py-style-guide.md); run its checker on any script you change. + +## Confinement + +### The claim + +Every process that runs as Hermes's user can change the world outside Hermes's own state directory in three ways only: + +1. **`host.sock`**, which gives the authority of one Endo guest: the guest's methods (`listMessages`, `request`, `lookup`, `reply`, `adopt`, `dismiss`, ...), on names in its own pet store. +2. **`llm.sock`**, which gives inference at one upstream, with a key that Hermes never holds. +3. **Its stdout and stderr**, which go to the journal. + +These processes are the gateway, every tool it runs (shell, code execution, browser), every MCP server it starts, and the LLM bridge. + +### The approach: assume nothing about Hermes + +The argument treats Hermes and its model as adversaries. It doesn't depend on which toolsets are enabled, what `config.yaml` says, or what the model chooses to do. That matters because Hermes can rewrite its own configuration: `config.yaml` is in its writable state directory. It can add MCP servers, turn tools on, or run any program its shell can reach. Every one of those runs as a descendant of the unit, so it inherits the same namespaces, mounts, cgroup and seccomp filter, and gains no new authority. The configuration decides only what Hermes does with the authority it has. + +So the argument is about the `sandbox` attribute set in [nix/hermes-guest.nix](nix/hermes-guest.nix), which every unit running as Hermes's user gets. It goes channel by channel: every way a Linux process can affect anything outside itself. + +### Channel by channel + +| Channel | What closes it | +|---|---| +| IP networking | `PrivateNetwork`: a network namespace with only loopback. `IPAddressDeny=any` with `IPAddressAllow=localhost` is a second check, enforced by eBPF on the cgroup. The namespace is shared with the bridge alone, so the only listener in it is the bridge's port, which forwards to `llm.sock`. | +| Unix sockets, by path | A path-named socket works across network namespaces. A socket on a read-only mount still accepts `connect()`, so `ProtectSystem=strict` alone doesn't stop this. The places sockets live are hidden: `TemporaryFileSystem` makes `/run` (and so `/var/run`) and `/var/lib` empty, `PrivateTmp` covers `/tmp`, and `ProtectHome` covers `/home`, `/root` and `/run/user`. Then `BindReadOnlyPaths` binds back just `host.sock` and `llm.sock`. | +| Unix sockets, abstract | The abstract namespace belongs to the network namespace, so it's private too. That cuts off D-Bus and X11 sockets bound there. | +| Other socket families | `RestrictAddressFamilies` allows `AF_UNIX`, plus `AF_INET` and `AF_INET6` for loopback. No `AF_NETLINK`, `AF_PACKET`, or `AF_VSOCK`; on a Linux host that runs VMs, `AF_VSOCK` reaches them. | +| systemd and D-Bus | The system bus socket is in the hidden `/run`. Upstream's module keeps a user manager running for this user, so cron jobs can `systemd-run --user`. That would start processes outside the sandbox, so the user doesn't linger and `/run/user` is hidden. Hermes's cron jobs fail closed. | +| Escaping the unit | Every process the unit forks stays in its cgroup, which `ProtectControlGroups` makes read-only, and stopping the unit stops them all. That covers the helpers Hermes detaches, which outlive a demo run: they can leave a process tree but not a cgroup. | +| Files | `ProtectSystem=strict` makes the whole filesystem read-only. The exceptions are the state directory (`BindPaths`, `ReadWritePaths`), a private `/tmp`, and a minimal private `/dev` (`PrivateDevices`). | +| Other processes | `ProtectProc=invisible` and `ProcSubset=pid` hide other users' processes in `/proc`. `PrivateIPC` gives SysV IPC and POSIX message queues their own namespace. Hermes's user can still signal or ptrace its own processes, and that's why the bridge, which also runs as Hermes's user, gets the same sandbox: taking it over gains nothing. | +| Privilege | Upstream sets `NoNewPrivileges`, so setuid binaries don't raise privilege. On top of that: `CapabilityBoundingSet=""`, `RestrictSUIDSGID`, and `RestrictNamespaces`, which rules out making a user namespace to gain capabilities in. | +| Kernel interfaces | `ProtectKernelTunables`, `ProtectKernelModules`, `ProtectKernelLogs`, `ProtectClock` and `ProtectHostname` block writes to sysctls, module loading, the kernel log, the clock and the hostname. `LockPersonality` and `SystemCallArchitectures=native` close the syscall-ABI tricks. | + +### The two sockets + +**`host.sock`** gives whatever its host serves there, so this part of the claim depends on the host. +- The host must serve only the guest's methods, bound to one guest agent. +- Arguments must be data: pet names, strings, message numbers. +- Object references must stay in the host's pet store; the guest sees an object only by its interface name. + +[test/fake_host.py](test/fake_host.py) is that protocol, and the demo checks that Hermes can work with it. The socket is mode 0600 and owned by Hermes's user. So the connection itself designates the guest, and no secret has to cross. Any process running as Hermes's user counts as Hermes, which is correct: all of them are confined the same way. + +**`llm.sock`** reaches [llm-proxy.py](llm-proxy.py), which runs as a separate dynamic user. +- It reads the key from its own systemd credential, which Hermes can't read. +- It forwards only paths under `/v1/`, only to the host part of one upstream URL. +- It replaces any `Authorization` header the client sends. +- An absolute-form request line, such as `GET http://elsewhere/`, doesn't start with `/v1`, so it gets a 404. + +### On macOS + +The VM runs the same unit, so everything above holds inside it. The VM adds a second boundary, which still holds if the VM's kernel is compromised. A process with root in the VM reaches: +- no network interface; +- the two vsock ports vfkit relays, to `hostDir/host.sock` and `hostDir/llm.sock`; +- the host's `/nix/store`, read-only; +- the state image; +- the serial console, which only whoever runs the VM sees. + +The trusted base for the claim grows by one, Apple's hypervisor, and loses the guest kernel. + +### What this doesn't claim + +- **Secrecy.** Hermes can read what its user can read: the store, `/etc`, world-readable files under `/var` outside `/var/lib`. Through `llm.sock` it can send any of that to the model provider. Through `host.sock` it can send it to its host, which is by design. The claim limits what Hermes can do, not what it can learn or tell those two parties. +- **Denial of service.** No `MemoryMax`, `TasksMax`, or CPU quota is set. Hermes can use as much of the machine as it likes, flood the journal, or spend the API key's quota. +- **Kernel bugs** on a Linux host, and covert or timing channels. +- **Sockets elsewhere.** The claim assumes nothing on the host listens on a Unix socket outside `/run`, `/var/lib`, `/tmp` and `/home` that Hermes's user may connect to, for example under `/srv`, `/opt` or `/var/spool`. If one does, add its directory to `TemporaryFileSystem`. + +### What has been checked, and what hasn't + +- Checked: both platforms' configurations evaluate. The demo passes against unmodified Hermes on macOS, outside any sandbox. +- Not checked: neither the Linux unit nor the VM has been started. +- Not checked: whether vfkit refuses guest connections to vsock ports it wasn't told about. +- Not checked: the host's guest socket and the proxy, except by reading the code. + +On a running Linux host, enter the unit's namespaces and try to get out. `nsenter` enters the namespaces and mounts but not the seccomp filter or capability limits, so this checks the network and filesystem rows of the table: + +```sh +pid=$(systemctl show -p MainPID --value hermes-agent) +sudo nsenter -t "$pid" -a -S "$(id -u hermes)" -G "$(id -g hermes)" sh -c ' + ls -A /run /run/hermes-guest /var/lib /home /tmp + ip -brief link + socat -T2 - TCP:1.1.1.1:443 Date: Sun, 29 Nov 2026 16:44:28 -0600 Subject: [PATCH 3/7] docs: condense CONTRIBUTING; status moves to the PR description Generated-by: Claude Opus 5.5 --- CONTRIBUTING.md | 121 ++++++++++++++---------------------------------- 1 file changed, 35 insertions(+), 86 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index aea3571..7f3ee5f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,29 +4,21 @@ How to check a change, and why the confinement holds. For what this is and how t ## Layout -- [nix/hermes-guest.nix](nix/hermes-guest.nix): the confined unit, the part that ports. Its `sandbox` attribute set is the confinement this document argues for. -- [nix/linux-host.nix](nix/linux-host.nix), [nix/llm-proxy.nix](nix/llm-proxy.nix): on a Linux host, 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 on the host. +- [nix/hermes-guest.nix](nix/hermes-guest.nix): the confined unit, the part that ports. Its `sandbox` attribute set is what [Confinement](#confinement) argues for. +- [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. - [llm-proxy.py](llm-proxy.py): the inference proxy, which holds the API key. - [test/](test/demo.py): unmodified Hermes against a fake host and a scripted model. ## Checking a change -Doctests, for the fake host and the scripted model: - ```sh -cd test && python3 -m doctest fake_host.py fake_llm.py +cd test +python3 -m doctest fake_host.py fake_llm.py +python3 demo.py path/to/hermes path/to/socat # ends with PASS ``` -The demo needs a `hermes` and a `socat`. Hermes's own flake doesn't build on macOS yet (its pnpm dependency hash is wrong there), so install it from a checkout with `uv sync --frozen --extra mcp`: - -```sh -cd test && python3 demo.py path/to/hermes-agent/.venv/bin/hermes "$(nix build --no-link --print-out-paths nixpkgs#socat)/bin/socat" -``` - -It ends with `PASS: Hermes acted as a guest, over MCP on host.sock` in a few seconds. Hermes starts helpers detached from the demo's process tree (`hermes_cli.default_plugins`). Under systemd they stay in the unit's cgroup; after a demo run, look for strays with `pgrep -fl hermes_cli`. - -Evaluate both platforms' configurations after a change to `nix/`: +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 nix eval --impure --expr '(builtins.getFlake (toString ./.)).lib.mkDarwin { @@ -34,93 +26,50 @@ nix eval --impure --expr '(builtins.getFlake (toString ./.)).lib.mkDarwin { }.runner.drvPath' ``` -Python here follows [DisciplinedPython](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/ocap-py-style-guide.md); run its checker on any script you change. +Python here follows [DisciplinedPython](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/ocap-py-style-guide.md); run its checker on scripts you change. When you change the sandbox, update the table below in the same commit. ## Confinement -### The claim +**Claim:** every process running as Hermes's user changes the world outside its state directory only by: -Every process that runs as Hermes's user can change the world outside Hermes's own state directory in three ways only: +1. connecting to `host.sock`: the authority of one Endo guest; +2. connecting to `llm.sock`: inference at one upstream, with a key it never holds; +3. writing to its stdout and stderr, which go to the journal. -1. **`host.sock`**, which gives the authority of one Endo guest: the guest's methods (`listMessages`, `request`, `lookup`, `reply`, `adopt`, `dismiss`, ...), on names in its own pet store. -2. **`llm.sock`**, which gives inference at one upstream, with a key that Hermes never holds. -3. **Its stdout and stderr**, which go to the journal. - -These processes are the gateway, every tool it runs (shell, code execution, browser), every MCP server it starts, and the LLM bridge. - -### The approach: assume nothing about Hermes - -The argument treats Hermes and its model as adversaries. It doesn't depend on which toolsets are enabled, what `config.yaml` says, or what the model chooses to do. That matters because Hermes can rewrite its own configuration: `config.yaml` is in its writable state directory. It can add MCP servers, turn tools on, or run any program its shell can reach. Every one of those runs as a descendant of the unit, so it inherits the same namespaces, mounts, cgroup and seccomp filter, and gains no new authority. The configuration decides only what Hermes does with the authority it has. - -So the argument is about the `sandbox` attribute set in [nix/hermes-guest.nix](nix/hermes-guest.nix), which every unit running as Hermes's user gets. It goes channel by channel: every way a Linux process can affect anything outside itself. - -### Channel by channel +**Approach: assume nothing about Hermes.** Hermes can rewrite its own `config.yaml`, add MCP servers, and run anything its shell reaches. All of it runs inside the unit, so it inherits the same namespaces, mounts, cgroup and seccomp filter. So the argument is about the `sandbox` in [nix/hermes-guest.nix](nix/hermes-guest.nix), which every unit running as Hermes's user gets, not about Hermes or its model. | Channel | What closes it | |---|---| -| IP networking | `PrivateNetwork`: a network namespace with only loopback. `IPAddressDeny=any` with `IPAddressAllow=localhost` is a second check, enforced by eBPF on the cgroup. The namespace is shared with the bridge alone, so the only listener in it is the bridge's port, which forwards to `llm.sock`. | -| Unix sockets, by path | A path-named socket works across network namespaces. A socket on a read-only mount still accepts `connect()`, so `ProtectSystem=strict` alone doesn't stop this. The places sockets live are hidden: `TemporaryFileSystem` makes `/run` (and so `/var/run`) and `/var/lib` empty, `PrivateTmp` covers `/tmp`, and `ProtectHome` covers `/home`, `/root` and `/run/user`. Then `BindReadOnlyPaths` binds back just `host.sock` and `llm.sock`. | -| Unix sockets, abstract | The abstract namespace belongs to the network namespace, so it's private too. That cuts off D-Bus and X11 sockets bound there. | -| Other socket families | `RestrictAddressFamilies` allows `AF_UNIX`, plus `AF_INET` and `AF_INET6` for loopback. No `AF_NETLINK`, `AF_PACKET`, or `AF_VSOCK`; on a Linux host that runs VMs, `AF_VSOCK` reaches them. | -| systemd and D-Bus | The system bus socket is in the hidden `/run`. Upstream's module keeps a user manager running for this user, so cron jobs can `systemd-run --user`. That would start processes outside the sandbox, so the user doesn't linger and `/run/user` is hidden. Hermes's cron jobs fail closed. | -| Escaping the unit | Every process the unit forks stays in its cgroup, which `ProtectControlGroups` makes read-only, and stopping the unit stops them all. That covers the helpers Hermes detaches, which outlive a demo run: they can leave a process tree but not a cgroup. | -| Files | `ProtectSystem=strict` makes the whole filesystem read-only. The exceptions are the state directory (`BindPaths`, `ReadWritePaths`), a private `/tmp`, and a minimal private `/dev` (`PrivateDevices`). | -| Other processes | `ProtectProc=invisible` and `ProcSubset=pid` hide other users' processes in `/proc`. `PrivateIPC` gives SysV IPC and POSIX message queues their own namespace. Hermes's user can still signal or ptrace its own processes, and that's why the bridge, which also runs as Hermes's user, gets the same sandbox: taking it over gains nothing. | -| Privilege | Upstream sets `NoNewPrivileges`, so setuid binaries don't raise privilege. On top of that: `CapabilityBoundingSet=""`, `RestrictSUIDSGID`, and `RestrictNamespaces`, which rules out making a user namespace to gain capabilities in. | -| Kernel interfaces | `ProtectKernelTunables`, `ProtectKernelModules`, `ProtectKernelLogs`, `ProtectClock` and `ProtectHostname` block writes to sysctls, module loading, the kernel log, the clock and the hostname. `LockPersonality` and `SystemCallArchitectures=native` close the syscall-ABI tricks. | +| IP networking | `PrivateNetwork`: only loopback, shared with the bridge alone, whose one listener forwards to `llm.sock`. `IPAddressDeny=any` with `IPAddressAllow=localhost` is a second check. | +| Unix sockets, by path | These cross network namespaces, and accept `connect()` even on a read-only mount. `TemporaryFileSystem` empties `/run` (so `/var/run`) and `/var/lib`, `PrivateTmp` covers `/tmp`, and `ProtectHome` covers `/home`, `/root` and `/run/user`. `BindReadOnlyPaths` binds back the two sockets. | +| Unix sockets, abstract | Private to the network namespace. | +| Other socket families | `RestrictAddressFamilies`: `AF_UNIX`, and `AF_INET`/`AF_INET6` for loopback. No `AF_NETLINK`, `AF_PACKET` or `AF_VSOCK`. | +| systemd, D-Bus | The system bus is in the hidden `/run`. No user manager: the user doesn't linger (so Hermes's cron jobs fail closed), and `/run/user` is hidden. | +| Escaping the unit | Descendants stay in the unit's cgroup (read-only under `ProtectControlGroups`) and stop with it, detached or not. | +| Files | `ProtectSystem=strict`: read-only, except the state directory, a private `/tmp`, and a minimal private `/dev`. | +| Other processes | `ProtectProc=invisible`, `ProcSubset=pid`, `PrivateIPC`. Hermes's user can still ptrace its own processes, so the bridge, which runs as that user, gets the same sandbox. | +| Privilege | `NoNewPrivileges`, an empty `CapabilityBoundingSet`, `RestrictSUIDSGID`, and `RestrictNamespaces` (no user namespaces). | +| Kernel interfaces | `ProtectKernelTunables`, `ProtectKernelModules`, `ProtectKernelLogs`, `ProtectClock`, `ProtectHostname`, `LockPersonality`, `SystemCallArchitectures=native`. | -### The two sockets +**`host.sock`** grants what its host serves. The host must serve only the guest's methods, bound to one agent. Arguments must be data (pet names, strings, message numbers), and references must stay in the host's pet store. The socket is mode 0600, owned by Hermes's user, so the connection designates the guest. Any process as that user counts as Hermes, and all of them are confined alike. -**`host.sock`** gives whatever its host serves there, so this part of the claim depends on the host. -- The host must serve only the guest's methods, bound to one guest agent. -- Arguments must be data: pet names, strings, message numbers. -- Object references must stay in the host's pet store; the guest sees an object only by its interface name. +**`llm.sock`** reaches [llm-proxy.py](llm-proxy.py), which runs as another user. It reads the key from its own systemd credential, which Hermes can't read. It forwards only `/v1/` paths, to one upstream host, and replaces any `Authorization` header the client sends. -[test/fake_host.py](test/fake_host.py) is that protocol, and the demo checks that Hermes can work with it. The socket is mode 0600 and owned by Hermes's user. So the connection itself designates the guest, and no secret has to cross. Any process running as Hermes's user counts as Hermes, which is correct: all of them are confined the same way. +**On macOS** the VM runs the same unit, and adds a boundary that holds even if the VM's kernel is compromised. Root in the VM reaches no network interface. It reaches the two vsock ports vfkit relays, the host's `/nix/store` read-only, and the state image. The trusted base gains Apple's hypervisor and loses the VM's kernel. -**`llm.sock`** reaches [llm-proxy.py](llm-proxy.py), which runs as a separate dynamic user. -- It reads the key from its own systemd credential, which Hermes can't read. -- It forwards only paths under `/v1/`, only to the host part of one upstream URL. -- It replaces any `Authorization` header the client sends. -- An absolute-form request line, such as `GET http://elsewhere/`, doesn't start with `/v1`, so it gets a 404. +**Not claimed:** +- **Secrecy.** Hermes can read what its user can read, and pass it to the model provider or to its host. +- **Denial of service.** No memory, task or CPU limits are set. +- **Kernel bugs** on a Linux host, and covert channels. +- **Sockets the sandbox doesn't hide**, such as under `/srv`. If the host listens on one that Hermes's user may connect to, add its directory to `TemporaryFileSystem`. -### On macOS - -The VM runs the same unit, so everything above holds inside it. The VM adds a second boundary, which still holds if the VM's kernel is compromised. A process with root in the VM reaches: -- no network interface; -- the two vsock ports vfkit relays, to `hostDir/host.sock` and `hostDir/llm.sock`; -- the host's `/nix/store`, read-only; -- the state image; -- the serial console, which only whoever runs the VM sees. - -The trusted base for the claim grows by one, Apple's hypervisor, and loses the guest kernel. - -### What this doesn't claim - -- **Secrecy.** Hermes can read what its user can read: the store, `/etc`, world-readable files under `/var` outside `/var/lib`. Through `llm.sock` it can send any of that to the model provider. Through `host.sock` it can send it to its host, which is by design. The claim limits what Hermes can do, not what it can learn or tell those two parties. -- **Denial of service.** No `MemoryMax`, `TasksMax`, or CPU quota is set. Hermes can use as much of the machine as it likes, flood the journal, or spend the API key's quota. -- **Kernel bugs** on a Linux host, and covert or timing channels. -- **Sockets elsewhere.** The claim assumes nothing on the host listens on a Unix socket outside `/run`, `/var/lib`, `/tmp` and `/home` that Hermes's user may connect to, for example under `/srv`, `/opt` or `/var/spool`. If one does, add its directory to `TemporaryFileSystem`. - -### What has been checked, and what hasn't - -- Checked: both platforms' configurations evaluate. The demo passes against unmodified Hermes on macOS, outside any sandbox. -- Not checked: neither the Linux unit nor the VM has been started. -- Not checked: whether vfkit refuses guest connections to vsock ports it wasn't told about. -- Not checked: the host's guest socket and the proxy, except by reading the code. - -On a running Linux host, enter the unit's namespaces and try to get out. `nsenter` enters the namespaces and mounts but not the seccomp filter or capability limits, so this checks the network and filesystem rows of the table: +To probe a running Linux host, enter the unit's namespaces. `nsenter` doesn't apply the seccomp filter or the capability limits, so this covers the network and file rows: ```sh pid=$(systemctl show -p MainPID --value hermes-agent) -sudo nsenter -t "$pid" -a -S "$(id -u hermes)" -G "$(id -g hermes)" sh -c ' - ls -A /run /run/hermes-guest /var/lib /home /tmp - ip -brief link - socat -T2 - TCP:1.1.1.1:443 Date: Sun, 29 Nov 2026 16:51:19 -0600 Subject: [PATCH 4/7] feat(sandbox): an empty root, by NixOS confinement The filesystem was the one part of the sandbox that started from the host's view and hid places from it (/run, /var/lib, /tmp, /home), so the argument had to assume no sockets elsewhere. Both units now start from an empty root: their closure (fullUnit, so PATH's packages too), /bin/sh, the state directory and the two sockets, and nothing else. socat is added to Hermes's closure by hand, since only config.yaml names it. CONTRIBUTING's table now has one row for files and sockets by path, and the "sockets the sandbox doesn't hide" caveat is gone. Generated-by: Claude Opus 5.5 --- CONTRIBUTING.md | 23 ++++++++++++----------- nix/hermes-guest.nix | 30 ++++++++++++++++-------------- 2 files changed, 28 insertions(+), 25 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 7f3ee5f..6868c50 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,19 +36,20 @@ Python here follows [DisciplinedPython](https://codeberg.org/dckc/awesome-ocap/s 2. connecting to `llm.sock`: inference at one upstream, with a key it never holds; 3. writing to its stdout and stderr, which go to the journal. -**Approach: assume nothing about Hermes.** Hermes can rewrite its own `config.yaml`, add MCP servers, and run anything its shell reaches. All of it runs inside the unit, so it inherits the same namespaces, mounts, cgroup and seccomp filter. So the argument is about the `sandbox` in [nix/hermes-guest.nix](nix/hermes-guest.nix), which every unit running as Hermes's user gets, not about Hermes or its model. +**Approach: assume nothing about Hermes.** Hermes can rewrite its own `config.yaml`, add MCP servers, and run anything its shell reaches. All of it runs inside the unit, so it inherits the same namespaces, mounts, cgroup and seccomp filter. So the argument is about the `sandbox` in [nix/hermes-guest.nix](nix/hermes-guest.nix), which every unit running as Hermes's user gets, and their `confinement`, not about Hermes or its model. + +Each part of the sandbox starts from nothing and adds what's needed, the way a CSS reset does. There's no denylist to keep complete. | Channel | What closes it | |---|---| | IP networking | `PrivateNetwork`: only loopback, shared with the bridge alone, whose one listener forwards to `llm.sock`. `IPAddressDeny=any` with `IPAddressAllow=localhost` is a second check. | -| Unix sockets, by path | These cross network namespaces, and accept `connect()` even on a read-only mount. `TemporaryFileSystem` empties `/run` (so `/var/run`) and `/var/lib`, `PrivateTmp` covers `/tmp`, and `ProtectHome` covers `/home`, `/root` and `/run/user`. `BindReadOnlyPaths` binds back the two sockets. | +| Files, and Unix sockets by path | NixOS `confinement`: the root is an empty directory. Bound into it are the unit's closure (read-only, `fullUnit`, so `PATH`'s packages too), `/bin/sh`, the state directory (`BindPaths`) and the two sockets (`BindReadOnlyPaths`), plus private `/dev`, `/proc`, `/sys` and `/tmp`. A path outside those doesn't exist in the unit's view. That matters for sockets, which cross network namespaces and accept `connect()` even on a read-only mount. | | Unix sockets, abstract | Private to the network namespace. | | Other socket families | `RestrictAddressFamilies`: `AF_UNIX`, and `AF_INET`/`AF_INET6` for loopback. No `AF_NETLINK`, `AF_PACKET` or `AF_VSOCK`. | -| systemd, D-Bus | The system bus is in the hidden `/run`. No user manager: the user doesn't linger (so Hermes's cron jobs fail closed), and `/run/user` is hidden. | +| systemd, D-Bus | The bus sockets aren't in the root. No user manager: the user doesn't linger, so Hermes's cron jobs fail closed. | | Escaping the unit | Descendants stay in the unit's cgroup (read-only under `ProtectControlGroups`) and stop with it, detached or not. | -| Files | `ProtectSystem=strict`: read-only, except the state directory, a private `/tmp`, and a minimal private `/dev`. | | Other processes | `ProtectProc=invisible`, `ProcSubset=pid`, `PrivateIPC`. Hermes's user can still ptrace its own processes, so the bridge, which runs as that user, gets the same sandbox. | -| Privilege | `NoNewPrivileges`, an empty `CapabilityBoundingSet`, `RestrictSUIDSGID`, and `RestrictNamespaces` (no user namespaces). | +| Privilege | `PrivateUsers` (a user namespace mapping only the unit's own user), `NoNewPrivileges`, an empty `CapabilityBoundingSet`, `RestrictSUIDSGID`, and `RestrictNamespaces`, so it can't make namespaces of its own. | | Kernel interfaces | `ProtectKernelTunables`, `ProtectKernelModules`, `ProtectKernelLogs`, `ProtectClock`, `ProtectHostname`, `LockPersonality`, `SystemCallArchitectures=native`. | **`host.sock`** grants what its host serves. The host must serve only the guest's methods, bound to one agent. Arguments must be data (pet names, strings, message numbers), and references must stay in the host's pet store. The socket is mode 0600, owned by Hermes's user, so the connection designates the guest. Any process as that user counts as Hermes, and all of them are confined alike. @@ -58,18 +59,18 @@ Python here follows [DisciplinedPython](https://codeberg.org/dckc/awesome-ocap/s **On macOS** the VM runs the same unit, and adds a boundary that holds even if the VM's kernel is compromised. Root in the VM reaches no network interface. It reaches the two vsock ports vfkit relays, the host's `/nix/store` read-only, and the state image. The trusted base gains Apple's hypervisor and loses the VM's kernel. **Not claimed:** -- **Secrecy.** Hermes can read what its user can read, and pass it to the model provider or to its host. +- **Secrecy.** Hermes can read its closure and its state, and pass them to the model provider or to its host. - **Denial of service.** No memory, task or CPU limits are set. - **Kernel bugs** on a Linux host, and covert channels. -- **Sockets the sandbox doesn't hide**, such as under `/srv`. If the host listens on one that Hermes's user may connect to, add its directory to `TemporaryFileSystem`. -To probe a running Linux host, enter the unit's namespaces. `nsenter` doesn't apply the seccomp filter or the capability limits, so this covers the network and file rows: +To probe a running Linux host, look at the unit's root and network from outside: ```sh pid=$(systemctl show -p MainPID --value hermes-agent) -sudo nsenter -t "$pid" -a -S "$(id -u hermes)" -G "$(id -g hermes)" sh -c \ - 'ls -A /run /var/lib /home; ip -brief link; socat -T2 - TCP:1.1.1.1:443 Date: Sun, 29 Nov 2026 16:58:56 -0600 Subject: [PATCH 5/7] feat: the Inference Cooperative as the example upstream, and a live demo - services.hermes-guest.reasoningEffort (and mkDarwin's): DeepSeek V4.1 takes only low, high, xhigh or max, and rejects Hermes's default. - The README's examples use gateway.inference.coop and deepseek-flash-tee, its TEE-hosted DeepSeek, which supports tool calling. - demo.py takes an optional MODEL and PROXY command: each connection to Hermes's model port is handed to PROXY as its stdin, as launchd and systemd hand them to llm-proxy.py, and only the outcome is checked. Generated-by: Claude Opus 5.5 --- CONTRIBUTING.md | 7 ++++++ README.md | 11 ++++++---- flake.nix | 3 ++- nix/hermes-guest.nix | 9 ++++++++ test/demo.py | 52 ++++++++++++++++++++++++++++++++++++-------- 5 files changed, 68 insertions(+), 14 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6868c50..a69209e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,6 +18,13 @@ python3 -m doctest fake_host.py fake_llm.py 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: + +```sh +python3 demo.py path/to/hermes path/to/socat deepseek-flash-tee \ + python3 ../llm-proxy.py https://gateway.inference.coop/v1 path/to/key +``` + 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 diff --git a/README.md b/README.md index 8f73339..01c61ff 100644 --- a/README.md +++ b/README.md @@ -26,11 +26,13 @@ macOS: [NixOS microVM (vfkit) ] imports = [ hermes-guest.nixosModules.linux-host ]; services.hermes-guest = { enable = true; - model = "anthropic/claude-sonnet-4"; + # the Inference Cooperative: https://docs.inference.coop/guides/api-access/ + model = "deepseek-flash-tee"; + reasoningEffort = "low"; # DeepSeek V4.1 takes low, high, xhigh or max hostSocketUnit = "endo-guest-hermes.socket"; }; services.hermes-llm-proxy = { - upstream = "https://openrouter.ai/api/v1"; + upstream = "https://gateway.inference.coop/v1"; keyFile = "/run/secrets/llm-key"; # a runtime path, not a nix path }; ``` @@ -42,8 +44,9 @@ Building the VM needs a Linux builder (for example nix-darwin's `nix.linux-build ```sh nix build --impure --expr '(builtins.getFlake (toString ./.)).lib.mkDarwin { hostDir = "/Users/me/.local/state/hermes-guest"; - model = "anthropic/claude-sonnet-4"; - upstream = "https://openrouter.ai/api/v1"; + model = "deepseek-flash-tee"; + reasoningEffort = "low"; + upstream = "https://gateway.inference.coop/v1"; keyFile = "/Users/me/.config/hermes-guest/llm-key"; }.host' mkdir -p ~/.local/state/hermes-guest diff --git a/flake.nix b/flake.nix index a67523b..50a9f56 100644 --- a/flake.nix +++ b/flake.nix @@ -59,6 +59,7 @@ model, upstream, keyFile, + reasoningEffort ? null, system ? "aarch64-darwin", }: let @@ -71,7 +72,7 @@ microvm.vmHostPackages = hostPkgs; services.hermes-guest = { enable = true; - inherit model; + inherit model reasoningEffort; vm.hostDir = hostDir; }; } diff --git a/nix/hermes-guest.nix b/nix/hermes-guest.nix index b4c19a3..b93d163 100644 --- a/nix/hermes-guest.nix +++ b/nix/hermes-guest.nix @@ -80,6 +80,12 @@ in type = lib.types.str; description = "The model name, as the proxy's upstream knows it."; }; + reasoningEffort = lib.mkOption { + type = lib.types.nullOr lib.types.str; + default = null; + example = "low"; + description = "Hermes's agent.reasoning_effort, for models that take only some levels (DeepSeek V4.1: low, high, xhigh, max)."; + }; }; config = lib.mkIf cfg.enable { @@ -98,6 +104,9 @@ in # 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"; + } + // lib.optionalAttrs (cfg.reasoningEffort != null) { + agent.reasoning_effort = cfg.reasoningEffort; }; mcpServers.host = { command = "${pkgs.socat}/bin/socat"; diff --git a/test/demo.py b/test/demo.py index c24cda4..47806a1 100644 --- a/test/demo.py +++ b/test/demo.py @@ -7,16 +7,24 @@ 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 +With MODEL and PROXY, 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 """ import json import logging import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer -from socketserver import StreamRequestHandler, ThreadingUnixStreamServer +from socketserver import (BaseRequestHandler, StreamRequestHandler, + ThreadingTCPServer, ThreadingUnixStreamServer) from fake_host import HostSide, Mailbox, Ref, handle_rpc from fake_llm import chunks, completion, next_step @@ -92,12 +100,20 @@ class LlmHandler(BaseHTTPRequestHandler): logging.debug(format, *args) -def hermes_config(socat, host_sock, llm_port): +class InetdHandler(BaseRequestHandler): + """One connection, handed to the proxy command as its stdin (inetd style).""" + + def handle(self): + self.server.popen(self.server.command, stdin=self.request).wait() + + +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({ + **dict(extra), "model": { "provider": "custom", - "default": MODEL, + "default": model, "base_url": f"http://127.0.0.1:{llm_port}/v1", "api_key": "held-by-proxy", }, @@ -127,8 +143,19 @@ def check(host, mailbox, seen, stdout): return [what for what, ok in expect.items() if not ok] +def check_outcome(host): + """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), + } + 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) @@ -137,8 +164,12 @@ def main(argv, make_tmpdir, run, popen, timeout_expired, environ): 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, [], [] + if live: + llm = ThreadingTCPServer(("127.0.0.1", 0), InetdHandler) + llm.popen, llm.command = popen, argv[4:] + 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() @@ -146,7 +177,9 @@ 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])) + hermes_config(socat, host_sock, llm.server_address[1], model, + # DeepSeek V4.1 takes low|high|xhigh|max, not Hermes's default + {"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 @@ -159,7 +192,7 @@ def main(argv, make_tmpdir, run, popen, timeout_expired, environ): 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) + env=env, capture_output=True, text=True, timeout=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:]) @@ -178,7 +211,8 @@ 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(host, mailbox, llm.seen, stdout) + llm.errors + failures = (check_outcome(host) if live + else 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) -- 2.53.0 From 783e4c595fa953c91e0bbffbb103efd2e5036847 Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Sun, 29 Nov 2026 17:14:02 -0600 Subject: [PATCH 6/7] 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 --- CONTRIBUTING.md | 5 +- guide/endo-guest.md | 94 ++++++++++++++++++++++++ test/demo.py | 170 +++++++++++++++++++++++++++++++++++++------- test/fake_host.py | 123 ++++++++++++++++++++++++++++++-- 4 files changed, 361 insertions(+), 31 deletions(-) create mode 100644 guide/endo-guest.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a69209e..e87fd56 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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/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. +- [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. ## 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: ```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 ``` +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: ```sh diff --git a/guide/endo-guest.md b/guide/endo-guest.md new file mode 100644 index 0000000..d159276 --- /dev/null +++ b/guide/endo-guest.md @@ -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/"}} +} +``` diff --git a/test/demo.py b/test/demo.py index 47806a1..dd9d8f3 100644 --- a/test/demo.py +++ b/test/demo.py @@ -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()) diff --git a/test/fake_host.py b/test/fake_host.py index 1c0bf1e..2757b03 100644 --- a/test/fake_host.py +++ b/test/fake_host.py @@ -3,7 +3,9 @@ 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. +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')) >>> guest = Mailbox(host) @@ -19,12 +21,35 @@ never holds one; it moves them between messages and names. (['Thanks for the ', '!'], ['it']) >>> host.received['it'] 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 logging +import re import threading from dataclasses import dataclass, field +from urllib.parse import urlencode, urljoin, urlsplit @dataclass(frozen=True) @@ -42,7 +67,52 @@ def describe(value): >>> describe(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 @@ -52,6 +122,7 @@ class HostSide: on_request: object # description -> value inbox: list = field(default_factory=list) received: dict = field(default_factory=dict) + definitions: list = field(default_factory=list) def send(self, guest, strings, edge_names, values): guest._deliver("package", "HOST", strings=strings, @@ -122,6 +193,30 @@ class Mailbox: record, values = self._message(messageNumber) 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): with self._lock: self._messages = [ @@ -152,10 +247,22 @@ TOOLS = { "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})), + "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. >>> box = Mailbox(HostSide(on_request=lambda d: 1)) @@ -171,7 +278,7 @@ def handle_rpc(mailbox, msg): if method == "initialize": reply["result"] = { "protocolVersion": params.get("protocolVersion", "2025-06-18"), - "capabilities": {"tools": {}}, + "capabilities": {"tools": {}, **({"resources": {}} if resources else {})}, "serverInfo": {"name": "fake-endo-host", "version": "0"}, } elif method == "ping": @@ -180,6 +287,14 @@ def handle_rpc(mailbox, msg): reply["result"] = {"tools": [ {"name": name, "description": desc, "inputSchema": schema} 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: name, args = params["name"], params.get("arguments") or {} logging.info("guest calls %s(%s)", name, json.dumps(args)) -- 2.53.0 From 3f9ba544775c8f5d20e25edff690720e38a3d931 Mon Sep 17 00:00:00 2001 From: Dan Connolly Date: Sun, 29 Nov 2026 23:15:06 -0600 Subject: [PATCH 7/7] 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 --- .gitignore | 1 + CONTRIBUTING.md | 31 +- flake.nix | 28 + guide/endo-guest.md | 83 +-- nix/darwin-host.nix | 9 +- nix/hermes-guest.nix | 24 +- nix/linux-host.nix | 9 + nix/vfkit-vm.nix | 13 +- test/demo.py | 349 +++++++++-- test/endo-catalog.json | 1304 ++++++++++++++++++++++++++++++++++++++++ test/endo_catalog.mjs | 27 + test/endo_host.mjs | 175 ++++++ test/fake_host.py | 498 ++++++++++----- test/transcript.py | 80 +++ test/webapp_caplet.mjs | 49 ++ 15 files changed, 2398 insertions(+), 282 deletions(-) create mode 100644 test/endo-catalog.json create mode 100644 test/endo_catalog.mjs create mode 100644 test/endo_host.mjs create mode 100644 test/transcript.py create mode 100644 test/webapp_caplet.mjs diff --git a/.gitignore b/.gitignore index ade4808..0a12824 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ __pycache__/ result result-* +runs/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e87fd56..bc8ed69 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,20 +5,25 @@ How to check a change, and why the confinement holds. For what this is and how t ## Layout - [nix/hermes-guest.nix](nix/hermes-guest.nix): the confined unit, the part that ports. Its `sandbox` attribute set is what [Confinement](#confinement) argues for. -- [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/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, and makes its downloads folder. +- [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, and its downloads folder shared by virtiofs. - [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. +- [guide/endo-guest.md](guide/endo-guest.md): what a guest can do (names, messages, `evaluate`, WebApps, the downloads folder, `define`), installed as Hermes's skill `endo-guest`, so it works whatever serves `host.sock`. +- [test/](test/demo.py): unmodified Hermes against a host (a fake one, or a real Endo daemon) and a model (scripted, or real). ## Checking a change ```sh +nix build .#demo-tools -o result-demo-tools cd test -python3 -m doctest fake_host.py fake_llm.py -python3 demo.py path/to/hermes path/to/socat # ends with PASS +python3 -m doctest demo.py fake_host.py fake_llm.py transcript.py +python3 demo.py --tools ../result-demo-tools path/to/hermes path/to/socat # ends with PASS ``` +These need Python 3.10 or later. Hermes and the checks get `demo-tools/bin` as their whole `PATH`: tools from the store, as the unit's closure gives them, and nothing of the machine's own. + +The fake host serves a subset of [@endo/agent-mcp-stdio](https://github.com/endojs/endo-but-for-bots/tree/llm/packages/agent-mcp-stdio)'s tools, with its names and schemas ([test/endo-catalog.json](test/endo-catalog.json), from `node endo_catalog.mjs ENDO_CHECKOUT`) and its rendering of answers. Its `evaluate` takes only `E(name).method(arg, ...)`. With `--host endo --endo ENDO_CHECKOUT`, a real Endo daemon is the host instead ([test/endo_host.mjs](test/endo_host.mjs)), its guest served by that package's broker; the checkout is endo-but-for-bots, branch `llm`, with its dependencies installed. Each run saves what happened in `runs/TASK`, replacing the last run of that task: `transcript.md` (the conversation as Hermes recorded it, reasoning and tool calls included), `mcp.jsonl` (every message on `host.sock`, either host), `host.json` (what the host received), and Hermes's output and logs. + 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 @@ -26,14 +31,14 @@ 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 ``` -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. +Add `--task install` to ask Hermes to install `six` and `ms`, with no networking but the package-index WebApps its host grants, and its downloads folder. On macOS it runs under `sandbox-exec`, with outbound network denied and its downloads folder read-only. It passes when the wheel and tarball came through `~/Downloads`, and 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: ```sh -nix eval --impure --expr '(builtins.getFlake (toString ./.)).lib.mkDarwin { +nix eval --impure --expr '((builtins.getFlake (toString ./.)).lib.mkDarwin { hostDir = "/tmp/h"; model = "m"; upstream = "https://example.com/v1"; keyFile = "/k"; -}.runner.drvPath' +}).runner.drvPath' ``` Python here follows [DisciplinedPython](https://codeberg.org/dckc/awesome-ocap/src/branch/master/style-guide/ocap-py-style-guide.md); run its checker on scripts you change. When you change the sandbox, update the table below in the same commit. @@ -53,7 +58,7 @@ Each part of the sandbox starts from nothing and adds what's needed, the way a C | Channel | What closes it | |---|---| | IP networking | `PrivateNetwork`: only loopback, shared with the bridge alone, whose one listener forwards to `llm.sock`. `IPAddressDeny=any` with `IPAddressAllow=localhost` is a second check. | -| Files, and Unix sockets by path | NixOS `confinement`: the root is an empty directory. Bound into it are the unit's closure (read-only, `fullUnit`, so `PATH`'s packages too), `/bin/sh`, the state directory (`BindPaths`) and the two sockets (`BindReadOnlyPaths`), plus private `/dev`, `/proc`, `/sys` and `/tmp`. A path outside those doesn't exist in the unit's view. That matters for sockets, which cross network namespaces and accept `connect()` even on a read-only mount. | +| Files, and Unix sockets by path | NixOS `confinement`: the root is an empty directory. Bound into it are the unit's closure (read-only, `fullUnit`, so `PATH`'s packages too), `/bin/sh`, the state directory (`BindPaths`), and the two sockets and the downloads folder (`BindReadOnlyPaths`), plus private `/dev`, `/proc`, `/sys` and `/tmp`. A path outside those doesn't exist in the unit's view. That matters for sockets, which cross network namespaces and accept `connect()` even on a read-only mount. | | Unix sockets, abstract | Private to the network namespace. | | Other socket families | `RestrictAddressFamilies`: `AF_UNIX`, and `AF_INET`/`AF_INET6` for loopback. No `AF_NETLINK`, `AF_PACKET` or `AF_VSOCK`. | | systemd, D-Bus | The bus sockets aren't in the root. No user manager: the user doesn't linger, so Hermes's cron jobs fail closed. | @@ -62,11 +67,13 @@ Each part of the sandbox starts from nothing and adds what's needed, the way a C | Privilege | `PrivateUsers` (a user namespace mapping only the unit's own user), `NoNewPrivileges`, an empty `CapabilityBoundingSet`, `RestrictSUIDSGID`, and `RestrictNamespaces`, so it can't make namespaces of its own. | | Kernel interfaces | `ProtectKernelTunables`, `ProtectKernelModules`, `ProtectKernelLogs`, `ProtectClock`, `ProtectHostname`, `LockPersonality`, `SystemCallArchitectures=native`. | -**`host.sock`** grants what its host serves. The host must serve only the guest's methods, bound to one agent. Arguments must be data (pet names, strings, message numbers), and references must stay in the host's pet store. The socket is mode 0600, owned by Hermes's user, so the connection designates the guest. Any process as that user counts as Hermes, and all of them are confined alike. +**`host.sock`** grants what its host serves. The host must serve only the guest's methods, bound to one agent, and references must stay in the host's pet store. Arguments are data (pet names, strings, message numbers) and code: `evaluate` runs the guest's source on the host's side, with only the guest's own references in scope, so it reaches nothing the guest couldn't reach by calls. The socket is mode 0600, owned by Hermes's user, so the connection designates the guest. Any process as that user counts as Hermes, and all of them are confined alike. + +**The downloads folder** is the host's to write, and read-only in the unit, so it's input, not a way out: Hermes can't write there, and so can't plant a file or symlink for the host to act on. The host writes what the guest asks, through references the guest holds (`E(dir).write(name, blob)`), so the bytes come from the web to the disk without passing through Hermes or the model. **`llm.sock`** reaches [llm-proxy.py](llm-proxy.py), which runs as another user. It reads the key from its own systemd credential, which Hermes can't read. It forwards only `/v1/` paths, to one upstream host, and replaces any `Authorization` header the client sends. -**On macOS** the VM runs the same unit, and adds a boundary that holds even if the VM's kernel is compromised. Root in the VM reaches no network interface. It reaches the two vsock ports vfkit relays, the host's `/nix/store` read-only, and the state image. The trusted base gains Apple's hypervisor and loses the VM's kernel. +**On macOS** the VM runs the same unit, and adds a boundary that holds even if the VM's kernel is compromised. Root in the VM reaches no network interface. It reaches the two vsock ports vfkit relays, the host's `/nix/store` read-only, the downloads folder's share, and the state image. The trusted base gains Apple's hypervisor and loses the VM's kernel, with one exception: the downloads share is read-only in the unit, but not at vfkit, so a compromised VM kernel could write to `hostDir/Downloads`. **Not claimed:** - **Secrecy.** Hermes can read its closure and its state, and pass them to the model provider or to its host. diff --git a/flake.nix b/flake.nix index 50a9f56..203e433 100644 --- a/flake.nix +++ b/flake.nix @@ -95,6 +95,34 @@ }; }; + packages = lib.genAttrs [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ] ( + system: + let + pkgs = nixpkgs.legacyPackages.${system}; + in + { + # what test/demo.py puts on PATH for Hermes and its checks, and + # nothing else: the tools a guest's shell has, from the store, as + # the confined unit's closure gives them + demo-tools = pkgs.buildEnv { + name = "hermes-guest-demo-tools"; + paths = [ + (pkgs.python3.withPackages (ps: [ ps.pip ])) + pkgs.nodejs + pkgs.socat + pkgs.bash + pkgs.coreutils + pkgs.findutils + pkgs.gnugrep + pkgs.gnused + pkgs.gnutar + pkgs.gzip + pkgs.unzip + ]; + }; + } + ); + formatter = lib.genAttrs [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ] ( system: nixpkgs.legacyPackages.${system}.nixfmt ); diff --git a/guide/endo-guest.md b/guide/endo-guest.md index d159276..d5c78e1 100644 --- a/guide/endo-guest.md +++ b/guide/endo-guest.md @@ -1,94 +1,73 @@ # 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. +Think of the `host` MCP server's tools as your system calls, and your host as your kernel. They're the only way you affect the world beyond your own sandbox. Your sandbox has no networking of its own: no sockets out, no DNS. You reach the web through the WebApps your host gives you, and only those. -## Names, not references +## Names work like file descriptors -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. +A name is like a file descriptor: you pass it to a tool to use the object it refers to. There's no `open(path)` that turns a string into access. Knowing a URL or an address gets you nothing; only the names you hold reach anything, and you get new ones from your host, by asking, or from what the objects you hold answer. Unlike a file descriptor, you choose a name, with `responseName` or `resultName`. +- A name is given as a path, a list of strings: `["pen"]`. +- `list` shows your names. `@host` is your host; names that start with `@` are given, not chosen. +- An object in a tool's answer shows as `"[remotable]"`. To keep it, name it. +- To learn what an object can do, evaluate `E(x).__getMethodNames__()`. +- `help` describes the tools. ## 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`: +`listMessages` shows your inbox. A message has a `number`, and `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"]} +{"recipient": ["@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`. +- `request(recipient, description, responseName)` asks your host for something, in words, and waits for the answer, which is kept under `responseName`. +- `evaluate(source, codeNames, petNamePaths, resultName)` evaluates JavaScript `source`, in which each of `codeNames` is the reference the matching one of `petNamePaths` names. If `resultName` is given, the answer is kept under it. + +Write `source` as a method call, `E(x).method(arg, ...)`, where `x` is a code name and each `arg` is a literal (a string, number, `true`, `false`, `null`, or an array or object of those) or a code name. Every host evaluates that form; some evaluate only that. ## 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`. +- `pathjoin(path)` narrows it to a path within its URL, and `query(params)` adds query parameters. Both answer a new WebApp, so give `resultName`. - `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. +- `blob()` answers the body as a blob, for bytes such as a tarball or a wheel: name it, then write it to a file (below). 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"} +{"source": "E(npm).pathjoin('ms')", "codeNames": ["npm"], "petNamePaths": [["npm"]], "resultName": ["ms-meta"]} +{"source": "E(meta).get()", "codeNames": ["meta"], "petNamePaths": [["ms-meta"]]} ``` -## Moving bytes: speak to host.sock from your shell +## Files: your downloads folder -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: +A tool's answer comes into your context, not onto your disk. To get a file onto your disk, ask your host for your downloads folder, `~/Downloads`, which your host writes and you read. Then have the host write into it: -```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)) +```json +{"source": "E(w).blob()", "codeNames": ["w"], "petNamePaths": [["six-wheel"]], "resultName": ["six-blob"]} +{"source": "E(d).write('six-1.17.0-py2.py3-none-any.whl', b)", "codeNames": ["d", "b"], "petNamePaths": [["downloads"], ["six-blob"]]} ``` -It's the same socket, and the same authority, as your `host` tools. +The bytes go from the WebApp to the file without passing through you. Name the blob first, as above: `write` takes a blob, not the promise of one. `E(d).list()` lists the folder. You can't write there yourself; copy or install from it. ## 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. +To get something done with references you don't hold, propose code to your host with `define(source, slots)`: +- `source` is a JavaScript expression, with no limit on its form; +- `slots` names its free variables, 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. +Your host reads the source and decides. It may endow the definition: bind each slot to a reference it holds, evaluate the source, and keep the result. The result 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. +In the source, `E` is eventual send (`E(x).method(...)` answers a promise) and `Far` makes a remotable object. -For example, a vat that answers the latest version of an npm package, given a WebApp for the registry: +For example, an object 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; } });" - }, + "source": "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/"}} } ``` diff --git a/nix/darwin-host.nix b/nix/darwin-host.nix index 2a76f8e..997dd08 100644 --- a/nix/darwin-host.nix +++ b/nix/darwin-host.nix @@ -33,7 +33,14 @@ let vm = plist "net.madmode.hermes-vm" { Label = "net.madmode.hermes-vm"; - ProgramArguments = [ "${runner}/bin/microvm-run" ]; + # vfkit shares hostDir/Downloads into the VM, so it must exist first + ProgramArguments = [ + "/bin/sh" + "-c" + ''mkdir -p "$0/Downloads" && exec "$1"'' + hostDir + "${runner}/bin/microvm-run" + ]; WorkingDirectory = hostDir; KeepAlive = true; StandardOutPath = "${hostDir}/vm.log"; diff --git a/nix/hermes-guest.nix b/nix/hermes-guest.nix index b93d163..dcf8721 100644 --- a/nix/hermes-guest.nix +++ b/nix/hermes-guest.nix @@ -2,14 +2,18 @@ # # This module is what ports: the same unit runs on a Linux host and inside # the macOS VM (./vfkit-vm.nix). It reaches the world through exactly two -# Unix sockets, and whatever imports it decides what serves them: +# Unix sockets and one directory, and whatever imports it decides what +# serves them: # -# hostSocket the guest's methods (listMessages, request, resolve, -# lookup, ...) as an MCP server, bound to one guest agent +# hostSocket the guest's methods (listMessages, request, evaluate, +# ...) as an MCP server, bound to one guest agent # llmSocket model inference, through a proxy that holds the API key +# downloadsDir the guest's downloads folder, ~/Downloads: the host +# writes it, and Hermes only reads it # -# The service has no network of its own (PrivateNetwork), and its root -# is empty except for its closure and those two sockets (confinement). +# The service has no network of its own (PrivateNetwork), and its root is +# empty except for its closure, those two sockets, the downloads folder, +# and its state (confinement). { config, lib, @@ -76,6 +80,14 @@ in default = 8080; description = "The loopback port, inside Hermes's own network namespace, that forwards to llmSocket."; }; + downloadsDir = lib.mkOption { + type = lib.types.str; + default = "/var/lib/hermes-downloads"; + description = '' + The guest's downloads folder, as the host sees it: the host writes files here (say, a + WebApp's body, by E(dir).write(name, blob)), and Hermes sees it, read-only, as ~/Downloads. + ''; + }; model = lib.mkOption { type = lib.types.str; description = "The model name, as the proxy's upstream knows it."; @@ -131,6 +143,8 @@ in BindReadOnlyPaths = [ cfg.hostSocket cfg.llmSocket + # read-only: Hermes can't plant anything there for the host to trip on + "${cfg.downloadsDir}:${hermes.stateDir}/Downloads" ]; BindPaths = [ hermes.stateDir ]; ProtectHome = lib.mkForce true; diff --git a/nix/linux-host.nix b/nix/linux-host.nix index fde91d2..cd1f388 100644 --- a/nix/linux-host.nix +++ b/nix/linux-host.nix @@ -23,7 +23,16 @@ in ''; }; + options.services.hermes-guest.downloadsUser = lib.mkOption { + type = lib.types.str; + example = "toybox"; + description = "The host's user, who writes downloadsDir; Hermes's group may read it."; + }; + config = lib.mkIf cfg.enable { + systemd.tmpfiles.rules = [ + "d ${cfg.downloadsDir} 0750 ${cfg.downloadsUser} ${config.services.hermes-agent.group} -" + ]; services.hermes-llm-proxy = { enable = true; socket = cfg.llmSocket; diff --git a/nix/vfkit-vm.nix b/nix/vfkit-vm.nix index 1604216..97b4bbb 100644 --- a/nix/vfkit-vm.nix +++ b/nix/vfkit-vm.nix @@ -2,7 +2,8 @@ # Inside the VM, systemd serves Hermes's two sockets too; each connection # is relayed over vsock to the host (CID 2), where vfkit connects it to a # Unix socket in hostDir. So the host's listeners on those two paths -# decide what Hermes can reach. +# decide what Hermes can reach. The downloads folder is hostDir/Downloads, +# shared into the VM by virtiofs. { config, lib, @@ -42,7 +43,7 @@ in hostDir = lib.mkOption { type = lib.types.str; example = "/Users/me/.local/state/hermes-guest"; - description = "The host directory with the VM's state image, and the two Unix sockets vfkit connects to."; + description = "The host directory with the VM's state image, the two Unix sockets vfkit connects to, and the guest's downloads folder, Downloads."; }; hostPort = lib.mkOption { type = lib.types.port; @@ -75,6 +76,14 @@ in mountPoint = "/nix/.ro-store"; proto = "virtiofs"; } + # the downloads folder, which the host writes; the unit binds it + # read-only into Hermes's home + { + tag = "downloads"; + source = "${vm.hostDir}/Downloads"; + mountPoint = cfg.downloadsDir; + proto = "virtiofs"; + } ]; volumes = [ { diff --git a/test/demo.py b/test/demo.py index dd9d8f3..f9b69a1 100644 --- a/test/demo.py +++ b/test/demo.py @@ -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()) diff --git a/test/endo-catalog.json b/test/endo-catalog.json new file mode 100644 index 0000000..eeb5f41 --- /dev/null +++ b/test/endo-catalog.json @@ -0,0 +1,1304 @@ +[ + { + "name": "help", + "description": "Describe your own capability surface, or one method of it by name.", + "inputSchema": { + "type": "object", + "properties": { + "methodName": { + "type": "string" + } + }, + "required": [], + "additionalProperties": false + } + }, + { + "name": "has", + "description": "Report whether a pet name path exists in your directory.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "list", + "description": "List the pet names in your directory, or in the directory at a path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [], + "additionalProperties": false + } + }, + { + "name": "remove", + "description": "Remove a pet name. The named value itself is not deleted.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "move", + "description": "Rename a pet name; the original name is removed.", + "inputSchema": { + "type": "object", + "properties": { + "fromPath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "toPath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "fromPath", + "toPath" + ], + "additionalProperties": false + } + }, + { + "name": "copy", + "description": "Give an existing value a second pet name.", + "inputSchema": { + "type": "object", + "properties": { + "fromPath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "toPath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "fromPath", + "toPath" + ], + "additionalProperties": false + } + }, + { + "name": "identify", + "description": "Report the formula identifier a pet name path designates.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "reverseIdentify", + "description": "List the pet names that designate a formula identifier.", + "inputSchema": { + "type": "object", + "properties": { + "identifier": { + "type": "string" + } + }, + "required": [ + "identifier" + ], + "additionalProperties": false + } + }, + { + "name": "listIdentifiers", + "description": "List the formula identifiers in your directory, or in the directory at a path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [], + "additionalProperties": false + } + }, + { + "name": "storeIdentifier", + "description": "Name the value a formula identifier designates.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "identifier": { + "type": "string" + } + }, + "required": [ + "petNamePath", + "identifier" + ], + "additionalProperties": false + } + }, + { + "name": "locate", + "description": "Report the locator for a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "listLocators", + "description": "List the locators in your directory, or in the directory at a path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [], + "additionalProperties": false + } + }, + { + "name": "reverseLocate", + "description": "List the pet names that designate a locator.", + "inputSchema": { + "type": "object", + "properties": { + "locator": { + "type": "string", + "description": "A locator, for example from locate or invite." + } + }, + "required": [ + "locator" + ], + "additionalProperties": false + } + }, + { + "name": "storeLocator", + "description": "Adopt a locator: give the value it designates a pet name in your directory.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "locator": { + "type": "string", + "description": "A locator, for example from locate or invite." + } + }, + "required": [ + "petNamePath", + "locator" + ], + "additionalProperties": false + } + }, + { + "name": "locateContent", + "description": "Report the content locator (a magnet URN) for a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "listContent", + "description": "List the content locators in your directory, or in the directory at a path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [], + "additionalProperties": false + } + }, + { + "name": "storeContent", + "description": "Store the content at a pet name path and report its content locator.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "reverseLocateContent", + "description": "List the pet names whose content a content locator designates.", + "inputSchema": { + "type": "object", + "properties": { + "locator": { + "type": "string", + "description": "A locator, for example from locate or invite." + } + }, + "required": [ + "locator" + ], + "additionalProperties": false + } + }, + { + "name": "internalizeContentLocator", + "description": "Internalize a content locator into the local content store.", + "inputSchema": { + "type": "object", + "properties": { + "locator": { + "type": "string", + "description": "A locator, for example from locate or invite." + } + }, + "required": [ + "locator" + ], + "additionalProperties": false + } + }, + { + "name": "loadContent", + "description": "Load the content a content locator designates.", + "inputSchema": { + "type": "object", + "properties": { + "locator": { + "type": "string", + "description": "A locator, for example from locate or invite." + } + }, + "required": [ + "locator" + ], + "additionalProperties": false + } + }, + { + "name": "invite", + "description": "Mint an invitation for a new correspondent and report its locator.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "accept", + "description": "Redeem an invitation locator and name the new correspondent.", + "inputSchema": { + "type": "object", + "properties": { + "locator": { + "type": "string", + "description": "A locator, for example from locate or invite." + }, + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "locator", + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "makeDirectory", + "description": "Create a new directory at a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "makePath", + "description": "Create the directory at a pet name path and any intermediate directories, only where they do not yet exist. makePath calls run one at a time, so one never replaces directories another created; a concurrent mkdir is not ordered against them.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "readText", + "description": "Read the text of a file at a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "maybeReadText", + "description": "Read the text of a file at a pet name path, or nothing if it is absent.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "writeText", + "description": "Write text to a file at a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "text": { + "type": "string" + } + }, + "required": [ + "petNamePath", + "text" + ], + "additionalProperties": false + } + }, + { + "name": "storeValue", + "description": "Store a JSON value under a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "value": {} + }, + "required": [ + "petNamePath", + "value" + ], + "additionalProperties": false + } + }, + { + "name": "glob", + "description": "List the file paths matching a glob pattern in the mount at a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "mountPath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "pattern": { + "type": "string" + }, + "followSymlinks": { + "type": "boolean" + } + }, + "required": [ + "mountPath", + "pattern" + ], + "additionalProperties": false + } + }, + { + "name": "grep", + "description": "Search file contents for a regular expression in the mount at a pet name path, optionally only in the given file paths.", + "inputSchema": { + "type": "object", + "properties": { + "mountPath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "pattern": { + "type": "string" + }, + "paths": { + "type": "array", + "items": { + "type": "string" + } + }, + "maxResults": { + "type": "integer", + "minimum": 1 + }, + "followSymlinks": { + "type": "boolean" + } + }, + "required": [ + "mountPath", + "pattern" + ], + "additionalProperties": false + } + }, + { + "name": "glorp", + "description": "Search the contents of the files matching a glob pattern for a regular expression, in the mount at a pet name path.", + "inputSchema": { + "type": "object", + "properties": { + "mountPath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "globPattern": { + "type": "string" + }, + "grepPattern": { + "type": "string" + }, + "maxResults": { + "type": "integer", + "minimum": 1 + }, + "followSymlinks": { + "type": "boolean" + } + }, + "required": [ + "mountPath", + "globPattern", + "grepPattern" + ], + "additionalProperties": false + } + }, + { + "name": "evaluate", + "description": "Evaluate JavaScript in a worker, with named values from your directory in scope. codeNames[i] is bound to petNamePaths[i].", + "inputSchema": { + "type": "object", + "properties": { + "workerName": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "source": { + "type": "string" + }, + "codeNames": { + "type": "array", + "items": { + "type": "string" + } + }, + "petNamePaths": { + "type": "array", + "items": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "resultName": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "source", + "codeNames", + "petNamePaths" + ], + "additionalProperties": false + } + }, + { + "name": "define", + "description": "Propose code with named slots to your host, who fills each slot with a value and runs it.", + "inputSchema": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "slots": { + "type": "object", + "additionalProperties": { + "type": "object", + "properties": { + "label": { + "type": "string" + } + }, + "required": [ + "label" + ], + "additionalProperties": false + } + } + }, + "required": [ + "source", + "slots" + ], + "additionalProperties": false + } + }, + { + "name": "listMessages", + "description": "List the messages in your inbox.", + "inputSchema": { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false + } + }, + { + "name": "send", + "description": "Send a package message: text fragments interleaved with named values. strings has one more entry than edgeNames; petNames names the values.", + "inputSchema": { + "type": "object", + "properties": { + "recipient": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "strings": { + "type": "array", + "items": { + "type": "string" + } + }, + "edgeNames": { + "type": "array", + "items": { + "type": "string" + } + }, + "petNames": { + "type": "array", + "items": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + } + }, + "required": [ + "recipient", + "strings", + "edgeNames", + "petNames" + ], + "additionalProperties": false + } + }, + { + "name": "reply", + "description": "Reply to a message in your inbox with a package message.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + }, + "strings": { + "type": "array", + "items": { + "type": "string" + } + }, + "edgeNames": { + "type": "array", + "items": { + "type": "string" + } + }, + "petNames": { + "type": "array", + "items": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + } + }, + "required": [ + "messageNumber", + "strings", + "edgeNames", + "petNames" + ], + "additionalProperties": false + } + }, + { + "name": "editMessage", + "description": "Replace the content of a message you sent; done marks it final.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + }, + "strings": { + "type": "array", + "items": { + "type": "string" + } + }, + "edgeNames": { + "type": "array", + "items": { + "type": "string" + } + }, + "petNames": { + "type": "array", + "items": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "done": { + "type": "boolean" + } + }, + "required": [ + "messageNumber", + "strings", + "edgeNames", + "petNames" + ], + "additionalProperties": false + } + }, + { + "name": "messageHistory", + "description": "List the revisions of a message.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + } + }, + "required": [ + "messageNumber" + ], + "additionalProperties": false + } + }, + { + "name": "adopt", + "description": "Give a pet name to a value carried by a message in your inbox.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + }, + "edgeName": { + "type": "string" + }, + "petName": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "messageNumber", + "edgeName", + "petName" + ], + "additionalProperties": false + } + }, + { + "name": "dismiss", + "description": "Remove a message from your inbox.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + } + }, + "required": [ + "messageNumber" + ], + "additionalProperties": false + } + }, + { + "name": "dismissAll", + "description": "Remove every message from your inbox.", + "inputSchema": { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false + } + }, + { + "name": "request", + "description": "Ask a correspondent for a value and wait for the answer, optionally naming it.", + "inputSchema": { + "type": "object", + "properties": { + "recipient": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "description": { + "type": "string" + }, + "responseName": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "recipient", + "description" + ], + "additionalProperties": false + } + }, + { + "name": "resolve", + "description": "Answer a request in your inbox with a named value.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + }, + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "messageNumber", + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "reject", + "description": "Decline a request in your inbox, optionally saying why.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + }, + "reason": { + "type": "string" + } + }, + "required": [ + "messageNumber" + ], + "additionalProperties": false + } + }, + { + "name": "sendValue", + "description": "Reply to a message with a named value.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + }, + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "messageNumber", + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "form", + "description": "Send a form for a correspondent to fill in.", + "inputSchema": { + "type": "object", + "properties": { + "recipient": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + }, + "description": { + "type": "string" + }, + "fields": { + "type": "array", + "items": { + "type": "object" + } + } + }, + "required": [ + "recipient", + "description", + "fields" + ], + "additionalProperties": false + } + }, + { + "name": "submit", + "description": "Submit values for a form in your inbox.", + "inputSchema": { + "type": "object", + "properties": { + "messageNumber": { + "anyOf": [ + { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + { + "type": "string", + "pattern": "^\\+?[0-9]+$" + } + ], + "description": "A message number from listMessages, for example 5 or \"5\" (write a number past 9007199254740991 as a decimal string)." + }, + "values": { + "type": "object" + } + }, + "required": [ + "messageNumber", + "values" + ], + "additionalProperties": false + } + }, + { + "name": "followMessages", + "description": "Follow your inbox: the current messages, then each new one. Returns a follower to read with readFollower.", + "inputSchema": { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false + } + }, + { + "name": "followNameChanges", + "description": "Follow the names in your directory: the current names, then each change. Returns a follower to read with readFollower.", + "inputSchema": { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false + } + }, + { + "name": "followLocatorNameChanges", + "description": "Follow the pet names that designate a locator. Returns a follower to read with readFollower.", + "inputSchema": { + "type": "object", + "properties": { + "locator": { + "type": "string", + "description": "A locator, for example from locate or invite." + } + }, + "required": [ + "locator" + ], + "additionalProperties": false + } + }, + { + "name": "followStream", + "description": "Follow the stream (a reader) stored under a pet name path. Returns a follower to read with readFollower.", + "inputSchema": { + "type": "object", + "properties": { + "petNamePath": { + "type": "array", + "items": { + "type": "string" + }, + "description": "A pet name path, for example [\"docs\", \"readme.md\"]." + } + }, + "required": [ + "petNamePath" + ], + "additionalProperties": false + } + }, + { + "name": "readFollower", + "description": "Read up to maxItems items from a follower, returning within waitMilliseconds in all. done is true once the stream has ended.", + "inputSchema": { + "type": "object", + "properties": { + "follower": { + "type": "string" + }, + "maxItems": { + "type": "integer", + "minimum": 1, + "maximum": 256 + }, + "waitMilliseconds": { + "type": "integer", + "minimum": 0, + "maximum": 30000 + } + }, + "required": [ + "follower" + ], + "additionalProperties": false + } + }, + { + "name": "closeFollower", + "description": "Stop following and release a follower.", + "inputSchema": { + "type": "object", + "properties": { + "follower": { + "type": "string" + } + }, + "required": [ + "follower" + ], + "additionalProperties": false + } + } +] diff --git a/test/endo_catalog.mjs b/test/endo_catalog.mjs new file mode 100644 index 0000000..041756e --- /dev/null +++ b/test/endo_catalog.mjs @@ -0,0 +1,27 @@ +#!/usr/bin/env node +// Print @endo/agent-mcp-stdio's tool catalog (name, description, inputSchema) +// as JSON, from an Endo checkout: the snapshot endo-catalog.json, which the +// fake host serves from so its tools are Endo's. +// +// usage: node endo_catalog.mjs ENDO_CHECKOUT > endo-catalog.json +import { pathToFileURL } from 'node:url'; +import { join } from 'node:path'; + +const [endo] = process.argv.slice(2); +const at = rel => pathToFileURL(join(endo, rel)).href; +await import(at('packages/init/index.js')); +const { makeAgentTools } = await import( + at('packages/agent-mcp-stdio/src/agent-interface.js') +); +const tools = makeAgentTools().tools ?? makeAgentTools(); +console.log( + JSON.stringify( + tools.map(({ name, description, inputSchema }) => ({ + name, + description, + inputSchema, + })), + null, + 2, + ), +); diff --git a/test/endo_host.mjs b/test/endo_host.mjs new file mode 100644 index 0000000..f4198d1 --- /dev/null +++ b/test/endo_host.mjs @@ -0,0 +1,175 @@ +#!/usr/bin/env node +// The host's side of demo.py --host endo: a real Endo daemon, a guest of +// its root host named `hermes`, and @endo/agent-mcp-stdio's broker serving +// that guest's tools on a Unix socket, which Hermes reaches by socat. +// +// usage: node endo_host.mjs ENDO_CHECKOUT DIR TASK (TASK: pen | install) +// +// The daemon's state, socket and cache go in DIR. It writes JSON lines to +// stdout: {"socket": PATH} when the broker listens, then {"message": M} for +// each message the host receives. It grants what TASK's host would: a Pen, +// or a WebApp for a package index the request names, or the guest's downloads +// folder, the directory $DOWNLOADS, as a mount. It stops the daemon +// when stdin closes. +import { pathToFileURL } from 'node:url'; +import { join } from 'node:path'; + +const [endo, dir, task] = process.argv.slice(2); +const at = rel => pathToFileURL(join(endo, rel)).href; +await import(at('packages/init/index.js')); +const { E } = await import(at('packages/eventual-send/src/no-shim.js')); +const { makeEndoClient, start, stop, purge } = await import( + at('packages/daemon/index.js') +); +const { startGuestBroker } = await import( + at('packages/agent-mcp-stdio/src/broker.js') +); + +const INDEXES = [ + 'https://pypi.org/', + 'https://files.pythonhosted.org/', + 'https://registry.npmjs.org/', +]; +const ASK = { + pen: ['Hello Hermes. Please ask me for a pen, then thank me with it.'], + install: [process.env.INSTALL_ASK], +}; + +const emit = record => { + const replacer = (_k, v) => + typeof v === 'bigint' + ? `${v}` + : typeof v === 'object' && v !== null && typeof v.then === 'function' + ? '[promise]' + : v; + process.stdout.write(`${JSON.stringify(record, replacer)}\n`); +}; + +const config = { + statePath: join(dir, 'state'), + ephemeralStatePath: join(dir, 'run'), + cachePath: join(dir, 'cache'), + sockPath: join(dir, 'endo.sock'), + // a free port for the daemon's HTTP gateway, not the default 8920 + address: '127.0.0.1:0', +}; +await purge(config); +await start(config); +const stopDaemon = () => stop(config).catch(() => {}); +process.on('uncaughtException', async error => { + console.error(error); + await stopDaemon(); + process.exit(1); +}); +process.on('unhandledRejection', async error => { + console.error(error); + await stopDaemon(); + process.exit(1); +}); + +let cancel; +const cancelled = new Promise((_, reject) => { + cancel = reject; +}); +cancelled.catch(() => {}); +const { getBootstrap, closed } = await makeEndoClient( + 'hermes-guest-demo', + config.sockPath, + cancelled, +); +const host = E(getBootstrap()).host(); + +// its pet name designates its handle; the guest itself is its @agent +const guest = await E(host).provideGuest('hermes'); +// the full : id: a bare number is qualified with the host's +// node, which reaches a second incarnation of the guest, with its own mail +const formulaId = String(await E(guest).identify('@agent')); +const broker = await startGuestBroker({ + connection: { host, closed }, + formulaId, + version: 'demo', + parentDir: dir, + diagnose: record => console.error('broker:', JSON.stringify(record)), +}); +await E(host).send('hermes', ASK[task], [], []); +// how the host's messages name the guest as their sender +const guestLocator = await E(host).locate('hermes'); +emit({ socket: broker.socketPath }); + +// What this host grants, by what a request says. +let granted = 0; +const grant = async description => { + granted += 1; + const name = `grant-${granted}`; + if (task === 'pen') { + await E(host).evaluate( + undefined, + "Far('Pen', { write: text => text })", + [], + [], + name, + ); + return name; + } + const url = INDEXES.find(u => description.includes(u.replace(/\/$/, ''))); + // a URL first: "a WebApp to download the wheel" asks for a WebApp + if (!url) { + if (/download|directory/i.test(description)) { + // the guest's downloads folder: a directory it reads, and this host writes + await E(host).provideMount(process.env.DOWNLOADS, name); + return name; + } + throw Error(`I can give WebApps for ${INDEXES.join(', ')}, and your downloads folder; name one`); + } + await E(host).makeUnconfined( + undefined, + pathToFileURL(new URL('webapp_caplet.mjs', import.meta.url).pathname).href, + { + resultName: name, + env: { + URL: url, + FAR: at('packages/far/src/index.js'), + BYTES_READER: at('packages/exo-stream/bytes-reader-from-iterator.js'), + }, + }, + ); + return name; +}; + +const seen = new Set(); +let open = true; +process.stdin.on('end', () => { + open = false; +}); +process.stdin.resume(); +while (open) { + // eslint-disable-next-line no-await-in-loop + for (const message of await E(host).listMessages()) { + const key = `${message.number}`; + if (seen.has(key)) continue; + seen.add(key); + const { promise, resolver, ...plain } = message; + emit({ message: { ...plain, fromGuest: message.from === guestLocator } }); + if (message.type === 'request') { + try { + // eslint-disable-next-line no-await-in-loop + const name = await grant(message.description); + // eslint-disable-next-line no-await-in-loop + await E(host).resolve(message.number, name); + emit({ granted: name, for: message.description }); + } catch (error) { + // eslint-disable-next-line no-await-in-loop + await E(host).reject(message.number, error.message); + emit({ refused: message.description, why: error.message }); + } + } + } + // eslint-disable-next-line no-await-in-loop + await new Promise(r => setTimeout(r, 200)); +} + +await broker.close(); +cancel(Error('demo over')); +await closed.catch(() => {}); +await stopDaemon(); +process.exit(0); diff --git a/test/fake_host.py b/test/fake_host.py index 2757b03..89d3c4a 100644 --- a/test/fake_host.py +++ b/test/fake_host.py @@ -1,49 +1,74 @@ -"""A guest's mailbox and pet store, and its methods as an MCP server. +"""A fake Endo host: one guest's mailbox and pet store, as Endo serves it. -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. As in -toybox's wallet, it may `call` a named reference's methods, and propose -code to its host with `define`. +Its tools are a subset of @endo/agent-mcp-stdio's, with that server's +names, descriptions and input schemas (from endo-catalog.json), and its +answers rendered as that server renders them: a string as is, other data +as JSON, a reference as "[remotable]". So a guest can't tell this host +from an Endo daemon's guest, as far as the subset goes, and a test can +swap one for the other. ->>> host = HostSide(on_request=lambda description: Ref('Pen')) +Two things are simpler than Endo: a pet name path has one name, and +`evaluate` takes only a method call, E(name).method(arg, ...), parsed +rather than run. + +>>> host = HostSide(on_request=lambda description: Ref('Pen', ('write',))) >>> 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']) +>>> print(guest.listMessages()) +[ + { + "number": "0", + "type": "package", + "from": "@host", + "strings": [ + "Hello. Please ask me for a pen." + ], + "names": [] + } +] +>>> guest.request(['@host'], 'a pen', ['pen']) +'"[remotable]"' +>>> print(guest.evaluate('E(p).__getMethodNames__()', ['p'], [['pen']])) +[ + "__getMethodNames__", + "write" +] +>>> print(guest.list()) +[ + "@agent", + "@host", + "@self", + "pen" +] +>>> guest.reply(0, ['Thanks for the ', '!'], ['it'], [['pen']]) +'Reply sent' >>> host.inbox[-1]['strings'], host.inbox[-1]['names'] (['Thanks for the ', '!'], ['it']) >>> host.received['it'] -Ref(interface='Pen') +Ref(interface='Pen', methods=('write',)) 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') +>>> guest.request(['@host'], 'https://registry.npmjs.org/', ['npm']) +'"[remotable]"' +>>> guest.evaluate("E(npm).pathjoin('ms')", ['npm'], [['npm']], resultName=['ms']) +'"[remotable]"' +>>> guest.evaluate('E(m).get()', ['m'], [['ms']]) 'fetched https://registry.npmjs.org/ms' ->>> guest.call('npm', 'pathjoin', ['https://elsewhere.example/']) +>>> guest.evaluate("E(npm).pathjoin('https://elsewhere.example/')", ['npm'], [['npm']]) 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'}}) +>>> guest.define("Far('Site', {})", {'site': {'label': 'a WebApp for the site'}}) +'Definition sent' >>> host.definitions[0]['slots'] {'site': {'label': 'a WebApp for the site'}} """ -import base64 +import ast import json import logging import re @@ -57,30 +82,57 @@ class Ref: """A reference, as the pet store holds it: never sent to the guest.""" interface: str + methods: tuple = () - -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 is_ref(value) else value + @property + def METHODS(self): + return self.methods def is_ref(value): return hasattr(value, "interface") +def render(value): + """A tool's answer as @endo/agent-mcp-stdio renders it. + + >>> render('hi'), render(None), render(Ref('Pen')) + ('hi', '', '"[remotable]"') + >>> print(render({'n': 1, 'pen': Ref('Pen')})) + { + "n": 1, + "pen": "[remotable]" + } + """ + if isinstance(value, str): + return value + if value is None: + return "" + return json.dumps(value, indent=2, + default=lambda v: "[remotable]" if is_ref(v) else str(v)) + + +def _name(path): + """The one name in a pet name path; this host keeps no directories.""" + if isinstance(path, str): + return path + if len(path) != 1: + raise ValueError(f"this host keeps only single names, not {'/'.join(path)}") + return path[0] + + +def _number(messageNumber): + return int(messageNumber) + + 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.""" + pathjoin and query, then fire with get or post. blob is this host's + addition, for bytes, as an Endo ReadableBlob: toybox's fetch device + answers text.""" interface = "WebApp" - METHODS = ("pathjoin", "query", "get", "getBase64", "post") + METHODS = ("pathjoin", "query", "get", "blob", "post") def __init__(self, fetch, url): self._fetch, self._url = fetch, url @@ -105,15 +157,82 @@ class WebApp: def get(self): return self._send("GET").decode("utf-8", errors="replace") - def getBase64(self): - return base64.b64encode(self._send("GET")).decode("ascii") + def blob(self): + return Blob(lambda: self._send("GET")) def post(self, body): return self._send("POST", body.encode()).decode("utf-8", errors="replace") +class Blob: + """A ReadableBlob: bytes, read when a reader asks.""" + + interface = "ReadableBlob" + METHODS = ("text",) + + def __init__(self, read): + self._read = read + + def bytes(self): + return self._read() + + def text(self): + return self._read().decode("utf-8", errors="replace") + + +class Dir: + """An EndoMount's write, for one directory: `save(name, data)` writes + there, and nowhere else. + + >>> saved = {} + >>> downloads = Dir(lambda name, data: saved.update({name: data}), lambda: sorted(saved)) + >>> downloads.write('six.whl', Blob(lambda: b'PK')) + >>> downloads.list(), saved + (['six.whl'], {'six.whl': b'PK'}) + >>> downloads.write('../.bashrc', Blob(lambda: b'')) + Traceback (most recent call last): + ... + ValueError: write: not a file name in this directory: ../.bashrc + """ + + interface = "EndoMount" + METHODS = ("write", "list") + + def __init__(self, save, names): + self._save, self._names = save, names + + def write(self, path, blob): + name = path if isinstance(path, str) else "/".join(path) + if not FILE_NAME.match(name) or name in (".", ".."): + raise ValueError(f"write: not a file name in this directory: {name}") + if not isinstance(blob, Blob): + raise TypeError("Expected a ReadableBlob source") + self._save(name, blob.bytes()) + + def list(self): + return self._names() + + +FILE_NAME = re.compile(r"^[\w.+-]+$") + SLOT = re.compile(r"^[A-Za-z_$][\w$]*$") +HELP = """EndoGuest - A confined agent with directory and mail capabilities. + +A guest can: +- Manage pet names for values (directory operations) +- Send and receive messages (mail operations) +- Request capabilities from its host + +Special names available: +- @self: This guest's own handle +- @host: The host that created this guest +- @agent: This guest's formula identifier + +Use help("methodName") for details on specific methods.""" + +SPECIAL = ("@agent", "@host", "@self") + @dataclass class HostSide: @@ -125,7 +244,7 @@ class HostSide: definitions: list = field(default_factory=list) def send(self, guest, strings, edge_names, values): - guest._deliver("package", "HOST", strings=strings, + guest._deliver("package", "@host", strings=strings, names=edge_names, values=values) def _receive(self, message, values): @@ -134,177 +253,258 @@ class HostSide: class Mailbox: - """One guest's powers. Method names are EndoGuest's.""" + """One guest's tools: @endo/agent-mcp-stdio's, by name and arguments.""" + + TOOLS = ("help", "has", "list", "listMessages", "send", "reply", "adopt", + "dismiss", "request", "evaluate", "define") def __init__(self, host): self._host = host self._lock = threading.Lock() - self._pets = {"HOST": Ref("Host")} + self._pets = {"@host": Ref("EndoHandle")} 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}, + {"number": str(number), "type": type_, "from": sender, **record}, list(values), )) - def _message(self, number): + def _message(self, messageNumber): for record, values in self._messages: - if record["number"] == number: + if record["number"] == str(_number(messageNumber)): return record, values - raise KeyError(f"no message {number}") + raise KeyError(f'No such message with number "{messageNumber}"') - def _to_host(self, to): - if to != "HOST": - raise KeyError(f"no recipient {to}; this guest can write only to HOST") + def _lookup(self, path): + name = _name(path) + if name not in self._pets: + raise KeyError(f'Unknown pet name "{name}"') + return self._pets[name] + + def _to_host(self, recipient): + if _name(recipient) != "@host": + raise KeyError(f"Unknown recipient {_name(recipient)}") + + def help(self, methodName=None): + return HELP + + def has(self, petNamePath): + return render(_name(petNamePath) in self._pets or _name(petNamePath) in SPECIAL) + + def list(self, petNamePath=None): + if petNamePath: + raise ValueError("this host keeps no directories") + return render(sorted(set(self._pets) | set(SPECIAL))) def listMessages(self): with self._lock: - return [dict(record) for record, _ in self._messages] + return render([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) + def request(self, recipient, description, responseName=None): + self._to_host(recipient) value = self._host.on_request(description) if responseName: - self._pets[responseName] = value - return describe(value) + self._pets[_name(responseName)] = value + return render(value) - def send(self, to, strings, edgeNames, petNames): - self._to_host(to) - values = [self._pets[n] for n in petNames] + def send(self, recipient, strings, edgeNames, petNames): + self._to_host(recipient) + if len(strings) != len(edgeNames) + 1: + raise ValueError("strings has one more entry than edgeNames") + values = [self._lookup(p) for p in petNames] self._host._receive( {"type": "package", "from": "guest", "strings": strings, "names": edgeNames}, values) + return "Message sent" def reply(self, messageNumber, strings, edgeNames, petNames): - record, _ = self._message(messageNumber) - self.send(record["from"], strings, edgeNames, petNames) - self._host.inbox[-1]["replyTo"] = messageNumber + self._message(messageNumber) + self.send(["@host"], strings, edgeNames, petNames) + self._host.inbox[-1]["replyTo"] = str(_number(messageNumber)) + return "Reply sent" def adopt(self, messageNumber, edgeName, petName): record, values = self._message(messageNumber) - self._pets[petName] = values[record["names"].index(edgeName)] + self._pets[_name(petName)] = values[record["names"].index(edgeName)] + return f"Adopted {edgeName} as {_name(petName)}" - 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 dismiss(self, messageNumber): + self._message(messageNumber) + with self._lock: + self._messages = [(r, v) for r, v in self._messages + if r["number"] != str(_number(messageNumber))] + return f"Dismissed message {messageNumber}" - def define(self, modules, slots): - """Propose to the host a vat of `modules`, its params named by `slots`.""" + def evaluate(self, source, codeNames, petNamePaths, workerName=None, resultName=None): + """Evaluate `source` with each of `codeNames` bound to what its path names. + + Constrained: `source` may only be E(name).method(arg, ...), each arg + a literal or a code name. Every object answers __getMethodNames__. + """ + if len(codeNames) != len(petNamePaths): + raise ValueError("Evaluator requires one pet name for each code name") + scope = {c: self._lookup(p) for c, p in zip(codeNames, petNamePaths)} + answer = run_send(parse_send(source, scope)) + if resultName: + self._pets[_name(resultName)] = answer + return render(answer) + + def define(self, source, slots): + """Propose to the host code `source`, its free variables 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): - with self._lock: - self._messages = [ - (r, v) for r, v in self._messages if r["number"] != messageNumber] + self._host.definitions.append({"source": source, "slots": slots}) + return "Definition sent" -def _schema(props, required=None): - return {"type": "object", "properties": props, - "required": list(props) if required is None else required} +_LITERALS = {"true": True, "false": False, "null": None} -STR, INT = {"type": "string"}, {"type": "integer"} -STRS = {"type": "array", "items": STR} +@dataclass(frozen=True) +class Send: + """E(target).method(*args), parsed.""" -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})), - "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"]}}})), -} + target: object + method: str + args: tuple -def handle_rpc(mailbox, msg, resources=None): +def run_send(send): + """Do `send`. + + >>> run_send(Send(Blob(lambda: b'hi'), 'text', ())) + 'hi' + >>> run_send(Send(Blob(lambda: b''), '__getMethodNames__', ())) + ['__getMethodNames__', 'text'] + """ + args = send.args + methods = ("__getMethodNames__", *getattr(send.target, "METHODS", ())) + if send.method == "__getMethodNames__": + return sorted(methods) + if send.method not in methods: + raise TypeError(f"target has no method {json.dumps(send.method)}, " + f"has {sorted(methods)}") + return getattr(send.target, send.method)(*args) + + +def parse_send(source, scope): + """Parse E(name).method(arg, ...) against `scope`, as a Send. + + Args are JSON-ish literals (strings, numbers, true, false, null, arrays, + objects) or names in scope. Anything else is refused, a send among the + args too: Endo's guarded methods, such as a mount's write, refuse a + promise, so a send's answer must be named first. + + >>> parse_send("E(npm).pathjoin('ms', [1, true])", {'npm': 'N'}) + Send(target='N', method='pathjoin', args=('ms', [1, True])) + >>> parse_send("E(d).write('x', E(w).blob())", {'d': 'D', 'w': 'W'}) + Traceback (most recent call last): + ... + ValueError: evaluate supports only E(name).method(arg, ...), not: E(d).write('x', E(w).blob()) + >>> parse_send("fetch('https://x/')", {}) + Traceback (most recent call last): + ... + ValueError: evaluate supports only E(name).method(arg, ...), not: fetch('https://x/') + >>> parse_send("E(a).m(c)", {'a': 1}) + Traceback (most recent call last): + ... + ValueError: evaluate: c is not in scope + """ + refuse = ValueError(f"evaluate supports only E(name).method(arg, ...), not: {source}") + try: + tree = ast.parse(source.strip().rstrip(";"), mode="eval").body + except SyntaxError: + raise refuse from None + + def send(node): + match node: + case ast.Call(func=ast.Attribute(value=ast.Call( + func=ast.Name(id="E"), args=[ast.Name(id=name)], keywords=[]), + attr=method), args=args, keywords=[]): + if name not in scope: + raise ValueError(f"evaluate: {name} is not in scope") + return Send(scope[name], method, tuple(value(a) for a in args)) + case _: + raise refuse + + def value(node): + match node: + case ast.Constant(value=v) if isinstance(v, (str, int, float)) and not isinstance(v, bool): + return v + case ast.UnaryOp(op=ast.USub(), operand=ast.Constant(value=v)) if type(v) in (int, float): + return -v + case ast.Name(id=n) if n in scope: + return scope[n] + case ast.Name(id=n) if n in _LITERALS: + return _LITERALS[n] + case ast.Name(id=n): + raise ValueError(f"evaluate: {n} is not in scope") + case ast.List(elts=elts): + return [value(e) for e in elts] + case ast.Dict(keys=keys, values=vals) if all( + isinstance(k, ast.Constant) and isinstance(k.value, str) for k in keys): + return {k.value: value(v) for k, v in zip(keys, vals)} + case _: + raise refuse + + return send(tree) + + +def tool_catalog(endo_catalog): + """The tools this host serves: Endo's entries for those it implements. + + >>> catalog = tool_catalog([{'name': 'list', 'description': 'd', 'inputSchema': {}}, + ... {'name': 'glob', 'description': 'g', 'inputSchema': {}}]) + >>> [t['name'] for t in catalog] + ['list'] + """ + return [t for t in endo_catalog if t["name"] in Mailbox.TOOLS] + + +def handle_rpc(mailbox, msg, tools): """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'}) + ... 'params': {'name': 'has', 'arguments': {'petNamePath': ['@host']}}}, [ + ... {'name': 'has'}])['result']['content'][0]['text'] + 'true' + >>> handle_rpc(box, {'jsonrpc': '2.0', 'id': 2, 'method': 'tools/call', + ... 'params': {'name': 'adopt', 'arguments': {'messageNumber': 9, + ... 'edgeName': 'x', 'petName': ['x']}}}, [{'name': 'adopt'}])['result'] + {'isError': True, 'content': [{'type': 'text', 'text': 'Error: No such message with number "9"'}]} + >>> 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"]} + names = {t["name"] for t in tools} if method == "initialize": reply["result"] = { "protocolVersion": params.get("protocolVersion", "2025-06-18"), - "capabilities": {"tools": {}, **({"resources": {}} if resources else {})}, - "serverInfo": {"name": "fake-endo-host", "version": "0"}, + "capabilities": {"tools": {"listChanged": False}, "logging": {}}, + "serverInfo": {"name": "endo", "version": "fake"}, } 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 == "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: + reply["result"] = {"tools": tools} + elif method == "tools/call" and params.get("name") in names: 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)}]} + text = getattr(mailbox, name)(**args) + reply["result"] = {"content": [{"type": "text", "text": text}]} except (KeyError, ValueError, TypeError) as err: reply["result"] = {"isError": True, "content": [ - {"type": "text", "text": str(err)}]} + {"type": "text", "text": f"Error: {err.args[0] if err.args else err}"}]} + elif method == "tools/call": + reply["error"] = {"code": -32001, "message": "tool-not-permitted"} else: - reply["error"] = {"code": -32601, "message": f"no method {method}"} + reply["error"] = {"code": -32601, "message": f"Method not found: {method}"} return reply diff --git a/test/transcript.py b/test/transcript.py new file mode 100644 index 0000000..f6b853b --- /dev/null +++ b/test/transcript.py @@ -0,0 +1,80 @@ +"""A Hermes session as Markdown: what was said, thought, and called, in order. + +Rows are Hermes's `messages` table (state.db), as dicts. + +>>> print(render([ +... {'role': 'user', 'content': 'Check your messages.'}, +... {'role': 'assistant', 'content': '', 'reasoning': 'I should look.', +... 'tool_calls': '[{"function": {"name": "mcp__host__listMessages", "arguments": "{}"}}]'}, +... {'role': 'tool', 'tool_name': 'mcp__host__listMessages', 'content': '[]'}, +... {'role': 'assistant', 'content': 'Nothing there.'}, +... ], system_prompt='You are Hermes.')) +# Hermes session + +
system prompt + +```` +You are Hermes. +```` +
+ +## user + +Check your messages. + +## assistant + +> I should look. + +calls `mcp__host__listMessages`: +````json +{} +```` + +## tool: mcp__host__listMessages + +```` +[] +```` + +## assistant + +Nothing there. + +""" + +import json + +FENCE = "````" + + +def _pretty(arguments): + try: + return json.dumps(json.loads(arguments), indent=2) + except (TypeError, ValueError): + return str(arguments) + + +def render(rows, system_prompt=None): + """Markdown for a session's `rows`, after its `system_prompt` if given.""" + out = ["# Hermes session", ""] + if system_prompt: + out += ["
system prompt", "", + FENCE, system_prompt, FENCE, "
", ""] + for row in rows: + role = row["role"] + content = row.get("content") or "" + if role == "tool": + out += [f"## tool: {row.get('tool_name')}", "", FENCE, content, FENCE, ""] + continue + out += [f"## {role}", ""] + thought = row.get("reasoning") or row.get("reasoning_content") + if thought: + out += ["\n".join("> " + line for line in thought.splitlines()), ""] + if content: + out += [content, ""] + for call in json.loads(row.get("tool_calls") or "[]"): + fn = call.get("function", {}) + out += [f"calls `{fn.get('name')}`:", FENCE + "json", + _pretty(fn.get("arguments")), FENCE, ""] + return "\n".join(out) diff --git a/test/webapp_caplet.mjs b/test/webapp_caplet.mjs new file mode 100644 index 0000000..ad14508 --- /dev/null +++ b/test/webapp_caplet.mjs @@ -0,0 +1,49 @@ +// An unconfined Endo caplet: a WebApp for one URL, as the fake host's +// WebApp is (fake_host.py), with Node's fetch. +// +// env: URL, the WebApp's URL; FAR and BYTES_READER, the file URLs of +// @endo/far and @endo/exo-stream's bytes-reader-from-iterator.js in the +// daemon's checkout (this file lives outside it, so it can't import them +// by name). + +const within = (base, url) => { + const b = new URL(base); + const u = new URL(url); + return u.origin === b.origin && u.pathname.startsWith(b.pathname); +}; + +const makeWebApp = (lib, fetch, url) => { + const { Far, bytesReaderFromIterator } = lib; + const fire = async (method, body) => { + const resp = await fetch(url, { method, body }); + return new Uint8Array(await resp.arrayBuffer()); + }; + return Far('WebApp', { + pathjoin(path) { + const next = new URL(path, url).href; + if (!within(url, next)) throw Error(`pathjoin: ${next} is not within ${url}`); + return makeWebApp(lib, fetch, next); + }, + query(params) { + const next = new URL(url); + for (const [k, v] of Object.entries(params)) next.searchParams.set(k, String(v)); + return makeWebApp(lib, fetch, next.href); + }, + get: async () => new TextDecoder().decode(await fire('GET')), + // the body as a bytes reader (it answers streamBase64), which a + // mount's write(path, blob) takes; fetched as the mount reads it + blob: () => + bytesReaderFromIterator( + (async function* body() { + yield await fire('GET'); + })(), + ), + post: async body => new TextDecoder().decode(await fire('POST', body)), + }); +}; + +export const make = async (_powers, _context, { env }) => { + const { Far } = await import(env.FAR); + const { bytesReaderFromIterator } = await import(env.BYTES_READER); + return makeWebApp({ Far, bytesReaderFromIterator }, globalThis.fetch, env.URL); +}; -- 2.53.0