Skip to content

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

8.6 KB
Raw Blame
// What a Skill Burger needs from a turn's desktop, kept in memory only: each computer call of a person's request as the
// driver saw it (real key names and element identities, which the chat's own rows redact or never had), kept past the
// request until its card is saved, and the computer a turn mounted, so a run in that turn reaches the same screen.
import type { ComputerPlace } from "../../shared/skill-burger/format.ts";
import type { JournalEntry } from "../saved-steps/driver-wire.ts";
import { ComputerJournal, type JournalScope, type RecordedCall } from "../saved-steps/journal.ts";

export interface DeskCall extends JournalEntry {
  place: ComputerPlace;
  /** The cloud computer's screen when the call was made, as its last screenshot or size read showed it. */
  screen?: { width: number; height: number };
}
export interface DeskSnapshot { requestId: string; calls: RecordedCall<DeskCall>[]; complete: boolean; tainted: boolean }

/** The capability a computer call comes with, as far as the desk reads it; `replay`: a Skill Burger's own replay call. */
export interface DeskCapability { kind: string; botId: string; threadId: string; generation: string; localVmTarget?: unknown; boxId?: string | null; teamComputerId?: string; replay?: boolean }

/** The computer a turn mounted (none for a VPS desktop, which no saved step drives) and what the turn allows on it. */
export interface TurnDesk {
  generation: string;
  computer?: { command: string; args: string[]; env: Record<string, string>; scope?: string; platform?: string };
  toolScope?: unknown;
  /** The person's live approval mode for this turn is full access: no call of it stops to ask. */
  approvalFull(): boolean;
  /** A token for the turn's computer, minted from the turn's own, whose calls the gate and the journals leave out. */
  replay?(token: string): string | null;
}

export const DESK_JOURNAL_BYTES = 16 * 1024 * 1024;
/** What the kept snapshots may weigh together, as JSON; a request's calls heavier than that are not kept. */
export const DESK_SNAPSHOT_BYTES = 16 * 1024 * 1024;
const SNAPSHOTS = 64;
const TURNS = 256;

const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);

function remember<V>(map: Map<string, V>, key: string, value: V, limit: number): void {
  map.delete(key);
  map.set(key, value);
  while (map.size > limit) map.delete(map.keys().next().value!);
}

/** A JPEG's width and height, read from its frame header. */
export function jpegSize(data: Buffer): { width: number; height: number } | null {
  if (data[0] !== 0xff || data[1] !== 0xd8) return null;
  for (let at = 2; at + 9 < data.length;) {
    if (data[at] !== 0xff) return null;
    const marker = data[at + 1]!;
    const length = data.readUInt16BE(at + 2);
    if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
      const height = data.readUInt16BE(at + 5);
      const width = data.readUInt16BE(at + 7);
      return width > 0 && height > 0 ? { width, height } : null;
    }
    at += 2 + length;
  }
  return null;
}

/** The cloud desktop's size from a get_screen_size answer ("1280 800" in the command's stdout) or a screenshot. */
export function cloudScreenSize(tool: string, result: unknown): { width: number; height: number } | null {
  const content = isRecord(result) && Array.isArray(result.content) ? result.content : [];
  if (tool === "screenshot") {
    const image = content.find((part) => isRecord(part) && part.type === "image" && typeof part.data === "string");
    return isRecord(image) ? jpegSize(Buffer.from(String(image.data), "base64")) : null;
  }
  if (tool !== "get_screen_size") return null;
  for (const part of content) {
    if (!isRecord(part) || typeof part.text !== "string") continue;
    let stdout = part.text;
    try {
      const parsed: unknown = JSON.parse(part.text);
      if (isRecord(parsed) && typeof parsed.stdout === "string") stdout = parsed.stdout;
    } catch { /* plain text */ }
    const found = /^\s*(\d{2,5})\s+(\d{2,5})\s*$/.exec(stdout);
    if (found) return { width: Number(found[1]), height: Number(found[2]) };
  }
  return null;
}

