Skip to content

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

4.3 KB
Raw Blame
import type { LiveCodexProgressFrame } from "../shared/wire.ts";

export interface SseFanoutClient {
  res: {
    write(chunk: string): boolean;
    writableLength: number;
    once(event: "drain", listener: () => void): unknown;
  };
  backpressured: boolean;
  /** The client's idempotent lifecycle owner: it leaves the fanout and stops the heartbeat before ending the response. */
  close(): void;
}

/** Past this, cut the client loose; its EventSource reconnects and replays via Last-Event-ID. */
export const SSE_MAX_BUFFERED_BYTES = 4 * 1024 * 1024;

export type SseFanoutOutcome = "sent" | "dropped" | "disconnected";

/** Only screen captures are skipped while backpressured; durable events are always written, or the client is disconnected to replay them. */
export function deliverSseFrame(client: SseFanoutClient, kind: string, frame: string): SseFanoutOutcome {
  if (client.res.writableLength > SSE_MAX_BUFFERED_BYTES) {
    client.close();
    return "disconnected";
  }
  if (client.backpressured && kind === "screen") return "dropped";
  try {
    if (!client.res.write(frame) && !client.backpressured) {
      // write() returns false past the 16 KB highWaterMark, which one screen frame clears: it means "not drained yet", and without the drain listener the flag latches forever.
      client.backpressured = true;
      client.res.once("drain", () => {
        client.backpressured = false;
      });
    }
    return "sent";
  } catch {
    return "disconnected";
  }
}

type LiveProgressClient = { send(kind: string, json: string): boolean; admin: boolean; appWindow: boolean; sessionId?: string; pushKey?: string };

/** Only the local app streams receive this frame. Status is ephemeral and has no replay cursor. */
export function deliverLiveCodexProgress(clients: Iterable<LiveProgressClient>, progress: LiveCodexProgressFrame): void {
  const json = JSON.stringify(progress);
  for (const client of clients) {
    if (!client.admin || !client.appWindow || client.sessionId || client.pushKey) continue;
    client.send(progress.kind, json);
  }
}

type HeartbeatBucket = {
  timer: ReturnType<typeof setInterval>;
  ticks: Set<() => void>;
};

const heartbeatBuckets = new Map<number, HeartbeatBucket>();

/** Shares one unref'd interval across all subscribers using the same cadence, starting lazily and clearing once empty. */
export function subscribeHeartbeat(everyMs: number, tick: () => void): () => void {
  let bucket = heartbeatBuckets.get(everyMs);
  if (!bucket) {
    const ticks = new Set<() => void>();
    const timer = setInterval(() => {
      for (const run of Array.from(ticks)) {
        if (!ticks.has(run)) continue;
        try {
          run();
        } catch {}
      }
    }, everyMs);
    timer.unref?.();
    bucket = { timer, ticks };
    heartbeatBuckets.set(everyMs, bucket);
  }
  bucket.ticks.add(tick);
  let active = true;
  return () => {
    if (!active) return;
    active = false;
    bucket.ticks.delete(tick);
    if (bucket.ticks.size === 0) {
      clearInterval(bucket.timer);
      if (heartbeatBuckets.get(everyMs) === bucket) heartbeatBuckets.delete(everyMs);
    }
  };
}

export interface SseHeartbeatStream {
  write(chunk: string): boolean;
  end(): void;
  writableEnded: boolean;
  destroyed: boolean;
  on(event: "error", listener: (error: Error) => void): unknown;
}

const SSE_HEARTBEAT_FRAME = `: keepalive\n\ndata: ${JSON.stringify({ kind: "ping" })}\n\n`;

/** Heartbeats `res` while `live()` holds. The returned close stops the heartbeat and runs `onClose` once, before the response ends; it runs by itself when the stream ends, errors or stops being live. */
export function openSseHeartbeat(res: SseHeartbeatStream, options: { everyMs: number; live: () => boolean; onClose: () => void }): () => void {
  let open = true;
  let stopHeartbeat: (() => void) | undefined;
  const close = () => {
    if (!open) return;
    open = false;
    stopHeartbeat?.();
    options.onClose();
    if (!res.writableEnded && !res.destroyed) res.end();
  };
  stopHeartbeat = subscribeHeartbeat(options.everyMs, () => {
    if (res.writableEnded || res.destroyed || !options.live()) return close();
    try {
      res.write(SSE_HEARTBEAT_FRAME);
    } catch {
      close();
    }
  });
  // Node reports a failed write, such as one after end, as an asynchronous 'error' event on the response; unhandled, it exits the process.
  res.on("error", close);
  return close;
}