Skip to content

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

14.9 KB
Raw Blame
// Fan-in event bus — port of upstream's ProviderService fan-in + EventNdjsonLogger tee, minus Effect.
import { appendFile } from "node:fs/promises";
import { join } from "node:path";

import { EVENTS_DIR } from "../config.ts";
import { flushNativeLog } from "../drivers/native.ts";
import { redactSecrets } from "../redact.ts";
import { batchSaves } from "../save-batch.ts";
import { capThreadLog, currentThreadLogCap } from "../thread-log-rotation.ts";
import { newId, type ProviderAdapter, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener } from "../contracts.ts";
import { LiveSteps } from "./live-steps.ts";
import { ProgressGate } from "./progress-gate.ts";
import { TextItems } from "./text-items.ts";

const INCOMPLETE_LOG_MESSAGE =
  "Canonical event history is incomplete: OpenMausBot could not write one or more events to disk. Live updates will continue.";

const DROPPED_EVENT_MESSAGE =
  "Canonical event history is incomplete: OpenMausBot dropped events because the event log queue was full; no disk write was attempted for them. Live updates will continue.";

const DELTA_MERGE_MS = 50;

/** Lines per drain batch, queued events and bytes before new ones are dropped, and threads appended at once. */
const EVENT_LOG_DEFAULTS = { batchLines: 64, queueEvents: 4096, queueBytes: 32 * 1024 * 1024, drainThreads: 8 };
/** A cap on each setting, so a mistyped size cannot switch the queue's memory guard off altogether. */
const EVENT_LOG_MAX = { batchLines: 4_096, queueEvents: 1_000_000, queueBytes: 1024 * 1024 * 1024, drainThreads: 64 };

export interface EventLogLimits {
  batchLines: number;
  queueEvents: number;
  queueBytes: number;
  drainThreads: number;
}

export interface EventLogDrops {
  events: number;
  bytes: number;
}

/** A zero, negative or non-numeric setting falls back to its default rather than stopping the log. */
export function eventLogLimits(env: Record<string, string | undefined> = process.env): EventLogLimits {
  const positive = (raw: string | undefined, fallback: number, max: number) => {
    const value = Number(raw);
    return Number.isInteger(value) && value > 0 ? Math.min(value, max) : fallback;
  };
  return {
    batchLines: positive(env.OMB_EVENT_LOG_BATCH_LINES, EVENT_LOG_DEFAULTS.batchLines, EVENT_LOG_MAX.batchLines),
    queueEvents: positive(env.OMB_EVENT_LOG_QUEUE_EVENTS, EVENT_LOG_DEFAULTS.queueEvents, EVENT_LOG_MAX.queueEvents),
    queueBytes: positive(env.OMB_EVENT_LOG_QUEUE_BYTES, EVENT_LOG_DEFAULTS.queueBytes, EVENT_LOG_MAX.queueBytes),
    drainThreads: positive(env.OMB_EVENT_LOG_DRAIN_THREADS, EVENT_LOG_DEFAULTS.drainThreads, EVENT_LOG_MAX.drainThreads),
  };
}

export type EventLogAppend = (
  path: string,
  data: string,
  options?: { mode?: number },
) => void | Promise<void>;

const defaultAppend: EventLogAppend = (path, data, options) => appendFile(path, data, options);

type QueuedLog = { event: RuntimeEvent; line: string; bytes: number };

type TextDelta = Extract<RuntimeEvent, { type: "content.delta" }>;

function sameStream(a: TextDelta, b: TextDelta): boolean {
  return a.provider === b.provider && a.providerInstanceId === b.providerInstanceId && a.turnId === b.turnId &&
    a.itemId === b.itemId && a.streamKind === b.streamKind && a.synthetic === b.synthetic;
}

/** What changes the chat's status line, and so makes a waiting status report stale; a heartbeat or a token count does not. */
const STATUS_LINE_EVENTS = new Set<RuntimeEvent["type"]>(["turn.started", "content.delta", "item.started", "item.completed", "request.opened"]);