export function createBurgerDesk(deps: { enabled(): boolean; replayToken?(token: string): string | null; snapshotBytes?: number }) {
  const journal = new ComputerJournal<DeskCall>({ totalBytes: DESK_JOURNAL_BYTES });
  const snapshots = new Map<string, DeskSnapshot & { bytes: number }>();
  const snapshotCap = deps.snapshotBytes ?? DESK_SNAPSHOT_BYTES;
  const keep = (threadId: string, snapshot: DeskSnapshot) => {
    snapshots.delete(threadId);
    const bytes = JSON.stringify(snapshot.calls).length;
    if (bytes > snapshotCap) return;
    remember(snapshots, threadId, { ...snapshot, bytes }, SNAPSHOTS);
    let total = 0;
    for (const kept of snapshots.values()) total += kept.bytes;
    for (const [oldest, kept] of snapshots) {
      if (total <= snapshotCap) break;
      snapshots.delete(oldest);
      total -= kept.bytes;
    }
  };
  const turns = new Map<string, TurnDesk>();
  const screens = new Map<string, { generation: string; size: { width: number; height: number } }>();
  const scopeOf = (capability: DeskCapability): JournalScope => ({ botId: capability.botId, threadId: capability.threadId, generation: capability.generation });
  /** A driver turn the desk records: this computer or a Local VM, never a team's computer or a cloud one. */
  const driverPlace = (capability: DeskCapability, asked?: string | null): ComputerPlace | null => {
    if (capability.kind !== "computer" || capability.teamComputerId || capability.boxId !== undefined) return null;
    return capability.localVmTarget || asked === "vm" ? "localVm" : "yourComputer";
  };
  return {
    enabled: () => deps.enabled(),
    driverPlace,
    gateChecked(capability: DeskCapability): void {
      if (deps.enabled() && driverPlace(capability)) journal.gateChecked(scopeOf(capability));
    },
    record(capability: DeskCapability, entry: JournalEntry, place: ComputerPlace): void {
      if (deps.enabled()) journal.record(scopeOf(capability), { ...entry, place });
    },
    /** A cloud computer call through the server's own route: counted when it is asked and recorded once it answers. */
    async cloud<T>(capability: DeskCapability, request: unknown, answer: Promise<T>): Promise<T> {
      const params = isRecord(request) && request.method === "tools/call" && isRecord(request.params) ? request.params : null;
      if (!deps.enabled() || !params || typeof params.name !== "string" || capability.kind !== "computer" || capability.teamComputerId || capability.replay) return answer;
      const scope = scopeOf(capability);
      journal.gateChecked(scope);
      const result = await answer;
      const size = cloudScreenSize(params.name, result);
      if (size) screens.set(scope.threadId, { generation: scope.generation, size });
      const seen = screens.get(scope.threadId);
      journal.record(scope, {
        tool: params.name, arguments: isRecord(params.arguments) ? params.arguments : {}, result: { isError: isRecord(result) && result.isError === true },
        place: "cloud", ...(seen?.generation === scope.generation ? { screen: seen.size } : {}),
      });
      return result;
    },
    taint(scope: Pick<JournalScope, "threadId" | "generation">): void {
      journal.taint(scope);
    },
    /** The person's request ended: its calls are kept for its card until the next request, and its turn's mount (with
     * its control tokens) is dropped. */
    settled(threadId: string, requestId: string, generations: ReadonlySet<string>): void {
      const taken = journal.take(threadId, generations);
      screens.delete(threadId);
      turns.delete(threadId);
      if (taken) keep(threadId, { requestId, ...taken });
      else snapshots.delete(threadId);
    },
    ended(threadId: string, generations: ReadonlySet<string>): void {
      journal.take(threadId, generations);
      screens.delete(threadId);
      snapshots.delete(threadId);
      turns.delete(threadId);
    },
    snapshot(threadId: string): DeskSnapshot | null {
      const kept = snapshots.get(threadId);
      if (!kept) return null;
      const { bytes: _bytes, ...snapshot } = kept;
      return snapshot;
    },
    remember(threadId: string, turn: TurnDesk): void {
      remember(turns, threadId, turn, TURNS);
    },
    /** The computer the turn `generation` of `threadId` mounted, or null for any other turn. */
    turn(threadId: string, generation: string): TurnDesk | null {
      const found = turns.get(threadId);
      if (found?.generation !== generation) return null;
      return deps.replayToken ? { ...found, replay: deps.replayToken } : found;
    },
  };
}
export type BurgerDesk = ReturnType<typeof createBurgerDesk>;