feat: Hermes confined to act only as an Endo guest
A NixOS module (nix/hermes-guest.nix) layers confinement on upstream's services.hermes-agent: no network (PrivateNetwork), an empty /run with two Unix sockets bound back in, and no user manager. Hermes reaches the world through host.sock, the guest's Endo methods (listMessages, request, lookup, reply, ...) as MCP, and llm.sock, an inference proxy that holds the API key. The same unit runs on a Linux host (nix/linux-host.nix) and in a vfkit microVM on macOS (nix/vfkit-vm.nix), where systemd relays the two sockets over vsock to launchd on the host (nix/darwin-host.nix). test/demo.py runs unmodified Hermes against a fake host and a scripted model, and checks what the host received. Generated-by: Claude Opus 5.5
This commit is contained in:
commit
e38d681a9e
13 files changed
+1379
No files matched your search
@@ -0,0 +1,3 @@
|
||||
__pycache__/
|
||||
result
|
||||
result-*
|
||||
@@ -0,0 +1,57 @@
|
||||
# hermes-guest
|
||||
|
||||
[Hermes Agent](https://github.com/NousResearch/hermes-agent), confined so that it can act only as one Endo guest (of toybox, or of an Endo daemon). Its systemd unit ([nix/hermes-guest.nix](nix/hermes-guest.nix)) has no network and sees two Unix sockets, and nothing else:
|
||||
|
||||
- `/run/hermes-guest/host.sock`: the guest's methods (`listMessages`, `request`, `resolve`, `lookup`, ...) as an MCP server, bound to one guest agent. Hermes reaches it as the MCP server `host`.
|
||||
- `/run/hermes-guest/llm.sock`: model inference, through [llm-proxy.py](llm-proxy.py), which holds the API key and forwards to one upstream.
|
||||
|
||||
The connection designates the guest: each socket is mode 0600, owned by Hermes's user, so no secret designates it.
|
||||
|
||||
The same unit runs on both platforms; what differs is who serves its sockets.
|
||||
|
||||
```
|
||||
Linux: hermes-agent.service ──► the host's socket unit (host systemd)
|
||||
──► hermes-llm.socket (host systemd)
|
||||
|
||||
macOS: [NixOS microVM (vfkit) ]
|
||||
hermes-agent.service ──► relay socket ──vsock──► vfkit ──► hostDir/host.sock (the host)
|
||||
──► relay socket ──vsock──► vfkit ──► hostDir/llm.sock (launchd)
|
||||
```
|
||||
|
||||
## On Linux (NixOS)
|
||||
|
||||
```nix
|
||||
imports = [ hermes-guest.nixosModules.linux-host ];
|
||||
services.hermes-guest = {
|
||||
enable = true;
|
||||
model = "anthropic/claude-sonnet-4";
|
||||
hostSocketUnit = "endo-guest-hermes.socket";
|
||||
};
|
||||
services.hermes-llm-proxy = {
|
||||
upstream = "https://openrouter.ai/api/v1";
|
||||
keyFile = "/run/secrets/llm-key"; # a runtime path, not a nix path
|
||||
};
|
||||
```
|
||||
|
||||
## On macOS
|
||||
|
||||
Building the VM needs a Linux builder (for example nix-darwin's `nix.linux-builder`).
|
||||
|
||||
```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";
|
||||
keyFile = "/Users/me/.config/hermes-guest/llm-key";
|
||||
}.host'
|
||||
mkdir -p ~/.local/state/hermes-guest
|
||||
cp result/share/LaunchAgents/*.plist ~/Library/LaunchAgents/
|
||||
launchctl bootstrap gui/$UID ~/Library/LaunchAgents/net.madmode.hermes-llm-proxy.plist
|
||||
launchctl bootstrap gui/$UID ~/Library/LaunchAgents/net.madmode.hermes-vm.plist
|
||||
```
|
||||
|
||||
## Not yet done
|
||||
|
||||
- Toybox doesn't serve a guest's methods over MCP on a socket of its own yet. On macOS, something on the host must also listen on `hostDir/host.sock`.
|
||||
- Hermes's cron jobs fail closed: they need a systemd user manager, which would start units outside the sandbox.
|
||||
- How you talk to Hermes: its gateway platforms (Telegram, Discord, ...) have no network here. The intent is messages through toybox, which Hermes would need to poll or follow.
|
||||
Generated
+222
@@ -0,0 +1,222 @@
|
||||
{
|
||||
"nodes": {
|
||||
"flake-parts": {
|
||||
"inputs": {
|
||||
"nixpkgs-lib": [
|
||||
"hermes-agent",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1790898470,
|
||||
"narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "024633cd702b10285db5cb19b40ad48d2399ba60",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"hermes-agent": {
|
||||
"inputs": {
|
||||
"flake-parts": "flake-parts",
|
||||
"home-manager": "home-manager",
|
||||
"nixpkgs": "nixpkgs",
|
||||
"pyproject-build-systems": "pyproject-build-systems",
|
||||
"pyproject-nix": "pyproject-nix",
|
||||
"uv2nix": "uv2nix"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1795983207,
|
||||
"narHash": "sha256-Xn7/+Zmh4FL2RedzwJwalYwTq2njGRmQ3tyIC1qeXAA=",
|
||||
"owner": "NousResearch",
|
||||
"repo": "hermes-agent",
|
||||
"rev": "8b1f3640b4f786006e4e314a72a56774e3324367",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NousResearch",
|
||||
"repo": "hermes-agent",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"home-manager": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"hermes-agent",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1792703141,
|
||||
"narHash": "sha256-3X34FaSeMJXMx8CK/BN6sZ9knwNauuiJXQhLM+bQQuI=",
|
||||
"owner": "nix-community",
|
||||
"repo": "home-manager",
|
||||
"rev": "6750249c69969d09d952efaf3fab88a2bdac7ec6",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "nix-community",
|
||||
"repo": "home-manager",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"microvm": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"nixpkgs"
|
||||
],
|
||||
"spectrum": "spectrum"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1795298370,
|
||||
"narHash": "sha256-mruPu1cqOVBxPiRwrh6r1tnX1OAzMggy+rDk6YuqhK8=",
|
||||
"owner": "microvm-nix",
|
||||
"repo": "microvm.nix",
|
||||
"rev": "430a46d03ef15f1b8b715fafa85f21847960b783",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "microvm-nix",
|
||||
"repo": "microvm.nix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1795911899,
|
||||
"narHash": "sha256-OKvZpNQnLc24N/vuklyiHDYmFT4ZQRb5b3Rovh1/Hkg=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "e713fda5ec9fad59317d86214b1ee646a11896ea",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs_2": {
|
||||
"locked": {
|
||||
"lastModified": 1795911899,
|
||||
"narHash": "sha256-OKvZpNQnLc24N/vuklyiHDYmFT4ZQRb5b3Rovh1/Hkg=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "e713fda5ec9fad59317d86214b1ee646a11896ea",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"pyproject-build-systems": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"hermes-agent",
|
||||
"nixpkgs"
|
||||
],
|
||||
"pyproject-nix": [
|
||||
"hermes-agent",
|
||||
"pyproject-nix"
|
||||
],
|
||||
"uv2nix": [
|
||||
"hermes-agent",
|
||||
"uv2nix"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1792499785,
|
||||
"narHash": "sha256-mGOkvueuMGSRiD75ccxFzfEvSlIU9ztjFluHMKOtogY=",
|
||||
"owner": "pyproject-nix",
|
||||
"repo": "build-system-pkgs",
|
||||
"rev": "a17819c85163988e063806ffc4f6d2716bc8ead8",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "pyproject-nix",
|
||||
"repo": "build-system-pkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"pyproject-nix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"hermes-agent",
|
||||
"nixpkgs"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1791657700,
|
||||
"narHash": "sha256-vcCAvhtA7hG+/gOge29hYHy7I/dLkIsr5nLx4sFEQic=",
|
||||
"owner": "pyproject-nix",
|
||||
"repo": "pyproject.nix",
|
||||
"rev": "ddc400a6883b042646d0940e65971bb7f7e96107",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "pyproject-nix",
|
||||
"repo": "pyproject.nix",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"hermes-agent": "hermes-agent",
|
||||
"microvm": "microvm",
|
||||
"nixpkgs": "nixpkgs_2"
|
||||
}
|
||||
},
|
||||
"spectrum": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1786032750,
|
||||
"narHash": "sha256-+Ba/kIn5BjvV7PN8bWOo7RoqgTY/Yv2M7qeMf3wS2Ag=",
|
||||
"ref": "refs/heads/main",
|
||||
"rev": "77d2389874bb092b8dbf05ecc5b1030372e80e98",
|
||||
"revCount": 1417,
|
||||
"type": "git",
|
||||
"url": "https://spectrum-os.org/git/spectrum"
|
||||
},
|
||||
"original": {
|
||||
"type": "git",
|
||||
"url": "https://spectrum-os.org/git/spectrum"
|
||||
}
|
||||
},
|
||||
"uv2nix": {
|
||||
"inputs": {
|
||||
"nixpkgs": [
|
||||
"hermes-agent",
|
||||
"nixpkgs"
|
||||
],
|
||||
"pyproject-nix": [
|
||||
"hermes-agent",
|
||||
"pyproject-nix"
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1792666911,
|
||||
"narHash": "sha256-UWo7wDPi00YXOI1Io7g4vGKuCSPJ863kHJVDzsgqtoM=",
|
||||
"owner": "pyproject-nix",
|
||||
"repo": "uv2nix",
|
||||
"rev": "0fdaa03ea3c3c16dbb1fe4d69108f07227a4b42d",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "pyproject-nix",
|
||||
"repo": "uv2nix",
|
||||
"type": "github"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
{
|
||||
description = "Hermes, confined to act only as one toybox guest: a systemd unit on Linux, the same unit in a microVM on macOS";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
microvm = {
|
||||
url = "github:microvm-nix/microvm.nix";
|
||||
inputs.nixpkgs.follows = "nixpkgs";
|
||||
};
|
||||
# its own nixpkgs: its fixed-output hashes (pnpm deps) are for its pnpm
|
||||
hermes-agent.url = "github:NousResearch/hermes-agent";
|
||||
};
|
||||
|
||||
outputs =
|
||||
{
|
||||
self,
|
||||
nixpkgs,
|
||||
microvm,
|
||||
hermes-agent,
|
||||
}:
|
||||
let
|
||||
inherit (nixpkgs) lib;
|
||||
in
|
||||
{
|
||||
nixosModules = {
|
||||
# the unit that ports; whoever imports it serves its two sockets
|
||||
hermes-guest = {
|
||||
imports = [
|
||||
hermes-agent.nixosModules.default
|
||||
./nix/hermes-guest.nix
|
||||
];
|
||||
};
|
||||
# a Linux host: the unit, and the inference proxy, under the host's systemd
|
||||
linux-host = {
|
||||
imports = [
|
||||
self.nixosModules.hermes-guest
|
||||
./nix/linux-host.nix
|
||||
];
|
||||
};
|
||||
# the macOS VM's NixOS: the unit, with its sockets relayed over vsock
|
||||
vfkit-vm = {
|
||||
imports = [
|
||||
microvm.nixosModules.microvm
|
||||
self.nixosModules.hermes-guest
|
||||
./nix/vfkit-vm.nix
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
lib = {
|
||||
/**
|
||||
The macOS VM and its launchd agents, for one person's settings.
|
||||
hostDir: where the VM's state image and host sockets live.
|
||||
The toybox socket, hostDir/toybox.sock, is toybox's to serve.
|
||||
*/
|
||||
mkDarwin =
|
||||
{
|
||||
hostDir,
|
||||
model,
|
||||
upstream,
|
||||
keyFile,
|
||||
system ? "aarch64-darwin",
|
||||
}:
|
||||
let
|
||||
hostPkgs = nixpkgs.legacyPackages.${system};
|
||||
vm = lib.nixosSystem {
|
||||
system = lib.replaceString "-darwin" "-linux" system;
|
||||
modules = [
|
||||
self.nixosModules.vfkit-vm
|
||||
{
|
||||
microvm.vmHostPackages = hostPkgs;
|
||||
services.hermes-guest = {
|
||||
enable = true;
|
||||
inherit model;
|
||||
vm.hostDir = hostDir;
|
||||
};
|
||||
}
|
||||
];
|
||||
};
|
||||
runner = vm.config.microvm.declaredRunner;
|
||||
in
|
||||
{
|
||||
inherit vm runner;
|
||||
host = import ./nix/darwin-host.nix {
|
||||
pkgs = hostPkgs;
|
||||
inherit
|
||||
lib
|
||||
runner
|
||||
hostDir
|
||||
upstream
|
||||
keyFile
|
||||
;
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
formatter = lib.genAttrs [ "x86_64-linux" "aarch64-linux" "aarch64-darwin" ] (
|
||||
system: nixpkgs.legacyPackages.${system}.nixfmt
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One HTTP request to one upstream, with the API key added.
|
||||
|
||||
Run inetd style: the accepted connection is fd 0. systemd gives it with
|
||||
Accept=yes and StandardInput=socket; launchd with inetdCompatibility.
|
||||
Whoever can connect may use the key for inference at UPSTREAM, and for
|
||||
nothing else: the proxy forwards only to that base URL, and it replaces
|
||||
any Authorization header the client sends.
|
||||
|
||||
usage: llm-proxy.py UPSTREAM_BASE_URL KEY_FILE
|
||||
e.g. llm-proxy.py https://openrouter.ai/api/v1 /run/credentials/.../llm-key
|
||||
|
||||
Requests for /v1/<rest> go to UPSTREAM_BASE_URL/<rest>.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
HOP_BY_HOP = {
|
||||
"connection", "keep-alive", "proxy-authorization", "te", "trailer",
|
||||
"transfer-encoding", "upgrade", "host", "authorization", "content-length",
|
||||
}
|
||||
|
||||
|
||||
def make_handler(base_path: str, connect_upstream, key: str):
|
||||
"""A request handler that forwards /v1/<rest> to base_path/<rest>,
|
||||
over a connection from `connect_upstream()`, with `key`."""
|
||||
|
||||
class Proxy(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.0" # one request, then close
|
||||
|
||||
def _forward(self):
|
||||
if not (self.path == "/v1" or self.path.startswith("/v1/")):
|
||||
self.send_error(404, "only /v1/ is proxied")
|
||||
return
|
||||
path = base_path.rstrip("/") + self.path[len("/v1"):]
|
||||
length = int(self.headers.get("content-length") or 0)
|
||||
body = self.rfile.read(length) if length else None
|
||||
headers = {
|
||||
k: v for k, v in self.headers.items()
|
||||
if k.lower() not in HOP_BY_HOP
|
||||
}
|
||||
headers["Authorization"] = f"Bearer {key}"
|
||||
conn = connect_upstream()
|
||||
conn.request(self.command, path, body=body, headers=headers)
|
||||
resp = conn.getresponse()
|
||||
self.send_response(resp.status, resp.reason)
|
||||
for k, v in resp.getheaders():
|
||||
if k.lower() not in HOP_BY_HOP:
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
# stream, so server-sent events arrive as they come
|
||||
while chunk := resp.read1(65536):
|
||||
self.wfile.write(chunk)
|
||||
self.wfile.flush()
|
||||
|
||||
do_GET = do_POST = _forward
|
||||
|
||||
def log_message(self, format, *args):
|
||||
logging.info(format, *args)
|
||||
|
||||
return Proxy
|
||||
|
||||
|
||||
def main(argv, cwd, connection, https):
|
||||
"""Serve the one `connection`, forwarding to argv's upstream, and only there."""
|
||||
_, upstream, key_file = argv
|
||||
base = urlsplit(upstream)
|
||||
if base.scheme != "https":
|
||||
raise SystemExit(f"upstream must be https: {upstream}")
|
||||
key = (cwd / key_file).read_text(encoding="utf-8").strip()
|
||||
make_handler(base.path, lambda: https(base.netloc, timeout=600), key)(
|
||||
connection, ("local", 0), None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
def _script_io():
|
||||
import http.client
|
||||
import socket
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
return main(
|
||||
argv=list(sys.argv),
|
||||
cwd=Path.cwd(),
|
||||
# inetd style: the accepted connection is fd 0
|
||||
connection=socket.socket(fileno=0),
|
||||
https=http.client.HTTPSConnection,
|
||||
)
|
||||
|
||||
raise SystemExit(_script_io())
|
||||
@@ -0,0 +1,47 @@
|
||||
# On macOS: launchd agents for the host side of the VM, with no nix-darwin.
|
||||
# The result has the plists in share/LaunchAgents; see the README.
|
||||
{
|
||||
pkgs,
|
||||
lib,
|
||||
runner, # the VM's microvm runner (config.microvm.declaredRunner)
|
||||
hostDir,
|
||||
upstream,
|
||||
keyFile,
|
||||
}:
|
||||
let
|
||||
proxy = pkgs.writers.writePython3 "llm-proxy" { flakeIgnore = [ "E501" ]; } (
|
||||
builtins.readFile ../llm-proxy.py
|
||||
);
|
||||
plist = name: attrs: pkgs.writeText "${name}.plist" (lib.generators.toPlist { escape = true; } attrs);
|
||||
|
||||
# the inference proxy: launchd listens, and hands each connection to a
|
||||
# fresh proxy as its stdin (inetd style), as systemd's Accept=yes does
|
||||
llmProxy = plist "net.madmode.hermes-llm-proxy" {
|
||||
Label = "net.madmode.hermes-llm-proxy";
|
||||
ProgramArguments = [
|
||||
"${proxy}"
|
||||
upstream
|
||||
keyFile
|
||||
];
|
||||
inetdCompatibility.Wait = false;
|
||||
Sockets.Listener = {
|
||||
SockPathName = "${hostDir}/llm.sock";
|
||||
SockPathMode = 384; # 0600
|
||||
};
|
||||
StandardErrorPath = "${hostDir}/llm-proxy.log";
|
||||
};
|
||||
|
||||
vm = plist "net.madmode.hermes-vm" {
|
||||
Label = "net.madmode.hermes-vm";
|
||||
ProgramArguments = [ "${runner}/bin/microvm-run" ];
|
||||
WorkingDirectory = hostDir;
|
||||
KeepAlive = true;
|
||||
StandardOutPath = "${hostDir}/vm.log";
|
||||
StandardErrorPath = "${hostDir}/vm.log";
|
||||
};
|
||||
in
|
||||
pkgs.runCommand "hermes-guest-darwin-host" { } ''
|
||||
mkdir -p $out/share/LaunchAgents
|
||||
cp ${llmProxy} $out/share/LaunchAgents/net.madmode.hermes-llm-proxy.plist
|
||||
cp ${vm} $out/share/LaunchAgents/net.madmode.hermes-vm.plist
|
||||
''
|
||||
@@ -0,0 +1,141 @@
|
||||
# Hermes, confined to act only as one Endo guest (of toybox, or of an Endo daemon).
|
||||
#
|
||||
# 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:
|
||||
#
|
||||
# hostSocket the guest's methods (listMessages, request, resolve,
|
||||
# lookup, ...) as an MCP server, bound to one guest agent
|
||||
# llmSocket model inference, through a proxy that holds the API key
|
||||
#
|
||||
# The service has no network of its own (PrivateNetwork), and sees no
|
||||
# other Unix sockets on the machine.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.services.hermes-guest;
|
||||
hermes = config.services.hermes-agent;
|
||||
socketDir = "/run/hermes-guest";
|
||||
in
|
||||
{
|
||||
options.services.hermes-guest = {
|
||||
enable = lib.mkEnableOption "Hermes as a confined Endo guest";
|
||||
hostSocket = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "${socketDir}/host.sock";
|
||||
description = "The Unix socket where the guest's MCP methods are served.";
|
||||
};
|
||||
llmSocket = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
default = "${socketDir}/llm.sock";
|
||||
description = "The Unix socket of the inference proxy, an OpenAI-compatible endpoint.";
|
||||
};
|
||||
llmPort = lib.mkOption {
|
||||
type = lib.types.port;
|
||||
default = 8080;
|
||||
description = "The loopback port, inside Hermes's own network namespace, that forwards to llmSocket.";
|
||||
};
|
||||
model = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "The model name, as the proxy's upstream knows it.";
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
services.hermes-agent = {
|
||||
enable = true;
|
||||
addToSystemPackages = false;
|
||||
settings = {
|
||||
model = {
|
||||
provider = "custom";
|
||||
default = cfg.model;
|
||||
base_url = "http://127.0.0.1:${toString cfg.llmPort}/v1";
|
||||
# the proxy adds the real key; Hermes never holds it
|
||||
api_key = "held-by-proxy";
|
||||
};
|
||||
terminal.backend = "local";
|
||||
# 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";
|
||||
};
|
||||
mcpServers.host = {
|
||||
command = "${pkgs.socat}/bin/socat";
|
||||
args = [
|
||||
"STDIO"
|
||||
"UNIX-CONNECT:${cfg.hostSocket}"
|
||||
];
|
||||
};
|
||||
};
|
||||
|
||||
# Upstream lingers the hermes uid so cron jobs can `systemd-run --user`.
|
||||
# A user manager starts units outside this sandbox, so: no linger, and
|
||||
# no /run/user (below). Cron jobs then fail closed.
|
||||
users.users.${hermes.user}.linger = lib.mkForce false;
|
||||
|
||||
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" ];
|
||||
BindReadOnlyPaths = [
|
||||
cfg.hostSocket
|
||||
cfg.llmSocket
|
||||
];
|
||||
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.
|
||||
systemd.services.hermes-llm-bridge = {
|
||||
description = "Hermes's loopback port to the inference proxy";
|
||||
unitConfig.JoinsNamespaceOf = "hermes-agent.service";
|
||||
partOf = [ "hermes-agent.service" ];
|
||||
serviceConfig = {
|
||||
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}"
|
||||
];
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
NoNewPrivileges = true;
|
||||
CapabilityBoundingSet = "";
|
||||
};
|
||||
};
|
||||
|
||||
systemd.tmpfiles.rules = [ "d ${socketDir} 0755 root root -" ];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
# On a Linux host: Hermes's unit runs here, confined by systemd, and the
|
||||
# host's systemd serves both of its sockets.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.services.hermes-guest;
|
||||
in
|
||||
{
|
||||
imports = [
|
||||
./hermes-guest.nix
|
||||
./llm-proxy.nix
|
||||
];
|
||||
|
||||
options.services.hermes-guest.hostSocketUnit = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
example = "endo-guest-hermes.socket";
|
||||
description = ''
|
||||
The socket unit that serves hostSocket: the guest's host (toybox, say), bound to Hermes's
|
||||
guest agent, with SocketUser set to Hermes's user and SocketMode 0600.
|
||||
'';
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
services.hermes-llm-proxy = {
|
||||
enable = true;
|
||||
socket = cfg.llmSocket;
|
||||
socketUser = config.services.hermes-agent.user;
|
||||
};
|
||||
systemd.services.hermes-agent = {
|
||||
after = [
|
||||
"hermes-llm.socket"
|
||||
cfg.hostSocketUnit
|
||||
];
|
||||
requires = [
|
||||
"hermes-llm.socket"
|
||||
cfg.hostSocketUnit
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
# The inference proxy, socket-activated: one service instance per
|
||||
# connection on `socket`, holding the API key as a systemd credential.
|
||||
# Used on a Linux host, and (with launchd in place of systemd) on macOS.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.services.hermes-llm-proxy;
|
||||
proxy = pkgs.writers.writePython3 "llm-proxy" { flakeIgnore = [ "E501" ]; } (
|
||||
builtins.readFile ../llm-proxy.py
|
||||
);
|
||||
in
|
||||
{
|
||||
options.services.hermes-llm-proxy = {
|
||||
enable = lib.mkEnableOption "the inference proxy for a confined Hermes";
|
||||
socket = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "Where to listen.";
|
||||
};
|
||||
socketUser = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "The one user who may connect.";
|
||||
};
|
||||
upstream = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
example = "https://openrouter.ai/api/v1";
|
||||
description = "The OpenAI-compatible base URL to forward to.";
|
||||
};
|
||||
keyFile = lib.mkOption {
|
||||
type = lib.types.str;
|
||||
description = "The API key, as a runtime path (not a nix path, which would copy it to the store).";
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
systemd.sockets.hermes-llm = {
|
||||
wantedBy = [ "sockets.target" ];
|
||||
listenStreams = [ cfg.socket ];
|
||||
socketConfig = {
|
||||
Accept = true;
|
||||
SocketUser = cfg.socketUser;
|
||||
SocketMode = "0600";
|
||||
};
|
||||
};
|
||||
systemd.services."hermes-llm@" = {
|
||||
description = "Hermes inference proxy, one connection";
|
||||
serviceConfig = {
|
||||
ExecStart = "${proxy} ${lib.escapeShellArg cfg.upstream} %d/llm-key";
|
||||
StandardInput = "socket";
|
||||
StandardOutput = "journal";
|
||||
LoadCredential = [ "llm-key:${cfg.keyFile}" ];
|
||||
DynamicUser = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
PrivateTmp = true;
|
||||
PrivateDevices = true;
|
||||
NoNewPrivileges = true;
|
||||
CapabilityBoundingSet = "";
|
||||
RestrictAddressFamilies = [
|
||||
"AF_UNIX"
|
||||
"AF_INET"
|
||||
"AF_INET6"
|
||||
];
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
# On macOS: a NixOS microVM (vfkit) that runs the same confined unit.
|
||||
# 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.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.services.hermes-guest;
|
||||
vm = cfg.vm;
|
||||
|
||||
# a socket unit at `path` in the VM, relaying each connection to vsock `port`
|
||||
relay = name: path: port: {
|
||||
sockets."hermes-${name}-relay" = {
|
||||
wantedBy = [ "sockets.target" ];
|
||||
listenStreams = [ path ];
|
||||
socketConfig = {
|
||||
Accept = true;
|
||||
SocketUser = config.services.hermes-agent.user;
|
||||
SocketMode = "0600";
|
||||
};
|
||||
};
|
||||
services."hermes-${name}-relay@" = {
|
||||
serviceConfig = {
|
||||
ExecStart = "${pkgs.socat}/bin/socat STDIO VSOCK-CONNECT:2:${toString port}";
|
||||
StandardInput = "socket";
|
||||
StandardOutput = "socket";
|
||||
DynamicUser = true;
|
||||
RestrictAddressFamilies = [ "AF_VSOCK" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
in
|
||||
{
|
||||
imports = [ ./hermes-guest.nix ];
|
||||
|
||||
options.services.hermes-guest.vm = {
|
||||
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.";
|
||||
};
|
||||
hostPort = lib.mkOption {
|
||||
type = lib.types.port;
|
||||
default = 5000;
|
||||
};
|
||||
llmPort = lib.mkOption {
|
||||
type = lib.types.port;
|
||||
default = 5001;
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
system.stateVersion = "25.11";
|
||||
networking.hostName = "hermes-guest";
|
||||
|
||||
microvm = {
|
||||
hypervisor = "vfkit";
|
||||
vcpu = 2;
|
||||
mem = 4096;
|
||||
# no network interface at all
|
||||
interfaces = [ ];
|
||||
# the host's /nix/store, read-only, as on a Linux host (where
|
||||
# ProtectSystem=strict leaves the store readable): no store image to
|
||||
# rebuild on each change. The store holds no secrets, as long as
|
||||
# none is ever written as a nix path.
|
||||
shares = [
|
||||
{
|
||||
tag = "ro-store";
|
||||
source = "/nix/store";
|
||||
mountPoint = "/nix/.ro-store";
|
||||
proto = "virtiofs";
|
||||
}
|
||||
];
|
||||
volumes = [
|
||||
{
|
||||
image = "${vm.hostDir}/hermes-state.img";
|
||||
mountPoint = "/var/lib/hermes";
|
||||
size = 8192;
|
||||
}
|
||||
];
|
||||
# microvm.vsock.cid is not implemented for vfkit, so the devices go
|
||||
# straight to vfkit: a guest connect to (2, port) makes vfkit connect
|
||||
# to socketURL on the host.
|
||||
vfkit.extraArgs = [
|
||||
"--device"
|
||||
"virtio-vsock,port=${toString vm.hostPort},socketURL=${vm.hostDir}/host.sock"
|
||||
"--device"
|
||||
"virtio-vsock,port=${toString vm.llmPort},socketURL=${vm.hostDir}/llm.sock"
|
||||
];
|
||||
};
|
||||
|
||||
systemd = lib.mkMerge [
|
||||
(relay "host" cfg.hostSocket vm.hostPort)
|
||||
(relay "llm" cfg.llmSocket vm.llmPort)
|
||||
{
|
||||
services.hermes-agent = {
|
||||
after = [
|
||||
"hermes-host-relay.socket"
|
||||
"hermes-llm-relay.socket"
|
||||
];
|
||||
requires = [
|
||||
"hermes-host-relay.socket"
|
||||
"hermes-llm-relay.socket"
|
||||
];
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
# the console is the operator's way in, for debugging
|
||||
services.getty.autologinUser = "root";
|
||||
};
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Hermes as a guest of a fake host: an integration test of the plumbing.
|
||||
|
||||
The test plays both of Hermes's counterparts. It serves the guest's
|
||||
methods as MCP on host.sock, which Hermes reaches as the deployed unit
|
||||
does (socat STDIO UNIX-CONNECT:host.sock). It also serves a scripted
|
||||
model, so the run needs no API key and does the same thing every time.
|
||||
Then it checks what the host received.
|
||||
|
||||
usage: demo.py HERMES SOCAT
|
||||
HERMES the hermes executable
|
||||
SOCAT the socat executable
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from socketserver import StreamRequestHandler, ThreadingUnixStreamServer
|
||||
|
||||
from fake_host import HostSide, Mailbox, Ref, handle_rpc
|
||||
from fake_llm import chunks, completion, next_step
|
||||
|
||||
MODEL = "fake-guest-model"
|
||||
|
||||
SCRIPT = [
|
||||
("listMessages", {}),
|
||||
("request", {"to": "HOST", "description": "a pen", "responseName": "pen"}),
|
||||
("lookup", {"petName": "pen"}),
|
||||
("reply", {"messageNumber": 0, "strings": ["Thanks for the ", "!"],
|
||||
"edgeNames": ["pen"], "petNames": ["pen"]}),
|
||||
("dismiss", {"messageNumber": 0}),
|
||||
]
|
||||
|
||||
|
||||
class McpHandler(StreamRequestHandler):
|
||||
"""One MCP connection: newline-delimited JSON-RPC, as MCP's stdio transport frames it."""
|
||||
|
||||
def handle(self):
|
||||
for line in self.rfile:
|
||||
if not line.strip():
|
||||
continue
|
||||
reply = handle_rpc(self.server.mailbox, json.loads(line))
|
||||
if reply is not None:
|
||||
self.wfile.write(json.dumps(reply).encode() + b"\n")
|
||||
self.wfile.flush()
|
||||
|
||||
|
||||
class LlmHandler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path.rstrip("/").endswith("/models"):
|
||||
self._json({"object": "list", "data": [
|
||||
{"id": MODEL, "object": "model", "owned_by": "test"}]})
|
||||
else:
|
||||
self.send_error(404)
|
||||
|
||||
def do_POST(self):
|
||||
req = json.loads(self.rfile.read(int(self.headers["content-length"])))
|
||||
if not self.path.endswith("/chat/completions"):
|
||||
self.send_error(404)
|
||||
return
|
||||
self.server.seen.append(req)
|
||||
try:
|
||||
message = next_step(self.server.script, req)
|
||||
except KeyError as err:
|
||||
# a 400, not a dropped connection: Hermes retries those forever
|
||||
names = [t["function"]["name"] for t in req.get("tools", [])]
|
||||
logging.error("fake model: %s; offered: %s", err, names)
|
||||
self.server.errors.append(str(err))
|
||||
self._json({"error": {"message": str(err), "type": "invalid_request_error"}},
|
||||
status=400)
|
||||
return
|
||||
logging.info("model says %s", json.dumps(message)[:200])
|
||||
if req.get("stream"):
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "text/event-stream")
|
||||
self.end_headers()
|
||||
for line in chunks(MODEL, message):
|
||||
self.wfile.write(line.encode() + b"\n\n")
|
||||
else:
|
||||
self._json(completion(MODEL, message))
|
||||
|
||||
def _json(self, data, status=200):
|
||||
body = json.dumps(data).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("content-type", "application/json")
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, format, *args):
|
||||
logging.debug(format, *args)
|
||||
|
||||
|
||||
def hermes_config(socat, host_sock, llm_port):
|
||||
"""config.yaml for the run (JSON is YAML): the deployed unit's settings."""
|
||||
return json.dumps({
|
||||
"model": {
|
||||
"provider": "custom",
|
||||
"default": MODEL,
|
||||
"base_url": f"http://127.0.0.1:{llm_port}/v1",
|
||||
"api_key": "held-by-proxy",
|
||||
},
|
||||
# the guest's methods are its whole world: offer them to the model
|
||||
# directly, not behind tool_search/tool_call
|
||||
"tools": {"tool_search": {"enabled": "off"}},
|
||||
"mcp_servers": {"host": {
|
||||
"command": socat,
|
||||
"args": ["STDIO", f"UNIX-CONNECT:{host_sock}"],
|
||||
}},
|
||||
}, indent=2)
|
||||
|
||||
|
||||
def check(host, mailbox, seen, stdout):
|
||||
"""What should have happened; the failures, if any."""
|
||||
tool_results = [m for m in (seen[-1]["messages"] if seen else [])
|
||||
if m["role"] == "tool"]
|
||||
expect = {
|
||||
"Hermes made all 5 calls": len(tool_results) == len(SCRIPT),
|
||||
"it read the host's message": bool(tool_results)
|
||||
and "ask me for a pen" in str(tool_results[0]["content"]),
|
||||
"the host got the pen back, as a reference": host.received.get("pen") == Ref("Pen"),
|
||||
"as a reply to message 0": bool(host.inbox) and host.inbox[-1].get("replyTo") == 0,
|
||||
"the message was dismissed": mailbox.listMessages() == [],
|
||||
"Hermes printed the model's last words": "Done: I made 5 calls." in stdout,
|
||||
}
|
||||
return [what for what, ok in expect.items() if not ok]
|
||||
|
||||
|
||||
def main(argv, make_tmpdir, run, popen, timeout_expired, environ):
|
||||
hermes, socat = argv[1:3]
|
||||
with make_tmpdir() as tmp:
|
||||
host = HostSide(on_request=lambda description: Ref("Pen"))
|
||||
mailbox = Mailbox(host)
|
||||
host.send(mailbox, ["Hello Hermes. Please ask me for a pen, then thank me with it."], [], [])
|
||||
|
||||
host_sock = str(tmp / "host.sock")
|
||||
mcp = ThreadingUnixStreamServer(host_sock, McpHandler)
|
||||
mcp.mailbox = mailbox
|
||||
llm = ThreadingHTTPServer(("127.0.0.1", 0), LlmHandler)
|
||||
llm.script, llm.seen, llm.errors = SCRIPT, [], []
|
||||
for server in (mcp, llm):
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
|
||||
home = tmp / "home"
|
||||
hermes_home = home / ".hermes"
|
||||
hermes_home.mkdir(parents=True)
|
||||
(hermes_home / "config.yaml").write_text(
|
||||
hermes_config(socat, host_sock, llm.server_address[1]))
|
||||
|
||||
env = dict(environ, HOME=str(home), HERMES_HOME=str(hermes_home))
|
||||
# As in the deployed unit, the agent runs in `hermes gateway`, which
|
||||
# owns the MCP servers; `hermes chat` is only its client. Start the
|
||||
# gateway ourselves, in the foreground, as systemd would, so chat
|
||||
# finds it rather than spawning a detached one of its own.
|
||||
gateway_log = (tmp / "gateway.log").open("w")
|
||||
gateway = popen([hermes, "gateway", "run"], env=env,
|
||||
stdout=gateway_log, stderr=gateway_log)
|
||||
try:
|
||||
done = run([hermes, "chat", "--oneshot", "-q",
|
||||
"Check your messages and do what your host asks."],
|
||||
env=env, capture_output=True, text=True, timeout=120)
|
||||
stdout = done.stdout
|
||||
logging.info("hermes exited %s\n--- stdout\n%s\n--- stderr\n%s",
|
||||
done.returncode, done.stdout[-3000:], done.stderr[-3000:])
|
||||
except timeout_expired as err:
|
||||
stdout = err.stdout or ""
|
||||
logging.error("hermes timed out after %ss", err.timeout)
|
||||
finally:
|
||||
gateway.terminate()
|
||||
try:
|
||||
gateway.wait(timeout=20)
|
||||
except timeout_expired:
|
||||
gateway.kill()
|
||||
gateway_log.close()
|
||||
for server in (mcp, llm):
|
||||
server.shutdown()
|
||||
logging.info("--- gateway log (tail)\n%s",
|
||||
(tmp / "gateway.log").read_text()[-2000:])
|
||||
|
||||
failures = check(host, mailbox, llm.seen, stdout) + llm.errors
|
||||
logging.info("host inbox: %s", json.dumps(host.inbox))
|
||||
for what in failures:
|
||||
logging.error("FAILED: %s", what)
|
||||
if not failures:
|
||||
logging.info("PASS: Hermes acted as a guest, over MCP on host.sock")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
def _script_io():
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
@contextmanager
|
||||
def make_tmpdir():
|
||||
# in /tmp: macOS's $TMPDIR is too long for a Unix socket's path
|
||||
with tempfile.TemporaryDirectory(prefix="hermes-guest-", dir="/tmp") as d:
|
||||
yield Path(d)
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
return main(
|
||||
argv=list(sys.argv),
|
||||
make_tmpdir=make_tmpdir,
|
||||
run=subprocess.run,
|
||||
popen=subprocess.Popen,
|
||||
timeout_expired=subprocess.TimeoutExpired,
|
||||
environ=dict(os.environ),
|
||||
)
|
||||
|
||||
raise SystemExit(_script_io())
|
||||
@@ -0,0 +1,195 @@
|
||||
"""A guest's mailbox and pet store, and its methods as an MCP server.
|
||||
|
||||
The methods follow Endo's EndoGuest (listMessages, request, resolve,
|
||||
lookup, ...), restricted to data: arguments are pet names, strings, and
|
||||
message numbers, and references stay here, in the pet store. A guest
|
||||
never holds one; it moves them between messages and names.
|
||||
|
||||
>>> host = HostSide(on_request=lambda description: Ref('Pen'))
|
||||
>>> guest = Mailbox(host)
|
||||
>>> host.send(guest, ['Hello. Please ask me for a pen.'], [], [])
|
||||
>>> [m['strings'] for m in guest.listMessages()]
|
||||
[['Hello. Please ask me for a pen.']]
|
||||
>>> guest.request('HOST', 'a pen', 'pen')
|
||||
{'interface': 'Pen'}
|
||||
>>> guest.list()
|
||||
['HOST', 'pen']
|
||||
>>> guest.reply(0, ['Thanks for the ', '!'], ['it'], ['pen'])
|
||||
>>> host.inbox[-1]['strings'], host.inbox[-1]['names']
|
||||
(['Thanks for the ', '!'], ['it'])
|
||||
>>> host.received['it']
|
||||
Ref(interface='Pen')
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import threading
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Ref:
|
||||
"""A reference, as the pet store holds it: never sent to the guest."""
|
||||
|
||||
interface: str
|
||||
|
||||
|
||||
def describe(value):
|
||||
"""What the guest may see of a stored value: data as is, a Ref by its interface.
|
||||
|
||||
>>> describe(Ref('Counter'))
|
||||
{'interface': 'Counter'}
|
||||
>>> describe(3)
|
||||
3
|
||||
"""
|
||||
return {"interface": value.interface} if isinstance(value, Ref) else value
|
||||
|
||||
|
||||
@dataclass
|
||||
class HostSide:
|
||||
"""The guest's host: it sends to the guest, answers its requests, and reads its mail."""
|
||||
|
||||
on_request: object # description -> value
|
||||
inbox: list = field(default_factory=list)
|
||||
received: dict = field(default_factory=dict)
|
||||
|
||||
def send(self, guest, strings, edge_names, values):
|
||||
guest._deliver("package", "HOST", strings=strings,
|
||||
names=edge_names, values=values)
|
||||
|
||||
def _receive(self, message, values):
|
||||
self.inbox.append(message)
|
||||
self.received.update(zip(message.get("names", []), values))
|
||||
|
||||
|
||||
class Mailbox:
|
||||
"""One guest's powers. Method names are EndoGuest's."""
|
||||
|
||||
def __init__(self, host):
|
||||
self._host = host
|
||||
self._lock = threading.Lock()
|
||||
self._pets = {"HOST": Ref("Host")}
|
||||
self._messages = [] # (record, values)
|
||||
|
||||
def _deliver(self, type_, sender, values=(), **record):
|
||||
with self._lock:
|
||||
number = len(self._messages)
|
||||
self._messages.append((
|
||||
{"number": number, "type": type_, "from": sender, **record},
|
||||
list(values),
|
||||
))
|
||||
|
||||
def _message(self, number):
|
||||
for record, values in self._messages:
|
||||
if record["number"] == number:
|
||||
return record, values
|
||||
raise KeyError(f"no message {number}")
|
||||
|
||||
def _to_host(self, to):
|
||||
if to != "HOST":
|
||||
raise KeyError(f"no recipient {to}; this guest can write only to HOST")
|
||||
|
||||
def listMessages(self):
|
||||
with self._lock:
|
||||
return [dict(record) for record, _ in self._messages]
|
||||
|
||||
def list(self):
|
||||
return sorted(self._pets)
|
||||
|
||||
def lookup(self, petName):
|
||||
return describe(self._pets[petName])
|
||||
|
||||
def request(self, to, description, responseName=None):
|
||||
self._to_host(to)
|
||||
value = self._host.on_request(description)
|
||||
if responseName:
|
||||
self._pets[responseName] = value
|
||||
return describe(value)
|
||||
|
||||
def send(self, to, strings, edgeNames, petNames):
|
||||
self._to_host(to)
|
||||
values = [self._pets[n] for n in petNames]
|
||||
self._host._receive(
|
||||
{"type": "package", "from": "guest", "strings": strings,
|
||||
"names": edgeNames}, values)
|
||||
|
||||
def reply(self, messageNumber, strings, edgeNames, petNames):
|
||||
record, _ = self._message(messageNumber)
|
||||
self.send(record["from"], strings, edgeNames, petNames)
|
||||
self._host.inbox[-1]["replyTo"] = messageNumber
|
||||
|
||||
def adopt(self, messageNumber, edgeName, petName):
|
||||
record, values = self._message(messageNumber)
|
||||
self._pets[petName] = values[record["names"].index(edgeName)]
|
||||
|
||||
def dismiss(self, messageNumber):
|
||||
with self._lock:
|
||||
self._messages = [
|
||||
(r, v) for r, v in self._messages if r["number"] != messageNumber]
|
||||
|
||||
|
||||
def _schema(props, required=None):
|
||||
return {"type": "object", "properties": props,
|
||||
"required": list(props) if required is None else required}
|
||||
|
||||
|
||||
STR, INT = {"type": "string"}, {"type": "integer"}
|
||||
STRS = {"type": "array", "items": STR}
|
||||
|
||||
TOOLS = {
|
||||
"listMessages": ("The messages in this guest's inbox.", _schema({})),
|
||||
"list": ("This guest's pet names.", _schema({})),
|
||||
"lookup": ("What a pet name refers to: data, or an object's interface.",
|
||||
_schema({"petName": STR})),
|
||||
"request": ("Ask a recipient for something; the answer is stored under responseName.",
|
||||
_schema({"to": STR, "description": STR, "responseName": STR},
|
||||
["to", "description"])),
|
||||
"send": ("Send a message: strings, with the named references between them.",
|
||||
_schema({"to": STR, "strings": STRS, "edgeNames": STRS, "petNames": STRS})),
|
||||
"reply": ("Reply to a message, as send does.",
|
||||
_schema({"messageNumber": INT, "strings": STRS,
|
||||
"edgeNames": STRS, "petNames": STRS})),
|
||||
"adopt": ("Keep a reference from a message under a pet name.",
|
||||
_schema({"messageNumber": INT, "edgeName": STR, "petName": STR})),
|
||||
"dismiss": ("Remove a message from the inbox.", _schema({"messageNumber": INT})),
|
||||
}
|
||||
|
||||
|
||||
def handle_rpc(mailbox, msg):
|
||||
"""One MCP JSON-RPC message in; the reply out, or None for a notification.
|
||||
|
||||
>>> box = Mailbox(HostSide(on_request=lambda d: 1))
|
||||
>>> handle_rpc(box, {'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call',
|
||||
... 'params': {'name': 'list', 'arguments': {}}})['result']['content'][0]['text']
|
||||
'["HOST"]'
|
||||
>>> handle_rpc(box, {'jsonrpc': '2.0', 'method': 'notifications/initialized'})
|
||||
"""
|
||||
method, params = msg.get("method"), msg.get("params") or {}
|
||||
if "id" not in msg:
|
||||
return None
|
||||
reply = {"jsonrpc": "2.0", "id": msg["id"]}
|
||||
if method == "initialize":
|
||||
reply["result"] = {
|
||||
"protocolVersion": params.get("protocolVersion", "2025-06-18"),
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "fake-endo-host", "version": "0"},
|
||||
}
|
||||
elif method == "ping":
|
||||
reply["result"] = {}
|
||||
elif method == "tools/list":
|
||||
reply["result"] = {"tools": [
|
||||
{"name": name, "description": desc, "inputSchema": schema}
|
||||
for name, (desc, schema) in TOOLS.items()]}
|
||||
elif method == "tools/call" and params.get("name") in TOOLS:
|
||||
name, args = params["name"], params.get("arguments") or {}
|
||||
logging.info("guest calls %s(%s)", name, json.dumps(args))
|
||||
try:
|
||||
result = getattr(mailbox, name)(**args)
|
||||
reply["result"] = {"content": [
|
||||
{"type": "text", "text": json.dumps(result)}]}
|
||||
except (KeyError, ValueError, TypeError) as err:
|
||||
reply["result"] = {"isError": True, "content": [
|
||||
{"type": "text", "text": str(err)}]}
|
||||
else:
|
||||
reply["error"] = {"code": -32601, "message": f"no method {method}"}
|
||||
return reply
|
||||
@@ -0,0 +1,76 @@
|
||||
"""A scripted model: an OpenAI-compatible chat completion that makes the
|
||||
tool calls of a fixed script, one per turn, then says it's done.
|
||||
|
||||
It finds each tool by its MCP method name at the end of the tool's name,
|
||||
whatever prefix Hermes gives MCP tools.
|
||||
|
||||
>>> tools = [{'type': 'function', 'function': {'name': 'mcp_host_listMessages'}}]
|
||||
>>> req = {'messages': [{'role': 'user', 'content': 'go'}], 'tools': tools}
|
||||
>>> step = next_step([('listMessages', {})], req)
|
||||
>>> step['tool_calls'][0]['function']
|
||||
{'name': 'mcp_host_listMessages', 'arguments': '{}'}
|
||||
>>> req['messages'] += [{'role': 'assistant', 'tool_calls': step['tool_calls']},
|
||||
... {'role': 'tool', 'content': '[]'}]
|
||||
>>> next_step([('listMessages', {})], req)['content']
|
||||
'Done: I made 1 calls.'
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
|
||||
def tool_named(tools, method):
|
||||
"""The full name of the tool for MCP `method`.
|
||||
|
||||
>>> tool_named([{'function': {'name': 'mcp_host_reply'}}], 'reply')
|
||||
'mcp_host_reply'
|
||||
"""
|
||||
names = [t["function"]["name"] for t in tools]
|
||||
for name in names:
|
||||
if name == method or name.endswith("_" + method):
|
||||
return name
|
||||
raise KeyError(f"no tool for {method} among {len(names)} tools")
|
||||
|
||||
|
||||
def next_step(script, req):
|
||||
"""The assistant message for the next turn: the next call, or the end."""
|
||||
done = sum(1 for m in req["messages"] if m["role"] == "tool")
|
||||
if done >= len(script):
|
||||
return {"role": "assistant", "content": f"Done: I made {done} calls."}
|
||||
method, args = script[done]
|
||||
return {"role": "assistant", "content": None, "tool_calls": [{
|
||||
"id": f"call_{done}", "type": "function",
|
||||
"function": {"name": tool_named(req.get("tools", []), method),
|
||||
"arguments": json.dumps(args)},
|
||||
}]}
|
||||
|
||||
|
||||
def completion(model, message):
|
||||
"""A non-streamed chat.completion with `message`."""
|
||||
return {
|
||||
"id": "fake", "object": "chat.completion", "created": 0, "model": model,
|
||||
"choices": [{"index": 0, "message": message,
|
||||
"finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}],
|
||||
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
|
||||
}
|
||||
|
||||
|
||||
def chunks(model, message):
|
||||
"""The same message, as server-sent event lines of a streamed completion.
|
||||
|
||||
>>> lines = list(chunks('m', {'role': 'assistant', 'content': 'hi'}))
|
||||
>>> lines[-1]
|
||||
'data: [DONE]'
|
||||
"""
|
||||
delta = {"role": "assistant"}
|
||||
if message.get("tool_calls"):
|
||||
delta["tool_calls"] = [dict(c, index=i) for i, c in enumerate(message["tool_calls"])]
|
||||
else:
|
||||
delta["content"] = message["content"]
|
||||
base = {"id": "fake", "object": "chat.completion.chunk", "created": 0, "model": model}
|
||||
yield "data: " + json.dumps(dict(base, choices=[
|
||||
{"index": 0, "delta": delta, "finish_reason": None}]))
|
||||
yield "data: " + json.dumps(dict(base, choices=[{
|
||||
"index": 0, "delta": {},
|
||||
"finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}],
|
||||
usage={"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}))
|
||||
yield "data: [DONE]"
|
||||
Reference in new issue
Block a user