Skip to content

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

17.7 KB
Raw Blame
// A run's desktop rows as the actions a Skill Burger repeats, read from the calls the computer itself saw. The chat's rows
// are matched to those calls one by one, in order, by tool, outcome and every argument the row still shows; anything less
// than an exact match, or a request whose calls weren't all seen, leaves the run's desktop steps to the AI. Security
// invariant: no action is kept that touched a field holding a secret, typed into one, or typed text the secret scrub
// would change; text typed where the focus can't be named is kept only as an input; element values are never read, and
// only what the action itself sent is kept. A final, can't-undo action leaves its step to the bot.
import { redactSecretsInText } from "../../shared/redact.ts";
import type { DeskRecording, RecordedAction } from "../../shared/skill-burger/computer.ts";
import type { ComputerPlace } from "../../shared/skill-burger/format.ts";
import { askIdOf, computerRows, type ComputerRow, type RunMessage } from "../../shared/skill-burger/layers.ts";
import { elementPath, type SlimStructured, type WireElement } from "../saved-steps/driver-wire.ts";
import { matchElement } from "../saved-steps/resolve.ts";
import { previewIsPartial } from "../tool-summary.ts";
import { flipsToggle, OBSERVATION_TOOLS, plainTextInput, unsafeStep, type ActionTool } from "../saved-steps/rules.ts";
import type { DeskSnapshot } from "./desk.ts";

type Call = DeskSnapshot["calls"][number];
interface Snapshot { pid?: number; windowId?: number; appName?: string; windowTitle?: string; elements: WireElement[]; complete: boolean }
interface KnownWindow { title: string; pid?: number; width?: number; height?: number }

/** Arguments that address a target in one run only; the action finds its target again instead. */
const ADDRESSING = new Set(["element_token", "pid", "window_id", "session", "delivery_mode", "post_action_wait", "delay_ms"]);
const KEPT: Record<string, readonly string[]> = {
  click: ["x", "y", "button", "count", "modifier"],
  double_click: ["x", "y"],
  right_click: ["x", "y", "modifier"],
  type_text: ["text", "x", "y"],
  set_value: ["value"],
  press_key: ["key", "modifiers"],
  hotkey: ["keys"],
  scroll: ["x", "y", "direction", "amount", "by"],
  drag: ["from_x", "from_y", "to_x", "to_y", "button"],
  invoke_menu: ["path"],
  launch_app: ["bundle_id", "name"],
  bring_to_front: [],
};
const CLOUD_KEPT: Record<string, readonly string[]> = {
  click: ["x", "y", "button", "count"], drag: ["x", "y", "to_x", "to_y"], type_text: ["text"], key_press: ["key"], scroll: ["x", "y", "direction", "amount"],
};
const LOOKS = new Set([...OBSERVATION_TOOLS, "get_window_state", "zoom", "get_cursor_position", "screenshot", "get_screen_size", "move", "exec_status"]);
const KEYBOARD = new Set(["type_text", "press_key", "hotkey", "set_value"]);

const num = (value: unknown): number | undefined => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
const strings = (value: unknown): string[] | undefined => (Array.isArray(value) && value.length && value.every((item) => typeof item === "string" && item) ? value as string[] : undefined);
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);

/** Every argument the stored row still shows (not masked, left out or cut) agrees with what the computer was sent. */
export function rowAgrees(row: ComputerRow, call: Pick<Call, "tool" | "arguments" | "result">): boolean {
  if (row.tool !== call.tool || row.ok === call.result.isError) return false;
  const input = row.input ?? {};
  for (const key of new Set([...Object.keys(input), ...Object.keys(call.arguments)])) {
    const shown = input[key];
    if (typeof shown === "string" && previewIsPartial(shown)) continue;
    if (!same(input[key], call.arguments[key])) return false;
  }
  return true;
}

/** A row that touched a secret: its step is saved without any of its calls. */
const SECRET = Symbol("secret");
/** A row that pressed a final action: its step is the bot's, under the person's approvals. */
const FINAL = Symbol("final");
type Read = RecordedAction | null | typeof SECRET | typeof FINAL;
const LINE_BREAK = /[\t\n\r]/;

/** The text an action types, null when it can't be kept, or SECRET when the secret scrub would change it. */
function cleanText(value: unknown): string | null | typeof SECRET {
  if (typeof value !== "string" || value.length > 4_000) return null;
  return redactSecretsInText(value) === value ? value : SECRET;
}

