Skip to content

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

1.5 KB
Raw Blame
// A receive batch can carry hundreds of completed-result acknowledgments; each one used to rewrite and fsync the whole
// link state. A run of them is now saved once, before any other frame is taken and before the batch returns.
import { frameSchema, type Frame } from "./protocol.ts";

/** Takes each frame that parses, in order. `take` gets a save for an acknowledgment that changed work: it is only
 * counted, and the count is spent on save attempts (stopping at the first that works) before a frame that is not an
 * acknowledgment, after a frame that throws, and at the end. */
export function receiveFrames(frames: readonly unknown[], take: (frame: Frame, saveAcknowledgment: () => void) => void,
  save: () => void, log: (line: string) => void): void {
  let pending = 0;
  const queue = () => { pending += 1; };
  const flush = () => {
    const attempts = pending;
    pending = 0;
    for (let attempt = 0; attempt < attempts; attempt += 1) {
      try { save(); return; } catch (error) { log(`bot link: done failed (${String(error)})`); }
    }
  };
  try {
    for (const raw of frames) {
      const parsed = frameSchema.safeParse(raw);
      if (!parsed.success || parsed.data.t !== "done") flush();
      if (!parsed.success) { log("bot link: a frame that did not parse was dropped"); continue; }
      try { take(parsed.data, queue); } catch (error) {
        flush();
        log(`bot link: ${parsed.data.t} failed (${String(error)})`);
      }
    }
  } finally { flush(); }
}