Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

19.5 KB
Raw Blame
// A computer's end of the link (server/bot-link/link.ts): one exchange after another with its Cloud, each held open
// there until it has something to say, so both directions travel over requests this computer makes. It runs in the
// server, so the link holds with the app's window closed for as long as the computer is awake.
//
// A request that fails starts a new session after a wait that doubles up to a minute: each side then sends again whatever
// the other has not acknowledged. The Cloud's answer that it sleeps stops the asking until this computer has work for it
// or the app says the Cloud is awake (`start`), since any request would start a sleeping Cloud; the app looks every
// minute and never asks the Cloud itself to find out.
//
// This server starting parks the link too, whatever it knew of the Cloud before: it asks nothing until the app says the
// Cloud is awake, and an "awake" the app heard before the link parked (`heardAt`) is stale and starts nothing, since the
// Admin's word lags the Cloud going to sleep and any request would start it again.
//
// Work a person waits on (a hand-off or room turn from a person's own line: `onWanted(true)`) may wake a parked Cloud:
// the exchanges that follow are not marked background until one is answered, so the Cloud counts them as use and answers
// them even if it has not yet noticed it was woken. Such a wake is bounded: WAKE_TRIES exchanges within WAKE_MS, and
// WAKES_PER_HOUR wakes an hour; past those the link stays parked and wakes it by itself once an hour has passed since the
// oldest (the bot is told when), and once a wake gets no answer it stays parked until new work or the app's "awake".
// Work no person waits on (a routine's, a scheduled run's) never wakes it: it waits, parked, until the Cloud is awake for
// another reason (the app's "awake"), and is given up after a while (away.ts). Everything else (directory news, idle
// polls) stays background and is never sent while parked, so it never wakes the Cloud or keeps it awake. An answer to a
// foreground exchange is the Cloud's own word that it is awake (`answeredAt`): the app's "asleep" heard before it is stale
// and parks nothing, and an "asleep" or "awake" that does not say when the app heard it changes nothing. (A background
// answer proves less: a Cloud the Admin is putting to sleep still answers until it stops, and the next poll would start it.)
import { createWriteStream, openAsBlob, rmSync } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";

import type { BotLink, EndedLink, FileTransfer } from "./link.ts";
import { FILE_PATH, HOLD_MS, LEVEL_HEADER, PROTOCOL_LEVEL, SYNC_PATH, levelOf, syncAnswer, type FileWay, type Frame } from "./protocol.ts";

const FIRST_RETRY_MS = 1_000;
const MAX_RETRY_MS = 60_000;
/** What the Cloud marks a held answer with while it goes to sleep (server/cloud-power.ts). */
const POWER_HEADER = "x-omb-cloud-power";
const BACKGROUND_HEADER = "x-omb-background";
/** One file may take this long to cross. */
const FILE_MS = 10 * 60_000;
/** A wake for work a person waits on: this long and this many exchanges at most (a stopped Cloud takes about 20 s to
 * start), and this many wakes in any hour. */
export const WAKE_MS = 150_000, WAKE_TRIES = 6, WAKES_PER_HOUR = 3;
const HOUR_MS = 60 * 60_000;
export const WAKE_RECHECK_MS = 60_000;

export interface DialerOptions {
  link: BotLink;
  fetch?: typeof fetch;
  log?(line: string): void;
  holdMs?: number;
  firstRetryMs?: number;
  /** What this computer says its version reads; a test stands in for an older app with it. */
  level?: number;
  now?: () => number;
  /** How often a person's work waiting for the hour's wakes to allow another looks again (WAKE_RECHECK_MS). */
  recheckMs?: number;
}