function cloudAction(call: Call): Read {
  const args = call.arguments;
  const kept = CLOUD_KEPT[call.tool];
  if (!kept || Object.keys(args).some((key) => !kept.includes(key))) return null;
  const at = num(args.x) !== undefined && num(args.y) !== undefined ? { point: { x: num(args.x)!, y: num(args.y)! } } : {};
  const screen = call.screen ? { screen: call.screen } : {};
  switch (call.tool) {
    case "click": {
      const button = args.button === undefined ? undefined : String(args.button);
      if (!at.point || !call.screen || (button && !["left", "right", "middle"].includes(button))) return null;
      return { tool: "click", ...at, ...screen, ...(button && button !== "left" ? { button: button as "right" | "middle" } : {}), ...(num(args.count) && num(args.count)! > 1 ? { count: num(args.count)! } : {}) };
    }
    case "drag":
      return at.point && call.screen && num(args.to_x) !== undefined && num(args.to_y) !== undefined ? { tool: "drag", ...at, to: { x: num(args.to_x)!, y: num(args.to_y)! }, ...screen } : null;
    case "scroll":
      return at.point && call.screen && typeof args.direction === "string" ? { tool: "scroll", ...at, ...screen, direction: args.direction as "up", ...(num(args.amount) ? { amount: num(args.amount)! } : {}) } : null;
    case "type_text": {
      // The cloud computer types into whatever has the focus, and nothing it answers names that field.
      const text = cleanText(args.text);
      return typeof text === "string" ? { tool: "type_text", text, focusUnknown: true } : text;
    }
    case "key_press": {
      if (typeof args.key !== "string" || !args.key) return null;
      const keys = args.key.split("+");
      if (unsafeStep({ tool: "press_key", args: { key: keys.at(-1), modifiers: keys.slice(0, -1) } }) === "final-action") return FINAL;
      return { tool: "press_key", key: args.key };
    }
    default:
      return null;
  }
}

/** Turns one driver's calls into actions, keeping what its looks at the screen showed. */
class DriverReader {
  private readonly apps = new Map<number, { bundleId?: string; name?: string; listed?: boolean }>();
  private readonly windows = new Map<number, KnownWindow>();
  private readonly trees = new Map<number, Snapshot>();
  private readonly secretWindows = new Set<number>();
  /** The window whose plain text field the last action, an element click, focused; null when the focus can't be named. */
  private typingInto: number | null = null;

  look(call: Call): void {
    const data: SlimStructured = call.result.structured ?? {};
    for (const app of data.apps ?? []) if (app.running !== false) this.learnApp(app.pid, { bundleId: app.bundle_id, name: app.name }, true);
    for (const window of data.windows ?? []) this.learnWindow(window.window_id, { title: window.title, pid: window.pid, ...(window.bounds ? { width: window.bounds.width, height: window.bounds.height } : {}) }, window.app_name);
    if (call.tool === "launch_app") this.learnApp(data.pid, { bundleId: data.bundle_id ?? (typeof call.arguments.bundle_id === "string" ? call.arguments.bundle_id : undefined), name: data.name ?? (typeof call.arguments.name === "string" ? call.arguments.name : undefined) });
    if (call.tool !== "get_window_state") return;
    this.learnApp(data.pid, { bundleId: data.bundle_id, name: data.app_name });
    if (data.window_id === undefined) return;
    if (data.window_title !== undefined) this.learnWindow(data.window_id, { title: data.window_title, pid: data.pid });
    this.trees.set(data.window_id, { pid: data.pid, windowId: data.window_id, appName: data.app_name, windowTitle: data.window_title, elements: data.elements ?? [], complete: data.elements_complete === true });
  }

  /** A repeat finds the app by its `list_apps` name, so that name wins: on Linux a window's app_name is its class
   * ("Proofapp.py") while list_apps names the process ("python3"). */
  private learnApp(pid: number | undefined, app: { bundleId?: string; name?: string }, listed = false): void {
    if (pid === undefined || (!app.bundleId && !app.name)) return;
    const known = this.apps.get(pid);
    if (known?.listed && !listed) return;
    this.apps.set(pid, listed ? { bundleId: app.bundleId ?? known?.bundleId, name: app.name ?? known?.name, listed } : { bundleId: known?.bundleId ?? app.bundleId, name: known?.name ?? app.name });
  }

