cli: iterate daemon holds one connection to a mind and serves it to local programs on localhost (#30)
jonas, 2026-11-28 20:58 UTC ยท 0a212f02d0662037dcdb3a56beab080589a60f64 ยท parent 935a3ab
7 files changed
- M core/lib/src/cli/README.md
- M core/lib/src/cli/cli.ts
- M core/lib/src/cli/config.ts
- A core/lib/src/cli/daemon-client.ts
- A core/lib/src/cli/daemon.test.ts
- A core/lib/src/cli/daemon.ts
- M core/lib/src/node.ts
M core/lib/src/cli/README.md
@@ -20,6 +20,7 @@ npx iterate use-my-computer --name myComputer npx iterate tunnel 5173 --name blog # a local port on blog.<address> npx iterate provide ./whatsapp.ts # a local file's functions as itx.whatsapp +npx iterate daemon start # this computer's one connection to the mind, for local programs npx iterate chatgpt connect example.com # a ChatGPT plan pays for the mind's Responses requests npx iterate git setup git.example.com # plain git at the mind's git host, with this computer's sign-in npx iterate logout @@ -703,6 +704,72 @@ - **The file is the bridge.** Whoever can read the key file can lend that name. Keep it on the bridge's machine alone. The private key is read in one function (`signer` in `bridge-key.ts`): a TPM, a Secure Enclave or the OS keychain would go there, so the key never leaves the hardware. + +## Daemon + +`iterate daemon` is one process on a computer that holds the connection to a mind. Every other +local program reaches the mind through it and makes no connection of its own: a bridge for a +coding agent's CLI (Claude Code, Codex, agy, Grok, OpenCode), a desktop app, a script. The same +code on Linux and macOS. Its code is [daemon.ts](daemon.ts) and [daemon-client.ts](daemon-client.ts). + +```sh +iterate login example.com # once: the daemon never signs in by itself +iterate daemon start # in the background; output in daemon.log of the config folder +iterate daemon # status: the minds, the local programs, their lends +iterate daemon stop +iterate daemon run # in the foreground, for systemd, launchd or a terminal +``` + +The daemon listens on `127.0.0.1`, on any free port (`--port` names one), and writes +`${XDG_CONFIG_HOME:-~/.config}/iterate/daemon.json` (mode 600): its pid, the port and a token that +is new at each start. One daemon runs for a config folder. It serves the profile's mind +(`--mind` names another), and connects to any other mind that a program names, with that mind's +stored sign-in. + +A program connects with a WebSocket and capnweb. From Node: + +```ts +import { connectDaemon } from "iterate/node"; + +const daemon = await connectDaemon({ name: "bridge.codex" }); +// lend the mind a capability: itx.beelink.codex.deliverEvent(event) now runs here +await daemon.provide( + "beelink.codex", + { deliverEvent: async (event) => {/* โฆ */} }, + { description: "Codex sessions on beelink" }, +); +// the mind's own API, over the daemon's connection: asked for at each use, disposed of after +{ + using itx = daemon.itx(); + using session = itx.cd("/agents/codex/abc"); + await session.append({ type: "codex/record-received", payload }); +} +await daemon.closed; // the daemon ended: connect and provide again +``` + +Without this package, in any language with capnweb: read `daemon.json`, open +`ws://127.0.0.1:<port>/` with no `Origin` header, and call `authenticate(token, { name, pid })` on +the root. Its answer has `provide(name, target, { description?, mind? })`, `itx(mind?)` and +`status()`. + +- **A lend follows the daemon's connection, not the program's.** The daemon lends each name again + over every connection it makes to the mind, and before a sign-in ends it makes the next + connection first, so a name is never without a lender. It reconnects for as long as it runs + (1 s, doubling, at most 60 s). A program does nothing at any of that. +- **A program that goes away takes its lends along**, at once. The newest lend of a name wins. +- **Ask for `itx()` at each use, and dispose of it after.** What it answers lives as long as the + daemon's current connection to the mind, and the calls on it go with the call that asks for it: + one round trip to the daemon. One that is never disposed of is held at the daemon until the + program goes away. A call waits up to 30 s for a connection, then fails. +- **Who may connect: this computer's user.** Whoever can read `daemon.json` can read the stored + sign-in beside it. The port alone opens nothing, and a request with an `Origin` header (a + browser's page) is refused. A program that connects acts as the sign-in's person, with all that + the person may do: there is no narrower grant for one program yet. +- **A service.** `iterate daemon run` under systemd or launchd, with the service's own restart. + Name the CLI by its file (`node <path>/bin/iterate.js daemon run`): the launcher runs its own + package in any working folder. + +Not tried on macOS. ## A ChatGPT plan
M core/lib/src/cli/cli.ts
@@ -3,8 +3,15 @@ // (./config.ts) names one mind; `--config <name>`, a folder mapped to a profile, the default // profile, or the only one picks it, and `--mind <address>` overrides it for one command. Every // connection is the Node client's (../node.ts `connectMind`). -import { spawnSync } from "node:child_process"; -import { existsSync, readFileSync, realpathSync, rmSync } from "node:fs"; +import { spawn, spawnSync } from "node:child_process"; +import { + existsSync, + mkdirSync, + openSync, + readFileSync, + realpathSync, + rmSync, +} from "node:fs"; import { readFile } from "node:fs/promises"; import { text as streamText } from "node:stream/consumers"; import { dirname, join, sep } from "node:path"; @@ -61,8 +68,11 @@ import { importProvidedFile, nameOfFile, type ProvidedFile, runProvide } from "./provide.ts"; import { finalStateOf, type ProvideState } from "./provide-state.ts"; import { runTunnel } from "./tunnel.ts"; +import { startDaemon } from "./daemon.ts"; +import { connectDaemon, DAEMON_FILE, readDaemonFile, runningDaemon } from "./daemon-client.ts"; import { shareMyComputer } from "./share-my-computer.ts"; import { + CONFIG_DIR, CONFIG_PATH, DEFAULT_CONFIG_NAME, readConfig, @@ -974,6 +984,100 @@ throw error; } }), + daemon: { + run: os + .input( + z.object({ + port: z + .number() + .int() + .min(0) + .max(65535) + .optional() + .describe("The localhost port to listen on (default: any free one)"), + mind: mindOption, + }), + ) + .meta({ + description: + "Hold this computer's one connection to a mind and serve it to local programs on localhost over capnweb, until Ctrl-C or a signal: for a service manager, or a terminal. Never signs in: run `iterate login` first", + }) + .handler(async ({ input }) => { + const daemon = await startDaemon({ + mind: await resolveMind(input.mind), + // a daemon has nobody at a terminal: a sign-in that ended is said, and tried again + connect: (address) => connectMind({ address, signIn: false }), + endsAt: signInEndsAt, + addressOf, + version: packageVersionOf(), + port: input.port, + }); + process.once("SIGINT", daemon.stop); + process.once("SIGTERM", daemon.stop); + await daemon.stopped; + // a socket of a mind that is still closing must not hold the process + process.exit(0); + }), + start: os + .input(z.object({ port: z.number().int().min(0).max(65535).optional(), mind: mindOption })) + .meta({ + description: + "Start the daemon in the background, with its output in daemon.log of the CLI's config folder; the same on Linux and macOS", + }) + .handler(async ({ input }) => { + const running = await runningDaemon(); + if (running) + return { already: true, pid: running.pid, port: running.port, mind: running.mind }; + // the mind is read here, where a person sees the error of a profile that names none + const mind = await resolveMind(input.mind); + const log = join(CONFIG_DIR, "daemon.log"); + mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); + const out = openSync(log, "a", 0o600); + const child = spawn( + process.execPath, + [ + // the file that runs now: the same CLI, whatever folder the daemon is in + process.argv[1]!, + "daemon", + "run", + "--mind", + mind, + ...(input.port === undefined ? [] : ["--port", String(input.port)]), + ], + { detached: true, stdio: ["ignore", out, out] }, + ); + child.unref(); + for (const giveUpAt = Date.now() + 15_000; Date.now() < giveUpAt; await sleep(100)) { + const file = readDaemonFile(); + if (file && file.pid === child.pid) return { pid: file.pid, port: file.port, mind, log }; + if (child.exitCode !== null) break; + } + throw new Error(`The daemon did not start: read ${log}.`); + }), + stop: os + .input(z.object({})) + .meta({ description: "Stop the daemon of this computer's user" }) + .handler(async () => { + // only a daemon that answered with this pid gets the signal (daemon-client.ts) + const running = await runningDaemon(); + if (!running) return { running: false }; + process.kill(running.pid, "SIGTERM"); + for (const giveUpAt = Date.now() + 10_000; Date.now() < giveUpAt; await sleep(100)) + if (!(await runningDaemon())) return { stopped: running.pid }; + throw new Error(`The daemon (pid ${running.pid}) did not stop in 10 s.`); + }), + status: os + .input(z.object({})) + .meta({ + default: true, + description: "The daemon's minds and their connections, the local programs and their lends", + }) + .handler(async () => { + if (!(await runningDaemon())) return { running: false, file: DAEMON_FILE }; + using daemon = await connectDaemon({ name: "iterate daemon status" }); + return await daemon.status(); + }), + }, config: { get: os .input(z.object({}))
M core/lib/src/cli/config.ts
@@ -15,7 +15,7 @@ } from "node:fs"; import { randomUUID } from "node:crypto"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { z } from "zod"; @@ -74,8 +74,8 @@ /** Write `value` to `path`, mode 600 in a folder of mode 700. A file that existed keeps its mode * through `writeFileSync`, so the mode is set again. */ -function writeJson(path: string, value: unknown) { - mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); +export function writePrivateJson(path: string, value: unknown) { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); chmodSync(path, 0o600); } @@ -85,7 +85,7 @@ export const writeConfigFile = (configFile: ConfigFile): void => { const parsed = ConfigFile.safeParse(configFile); if (!parsed.success) throw new Error(`Invalid config file: ${z.prettifyError(parsed.error)}`); - writeJson(CONFIG_PATH, parsed.data); + writePrivateJson(CONFIG_PATH, parsed.data); }; /** A named profile, or an Error naming what is wrong. The default profile exists empty. */ @@ -109,14 +109,14 @@ } export function writeSession(resource: string, session: StoredSession) { - writeJson(SESSIONS_PATH, { ...readJson(SESSIONS_PATH, SessionsFile), [resource]: session }); + writePrivateJson(SESSIONS_PATH, { ...readJson(SESSIONS_PATH, SessionsFile), [resource]: session }); } export function removeSession(resource: string) { const sessions = readJson(SESSIONS_PATH, SessionsFile); if (!(resource in sessions)) return; delete sessions[resource]; - writeJson(SESSIONS_PATH, sessions); + writePrivateJson(SESSIONS_PATH, sessions); } /** What the lock file holds, or "" when it is gone. */
A core/lib/src/cli/daemon-client.ts
@@ -0,0 +1,138 @@ +// daemon-client.ts โ A LOCAL PROGRAM'S CONNECTION TO `iterate daemon` (daemon.ts): what a bridge, a +// desktop app or a script imports as `connectDaemon` from `iterate/node`. It reads the daemon's +// file for the port and the token, opens one WebSocket to localhost, and talks capnweb. It makes +// no connection to the mind and holds no sign-in. +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb"; +import WebSocket from "ws"; +import { z } from "zod"; +import type { MindItx } from "../node.ts"; +import { withTimeout } from "../lib.ts"; +import { CONFIG_DIR } from "./config.ts"; +import type { DaemonApi, DaemonSessionApi, DaemonStatus } from "./daemon.ts"; +import { rpcTargetOf } from "./provide.ts"; + +/** Where a daemon says how to reach it, for as long as it runs. */ +export const DAEMON_FILE = join(CONFIG_DIR, "daemon.json"); + +/** `daemon.json`: written once the server listens, removed when the daemon ends. */ +export const DaemonFile = z.object({ + pid: z.number().int(), + port: z.number().int(), + /** what `authenticate` takes: 32 random bytes, new at each start */ + token: z.string(), + /** the mind that a call names none for */ + mind: z.string(), + version: z.string(), + startedAt: z.string(), +}); +export type DaemonFile = z.infer<typeof DaemonFile>; + +/** The file of a daemon, or null when there is none or it does not parse (a stale one's). */ +export function readDaemonFile(path = DAEMON_FILE): DaemonFile | null { + if (!existsSync(path)) return null; + try { + return DaemonFile.parse(JSON.parse(readFileSync(path, "utf8"))); + } catch { + return null; + } +} + +/** THE DAEMON THAT ANSWERS NOW, as its file says it, or null. Only an answer counts: a file + * outlives a daemon that crashed, and its pid may by then be another process's, so nothing + * is ever told from the pid, and no signal is sent to it, before the daemon has answered with it. */ +export async function runningDaemon(path = DAEMON_FILE): Promise<DaemonFile | null> { + const file = readDaemonFile(path); + if (!file) return null; + try { + using daemon = await connectDaemon({ name: "iterate daemon", file: path }); + return (await daemon.status()).pid === file.pid ? file : null; + } catch { + return null; + } +} + +export type DaemonConnection = Disposable & { + status(): Promise<DaemonStatus>; + /** THE MIND'S ROOT CONTEXT over the daemon's connection (`mind`: another mind than the + * daemon's own). Ask for it at each use and dispose of it after (`using`): the calls on it + * go with the call that asks for it, so a use costs one round trip to the daemon. A copy + * that is kept ends when the daemon replaces its connection to the mind, about once an + * hour, and one that is never disposed of is held at the daemon until this program goes. */ + itx(mind?: string): MindItx; + /** LEND `provided` TO THE MIND as `itx.<name>` until the answer is disposed of or this + * connection closes: a plain object of functions (wrapped as `iterate provide` wraps a file's, + * provide.ts `rpcTargetOf`) or an `RpcTarget` of this package's capnweb. The daemon lends it + * again over each connection it makes to the mind, so the program does nothing at a reconnect + * of the daemon's. After this connection closes, connect and provide again. */ + provide( + name: string, + provided: object, + options?: { description?: string; mind?: string }, + ): Promise<Disposable>; + /** resolves when the socket to the daemon has closed */ + closed: Promise<{ code: number; reason: string }>; +}; + +/** CONNECT TO THE DAEMON OF THIS COMPUTER'S USER. It fails with the command that starts one when + * none runs. `name` is what `iterate daemon status` shows for this program. */ +export async function connectDaemon( + input: { name?: string; file?: string } = {}, +): Promise<DaemonConnection> { + const path = input.file || DAEMON_FILE; + const file = readDaemonFile(path); + const none = `No iterate daemon runs here (${path}). Start one: iterate daemon start.`; + if (!file) throw new Error(none); + const socket = new WebSocket(`ws://127.0.0.1:${file.port}/`, { handshakeTimeout: 5_000 }); + const closed = new Promise<{ code: number; reason: string }>((resolve) => { + socket.once("close", (code, reason) => resolve({ code, reason: reason.toString() })); + }); + // The transport surfaces failures through RPC and `closed`; ws also emits an EventEmitter error. + socket.on("error", () => {}); + // ws implements the DOM event/send/close interface consumed by capnweb. + const api = newWebSocketRpcSession<DaemonApi>(socket as unknown as globalThis.WebSocket); + // `authenticate` is never awaited: the calls on its answer go with it (connected-mind.ts) + const session: RpcStub<DaemonSessionApi> = (() => { + using promise = api.authenticate(file.token, { + name: input.name || process.title, + pid: process.pid, + }); + return promise.dup() as unknown as RpcStub<DaemonSessionApi>; + })(); + try { + // the first call proves the socket and the token; a port that something else took never answers + await withTimeout(Promise.resolve(session.status()), 5_000, "The iterate daemon's answer"); + } catch (error) { + socket.terminate(); + const why = error instanceof Error ? error.message : String(error); + // nothing listens on the file's port: its daemon is gone + if (/ECONNREFUSED|closed|WebSocket/i.test(why)) throw new Error(none, { cause: error }); + throw new Error(`Could not connect to the iterate daemon on port ${file.port}: ${why}`, { + cause: error, + }); + } + return { + status: async () => await session.status(), + // the promise's stub: a call on it is sent with this one, and `await` of it gives the stub + itx: (mind) => session.itx(mind) as unknown as MindItx, + provide: async (name, provided, options) => { + const target = provided instanceof RpcTarget ? provided : rpcTargetOf(provided); + // the daemon's handle of the lend: disposing of it ends the lend + return (await session.provide( + name, + target as unknown as RpcStub<RpcTarget>, + options, + )) as unknown as Disposable; + }, + closed, + [Symbol.dispose]() { + try { + session[Symbol.dispose](); + api[Symbol.dispose](); + } finally { + socket.close(); + } + }, + }; +}
A core/lib/src/cli/daemon.test.ts
@@ -0,0 +1,268 @@ +// daemon.test.ts โ `iterate daemon` (daemon.ts) and a program's connection to it +// (daemon-client.ts), over real sockets and real capnweb sessions on localhost. The mind is a +// stand-in: a WebSocket server whose root keeps what is lent to it, as a mind's `provide` does. +import { existsSync, mkdtempDisposableSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb"; +import { expect, test, vi } from "vitest"; +import WebSocket, { WebSocketServer } from "ws"; +import type { MindConnection, MindItx } from "../node.ts"; +import { connectDaemon, readDaemonFile, runningDaemon } from "./daemon-client.ts"; +import { startDaemon } from "./daemon.ts"; + +type Lent = RpcStub<RpcTarget> & { + deliverEvent(event: { type: string }): Promise<string>; + files: { read(path: string): Promise<Uint8Array> }; +}; + +/** A mind that keeps the newest lend of each name, and says which of its connections holds it. */ +async function standInMind() { + const lent = new Map<string, { target: Lent; connection: number }>(); + const appended: { path: string; type: string }[] = []; + const sockets: WebSocket[] = []; + class Context extends RpcTarget { + path: string; + connection: number; + constructor(path: string, connection: number) { + super(); + this.path = path; + this.connection = connection; + } + whoami() { + return { path: this.path }; + } + cd(path: string) { + return new Context(path, this.connection); + } + append(event: { type: string }) { + appended.push({ path: this.path, type: event.type }); + return [{ ...event, offset: appended.length, path: this.path }]; + } + provide(match: string, target: Lent) { + const mine = { target: target.dup() as Lent, connection: this.connection }; + lent.set(match, mine); + return new (class extends RpcTarget { + [Symbol.dispose]() { + if (lent.get(match) === mine) lent.delete(match); + } + })(); + } + } + const server = new WebSocketServer({ port: 0, host: "127.0.0.1" }); + await new Promise((resolve) => server.once("listening", resolve)); + server.on("connection", (socket) => { + sockets.push(socket); + newWebSocketRpcSession( + socket as unknown as globalThis.WebSocket, + new Context("/", sockets.length), + ); + }); + const { port } = server.address() as { port: number }; + let refuse = ""; + const connect = async (address: string): Promise<MindConnection> => { + if (refuse) throw new Error(refuse); + const socket = new WebSocket(`ws://127.0.0.1:${port}`); + socket.on("error", () => {}); + const closed = new Promise<{ code: number; reason: string }>((resolve) => + socket.once("close", (code, reason) => resolve({ code, reason: reason.toString() })), + ); + const itx = newWebSocketRpcSession( + socket as unknown as globalThis.WebSocket, + ) as unknown as MindItx; + await itx.whoami(); + return { address, itx, closed, [Symbol.dispose]: () => socket.close() }; + }; + return { + lent, + appended, + connect, + /** how many connections the daemon has made */ + connections: () => sockets.length, + /** the mind closes the newest connection, as it does when a sign-in ends */ + drop: () => sockets.at(-1)!.close(4000, "the sign-in ended"), + refuse: (why: string) => (refuse = why), + [Symbol.dispose]: () => { + for (const socket of sockets) socket.terminate(); + server.close(); + }, + }; +} + +const daemonFor = async ( + mind: Awaited<ReturnType<typeof standInMind>>, + folder: string, + more: Partial<Parameters<typeof startDaemon>[0]> = {}, +) => + startDaemon({ + mind: "iterate.example.com", + connect: mind.connect, + addressOf: (typed) => typed, + version: "0.0.0-test", + file: join(folder, "daemon.json"), + log: () => {}, + timing: { reconnectMs: 20, retireAfterMs: 20 }, + ...more, + }); + +const bridge = { + deliverEvent: (event: { type: string }) => `delivered ${event.type}`, + files: { read: (path: string) => new TextEncoder().encode(path) }, +}; + +test("a local program lends a capability to the mind and reaches the mind's itx, both through the daemon's one connection; when the program goes away its lend goes too", async () => { + using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-")); + using mind = await standInMind(); + const daemon = await daemonFor(mind, folder.path); + const file = join(folder.path, "daemon.json"); + try { + expect(readDaemonFile(file)).toMatchObject({ pid: process.pid, mind: "iterate.example.com" }); + expect(statSync(file).mode & 0o777).toBe(0o600); + + const program = await connectDaemon({ name: "bridge.codex", file }); + await program.provide("beelink.codex", bridge, { description: "Codex sessions on beelink" }); + // the mind calls what the program lent: a function, and one of a nested object, with bytes + const lent = mind.lent.get("itx.beelink.codex")!.target; + expect(await lent.deliverEvent({ type: "message-received" })).toBe( + "delivered message-received", + ); + expect(new TextDecoder().decode(await lent.files.read("a.txt"))).toBe("a.txt"); + // the mind's itx, in one pipeline: no connection to the mind of the program's own + using itx = program.itx(); + using session = itx.cd("/agents/codex/one"); + const [event] = await session.append({ type: "codex/noted" }); + expect(event).toMatchObject({ path: "/agents/codex/one", type: "codex/noted" }); + expect(mind.connections()).toBe(1); + expect(await program.status()).toMatchObject({ + mind: "iterate.example.com", + minds: [{ address: "iterate.example.com", state: "connected" }], + clients: [{ name: "bridge.codex", pid: process.pid }], + lends: [{ name: "itx.beelink.codex", client: "bridge.codex", live: true }], + }); + + program[Symbol.dispose](); + await vi.waitFor(() => expect(mind.lent.has("itx.beelink.codex")).toBe(false)); + } finally { + daemon.stop(); + } + await daemon.stopped; + expect(existsSync(file)).toBe(false); +}); + +test("the daemon's connection to the mind closes: it connects again and lends every name again, and a program does nothing", async () => { + using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-")); + using mind = await standInMind(); + const daemon = await daemonFor(mind, folder.path); + try { + using program = await connectDaemon({ file: join(folder.path, "daemon.json") }); + await program.provide("codex", bridge); + expect(mind.lent.get("itx.codex")!.connection).toBe(1); + + mind.refuse("the network is down"); + mind.drop(); + await vi.waitFor(async () => + expect((await program.status()).minds[0]).toMatchObject({ + state: "reconnecting", + lastFailure: "the network is down", + }), + ); + mind.refuse(""); + await vi.waitFor(() => expect(mind.lent.get("itx.codex")!.connection).toBe(2)); + expect(await mind.lent.get("itx.codex")!.target.deliverEvent({ type: "again" })).toBe( + "delivered again", + ); + expect(await program.itx().whoami()).toEqual({ path: "/" }); + } finally { + daemon.stop(); + } +}); + +test("before a sign-in ends the daemon makes the next connection and lends over it first, so a name is never without a lender", async () => { + using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-")); + using mind = await standInMind(); + let endsAt: number | undefined = Date.now() + 150; + const daemon = await daemonFor(mind, folder.path, { + // the first connection's sign-in ends soon; the next one's end is not known + endsAt: () => { + const ends = endsAt; + endsAt = undefined; + return ends; + }, + timing: { reconnectMs: 20, renewBeforeMs: 50, retireAfterMs: 20 }, + }); + try { + using program = await connectDaemon({ file: join(folder.path, "daemon.json") }); + await program.provide("codex", bridge); + const seen = new Set<number | undefined>(); + await vi.waitFor(() => { + seen.add(mind.lent.get("itx.codex")?.connection); + expect(mind.lent.get("itx.codex")!.connection).toBe(2); + }); + // never unlent on the way from the first connection to the second + expect(seen.has(undefined)).toBe(false); + expect((await program.status()).minds[0]!.state).toBe("connected"); + expect(await mind.lent.get("itx.codex")!.target.deliverEvent({ type: "after" })).toBe( + "delivered after", + ); + } finally { + daemon.stop(); + } +}); + +test("the port alone opens nothing: a wrong token is refused, and so is a browser's page", async () => { + using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-")); + using mind = await standInMind(); + const daemon = await daemonFor(mind, folder.path); + try { + const { port } = daemon.file; + const socket = new WebSocket(`ws://127.0.0.1:${port}/`); + const api = newWebSocketRpcSession<{ authenticate(token: string): { status(): unknown } }>( + socket as unknown as globalThis.WebSocket, + ); + await expect(api.authenticate("a guess").status()).rejects.toThrow( + "Not the iterate daemon's token", + ); + socket.close(); + + const page = new WebSocket(`ws://127.0.0.1:${port}/`, { origin: "https://example.com" }); + const refused = await new Promise<number | undefined>((resolve) => { + page.once("unexpected-response", (_request, response) => resolve(response.statusCode)); + page.once("open", () => resolve(undefined)); + page.on("error", () => {}); + }); + expect(refused).toBe(403); + } finally { + daemon.stop(); + } +}); + +test("a file that a dead daemon left is no daemon: its pid may be another process's, so only an answer counts, and a new daemon writes over it", async () => { + using folder = mkdtempDisposableSync(join(tmpdir(), "iterate-daemon-")); + using mind = await standInMind(); + const file = join(folder.path, "daemon.json"); + // a port that nothing listens on, and the pid of a process that runs (this test's parent) + const unused = new WebSocketServer({ port: 0, host: "127.0.0.1" }); + await new Promise((resolve) => unused.once("listening", resolve)); + const { port } = unused.address() as { port: number }; + await new Promise((resolve) => unused.close(resolve)); + writeFileSync( + file, + JSON.stringify({ + pid: process.ppid, + port, + token: "left-behind", + mind: "iterate.example.com", + version: "0.0.0-test", + startedAt: new Date().toISOString(), + }), + ); + expect(await runningDaemon(file)).toBe(null); + await expect(connectDaemon({ file })).rejects.toThrow("No iterate daemon runs here"); + + const daemon = await daemonFor(mind, folder.path); + try { + expect(await runningDaemon(file)).toMatchObject({ pid: process.pid, port: daemon.file.port }); + } finally { + daemon.stop(); + } +});
A core/lib/src/cli/daemon.ts
@@ -0,0 +1,449 @@ +// daemon.ts โ `iterate daemon`: ONE PROCESS ON A COMPUTER THAT HOLDS THE CONNECTION TO A MIND, and a +// server on localhost where every other local program reaches the mind through it. A bridge for a +// coding agent's CLI (Claude Code, Codex, agy, Grok, OpenCode), a desktop app or a script connects +// to `ws://127.0.0.1:<port>` over capnweb, and makes no connection to the mind of its own: +// +// provide(name, target) lends the program's own capability to the mind as `itx.<name>`, over +// every connection the daemon makes, until the program goes away +// itx() the mind's root context, over the daemon's connection +// status() the minds, their connections, the programs and their lends +// +// The same code on Linux and macOS: Node's `http` and `ws`, one file in the CLI's config folder +// (`daemon.json`: pid, port and the token), no unix socket and no service manager. A program +// finds the daemon by that file (daemon-client.ts `connectDaemon`). +// +// WHO MAY CONNECT: whoever can read `daemon.json` (mode 600: this computer's user), which is who +// can read the stored sign-in beside it. The port alone opens nothing: the session's first call is +// `authenticate(token)`, and a request that a browser's page made (it carries `Origin`) is refused +// before that. The daemon acts as the sign-in's person, so a program that connects does too. +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { rmSync } from "node:fs"; +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import { newWebSocketRpcSession, RpcTarget, type RpcStub } from "capnweb"; +import { WebSocketServer } from "ws"; +import type { MindConnection, MindItx } from "../node.ts"; +import { writePrivateJson } from "./config.ts"; +import { DAEMON_FILE, type DaemonFile, readDaemonFile, runningDaemon } from "./daemon-client.ts"; + +/** A capability's name: `itx.<name>`, dotted segments allowed (`beelink.codex`), as provide.ts. */ +const NAME = /^[a-zA-Z][a-zA-Z0-9]*(\.[a-zA-Z][a-zA-Z0-9]*)*$/; + +/** What `status()` answers. */ +export type DaemonStatus = { + pid: number; + port: number; + version: string; + mind: string; + startedAt: string; + minds: { + address: string; + state: "connecting" | "connected" | "reconnecting"; + since: string; + lastFailure?: string; + }[]; + clients: { id: number; name: string; pid?: number }[]; + lends: { mind: string; name: string; client: string; live: boolean }[]; +}; + +/** What a program gets after `authenticate`. */ +export interface DaemonSessionApi { + status(): DaemonStatus; + /** The root context of `mind` (the daemon's own mind when none is named), over the connection + * that is up now, waited for when none is. It lives as long as that connection: ask for it at + * each use and keep no copy, since the daemon replaces its connection before a sign-in ends. */ + itx(mind?: string): Promise<MindItx>; + /** Lend `target` to the mind as `itx.<name>`, now and over every later connection. The newest + * lend of a name wins. It ends when its answer is disposed of or this program's socket closes. */ + provide( + name: string, + target: RpcStub<RpcTarget>, + options?: { description?: string; mind?: string }, + ): Promise<Disposable>; +} + +/** The root of a local session: nothing but the way in. */ +export interface DaemonApi { + authenticate(token: string, client?: { name?: string; pid?: number }): DaemonSessionApi; +} + +/** How long a call waits for a connection to the mind before it fails. */ +const CONNECTION_WAIT_MS = 30_000; +/** How long a replaced connection stays open for the calls already on it (the mind closes it at + * the hour anyway). */ +const RETIRE_AFTER_MS = 30_000; +/** As provide.ts `renewBeforeMs`: under a minute, so that the stored sign-in counts as ending and + * is refreshed; by chance, so that two programs on one sign-in do not renew in the same moment. */ +const renewBeforeMs = () => 20_000 + Math.floor(Math.random() * 35_000); + +type Lend = { + key: string; + mind: string; + name: string; + description?: string; + target: RpcStub<RpcTarget>; + client: Client; + /** the mind's handle of this lend, for each connection it is lent over */ + handles: Map<MindConnection, Disposable>; +}; +type Client = { id: number; name: string; pid?: number; lends: Set<Lend> }; + +const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error)); +const quietly = (fn: () => void) => { + try { + fn(); + } catch { + // already gone: a stub of a closed connection, a file removed + } +}; + +export type Daemon = { + file: DaemonFile; + /** resolves when the daemon has stopped */ + stopped: Promise<void>; + stop(): void; +}; + +/** START THE DAEMON: listen on localhost, write `daemon.json`, connect to `mind`. It answers once + * the server listens. The connection to a mind is made in the background and made again for as + * long as the daemon runs (1 s, doubling, at most 60 s): a daemon that starts with no network, or + * before anyone signed in, comes up when it can. The daemon never signs in by itself. */ +export async function startDaemon(input: { + /** the default mind's address, as node.ts `addressOf` answers it */ + mind: string; + /** a connection to a mind, never one that asks a person to sign in */ + connect: (address: string) => Promise<MindConnection>; + /** when the sign-in of the connection made last ends, as epoch ms (provide.ts THE HANDOVER) */ + endsAt?: (address: string) => number | undefined; + /** a typed address as a mind's (node.ts `addressOf`), for a call that names a mind */ + addressOf: (typed: string) => string; + version: string; + /** 0, the default: any free port */ + port?: number; + file?: string; + log?: (line: string) => void; + /** a test's: the reconnect delays and the handover's timing */ + timing?: { reconnectMs?: number; renewBeforeMs?: number; retireAfterMs?: number }; +}): Promise<Daemon> { + const path = input.file || DAEMON_FILE; + const log = input.log || ((line) => console.error(`${new Date().toISOString()} ${line}`)); + // ONE DAEMON FOR A FILE. A file whose daemon no longer answers is a dead one's (a crash, a + // reboot: its pid may be another process's by now) and is written over. + const earlier = await runningDaemon(path); + if (earlier && earlier.pid !== process.pid) + throw new Error( + `An iterate daemon already runs here (pid ${earlier.pid}, port ${earlier.port}). Stop it first: iterate daemon stop.`, + ); + let stopping = false; + + // โโ minds โโ one lasting connection for each mind in use + type Link = { + address: string; + live: MindConnection | null; + state: "connecting" | "connected" | "reconnecting"; + since: number; + lastFailure?: string; + waiters: (() => void)[]; + }; + const links = new Map<string, Link>(); + const lends = new Map<string, Lend>(); + + const lendOver = async (lend: Lend, connection: MindConnection) => { + const handle = await connection.itx.provide( + `itx.${lend.name}`, + lend.target, + lend.description ? { description: lend.description } : undefined, + ); + // No `lendEnded()` is asked for: a call of it that still waits would hold the lend at the + // mind after its handle is disposed of, and a program that goes away must take its name along. + lend.handles.set(connection, handle); + }; + const endLend = (lend: Lend) => { + if (lends.get(lend.key) === lend) lends.delete(lend.key); + lend.client.lends.delete(lend); + for (const handle of lend.handles.values()) quietly(() => handle[Symbol.dispose]()); + lend.handles.clear(); + quietly(() => lend.target[Symbol.dispose]()); + log(`${lend.client.name} no longer lends itx.${lend.name} to ${lend.mind}`); + }; + + /** A connection with every lend of this mind lent over it. */ + const open = async (address: string) => { + const connection = await input.connect(address); + try { + for (const lend of lends.values()) + if (lend.mind === address) await lendOver(lend, connection); + } catch (error) { + connection[Symbol.dispose](); + throw error; + } + return { connection, endsAt: input.endsAt?.(address) }; + }; + const forget = (connection: MindConnection) => { + for (const lend of lends.values()) lend.handles.delete(connection); + quietly(() => connection[Symbol.dispose]()); + }; + + const linkOf = (mind?: string): Link => { + const address = mind ? input.addressOf(mind) : input.mind; + const known = links.get(address); + if (known) return known; + const link: Link = { address, live: null, state: "connecting", since: Date.now(), waiters: [] }; + links.set(address, link); + const setState = (state: Link["state"], said: string) => { + link.state = state; + link.since = Date.now(); + log(said); + }; + void (async () => { + for (let wait = input.timing?.reconnectMs ?? 1000; !stopping;) { + let upAt: number | undefined; + try { + let { connection, endsAt } = await open(address); + link.live = connection; + link.lastFailure = undefined; + upAt = Date.now(); + setState("connected", `connected to ${address}`); + for (const waiter of link.waiters.splice(0)) waiter(); + // THE HANDOVER (provide.ts): a while before the sign-in ends, the next connection is + // made and every name lent over it, and only then does the old one go. When the next + // one cannot be made, this one is kept until it closes. + for (;;) { + let timer: ReturnType<typeof setTimeout> | undefined; + const before = input.timing?.renewBeforeMs ?? renewBeforeMs(); + const why = await Promise.race([ + connection.closed, + ...(endsAt === undefined + ? [] + : [ + new Promise<"renew">((resolve) => { + timer = setTimeout( + () => resolve("renew"), + Math.max(endsAt! - Date.now() - before, 0), + ); + }), + ]), + ]); + clearTimeout(timer); + if (stopping) return; + if (why !== "renew") { + link.lastFailure = `${why.code}: ${why.reason || "connection closed"}`; + break; + } + const next = await open(address).catch((error: unknown) => { + log(`could not renew the connection to ${address}: ${messageOf(error)}`); + return null; + }); + if (!next) { + endsAt = undefined; + continue; + } + const old = connection; + ({ connection, endsAt } = next); + link.live = connection; + // the calls already on the old connection end on it + const retire = setTimeout( + () => forget(old), + input.timing?.retireAfterMs ?? RETIRE_AFTER_MS, + ); + retire.unref(); + log(`renewed the connection to ${address} before its sign-in ended`); + } + } catch (error) { + link.lastFailure = messageOf(error); + } + if (link.live) forget(link.live); + link.live = null; + if (stopping) return; + if (upAt !== undefined && Date.now() - upAt >= 60_000) + wait = input.timing?.reconnectMs ?? 1000; + setState( + "reconnecting", + `no connection to ${address} (${link.lastFailure}): the next try in ${wait / 1000} s`, + ); + await new Promise((resolve) => setTimeout(resolve, wait)); + wait = Math.min(60_000, wait * 2); + } + })(); + return link; + }; + + /** The connection of `link` that is up, waited for at most CONNECTION_WAIT_MS. */ + const connected = (link: Link): Promise<MindConnection> => { + if (link.live) return Promise.resolve(link.live); + return new Promise((resolve, reject) => { + const waiter = () => { + clearTimeout(timer); + resolve(link.live!); + }; + const timer = setTimeout(() => { + link.waiters = link.waiters.filter((other) => other !== waiter); + reject( + new Error( + `The iterate daemon has no connection to ${link.address}${link.lastFailure ? `: ${link.lastFailure}` : ""}`, + ), + ); + }, CONNECTION_WAIT_MS); + link.waiters.push(waiter); + }); + }; + + // โโ the local server โโ + const token = randomBytes(32).toString("base64url"); + const clients = new Set<Client>(); + let clientSeq = 0; + let file: DaemonFile; + + class Session extends RpcTarget implements DaemonSessionApi { + #client: Client; + constructor(client: Client) { + super(); + this.#client = client; + } + status(): DaemonStatus { + return { + pid: file.pid, + port: file.port, + version: file.version, + mind: file.mind, + startedAt: file.startedAt, + minds: [...links.values()].map((link) => ({ + address: link.address, + state: link.state, + since: new Date(link.since).toISOString(), + lastFailure: link.lastFailure, + })), + clients: [...clients].map(({ id, name, pid }) => ({ id, name, pid })), + lends: [...lends.values()].map((lend) => ({ + mind: lend.mind, + name: `itx.${lend.name}`, + client: lend.client.name, + live: lend.handles.size > 0, + })), + }; + } + async itx(mind?: string): Promise<MindItx> { + return (await connected(linkOf(mind))).itx.dup(); + } + async provide( + name: string, + target: RpcStub<RpcTarget>, + options?: { description?: string; mind?: string }, + ): Promise<Disposable> { + if (typeof name !== "string" || !NAME.test(name)) + throw new Error( + `${JSON.stringify(name)} is not a capability name: letters and digits starting with a letter, dotted segments allowed (codex, beelink.codex).`, + ); + const link = linkOf(options?.mind); + const key = `${link.address} ${name}`; + const earlier = lends.get(key); + if (earlier) endLend(earlier); // the newest lend of a name wins, as at the mind + const client = this.#client; + const lend: Lend = { + key, + mind: link.address, + name, + description: options?.description, + // the argument's stub ends with this call: the lend keeps its own + target: target.dup(), + client, + handles: new Map(), + }; + lends.set(key, lend); + client.lends.add(lend); + // with no connection now, the name is lent when the next one is made (`open`) + if (link.live) + await lendOver(lend, link.live).catch((error: unknown) => { + endLend(lend); + throw error; + }); + log(`${client.name} lends itx.${name} to ${link.address}`); + return new LendHandle(() => endLend(lend)); + } + } + class LendHandle extends RpcTarget { + #end: () => void; + constructor(end: () => void) { + super(); + this.#end = end; + } + [Symbol.dispose]() { + this.#end(); + } + } + class Root extends RpcTarget implements DaemonApi { + #client: Client; + constructor(client: Client) { + super(); + this.#client = client; + } + authenticate(given: string, client?: { name?: string; pid?: number }): Session { + const a = Buffer.from(String(given)); + const b = Buffer.from(token); + if (a.length !== b.length || !timingSafeEqual(a, b)) + throw new Error(`Not the iterate daemon's token: read it from ${path}.`); + if (typeof client?.name === "string") this.#client.name = client.name.slice(0, 100); + if (typeof client?.pid === "number") this.#client.pid = client.pid; + clients.add(this.#client); + log(`${this.#client.name} connected`); + return new Session(this.#client); + } + } + + const sockets = new WebSocketServer({ noServer: true }); + const server: Server = createServer((_request, response) => { + response.writeHead(426, { "content-type": "text/plain" }); + response.end("The iterate daemon: connect with a WebSocket (capnweb).\n"); + }); + server.on("upgrade", (request, socket, head) => { + // A browser sends `Origin` with every WebSocket it opens, and a page of any site can dial + // localhost: no page gets a session here. A local program sends none. + if (request.headers.origin !== undefined) { + socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"); + return; + } + sockets.handleUpgrade(request, socket, head, (webSocket) => { + const client: Client = { id: ++clientSeq, name: "unnamed", lends: new Set() }; + webSocket.on("error", () => {}); + webSocket.once("close", () => { + // a program that goes away takes its lends with it at once, on every mind + for (const lend of [...client.lends]) endLend(lend); + if (clients.delete(client)) log(`${client.name} disconnected`); + }); + // ws implements the DOM event/send/close interface consumed by capnweb. + newWebSocketRpcSession(webSocket as unknown as globalThis.WebSocket, new Root(client)); + }); + }); + await new Promise<void>((resolve, reject) => { + server.once("error", reject); + // 127.0.0.1 and nothing else: never a network's interface + server.listen(input.port ?? 0, "127.0.0.1", resolve); + }); + file = { + pid: process.pid, + port: (server.address() as AddressInfo).port, + token, + mind: input.mind, + version: input.version, + startedAt: new Date().toISOString(), + }; + writePrivateJson(path, file); + log(`the iterate daemon ${file.version} listens on 127.0.0.1:${file.port} for ${file.mind}`); + linkOf(); + + let markStopped = () => {}; + const stopped = new Promise<void>((resolve) => (markStopped = resolve)); + const stop = () => { + if (stopping) return; + stopping = true; + for (const lend of [...lends.values()]) endLend(lend); + for (const link of links.values()) if (link.live) quietly(() => link.live![Symbol.dispose]()); + for (const webSocket of sockets.clients) webSocket.terminate(); + server.close(); + // not another daemon's, which started after this one's file was lost + if (readDaemonFile(path)?.pid === process.pid) rmSync(path, { force: true }); + log("the iterate daemon stopped"); + markStopped(); + }; + return { file, stopped, stop }; +}
M core/lib/src/node.ts
@@ -39,6 +39,11 @@ /** What `iterate provide --json` prints, one per line: parse each line with it. */ export { ProvideState } from "./cli/provide-state.ts"; +/** A local program's connection to `iterate daemon`, which holds this computer's one connection + * to a mind (cli/daemon.ts): lend the mind a capability, and reach the mind's `itx`. */ +export { connectDaemon, type DaemonConnection } from "./cli/daemon-client.ts"; +export type { DaemonStatus } from "./cli/daemon.ts"; + /** Where a line for the person goes: stderr, so stdout stays a command's answer. */ const printToStderr = (line: string) => console.error(line);