Skip to content

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

9.3 KB
Raw Blame
import { userError } from "../user-errors.ts";
import { savedLoginResumePrompt } from "../../shared/logins.ts";
import { handoffNote, isHandoff, signInCardResumePrompt, signInOutcome, signInWaits } from "../../shared/sign-in-request.ts";
import type { ComputerHelpRef } from "../../shared/wire.ts";
import type { HandoffView } from "../coordinator.ts";
import type { BotRecord, Message, Store } from "../store.ts";
import type { Surface } from "../surface.ts";

export interface SignInSettleDeps {
  store: Pick<Store, "activePath" | "bot" | "patchMessage">;
  signInMessage(botId: string, threadId: string, messageId: string): Message | null;
  answerCardNode(threadId: string, messageId: string, text: string): boolean;
  releaseCardNode(threadId: string, messageId: string, reason: string): void;
  resumableCards(threadId: string, since: number): Array<{ id: string }>;
  /** The work parked on the person in this conversation: its own, or work handed on to it. */
  parkedDirect(threadId: string): HandoffView | undefined;
  /** Ends the card's plea for help and returns the computers it held. */
  settleHelp(messageId: string): string[];
  handBackBrowser(bot: BotRecord, threadId: string): void;
  releaseComputer(key: string): void;
  /** The control key a person's hold on this conversation's computer sits on. */
  computerKey(bot: BotRecord, threadId: string): string;
  /** True when several bots drive the computer behind this control key, so no one bot's card may hand it back alone. */
  sharedKey(key: string): boolean;
  /** The sign-in cards on this control key that still wait for the person. */
  pleas(key: string): ComputerHelpRef[];
}

export type SignInSettled = { status: number; body: Record<string, unknown> };

/** The line that resumes work handed on when the person answered its sign-in in the chat instead of pressing Done. */
export function signInChatPrompt(site: string, line: string, instruction?: string): string {
  if (instruction) return `OpenMausBot handoff update: instead of pressing I'm done on ${JSON.stringify(instruction)}, the person wrote in the chat: ${JSON.stringify(line.slice(0, 400))}. Re-read the page first (a new snapshot or screenshot): your earlier refs are stale. Then continue as their line says. Never ask for a password, a one-time code or payment details in chat.`;
  return `OpenMausBot sign-in update: instead of pressing Done on the sign-in to ${site}, the person wrote in the chat: ${JSON.stringify(line.slice(0, 400))}. Check you are signed in, then continue the task that paused for it. Never ask them for a password or a one-time code in chat.`;
}