  private learnWindow(id: number, window: KnownWindow, appName?: string): void {
    const known = this.windows.get(id);
    this.windows.set(id, { title: window.title, pid: window.pid ?? known?.pid, width: window.width ?? known?.width, height: window.height ?? known?.height });
    if (appName && window.pid !== undefined) this.learnApp(window.pid, { name: appName });
  }

  private app(pid: number | undefined): RecordedAction["app"] | null {
    const app = pid === undefined ? undefined : this.apps.get(pid);
    if (!app?.bundleId && !app?.name) return null;
    return { ...(app.bundleId ? { bundleId: app.bundleId } : {}), ...(app.name ? { name: app.name } : {}) };
  }

  /** The element a token named, as its role, label and ancestor path: only from a whole tree, and only when unique. */
  private element(token: string): { element: RecordedAction["element"] & object; tree: Snapshot } | null {
    for (const tree of this.trees.values()) {
      const found = tree.elements.find((candidate) => candidate.element_token === token);
      if (!found) continue;
      if (!tree.complete || !found.label) return null;
      const path = elementPath(tree.elements, found);
      if (!path) return null;
      const twins = matchElement(tree.elements, { role: found.role, label: found.label, path });
      if (!twins.ok || twins.value.element_index !== found.element_index) return null;
      return { element: { role: found.role, label: found.label, path }, tree };
    }
    return null;
  }

  action(call: Call): Read {
    const focused = this.typingInto;
    this.typingInto = null;
    return this.read(call, focused);
  }

  /** A call that failed may still have moved the focus. */
  failed(): void {
    this.typingInto = null;
  }

  private read(call: Call, focused: number | null): Read {
    const { tool, arguments: args } = call;
    const kept = KEPT[tool];
    if (!kept) return null;
    for (const key of Object.keys(args)) if (!ADDRESSING.has(key) && !kept.includes(key)) return null;
    if (args.delivery_mode !== undefined && args.delivery_mode !== "background" && args.delivery_mode !== "foreground") return null;
    const foreground = args.delivery_mode === "foreground" ? { foreground: true as const } : {};
    if (tool === "launch_app") {
      const bundleId = typeof args.bundle_id === "string" ? args.bundle_id : undefined;
      const name = typeof args.name === "string" ? args.name : undefined;
      return bundleId || name ? { tool, app: { ...(bundleId ? { bundleId } : {}), ...(name ? { name } : {}) } } : null;
    }
    let pid = num(args.pid);
    let windowId = num(args.window_id);
    let element: RecordedAction["element"];
    if (typeof args.element_token === "string") {
      const found = this.element(args.element_token);
      if (!found) return null;
      element = found.element;
      pid = found.tree.pid ?? pid;
      windowId = found.tree.windowId ?? windowId;
      if (flipsToggle(tool as ActionTool, element.role)) return null;
    } else if (args.element_token !== undefined) return null;
    const app = this.app(pid);
    if (!app) return null;
    const window = windowId === undefined ? undefined : this.windows.get(windowId);
    if (windowId !== undefined && !window) return null;
    const recordedWindow = window ? { title: window.title, ...(window.width && window.height ? { width: Math.round(window.width), height: Math.round(window.height) } : {}) } : undefined;
    const point = num(args.x) !== undefined && num(args.y) !== undefined ? { x: num(args.x)!, y: num(args.y)! } : undefined;
    if ((args.x !== undefined || args.y !== undefined) && !point) return null;
    if (point && (element || !recordedWindow?.width)) return null;
    const unsafe = unsafeStep({ tool: tool as ActionTool, args, window: recordedWindow, element });
    if (unsafe === "final-action") return FINAL;
    if (element) {
      if (unsafe === "secret-field") {
        if (windowId !== undefined) this.secretWindows.add(windowId);
        return SECRET;
      }
    } else if (KEYBOARD.has(tool) && windowId !== undefined && this.secretWindows.has(windowId)) return SECRET;
    else if (KEYBOARD.has(tool) && windowId === undefined) return null;
    const base = { app, ...(recordedWindow ? { window: recordedWindow } : {}), ...(element ? { element } : {}), ...(point ? { point } : {}), ...foreground };
    switch (tool) {
      case "click": case "double_click": case "right_click": {
        if (!element && !point) return null;
        const button = typeof args.button === "string" && args.button !== "left" ? args.button : undefined;
        const modifiers = args.modifier === undefined ? undefined : strings(args.modifier);
        if ((args.modifier !== undefined && !modifiers) || (button && !["right", "middle"].includes(button))) return null;
        const count = num(args.count);
        if (tool !== "right_click" && element && plainTextInput(element.role) && windowId !== undefined && !modifiers) this.typingInto = windowId;
        return { tool, ...base, ...(button ? { button: button as "right" } : {}), ...(count && count > 1 && count <= 3 ? { count } : {}), ...(modifiers ? { modifiers } : {}) };
      }
      case "type_text": case "set_value": {
        const text = cleanText(tool === "set_value" ? args.value : args.text);
        if (typeof text !== "string" || (tool === "set_value" && !element)) return text === SECRET ? SECRET : null;
        if (element) return { tool, ...base, text };
        const known = !point && focused !== null && focused === windowId;
        if (known && !LINE_BREAK.test(text)) this.typingInto = focused;
        return { tool, ...base, text, ...(known ? {} : { focusUnknown: true as const }) };
      }
      case "press_key": {
        const modifiers = args.modifiers === undefined ? undefined : strings(args.modifiers);
        if (typeof args.key !== "string" || !args.key || (args.modifiers !== undefined && !modifiers)) return null;
        return { tool, ...base, key: args.key, ...(modifiers ? { modifiers } : {}) };
      }
      case "hotkey": {
        const keys = strings(args.keys);
        return keys && keys.length <= 8 ? { tool, ...base, keys } : null;
      }
      case "scroll": {
        if (!["up", "down", "left", "right"].includes(String(args.direction)) || (!element && !point)) return null;
        const amount = num(args.amount);
        return { tool, ...base, direction: args.direction as "up", ...(amount && amount <= 50 ? { amount: Math.round(amount) } : {}), ...(args.by === "line" || args.by === "page" ? { by: args.by } : {}) };
      }
      case "drag": {
        const from = num(args.from_x) !== undefined && num(args.from_y) !== undefined ? { x: num(args.from_x)!, y: num(args.from_y)! } : undefined;
        const to = num(args.to_x) !== undefined && num(args.to_y) !== undefined ? { x: num(args.to_x)!, y: num(args.to_y)! } : undefined;
        if (!from || !to || element || !recordedWindow?.width || (args.button !== undefined && args.button !== "left")) return null;
        return { tool, ...base, point: from, to };
      }
      case "invoke_menu": {
        const path = strings(args.path);
        return path && path.length <= 8 && recordedWindow ? { tool, ...base, menuPath: path } : null;
      }
      case "bring_to_front":
        return { tool, ...base };
      default:
        return null;
    }
  }
}

