Skip to content

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

1.8 KB
Raw Blame
// A bot's room turns keep one activity per room thread, so ending one leaves the bot's other room threads running.
import type { BotActivity } from "../shared/wire.ts";

export const ACTIVITY_BUSY: ReadonlySet<BotActivity> = new Set(["working", "waiting-on-you", "no-signal"]);

export class RoomActivities {
  private readonly byBot = new Map<string, Map<string, BotActivity>>();

  /** False when the thread already had this activity. */
  set(botId: string, threadId: string, activity: BotActivity): boolean {
    const threads = this.byBot.get(botId) ?? new Map<string, BotActivity>();
    if ((threads.get(threadId) ?? "idle") === activity) return false;
    if (activity === "idle") threads.delete(threadId);
    else threads.set(threadId, activity);
    if (threads.size) this.byBot.set(botId, threads);
    else this.byBot.delete(botId);
    return true;
  }

  /** This bot's room turn in one room thread, shaped like a task's activity. */
  of(botId: string, threadId: string): { activity: BotActivity; busy: boolean } {
    const activity = this.byBot.get(botId)?.get(threadId) ?? "idle";
    return { activity, busy: ACTIVITY_BUSY.has(activity) };
  }

  activities(botId: string): BotActivity[] {
    return [...(this.byBot.get(botId)?.values() ?? [])];
  }

  /** Room threads this bot has a running turn in. */
  busyThreads(botId: string): string[] {
    return [...(this.byBot.get(botId) ?? [])].filter(([threadId, activity]) => threadId && ACTIVITY_BUSY.has(activity)).map(([threadId]) => threadId);
  }

  /** A turn in this room thread, or one set without a thread, is running. */
  busyIn(botId: string, threadId: string): boolean {
    return this.of(botId, threadId).busy || this.of(botId, "").busy;
  }

  forget(botId: string): void {
    this.byBot.delete(botId);
  }
}