feat: teach the guest call, WebApps and define; install through the host

- guide/endo-guest.md, served as the MCP resource endo://guide: names
  and messages, toybox-style call, WebApps, define, and moving bytes
  over host.sock from the shell.
- The fake host gains call, define (toybox's modules-and-slots shape,
  recorded for the host) and a WebApp narrowed to one URL, with
  getBase64 for bytes, since toybox's fetch device answers text.
- demo.py --task install: with a real model, Hermes installs six and ms
  with no network but package-index WebApps its host grants; on macOS
  under sandbox-exec with outbound network denied. Checked by importing
  both from where Hermes put them.
- Temp cleanup logs, rather than fails, when Hermes's detached helpers
  are still writing.

Generated-by: Claude Opus 5.5
This commit is contained in:
dckc committed 2026-11-29 17:14:02 -06:00
1 parent cfffe56cce
commit 783e4c595f
4 files changed
+361 -31

No files matched your search

+119 -4
View File
@@ -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))