export function createSignInSettle(deps: SignInSettleDeps) {
  const { store } = deps;

  /** The person is through with the place the card lent them: its plea goes, and the browser or computer goes back to the
   * bot. A computer several bots share goes back only when the person pressed Done or Cancel and no other card waits for it.
   * Their Done also hands back where the conversation works now, which a repin since the card may have moved. */
  const handPlaceBack = (bot: BotRecord, threadId: string, messageId: string, place: Surface, byPerson: boolean): void => {
    const pleaded = deps.settleHelp(messageId);
    if (place === "browser") deps.handBackBrowser(bot, threadId);
    else for (const key of new Set([...pleaded, ...(byPerson || !pleaded.length ? [deps.computerKey(bot, threadId)] : [])])) {
      if (!deps.sharedKey(key) || (byPerson && !deps.pleas(key).length)) deps.releaseComputer(key);
    }
  };

  const settle = (botId: string, threadId: string, messageId: string, outcome: "done" | "cancelled", saved?: { site: string }, rawNote?: unknown): SignInSettled => {
    const bot = store.bot(botId);
    const message = deps.signInMessage(botId, threadId, messageId);
    if (!bot || !message?.signIn) return { status: 404, body: { ...userError("serverError.signIn.requestMissing") } };
    const card = message.signIn;
    if (card.superseded) return { status: 409, body: { ...userError("serverError.signIn.requestReplaced") } };
    if (card.answeredInChat) return { status: 409, body: { ...userError("serverError.signIn.answeredInChat") } };
    const settled = signInOutcome(card);
    if (settled && settled !== outcome) {
      return { status: 409, body: { ...userError(settled === "done" ? "serverError.signIn.alreadyDone" : settled === "expired" ? "serverError.signIn.expired" : "serverError.signIn.alreadyCancelled") } };
    }
    if (settled && card.resumed) return { status: 200, body: { [outcome]: true, resumed: true } };
    if (!settled) handPlaceBack(bot, threadId, message.id, card.place, true);
    const savedLogin = saved?.site ?? card.savedLogin;
    const note = settled ? card.note : handoffNote(rawNote) ?? card.note;
    const resumed = deps.answerCardNode(threadId, message.id, savedLogin ? savedLoginResumePrompt(savedLogin) : signInCardResumePrompt({ ...card, note }, outcome));
    store.patchMessage(threadId, message.id, {
      signIn: { ...card, ...(outcome === "done" ? { done: true } : { cancelled: true }), ...(savedLogin ? { savedLogin } : {}), ...(note ? { note } : {}), ...(resumed ? { resumed: true, error: undefined } : {}) },
    });
    return { status: 200, body: { [outcome]: true, resumed, ...(savedLogin ? { saved: true, site: savedLogin } : {}) } };
  };

  /** Nobody answered the handoff in time: the place goes back to the bot, and the bot is told and resumed. */
  const expire = (botId: string, threadId: string, messageId: string): boolean => {
    const bot = store.bot(botId);
    const message = deps.signInMessage(botId, threadId, messageId);
    const card = message?.signIn;
    if (!bot || !message || !card || card.stopped || !signInWaits(card)) return false;
    handPlaceBack(bot, threadId, message.id, card.place, false);
    const resumed = deps.answerCardNode(threadId, message.id, signInCardResumePrompt(card, "expired"));
    store.patchMessage(threadId, message.id, { signIn: { ...card, expired: true, ...(resumed ? { resumed: true, error: undefined } : {}) } });
    return true;
  };

  /** Settles these sign-in cards as answered in the chat, and returns the ids it settled. */
  const answered = (bot: BotRecord, threadId: string, only?: readonly string[]): Array<{ id: string; site: string; instruction?: string }> => {
    const settled: Array<{ id: string; site: string; instruction?: string }> = [];
    for (const message of store.activePath(threadId)) {
      const card = message.signIn;
      if (message.kind !== "signin" || !card || card.stopped || !signInWaits(card) || (only && !only.includes(message.id))) continue;
      handPlaceBack(bot, threadId, message.id, card.place, false);
      store.patchMessage(threadId, message.id, { signIn: { ...card, answeredInChat: true, error: undefined } });
      settled.push({ id: message.id, site: card.site, ...(isHandoff(card) ? { instruction: card.instruction } : {}) });
    }
    return settled;
  };

  /** The person's own line answers every sign-in request still open in their conversation, as Done would. Work handed on
   * that waited on those cards carries the line on (true: no new turn starts for it); a person's own conversation goes on
   * with the turn the line starts, so the work parked there ends and nothing resumes it twice. */
  const answerInChat = (botId: string, threadId: string, line?: string): boolean => {
    const bot = store.bot(botId);
    if (!bot) return false;
    const settled = answered(bot, threadId);
    const parked = deps.parkedDirect(threadId);
    const card = settled.find((one) => parked?.cards?.includes(one.id));
    if (!parked || !card || deps.resumableCards(threadId, parked.startedAt ?? parked.createdAt).some((open) => parked.cards!.includes(open.id))) return false;
    if (parked.parentId && line !== undefined) return deps.answerCardNode(threadId, card.id, signInChatPrompt(card.site, line, card.instruction));
    deps.releaseCardNode(threadId, card.id, "The person answered in the chat");
    return false;
  };

  /** Another bot passed an answer on to the work parked on these cards: they no longer wait on the person. */
  const answeredElsewhere = (node: HandoffView): void => {
    const bot = store.bot(node.botId);
    if (bot) answered(bot, node.threadId, node.cards ?? []);
  };

  /** The bot asked for a sign-in, then went on with that site — in the asking turn or a later one: the sign-in went
   * through, so the card stops waiting on the person. A newer request for the site supersedes the older card, so the
   * one this settles is the site's only open ask. */
  const verified = (botId: string, threadId: string): void => {
    const bot = store.bot(botId);
    if (!bot) return;
    const path = store.activePath(threadId);
    path.forEach((message, index) => {
      const card = message.signIn;
      if (message.kind !== "signin" || !card || isHandoff(card) || card.stopped || !signInWaits(card)) return;
      const site = card.site.toLowerCase();
      const used = path.slice(index + 1).some((row) => row.kind === "activity" && row.tool?.ok === true && (row.tool.input ?? "").toLowerCase().includes(site));
      if (!used) return;
      handPlaceBack(bot, threadId, message.id, card.place, false);
      store.patchMessage(threadId, message.id, { signIn: { ...card, done: true, resumed: true, error: undefined } });
    });
  };

  return { settle, expire, answerInChat, answeredElsewhere, verified };
}