Skip to content

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

7.9 KB
Raw Blame
// A computer step's actions in words: the step's label, its lines in SKILL.md, and the parts the card's templates fill
// ("Click “Save” in TextEdit", "Type {recipient}", "Press ⌘S").
import type { ComputerAction, ComputerPlace, WorkflowRef } from "./format.ts";

const LABEL_MAX = 120;
const QUOTED_MAX = 40;

const MAC_KEYS: Record<string, string> = { cmd: "⌘", command: "⌘", meta: "⌘", super: "⌘", option: "⌥", alt: "⌥", opt: "⌥", shift: "⇧", ctrl: "⌃", control: "⌃" };
const OTHER_KEYS: Record<string, string> = { cmd: "Super", command: "Super", meta: "Super", super: "Super", option: "Alt", alt: "Alt", opt: "Alt", shift: "Shift", ctrl: "Ctrl", control: "Ctrl" };
const NAMED: Record<string, string> = { return: "Return", enter: "Enter", escape: "Esc", esc: "Esc", tab: "Tab", space: "Space", delete: "Delete", backspace: "Backspace", up: "↑", down: "↓", left: "←", right: "→" };

const clip = (text: string, max = QUOTED_MAX) => (text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text);
const quoted = (text: string) => `“${clip(text)}”`;

/** The keys an action presses, as a person writes them: ⌘S on the person's own computer, Ctrl+S elsewhere. */
export function keysLine(action: Pick<ComputerAction, "key" | "keys" | "modifiers">, on: ComputerPlace): string {
  const parts = action.keys ?? [...(action.modifiers ?? []), ...(action.key ? action.key.split("+") : [])];
  const mac = on === "yourComputer";
  const names = parts.map((part) => {
    const lower = part.toLowerCase();
    const modifier = (mac ? MAC_KEYS : OTHER_KEYS)[lower];
    if (modifier) return { text: modifier, modifier: true };
    return { text: NAMED[lower] ?? (part.length === 1 ? part.toUpperCase() : part[0]!.toUpperCase() + part.slice(1)), modifier: false };
  });
  if (!mac) return names.map((name) => name.text).join("+");
  return names.filter((name) => name.modifier).map((name) => name.text).join("") + names.filter((name) => !name.modifier).map((name) => name.text).join("+");
}

/** What an action types, with an input shown as its name. */
export function typedLine(text: ComputerAction["text"]): string {
  if (text === undefined) return "";
  if (typeof text === "string") return quoted(text);
  const ref = text as WorkflowRef;
  return "$arg" in ref ? `{${ref.$arg}}` : `{${ref.$step}}`;
}

const appName = (action: ComputerAction) => action.app?.name ?? action.app?.bundleId ?? "";
const inApp = (action: ComputerAction) => (appName(action) ? ` in ${appName(action)}` : "");

/** Where a pointer action lands: its element, else its point in a window or on the screen. */
function target(action: ComputerAction): string {
  if (action.element) return `${quoted(action.element.label)}${inApp(action)}`;
  const at = action.point ? `at ${Math.round(action.point.x)},${Math.round(action.point.y)}` : "";
  if (action.window) return `${at} in ${quoted(action.window.title || appName(action))}`.trim();
  return at || "the screen";
}

/** One action as a line of the step: "Click “Save” in TextEdit". */
export function actionLine(action: ComputerAction, on: ComputerPlace): string {
  switch (action.tool) {
    case "click": return `Click ${target(action)}`;
    case "double_click": return `Double-click ${target(action)}`;
    case "right_click": return `Right-click ${target(action)}`;
    case "type_text": return `Type ${typedLine(action.text)}${action.element ? ` in ${quoted(action.element.label)}` : ""}`;
    case "set_value": return `Fill ${action.element ? quoted(action.element.label) : "the field"} with ${typedLine(action.text)}`;
    case "press_key":
    case "hotkey": return `Press ${keysLine(action, on)}`;
    case "scroll": return `Scroll ${action.direction ?? "down"} ${action.element ? `in ${quoted(action.element.label)}` : target(action)}`.trim();
    case "drag": return `Drag ${action.window ? `in ${quoted(action.window.title || appName(action))}` : "on the screen"}`;
    case "invoke_menu": return `Choose ${(action.menuPath ?? []).join(" › ")}${inApp(action)}`;
    case "launch_app": return `Open ${appName(action) || "the app"}`;
    case "bring_to_front": return `Bring ${appName(action) || "the app"} to the front`;
  }
}

