iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / lib / src / cli / daemon.tsmain at 949894f

// 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 };
}