function isTerminalEvent(event: RuntimeEvent): boolean {
  if (event.type === "turn.completed" || event.type === "cap.exhausted" || event.type === "session.exited") {
    return true;
  }
  return event.type === "runtime.error" && event.terminal === true;
}

export class EventBus {
  private listeners = new Set<RuntimeEventListener>();
  private unsubscribes = new Map<string, () => void>();
  private pendingLogWarnings = new Map<string, RuntimeEvent>();
  private pendingText = new Map<string, { event: TextDelta; timer: ReturnType<typeof setTimeout> }>();
  private readonly appendLog: EventLogAppend;
  private readonly limits: EventLogLimits;
  private readonly dropped: EventLogDrops = { events: 0, bytes: 0 };
  private queued: QueuedLog[] = [];
  private queuedBytes = 0;
  private pumping = false;
  private kickScheduled = false;
  private readonly drainWaiters: Array<() => void> = [];
  private readonly queuedLogWarnings = new Map<string, RuntimeEvent>();
  // A status-line report is live only: delivered to listeners, never queued for the log.
  private readonly progress = new ProgressGate((event) => {
    if (this.pendingText.has(event.threadId)) this.flushThread(event.threadId);
    this.deliver(event);
  });
  private readonly adapters = new Map<string, ProviderAdapter>();
  private readonly steps = new LiveSteps({
    offer: (event) => this.progress.offer(event),
    enginePid: (event) => this.adapters.get(event.providerInstanceId ?? "")?.enginePid?.(event.threadId),
  });

  private readonly gate?: (event: RuntimeEvent) => boolean;
  private readonly textItems = new TextItems();

  /** `gate` sees each adapter event first; true means it took the event and publishes what it chooses. */
  constructor(appendLog: EventLogAppend = defaultAppend, gate?: (event: RuntimeEvent) => boolean, limits: EventLogLimits = eventLogLimits()) {
    this.appendLog = appendLog;
    this.gate = gate;
    // A batch or worker count below one would leave drain() unable to empty the queue.
    this.limits = {
      batchLines: Math.min(EVENT_LOG_MAX.batchLines, Math.max(1, Math.floor(limits.batchLines) || 1)),
      queueEvents: Math.min(EVENT_LOG_MAX.queueEvents, Math.max(1, Math.floor(limits.queueEvents) || 1)),
      queueBytes: Math.min(EVENT_LOG_MAX.queueBytes, Math.max(1, Math.floor(limits.queueBytes) || 1)),
      drainThreads: Math.min(EVENT_LOG_MAX.drainThreads, Math.max(1, Math.floor(limits.drainThreads) || 1)),
    };
  }

  /** Events the queue's bounds refused since this bus started, and their size. Never counted as disk failures. */
  dropStats(): EventLogDrops {
    return { ...this.dropped };
  }

  attach(instances: ProviderInstance[]) {
    for (const instance of instances) {
      this.detach(instance.instanceId);
      this.adapters.set(instance.instanceId, instance.adapter);
      const unsub = instance.adapter.onEvent((event) => {
        // An adapter may only emit events for its own driver kind.
        if (event.provider !== instance.driverKind) {
          console.error(`bus: dropped cross-driver event from ${instance.instanceId}`);
          return;
        }
        const stamped = { ...event, providerInstanceId: instance.instanceId };
        if (!this.gate?.(stamped)) this.publish(stamped);
      });
      this.unsubscribes.set(instance.instanceId, unsub);
    }
  }

