#!/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);