/** A computer step's label: its actions in a line, the first ones named and the rest counted. */
export function computerLabel(actions: readonly ComputerAction[], on: ComputerPlace): string {
  const lines = actions.map((action) => actionLine(action, on));
  let label = lines[0] ?? "Use the computer";
  for (let index = 1; index < lines.length; index += 1) {
    const rest = lines.length - index;
    const next = `${label}, ${lines[index]![0]!.toLowerCase()}${lines[index]!.slice(1)}`;
    const more = rest > 1 ? `, and ${rest - 1} more` : "";
    if (`${next}${more}`.length > LABEL_MAX) return clip(`${label}, and ${rest} more`, LABEL_MAX);
    label = next;
  }
  return clip(label, LABEL_MAX);
}

/** An action as the server recorded it, before the draft turns the typed text into an input. Security invariant:
 * `focusUnknown` text went wherever the focus was, which may have been a secret field, so it is kept only as an input
 * (text from the ask or an earlier step), never as written. */
export type RecordedAction = Omit<ComputerAction, "text"> & { text?: string; focusUnknown?: true };

/** A run's desktop actions as the server recorded them: each desktop tool row's action, or null where that row can't be
 * repeated as recorded (a look at the screen has no action and isn't listed). */
export interface DeskRecording {
  on: ComputerPlace;
  actions: ReadonlyMap<string, RecordedAction | null>;
  /** Rows that touched a field holding a secret, typed into one, or typed a secret: their step keeps none of its calls. */
  secret?: ReadonlySet<string>;
  /** Rows that pressed a final, can't-undo action (send, delete, pay): their step is the bot's, under the person's approvals. */
  final?: ReadonlySet<string>;
}

/** The `where` a step on `on` keeps: the person's own computer, or a computer the bot drives. */
export const placeWhere = (on: ComputerPlace): "yourComputer" | "vm" => (on === "yourComputer" ? "yourComputer" : "vm");

/** An action as the card's templates take it: which template, and the values that fill it, never a typed value. */
export interface ActionView {
  /** The template: click, doubleClick, rightClick, type, fill, press, scroll, drag, menu, open, front. */
  kind: "click" | "doubleClick" | "rightClick" | "type" | "fill" | "press" | "scroll" | "drag" | "menu" | "open" | "front";
  /** What it acts on: an element (its label and app), a point in a window, or a point on the screen. */
  on?: { label: string; app: string } | { window: string } | { screen: true };
  /** What it types: an input's name, or "text" for text saved as it was. */
  input?: string;
  keys?: string;
  menu?: string;
  app?: string;
  direction?: string;
}

const VIEW_KIND: Record<ComputerAction["tool"], ActionView["kind"]> = {
  click: "click", double_click: "doubleClick", right_click: "rightClick", type_text: "type", set_value: "fill", press_key: "press", hotkey: "press",
  scroll: "scroll", drag: "drag", invoke_menu: "menu", launch_app: "open", bring_to_front: "front",
};

export function actionView(action: ComputerAction, on: ComputerPlace): ActionView {
  const name = appName(action);
  const where: ActionView["on"] = action.element ? { label: clip(action.element.label), app: name } : action.window ? { window: clip(action.window.title || name) } : action.point ? { screen: true } : undefined;
  const input = action.text === undefined ? undefined : typeof action.text === "string" ? "text" : "$arg" in action.text ? action.text.$arg : action.text.$step;
  return {
    kind: VIEW_KIND[action.tool],
    ...(where ? { on: where } : {}),
    ...(input ? { input } : {}),
    ...(action.tool === "press_key" || action.tool === "hotkey" ? { keys: keysLine(action, on) } : {}),
    ...(action.menuPath ? { menu: action.menuPath.join(" › ") } : {}),
    ...(name ? { app: name } : {}),
    ...(action.direction ? { direction: action.direction } : {}),
  };
}