  publish(unstamped: RuntimeEvent) {
    // Reply text is keyed by its message from here on: the delta merge below and every listener see the same id.
    const raw = this.textItems.stamp(unstamped);
    if (!raw) return;
    if (raw.type === "turn.progress") {
      this.progress.offer(this.steps.progress(raw));
      return;
    }
    if (raw.type === "item.output") {
      this.steps.output(raw);
      return;
    }
    const event = this.steps.observe(raw, isTerminalEvent(raw));
    if (STATUS_LINE_EVENTS.has(event.type) || isTerminalEvent(event)) this.progress.supersede(event.threadId, isTerminalEvent(event));
    const pending = this.pendingText.get(event.threadId);
    if (event.type === "content.delta") {
      if (pending && sameStream(pending.event, event)) {
        pending.event = { ...pending.event, delta: pending.event.delta + event.delta };
        return;
      }
      if (pending) this.flushThread(event.threadId);
      const timer = setTimeout(() => this.flushThread(event.threadId), DELTA_MERGE_MS);
      timer.unref?.();
      this.pendingText.set(event.threadId, { event, timer });
      return;
    }
    if (pending) this.flushThread(event.threadId);
    this.write(event);
    this.steps.announce(event);
  }

  flush(): Promise<void> {
    for (const threadId of Array.from(this.pendingText.keys())) this.flushThread(threadId);
    return this.flushDisk();
  }

  async flushWithin(ms: number): Promise<boolean> {
    let timer: ReturnType<typeof setTimeout> | undefined;
    const timeout = new Promise<false>((resolve) => {
      // Not unref'd: the caller is waiting on this answer before it exits.
      timer = setTimeout(() => resolve(false), ms);
    });
    try {
      return await Promise.race([this.flush().then(() => this.pendingLogWarnings.size === 0), timeout]);
    } finally {
      clearTimeout(timer);
    }
  }

  private flushThread(threadId: string) {
    const pending = this.pendingText.get(threadId);
    if (!pending) return;
    // Gone from the map before delivery: a listener may publish on this thread.
    this.pendingText.delete(threadId);
    clearTimeout(pending.timer);
    this.write(pending.event);
  }

  private write(event: RuntimeEvent) {
    // Queue first, then deliver: a listener publishing during delivery queues after this, so the log keeps publication order.
    this.enqueue(event);
    this.deliver(event);
    if (!isTerminalEvent(event)) return;
    flushNativeLog(event.threadId);
    void this.flushDisk();
  }

  private enqueue(event: RuntimeEvent) {
    // People paste this log into bug reports: scrub credential-shaped content as the native tee does.
    const line = JSON.stringify(redactSecrets(event));
    const bytes = Buffer.byteLength(line);
    const overCount = this.queued.length >= this.limits.queueEvents;
    const overBytes = this.queued.length > 0 && this.queuedBytes + bytes > this.limits.queueBytes;
    if ((overCount || overBytes) && !isTerminalEvent(event)) {
      this.dropped.events += 1;
      this.dropped.bytes += bytes;
      if (!this.queuedLogWarnings.has(event.threadId)) {
        const warning = this.logWarning(event, DROPPED_EVENT_MESSAGE);
        this.queuedLogWarnings.set(event.threadId, warning);
        // Queued before delivery: listeners may publish synchronously.
        this.push(warning);
        console.error(`bus: canonical event log queue is full; dropped ${this.dropped.events} events so far`);
        this.deliver(warning);
      }
      return;
    }
    this.queuedLogWarnings.delete(event.threadId);
    this.push(event, line, bytes);
  }

  private push(event: RuntimeEvent, line = JSON.stringify(redactSecrets(event)), bytes = Buffer.byteLength(line)) {
    this.queued.push({ event, line, bytes });
    this.queuedBytes += bytes;
    this.kick();
  }

  private kick() {
    if (this.pumping || this.kickScheduled) return;
    this.kickScheduled = true;
    queueMicrotask(() => {
      this.kickScheduled = false;
      if (this.queued.length === 0 || this.pumping) {
        this.settleDrain();
        return;
      }
      this.pumping = true;
      void this.drain().catch((error: unknown) => {
        console.error("bus: canonical event log drain failed", error);
      }).finally(() => {
        this.pumping = false;
        if (this.queued.length > 0) this.kick();
        else this.settleDrain();
      });
    });
  }