export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, holdMs = HOLD_MS, firstRetryMs = FIRST_RETRY_MS, level = PROTOCOL_LEVEL, now = Date.now, recheckMs = WAKE_RECHECK_MS }: DialerOptions) {
  let running = false, stopped = true, asleep = false, needsPairing = false;
  /** `wake`: work a person waits on is waking the Cloud until `wakeUntil` or WAKE_TRIES exchanges (`wakeTries`), so
   * exchanges are not background until one is answered; `wakes`: when each wake of the last hour began. `provedAt`: when
   * the Cloud last answered a foreground exchange since the link last parked (its own word that it is awake); `staleSaid`: the
   * app's last "asleep" that was older, so it is logged once. */
  let wake = false, wakeUntil = 0, wakeTries = 0, provedAt = -Infinity, staleSaid: number | undefined | null = null;
  /** When the link last parked (this computer's clock): an app's "awake" heard before it is stale. `cloudAsleepAt`: when the
   * Cloud itself last answered that it sleeps, which the app holds as asleep (cloud-power.mjs `hold`), as Files and lending do. */
  let parkedAt = -Infinity, cloudAsleepAt = -Infinity;
  const wakes: number[] = [];
  let session = "", ack = 0, fresh = true, retryMs = firstRetryMs;
  let active: AbortController | null = null, held: AbortController | null = null;
  let wakeUp: (() => void) | null = null;
  const pause = (ms: number) => new Promise<void>((resolve) => {
    const timer = setTimeout(() => { wakeUp = null; resolve(); }, ms);
    timer.unref?.();
    wakeUp = () => { clearTimeout(timer); wakeUp = null; resolve(); };
  });
  const carriesWork = (frames: readonly { frame: Frame }[]) => frames.some(({ frame }) => frame.t === "handoff" || frame.t === "result" || frame.t === "cancel");

  /** A file's bytes, over requests of this computer's: put before the frame that names it, got after one that does. An
   * answer in the 400s says the Cloud will not take or does not have it (`gone`); anything else is tried again. */
  const fileUrl = (origin: string, id: string, way: FileWay, index: number, name: string, more: Record<string, string> = {}) => `${origin}${FILE_PATH}?${new URLSearchParams({ id, way, index: String(index), name, ...more })}`;
  const refusedFile = async (response: Response) => {
    const told = await response.json().then((answer) => { const error = (answer as { error?: unknown } | null)?.error; return typeof error === "string" ? error : ""; }, () => "");
    return Object.assign(new Error(told || `the Cloud answered ${response.status}`), { gone: response.status >= 400 && response.status < 500 && ![401, 403, 408, 429].includes(response.status) });
  };
  const cloud = () => { const target = link.dial(); if (!target) throw new Error("not linked"); return { ...target, headers: { authorization: `Bearer ${target.token}`, origin: target.origin } }; };
  const transfer: FileTransfer = {
    async holds(id, way, index, file) {
      const target = cloud();
      const response = await fetchImpl(fileUrl(target.origin, id, way, index, file.name, { probe: "1", bytes: String(file.bytes) }), { redirect: "error", signal: AbortSignal.timeout(30_000), headers: target.headers });
      if (!response.ok) throw await refusedFile(response);
      return (await response.json() as { have?: unknown }).have === true;
    },
    async push(id, way, index, file) {
      const target = cloud();
      let body: Blob;
      try {
        // Node 24.0 openAsBlob() loses missing-file error codes.
        await stat(file.path);
        body = await openAsBlob(file.path);
      } catch (error) {
        if (typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) throw Object.assign(error, { gone: true });
        throw error;
      }
      const response = await fetchImpl(fileUrl(target.origin, id, way, index, file.name), { method: "PUT", redirect: "error", signal: AbortSignal.timeout(FILE_MS),
        headers: { ...target.headers, "content-type": "application/octet-stream" }, body });
      if (!response.ok) throw await refusedFile(response);
      await response.body?.cancel();
    },
    async pull(id, way, index, meta, to) {
      const target = cloud();
      const response = await fetchImpl(fileUrl(target.origin, id, way, index, meta.name), { redirect: "error", signal: AbortSignal.timeout(FILE_MS), headers: target.headers });
      if (!response.ok || !response.body) throw await refusedFile(response);
      // No more than the frame said: a file that turns out larger is not kept.
      let taken = 0, over = false;
      const capped = new Transform({ transform(chunk: Buffer, _encoding, done) { taken += chunk.length; over = taken > meta.bytes; done(over ? new Error("too large") : null, chunk); } });
      try {
        await pipeline(Readable.fromWeb(response.body as import("node:stream/web").ReadableStream), capped, createWriteStream(to, { mode: 0o600 }));
      } catch (error) {
        rmSync(to, { force: true });
        throw over ? Object.assign(new Error(`${meta.name} is larger than it was said to be`), { gone: true }) : error;
      }
      if (taken !== meta.bytes) { rmSync(to, { force: true }); throw new Error(`${meta.name} did not arrive whole`); }
    },
  };
  link.setTransfer(transfer);
  const stopListening = link.onOutgoing(() => { held?.abort(); });
  /** The wake had its time or its tries without an answer. */
  const wakeOver = () => wake && (now() >= wakeUntil || wakeTries >= WAKE_TRIES);
  const endWake = (peer: string | null) => { if (!wake) return; wake = false; if (peer) link.setWaking(peer, false); };
  /** A person's work that found the wakes of the last hour used up: it is tried again by itself once the oldest is an hour old. */
  let wakeAgain: NodeJS.Timeout | null = null;
  const wanted = (person: boolean): void => {
    if (stopped) return;
    if (wake && !wakeOver()) { wakeUp?.(); return; }
    const peer = link.cloudPeer(), at = now();
    while (wakes.length && at - wakes[0]! >= HOUR_MS) wakes.shift();
    if (person && asleep && peer && !needsPairing && link.dial()) {
      if (wakes.length < WAKES_PER_HOUR) {
        wakes.push(at);
        wake = true; wakeUntil = at + WAKE_MS; wakeTries = 0;
        link.wakeLater?.(peer, 0);
        link.setWaking(peer, true);
      } else if (!wakeAgain) waitForWake(peer, at);
    }
    // Background work, or a person's past the wakes an hour allows (tried again as above): a parked link stays parked; it
    // goes with the next "awake".
    if (asleep && !wake) return;
    asleep = false; retryMs = firstRetryMs;
    wakeUp?.();
  };
  /** The wakes of the last hour are used up: the bot is told when, and it is looked at again (at most every `recheckMs`,
   * so a clock that moves on is noticed) until a wake is allowed, while a person's work for the Cloud still waits. */
  function waitForWake(peer: string, at: number): void {
    const ms = wakes[0]! + HOUR_MS - at + 1_000;
    link.wakeLater?.(peer, ms);
    wakeAgain = setTimeout(() => {
      wakeAgain = null;
      if (stopped || !asleep || !link.personWaiting?.(peer)) { link.wakeLater?.(peer, 0); return; }
      const now2 = now();
      while (wakes.length && now2 - wakes[0]! >= HOUR_MS) wakes.shift();
      if (wakes.length < WAKES_PER_HOUR) wanted(true); else waitForWake(peer, now2);
    }, Math.min(ms, recheckMs));
    wakeAgain.unref?.();
  }
  const stopWanted = link.onWanted(wanted);
  /** The Cloud answered that it sleeps, the app's word parks the link, or a wake got no answer: nothing asks it until
   * there is new work for it or the app says it is awake. */
  const park = (peer: string | null) => {
    asleep = true; fresh = true; provedAt = -Infinity; parkedAt = now();
    endWake(peer);
    link.setSleeps(true);
    if (peer) link.setOnline(peer, false);
  };

  async function exchange(target: { origin: string; token: string }, peer: string): Promise<void> {
    // A new session takes everything the Cloud sends again from the start: a Cloud that ended this link and paired it again
    // numbers its frames from one again, and a count kept from before would pass over its hello.
    if (fresh) { link.sessionStarted(peer); ack = 0; }
    const sending = link.outgoing(peer, 0);
    const controller = new AbortController();
    active = controller;
    const timeout = setTimeout(() => controller.abort(), holdMs + 15_000);
    timeout.unref?.();
    const wait = sending.length > 0 || fresh ? 0 : holdMs;
    if (wait > 0) held = controller;
    const foreground = wake || carriesWork(sending);
    if (wake) wakeTries += 1;
    try {
      const response = await fetchImpl(`${target.origin}${SYNC_PATH}`, {
        method: "POST", redirect: "error", cache: "no-store", signal: controller.signal,
        headers: { "content-type": "application/json", accept: "application/json", authorization: `Bearer ${target.token}`, origin: target.origin, [LEVEL_HEADER]: String(level),
          ...(foreground ? {} : { [BACKGROUND_HEADER]: "1" }) },
        body: JSON.stringify({ fresh, ack, frames: sending.map((entry) => entry.frame), wait }),
      });
      controller.signal.throwIfAborted();
      if (response.status === 503 && response.headers.get(POWER_HEADER) === "asleep") {
        await response.body?.cancel();
        park(peer);
        cloudAsleepAt = parkedAt;
        return;
      }
      if (response.status === 401 || response.status === 403) {
        await response.body?.cancel();
        needsPairing = true;
        endWake(peer);
        link.setOnline(peer, false);
        return;
      }
      if (!response.ok) { await response.body?.cancel(); throw new Error(`the Cloud answered ${response.status}`); }
      const data: unknown = await response.json();
      controller.signal.throwIfAborted();
      const answer = syncAnswer.safeParse(data);
      if (!answer.success) throw new Error("the Cloud's answer did not parse");
      if (foreground) { provedAt = now(); wake = false; }
      link.outgoing(peer, sending.at(-1)?.seq ?? 0);
      if (answer.data.session !== session) {
        const restarted = session !== "";
        session = answer.data.session; ack = 0;
        if (restarted && !fresh) { fresh = true; return; }
      }
      fresh = false; retryMs = firstRetryMs;
      link.setOnline(peer, true);
      link.setLevel(peer, levelOf(response.headers.get(LEVEL_HEADER)));
      const news = answer.data.frames.filter((entry) => entry.seq > ack);
      link.receive(peer, news.map((entry) => entry.frame));
      ack = Math.max(ack, ...news.map((entry) => entry.seq));
    } catch (error) {
      if (held === controller && controller.signal.aborted && !stopped && !asleep && link.hasOutgoing(peer)) return;
      throw error;
    } finally {
      clearTimeout(timeout);
      if (active === controller) active = null;
      if (held === controller) held = null;
    }
  }

  async function loop(): Promise<void> {
    if (running) return;
    running = true;
    try {
      while (!stopped) {
        const target = link.dial(), peer = link.cloudPeer();
        if (!target || !peer || needsPairing) break;
        if (asleep) { await pause(24 * 60 * 60_000); continue; }
        if (wakeOver()) { park(peer); continue; }
        try { await exchange(target, peer); } catch (error) {
          if (stopped) break;
          link.setOnline(peer, false);
          // The Cloud no longer answers, so its last answer proves nothing about now: the app's word governs again.
          fresh = true; provedAt = -Infinity;
          if (wakeOver()) {
            log("bot link: the Cloud did not answer while it was woken for work; it is left asleep until there is new work or the app says it is awake");
            park(peer);
            continue;
          }
          if (!asleep) log(`bot link: the Cloud could not be reached (${error instanceof Error ? error.message : String(error)}); trying again in ${Math.round(retryMs / 1000)} s`);
          await pause(retryMs * (0.75 + Math.random() / 2));
          retryMs = Math.min(retryMs * 2, MAX_RETRY_MS);
        }
      }
    } finally { running = false; }
  }

  /** One request that says the link is over. True when the Cloud took it, or no longer knows the link. */
  async function bye(ended: Pick<EndedLink, "origin" | "token">): Promise<boolean> {
    try {
      const response = await fetchImpl(`${ended.origin}${SYNC_PATH}`, { method: "POST", redirect: "error", signal: AbortSignal.timeout(5_000),
        headers: { "content-type": "application/json", authorization: `Bearer ${ended.token}`, origin: ended.origin, [BACKGROUND_HEADER]: "1" },
        body: JSON.stringify({ ack: 0, frames: [{ t: "bye" } satisfies Frame], wait: 0 }) });
      await response.body?.cancel();
      return response.ok || response.status === 401 || response.status === 403;
    } catch { return false; }
  }

  return {
    /** Starts asking, or asks again at once: after turning on, after pairing again, or when the app says the Cloud is
     * awake. `gentle`: this server just started, so the Cloud is left alone until the app says it is awake or there is
     * work for it (it may have gone to sleep, or stopped, since this server last asked). `heardAt`: when the app heard the
     * Admin say it is awake (this computer's clock); a word heard before the link parked starts nothing. */
    start({ gentle = false, heardAt }: { gentle?: boolean; heardAt?: number } = {}): void {
      if (!stopped && asleep && heardAt !== undefined && heardAt <= parkedAt) {
        log("bot link: the app says the Cloud is awake, but heard it before the Cloud went to sleep; the link stays parked");
        return;
      }
      stopped = false; asleep = gentle; needsPairing = false; fresh = true; retryMs = firstRetryMs;
      if (gentle) parkedAt = now();
      endWake(link.cloudPeer());
      wakeUp?.();
      void loop();
    },
    /** The app says the Cloud sleeps now: nothing asks it until there is work for it or it is awake again. `heardAt`: when
     * the app first heard that word (this computer's clock). It parks nothing while work a person waits on is waking the
     * Cloud (within the wake's bounds), or when the Cloud has answered such work since: the Admin's word lags the Cloud's. */
    sleep(heardAt?: number): void {
      if (stopped) return;
      if (heardAt === undefined) { log("bot link: the app says the Cloud sleeps without saying when it heard it; the link is left as it is"); return; }
      if ((wake && !wakeOver()) || (heardAt !== undefined && heardAt <= provedAt)) {
        if (staleSaid !== heardAt) log(`bot link: the app says the Cloud sleeps, but it has answered since${wake ? " (waking it for work)" : ""}; the link stays up`);
        staleSaid = heardAt;
        return;
      }
      park(link.cloudPeer());
      active?.abort();
    },
    /** Stops asking. `bye`: the link was turned off here, so the Cloud is told once, unless it sleeps. True when it knows. */
    async stop({ bye: tell = false }: { bye?: boolean } = {}): Promise<boolean> {
      const target = link.dial(), sleeping = asleep;
      stopped = true;
      endWake(link.cloudPeer());
      active?.abort();
      wakeUp?.();
      return tell && target !== null && !sleeping ? bye(target) : false;
    },
    /** The app says this Cloud is awake: links to it that ended while it could not be told are ended there now. */
    async tellEnded(origin: string): Promise<void> {
      const told: string[] = [];
      for (const ended of link.ended()) if (ended.origin === origin && await bye(ended)) told.push(ended.token);
      if (told.length) link.forgetEnded(told);
    },
    state: () => ({ running: !stopped, asleep, needsPairing, ...(asleep && Number.isFinite(parkedAt) ? { parkedAt } : {}), ...(Number.isFinite(cloudAsleepAt) ? { cloudAsleepAt } : {}),
      ...(Number.isFinite(provedAt) ? { answeredAt: provedAt } : {}) }),
    close(): void { stopped = true; if (wakeAgain) clearTimeout(wakeAgain); active?.abort(); wakeUp?.(); stopListening(); stopWanted(); link.setTransfer(null); },
  };
}