/** The run's desktop actions, each tool row's own, from the calls of the request that ran them; null when the calls
 * weren't all seen, a request was refused, they came from more than one computer, or the rows don't match them exactly. */
export function deskRecording(messages: readonly RunMessage[], snapshot: DeskSnapshot | null): DeskRecording | null {
  if (!snapshot || !snapshot.complete || snapshot.tainted || !snapshot.calls.length || snapshot.requestId !== askIdOf(messages)) return null;
  const places = new Set(snapshot.calls.map((call) => call.place));
  if (places.size !== 1) return null;
  const on: ComputerPlace = snapshot.calls[0]!.place;
  const rows = computerRows(messages);
  if (rows.length !== snapshot.calls.length || rows.some((row, index) => !rowAgrees(row, snapshot.calls[index]!))) return null;
  const actions = new Map<string, RecordedAction | null>();
  const secret = new Set<string>();
  const final = new Set<string>();
  const reader = new DriverReader();
  snapshot.calls.forEach((call, index) => {
    if (LOOKS.has(call.tool) || call.tool.startsWith("list_") || call.tool.startsWith("get_")) {
      if (on !== "cloud") reader.look(call);
      return;
    }
    if (on !== "cloud" && call.tool === "launch_app" && !call.result.isError) reader.look(call);
    const refused = call.result.isError || call.result.rpcError || call.result.structured?.refusal;
    if (refused) reader.failed();
    const action = refused ? null : on === "cloud" ? cloudAction(call) : reader.action(call);
    if (action === SECRET) secret.add(rows[index]!.id);
    if (action === FINAL) final.add(rows[index]!.id);
    actions.set(rows[index]!.id, action === SECRET || action === FINAL ? null : action);
  });
  return { on, actions, ...(secret.size ? { secret } : {}), ...(final.size ? { final } : {}) };
}