Skip to content

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

6.6 KB
Raw Blame
// How a Skill Burger run reaches the screen its own turn mounted. Security invariant: a driver computer (this computer, a
// Local VM) is reached only through the turn's gated bridge, so the control gate and the person's consent apply to every
// replayed call as to the bot's own; the cloud computer only through the server's own route. Both go with a token the
// server minted from the turn's own capability and marked as a replay, so the gate count and the journals leave its calls
// out; no engine ever holds it.
import { ChatMcpClient } from "../drivers/chat-mcp-tools.ts";
import { SPAWNED_PROXIES } from "../proxy-paths.ts";
import type { ComputerPlace } from "../../shared/skill-burger/format.ts";
import { allowsTool } from "../../shared/tool-scope.ts";
import { callOutcome, STEP_TIMEOUT_MS } from "../saved-steps/computer-client.ts";
import type { CallOutcome, ComputerCaller } from "../saved-steps/resolve.ts";
import type { TurnDesk } from "./desk.ts";

export interface DeskSession extends ComputerCaller {
  /** The tools the computer lists, or null when it can't tell. */
  tools: ReadonlySet<string> | null;
  close(): Promise<void>;
}

/** What a run may do with its turn's computer. */
export interface DeskReach {
  place: ComputerPlace;
  /** Every one of `tools` would run on this turn without stopping to ask the person, and the turn's tool scope allows it. */
  allowed(tools: readonly string[]): boolean;
  open(signal: AbortSignal): Promise<DeskSession>;
}

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

/** The place a turn's mounted computer is: this computer's gated proxy, a Local VM's bridge, or the cloud computer's. */
export function placeOf(computer: NonNullable<TurnDesk["computer"]>): ComputerPlace | null {
  if (computer.scope === "local-computer" && computer.env.OMB_CONTROL_URL) return "yourComputer";
  if (computer.args[0] === SPAWNED_PROXIES.containerMcp && computer.env.OMB_CONTROL_URL) return "localVm";
  if (computer.args[0] === SPAWNED_PROXIES.harnessMcp && computer.args[1] === COMPUTER_SERVER && computer.env.OMB_HARNESS_URL && computer.env.OMB_MCP_TOKEN_COMPUTER) return "cloud";
  return null;
}

async function openDriver(computer: NonNullable<TurnDesk["computer"]>, signal: AbortSignal): Promise<DeskSession> {
  if (!computer.env.OMB_CONTROL_URL || !computer.env.OMB_CONTROL_TOKEN) throw new Error("this computer is not behind its control gate");
  const client = new ChatMcpClient({ command: computer.command, args: computer.args, env: { ...computer.env, OMB_COMPUTER_JOURNAL: "0" } }, true);
  let listed: unknown[];
  try {
    listed = await client.tools(signal);
  } catch (error) {
    await client.close().catch(() => {});
    throw error;
  }
  const names = listed.flatMap((tool) => (isRecord(tool) && typeof tool.name === "string" ? [tool.name] : []));
  return {
    tools: names.length ? new Set(names) : null,
    async call(tool, args, callSignal) {
      try {
        return callOutcome(await client.call("tools/call", { name: tool, arguments: args }, callSignal, STEP_TIMEOUT_MS));
      } catch (error) {
        return { ok: false, error: error instanceof Error ? error.message : "the computer could not be reached" };
      }
    },
    close: () => client.close(),
  };
}

/** The cloud computer's answer as a call outcome: its text parts read as JSON where they are. */
export function cloudOutcome(answer: unknown): CallOutcome {
  const result = isRecord(answer) && isRecord(answer.result) ? answer.result : null;
  if (!result || !Array.isArray(result.content)) return { ok: false, error: isRecord(answer) && typeof answer.error === "string" ? answer.error : "the cloud computer returned an invalid result" };
  const texts = result.content.flatMap((part) => (isRecord(part) && typeof part.text === "string" ? [part.text] : []));
  if (result.isError === true) return { ok: false, error: texts.join(" ").slice(0, 300) || "the cloud computer reported an error" };
  let structured: Record<string, unknown> = {};
  try { const parsed: unknown = JSON.parse(texts[0] ?? ""); if (isRecord(parsed)) structured = parsed; } catch { /* plain text */ }
  if (structured.ok === false) return { ok: false, error: String(structured.stderr || structured.stdout || "the command failed").slice(0, 300) };
  return { ok: true, structured };
}

function openCloud(computer: NonNullable<TurnDesk["computer"]>, fetchImpl: typeof fetch): DeskSession {
  const url = new URL("/api/internal/computer/mcp", computer.env.OMB_HARNESS_URL).href;
  let id = 0;
  return {
    tools: null,
    async call(tool, args, signal) {
      try {
        const response = await fetchImpl(url, {
          method: "POST", signal: AbortSignal.any([signal, AbortSignal.timeout(STEP_TIMEOUT_MS)]),
          headers: { authorization: `Bearer ${computer.env.OMB_MCP_TOKEN_COMPUTER}`, "content-type": "application/json" },
          body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method: "tools/call", params: { name: tool, arguments: args } }),
        });
        return cloudOutcome(await response.json().catch(() => null));
      } catch (error) {
        return { ok: false, error: error instanceof Error ? error.message : "the cloud computer could not be reached" };
      }
    },
    close: async () => {},
  };
}

/** The turn's computer with its token swapped for a replay token, when the server mints them. */
function replayComputer(turn: TurnDesk, computer: NonNullable<TurnDesk["computer"]>, place: ComputerPlace): NonNullable<TurnDesk["computer"]> {
  if (!turn.replay) return computer;
  const key = place === "cloud" ? "OMB_MCP_TOKEN_COMPUTER" : "OMB_CONTROL_TOKEN";
  const token = computer.env[key];
  const marked = token ? turn.replay(token) : null;
  if (!marked) throw new Error("this turn's computer could not be reached for a repeat");
  return { ...computer, env: { ...computer.env, [key]: marked } };
}

/** The run's reach into the computer its own turn mounted, or null when it mounted none this run can drive. */
export function deskReach(turn: TurnDesk | null, deps: { fetch?: typeof fetch; openDriver?: typeof openDriver } = {}): DeskReach | null {
  const computer = turn?.computer;
  const place = computer ? placeOf(computer) : null;
  if (!turn || !computer || !place) return null;
  return {
    place,
    allowed: (tools) => turn.approvalFull() && tools.every((name) => allowsTool(turn.toolScope, { kind: "mcp", server: COMPUTER_SERVER, name })),
    open: async (signal) => {
      const marked = replayComputer(turn, computer, place);
      return place === "cloud" ? openCloud(marked, deps.fetch ?? fetch) : (deps.openDriver ?? openDriver)(marked, signal);
    },
  };
}