  /** Nothing of this conversation waits for its log, and no append is under way. */
  logQuiet(threadId: string): boolean {
    return !this.pumping && !this.kickScheduled && !this.queued.some((item) => item.event.threadId === threadId);
  }

  private flushDisk(): Promise<void> {
    if (this.queued.length === 0 && !this.pumping && !this.kickScheduled) return Promise.resolve();
    return new Promise((resolve) => {
      this.drainWaiters.push(resolve);
      this.kick();
    });
  }

  private settleDrain() {
    if (this.queued.length > 0 || this.pumping || this.kickScheduled) return;
    const waiters = this.drainWaiters.splice(0);
    for (const resolve of waiters) resolve();
  }

  private async drain(): Promise<void> {
    while (this.queued.length > 0) {
      const batch = this.queued.splice(0, this.limits.batchLines);
      let bytes = 0;
      for (const item of batch) bytes += item.bytes;
      this.queuedBytes -= bytes;
      // One append per thread per batch, so its lines keep publication order; different threads append at the same time.
      const groups = new Map<string, QueuedLog[]>();
      for (const item of batch) {
        const items = groups.get(item.event.threadId);
        if (items) items.push(item);
        else groups.set(item.event.threadId, [item]);
      }
      const pending = [...groups.entries()];
      const workers = Math.min(this.limits.drainThreads, pending.length);
      await Promise.all(Array.from({ length: workers }, async () => {
        for (let group = pending.shift(); group; group = pending.shift()) {
          await this.appendGroup(group[0], group[1]);
        }
      }));
    }
  }

  private async appendGroup(threadId: string, items: QueuedLog[]): Promise<void> {
    const warning = this.pendingLogWarnings.get(threadId);
    const events = items.map((item) => item.event);
    const lines = items.map((item) => item.line);
    if (warning) lines.unshift(JSON.stringify(redactSecrets(warning)));
    const file = join(EVENTS_DIR, `${threadId}.ndjson`);
    try {
      await this.appendLog(file, lines.join("\n") + "\n", { mode: 0o600 });
      if (warning) this.pendingLogWarnings.delete(threadId);
      capThreadLog(file, currentThreadLogCap());
    } catch (error) {
      this.noteDiskFailure(events[0], error);
    } finally {
      const queuedWarning = this.queuedLogWarnings.get(threadId);
      if (queuedWarning && events.includes(queuedWarning)) this.queuedLogWarnings.delete(threadId);
    }
  }

  private logWarning(event: RuntimeEvent, message: string): RuntimeEvent {
    return {
      eventId: newId(),
      provider: event.provider,
      providerInstanceId: event.providerInstanceId,
      threadId: event.threadId,
      createdAt: new Date().toISOString(),
      turnId: event.turnId,
      type: "runtime.error",
      message,
    };
  }

  /** Never through publish(): that would retry the same failed write and recurse. */
  private noteDiskFailure(event: RuntimeEvent, error: unknown) {
    if (this.pendingLogWarnings.has(event.threadId)) return;
    const warning = this.logWarning(event, INCOMPLETE_LOG_MESSAGE);
    this.pendingLogWarnings.set(event.threadId, warning);
    console.error("bus: canonical event log write failed", error);
    this.deliver(warning);
  }

  private deliver(event: RuntimeEvent) {
    batchSaves(() => {
      for (const listener of Array.from(this.listeners)) {
        try {
          listener(event);
        } catch (e) {
          console.error("bus: listener threw", e);
        }
      }
    });
  }

  subscribe(listener: RuntimeEventListener): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  detachAll() {
    for (const id of this.unsubscribes.keys()) this.detach(id);
  }

  detach(instanceId: string) {
    this.unsubscribes.get(instanceId)?.();
    this.unsubscribes.delete(instanceId);
    this.adapters.delete(instanceId);
    void this.flush();
  }
}