Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud computer: run long commands in the background and check on them
milind-soni015b5414a491
diff --git a/apps/docs/content/docs/computers/cloud-and-vps.mdx b/apps/docs/content/docs/computers/cloud-and-vps.mdxindex e3adac0ed3..8d13ce8bd5 100644--- a/apps/docs/content/docs/computers/cloud-and-vps.mdx+++ b/apps/docs/content/docs/computers/cloud-and-vps.mdx@@ -30,6 +30,15 @@ Reddit at all. Reddit blocks bots that browse from cloud computers and can banthe account, so the bot is told to use the Reddit connected app or ask you to doit on your own computer.+A bot's `exec` call waits for its command to finish, so a long one (a big+download, a build, a data job) can run out of time while it keeps going on the+Boat. For those, the bot starts the command with `background: true`, which+answers at once with a process id, and follows it with `exec_status`, which shows+whether it is still running, its exit code and the end of its output. When a+plain `exec` runs out of time, the bot is told the command may still be running,+so it checks instead of starting a second copy. This works with your own Boat key+and with the cloud computers included in a Cloud plan.+## Bring your own VPSOpenMausBot can control Docker on an x86_64 Linux server through an SSH config alias. The agent process stays on your local machine; only Docker commands and the managed desktop container run on the VPS.diff --git a/server/boat.ts b/server/boat.tsindex de8f0107eb..8cea6a5dfc 100644--- a/server/boat.ts+++ b/server/boat.ts@@ -136,7 +136,7 @@ function snapshotBoatConfig(cfg: AppConfig): AppConfig {}/** An own token goes to Boat; Cloud Pro's included token only to its relay. */-function boatFetch(cfg: AppConfig, path: string, opts: RequestInit = {}) {+export function boatFetch(cfg: AppConfig, path: string, opts: RequestInit = {}) {const account = boatAccount(cfg);return fetch(`${account?.api ?? boatProviderApi()}${relayPath(account, path)}`, {...opts,@@ -361,7 +361,7 @@ export async function runCommand(cfg: AppConfig, boxId: string, command: string,ok: res.ok && body?.exitCode === 0,exitCode: body?.exitCode ?? null,stdout: body?.stdout ?? "",- stderr: body?.stderr ?? "",+ stderr: body?.stderr ?? "", ...(body?.timedOut === true ? { timedOut: true as const } : {}),};}@@ -722,7 +722,7 @@ function deletionFenceError(): Error & { status: number } {);}-function assertBoatNotDeleting(boxId: string): void {+export function assertBoatNotDeleting(boxId: string): void {if (getBoatDeletion(boxId)) throw deletionFenceError();}diff --git a/server/cloud-computer-background.test.ts b/server/cloud-computer-background.test.tsnew file mode 100644index 0000000000..fa3c1d3c7e--- /dev/null+++ b/server/cloud-computer-background.test.ts@@ -0,0 +1,225 @@+// One loopback stub plays Boat (/boat/api/v1, sandboxes) and the Admin's included-Boat relay (/relay/api/box/v1, boxes).+import { createServer, type Server } from "node:http";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { AppConfig } from "./config.ts";++const BOX = "bx_23456789", OTHER_BOX = "bx_3456789a";+const OWN_KEY = "boat_own-synthetic-key", INCLUDED = "box_omb_included-synthetic-token";+type Process = { polls: number; runningFor: number; exitCode: number | null; stdout: string; stderr: string; lost?: boolean };+let server: Server;+let base = "";+let tools: typeof import("./cloud-computer-tools.ts");+let background: typeof import("./cloud-computer-background.ts");+let journal: typeof import("./boat-delete-journal.ts");+const processes = new Map<string, Process>();+const calls: Array<{ method: string; path: string; query: string; body: any; authorization?: string }> = [];+let nextProcessId = 41;+let hold = false;+let syncReply: Record<string, unknown> = { exitCode: 0, stdout: "done", stderr: "" };+let startReply: { status: number; body: unknown } | undefined;++beforeAll(async () => {+ server = createServer(async (req, res) => {+ let raw = "";+ for await (const part of req) raw += part;+ const url = new URL(req.url ?? "/", "http://boat.test");+ calls.push({ method: req.method ?? "GET", path: url.pathname, query: url.search, body: raw ? JSON.parse(raw) : null, authorization: req.headers.authorization });+ const send = (status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };+ const route = /^(?:\/boat\/api\/v1\/sandboxes|\/relay\/api\/box\/v1\/boxes)\/(bx_[a-z0-9]{8})\/commands(?:\/(\d+))?$/.exec(url.pathname);+ if (!route) return send(404, { ok: false, code: "not_found", message: `unexpected ${req.method} ${url.pathname}` });+ const [, box, pid] = route;+ if (req.method === "POST" && !pid) {+ if (hold) return;+ if (startReply && JSON.parse(raw).detached) return send(startReply.status, startReply.body);+ if (!JSON.parse(raw).detached) return send(200, syncReply);+ const processId = nextProcessId++;+ processes.set(`${box}:${processId}`, { polls: 0, runningFor: 1, exitCode: 0, stdout: "", stderr: "" });+ return send(200, { ok: true, type: "command.started", success: true, processId, pid: 9000 + processId, command: "fixture", startedAt: new Date().toISOString() });+ }+ if (req.method === "GET" && pid) {+ if (hold) return;+ const process = processes.get(`${box}:${pid}`);+ if (!process) return send(404, { ok: false, code: "not_found", message: "No such process." });+ const running = process.polls++ < process.runningFor;+ return send(200, {+ ok: true, type: "command.status", success: true, processId: Number(pid), status: running ? "running" : process.lost ? "lost" : "exited", running,+ exitCode: running ? null : process.exitCode, signal: null, stdout: process.stdout, stderr: process.stderr,+ });+ }+ send(405, { ok: false });+ });+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));+ base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;+ tools = await import("./cloud-computer-tools.ts");+ background = await import("./cloud-computer-background.ts");+ journal = await import("./boat-delete-journal.ts");+});+afterAll(async () => { vi.unstubAllEnvs(); server.closeAllConnections(); await new Promise<void>(resolve => server.close(() => resolve())); });+beforeEach(() => {+ calls.length = 0; processes.clear(); hold = false; startReply = undefined;+ syncReply = { exitCode: 0, stdout: "done", stderr: "" };+});++type Result = { isError?: boolean; content: Array<{ type: string; text: string }> };+const json = (result: unknown) => JSON.parse((result as Result).content[0].text);++describe.each([+ ["your own Boat key", { box: { token: OWN_KEY } } as AppConfig, "/boat/api/v1/sandboxes", `Bearer ${OWN_KEY}`],+ ["the included Boat's relay", {} as AppConfig, "/relay/api/box/v1/boxes", `Bearer ${INCLUDED}`],+])("background commands with %s", (_label, cfg, root, authorization) => {+ beforeEach(() => {+ vi.stubEnv("BOX_TOKEN", undefined);+ vi.stubEnv("OMB_BOAT_API", `${base}/boat/api/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `${base}/relay/api/box/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", INCLUDED);+ });++ const call = (name: string, args: unknown, boxId = BOX, budgetMs?: number) => {+ let gated = 0, checks = 0;+ const done = tools.cloudComputerRpc({ method: "tools/call", params: { name, arguments: args } }, {+ cfg, boxId: () => boxId, signal: new AbortController().signal, ...(budgetMs ? { budgetMs } : {}),+ gate: async () => { gated++; return { held: false }; }, assertActive: () => { checks++; },+ }) as Promise<Result>;+ return { done, gated: () => gated, checks: () => checks };+ };+ const start = async (boxId = BOX) => json(await call("exec", { command: "python3 job.py > out.csv", background: true }, boxId).done).processId as string;++ it("starts a command detached, through the gate, and answers at once with a process id", async () => {+ const started = call("exec", { command: "python3 job.py > out.csv", background: true });+ const result = await started.done;+ expect(result.isError).not.toBe(true);+ expect(json(result)).toMatchObject({ processId: expect.stringMatching(new RegExp(background.PROCESS_ID_PATTERN)), status: "running" });+ expect([started.gated(), started.checks()]).toEqual([1, 2]);+ expect(calls).toHaveLength(1);+ expect(calls[0]).toMatchObject({ method: "POST", path: `${root}/${BOX}/commands`, authorization, body: { detached: true } });+ expect(Object.keys(calls[0].body).sort()).toEqual(["command", "detached"]);+ expect(calls[0].body.command).toContain("exec env -i");+ expect(calls[0].body.command).toContain("python3 job.py > out.csv");+ });++ it("reports a running command, then its exit code and output once it finishes", async () => {+ const processId = await start();+ const process = processes.get(`${BOX}:${processId.split("-")[1]}`)!;+ Object.assign(process, { exitCode: 3, stdout: "rows: 1200\n", stderr: "warning: slow disk\n" });+ expect(json(await call("exec_status", { process_id: processId }).done)).toEqual({ processId, status: "running", exitCode: null, stdout: "rows: 1200\n", stderr: "warning: slow disk\n" });+ const finished = await call("exec_status", { process_id: processId }).done;+ expect(finished.isError).not.toBe(true);+ expect(json(finished)).toEqual({ processId, status: "finished", exitCode: 3, stdout: "rows: 1200\n", stderr: "warning: slow disk\n" });+ const reads = calls.filter(entry => entry.method === "GET");+ expect(reads.map(entry => [entry.path, entry.query, entry.authorization])).toEqual(Array(2).fill([`${root}/${BOX}/commands/${processId.split("-")[1]}`, "?tailBytes=12000", authorization]));+ });++ it("waits for the command to finish when asked, polling the computer rather than the bot", async () => {+ const processId = await start();+ Object.assign(processes.get(`${BOX}:${processId.split("-")[1]}`)!, { runningFor: 2, stdout: "loaded\n" });+ const began = Date.now();+ expect(json(await call("exec_status", { process_id: processId, wait_seconds: 30 }).done)).toMatchObject({ status: "finished", exitCode: 0, stdout: "loaded\n" });+ expect(Date.now() - began).toBeGreaterThanOrEqual(3_500);+ expect(calls.filter(entry => entry.method === "GET")).toHaveLength(3);+ });++ it("stops waiting when the wait is over and says the command is still running", async () => {+ const processId = await start();+ processes.get(`${BOX}:${processId.split("-")[1]}`)!.runningFor = 100;+ expect(json(await call("exec_status", { process_id: processId, wait_seconds: 3 }).done)).toMatchObject({ status: "running", exitCode: null });+ expect(calls.filter(entry => entry.method === "GET")).toHaveLength(2);+ });++ it("returns only the end of long output, and never half a character", async () => {+ const processId = await start();+ // 6,003 UTF-16 units: the last 4,000 begin on the second half of an emoji.+ const stdout = "π".repeat(3_000) + "END", stderr = "e".repeat(5_000) + "LAST";+ Object.assign(processes.get(`${BOX}:${processId.split("-")[1]}`)!, { runningFor: 0, stdout, stderr });+ const status = json(await call("exec_status", { process_id: processId }).done);+ expect(status.stdout).toBe("π".repeat(1_998) + "END");+ expect(status.stderr).toBe("e".repeat(background.STDERR_TAIL_CHARS - 4) + "LAST");+ expect(status.outputCut).toMatch(/Only the end of the output/);+ });++ it("refuses a process id from another computer without asking either computer", async () => {+ const theirs = await start(OTHER_BOX);+ calls.length = 0;+ const read = call("exec_status", { process_id: theirs });+ const refused = await read.done;+ expect(refused).toEqual({ isError: true, content: [{ type: "text", text: expect.stringContaining("not from this cloud computer") }] });+ expect(read.gated()).toBe(1);+ const forged = `bg-${theirs.split("-")[1]}-00000000`;+ expect((await call("exec_status", { process_id: forged }).done).content[0].text).toContain("not from this cloud computer");+ await expect(background.backgroundStatus(cfg, BOX, { process_id: theirs }, new AbortController().signal)).resolves.toMatchObject({ isError: true });+ expect(calls).toEqual([]);+ expect(json(await call("exec_status", { process_id: theirs }, OTHER_BOX).done)).toMatchObject({ processId: theirs, status: "running" });+ });++ it.each([+ ["a bare number", "exec_status", { process_id: "42" }],+ ["a process id with shell syntax", "exec_status", { process_id: "bg-42-0000000a; reboot" }],+ ["a wait past the cap", "exec_status", { process_id: "bg-42-0000000a", wait_seconds: 61 }],+ ["an extra field", "exec_status", { process_id: "bg-42-0000000a", command: "true" }],+ ["a background flag that is not a boolean", "exec", { command: "true", background: "yes" }],+ ])("refuses %s before the gate or the computer", async (_label, name, args) => {+ const refused = call(name, args);+ expect(await refused.done).toEqual({ isError: true, content: [{ type: "text", text: expect.stringMatching(/input schema/) }] });+ expect(refused.gated()).toBe(0);+ expect(calls).toEqual([]);+ });++ it("says when the computer no longer knows the process, or lost track of it", async () => {+ expect((await call("exec_status", { process_id: background.processIdOn(BOX, 7) }).done).content[0].text).toContain("no background command with that process_id");+ const processId = await start();+ Object.assign(processes.get(`${BOX}:${processId.split("-")[1]}`)!, { runningFor: 0, lost: true, exitCode: null });+ expect(json(await call("exec_status", { process_id: processId }).done)).toMatchObject({ status: "lost", exitCode: null, note: expect.stringContaining("lost track") });+ });++ it("does not start or read a command on a computer that is being deleted", async () => {+ const processId = await start();+ journal.prepareBoatDeletion({ boxId: BOX, name: "ogb-0123456789ab-bot-abc123", ownerBotId: null });+ try {+ calls.length = 0;+ await expect(call("exec", { command: "true", background: true }).done).rejects.toMatchObject({ status: 409 });+ await expect(call("exec_status", { process_id: processId }).done).rejects.toMatchObject({ status: 409 });+ expect(calls).toEqual([]);+ } finally { journal.retireBoatDeletion(BOX); }+ });++ it("says a start may have happened when the computer failed mid-way, and never retries it", async () => {+ startReply = { status: 502, body: { ok: false, code: "boat_direct_failed", message: "upstream failed" } };+ const result = await call("exec", { command: "make all", background: true }).done;+ expect(result.isError).toBe(true);+ expect(result.content[0].text).toContain("may have started");+ startReply = { status: 409, body: { ok: false, code: "sandbox_not_ready", message: "Resume it first." } };+ expect((await call("exec", { command: "make all", background: true }).done).content[0].text).not.toContain("may have started");+ expect(calls.filter(entry => entry.method === "POST")).toHaveLength(2);+ });++ it("reports the result when the computer service ran a background command to the end instead", async () => {+ startReply = { status: 200, body: { exitCode: 2, stdout: "x".repeat(5_000), stderr: "boom" } };+ const result = await call("exec", { command: "make all", background: true }).done;+ expect(result.isError).toBe(true);+ expect(json(result)).toMatchObject({ status: "finished", exitCode: 2, stdout: "x".repeat(background.STDOUT_TAIL_CHARS), stderr: "boom", note: expect.stringContaining("to the end") });+ startReply = { status: 200, body: { ok: true } };+ expect((await call("exec", { command: "make all", background: true }).done).content[0].text).toContain("did not say which process it started");+ expect(calls.filter(entry => entry.method === "POST")).toHaveLength(2);+ });++ it("tells the bot a plain exec that ran out of time may still be running, and not to repeat it blindly", async () => {+ hold = true;+ const late = await call("exec", { command: "sleep 600" }, BOX, 400).done;+ expect(late).toEqual({ isError: true, content: [{ type: "text", text: background.EXEC_LATE }] });+ expect(background.EXEC_LATE).toMatch(/may still be running.*do not run it again blindly.*background: true.*exec_status/s);+ server.closeAllConnections();+ hold = false;+ syncReply = { exitCode: null, stdout: "", stderr: "", timedOut: true };+ expect(await call("exec", { command: "sleep 600" }).done).toEqual({ isError: true, content: [{ type: "text", text: background.EXEC_LATE }] });+ expect(calls.filter(entry => entry.method === "POST")).toHaveLength(2);+ });++ it("answers a late start or status read with what is safe to do next", async () => {+ hold = true;+ expect((await call("exec", { command: "make all", background: true }, BOX, 300).done).content[0].text).toMatch(/did not confirm the start.*may have started/);+ server.closeAllConnections();+ expect((await call("exec_status", { process_id: background.processIdOn(BOX, 41) }, BOX, 300).done).content[0].text).toMatch(/Nothing was changed; call exec_status again/);+ server.closeAllConnections();+ expect((await call("get_screen_size", {}, BOX, 300).done).content[0].text).toBe(tools.CLOUD_COMPUTER_LATE);+ server.closeAllConnections();+ });+});diff --git a/server/cloud-computer-background.ts b/server/cloud-computer-background.tsnew file mode 100644index 0000000000..ba02f25906--- /dev/null+++ b/server/cloud-computer-background.ts@@ -0,0 +1,117 @@+// Boat (docs.boat.dev/openapi/boat-v1.yaml): POST /sandboxes/{id}/commands with `detached: true` answers at once with an+// integer processId; GET /sandboxes/{id}/commands/{processId} answers `running`, `status` (running, exited or lost),+// `exitCode` and the end of each log, cut to `tailBytes`. A processId means something only on the sandbox that started it.+import { createHash } from "node:crypto";+import { setTimeout as delay } from "node:timers/promises";+import { assertBoatNotDeleting, boatAccount, boatErrorMessage, boatFetch, isolatedRemoteCommand } from "./boat.ts";+import type { CloudComputerResult } from "./cloud-computer-tools.ts";+import type { AppConfig } from "./config.ts";++const PROCESS_ID = /^bg-([1-9][0-9]{0,15})-([0-9a-f]{8})$/;+export const PROCESS_ID_PATTERN = PROCESS_ID.source;+export const STATUS_WAIT_MAX_SECONDS = 60;+export const STDOUT_TAIL_CHARS = 4_000;+export const STDERR_TAIL_CHARS = 2_000;+const POLL_MS = 2_000;+const MAX_UTF8_BYTES_PER_UTF16_UNIT = 3;+const TAIL_BYTES = MAX_UTF8_BYTES_PER_UTF16_UNIT * STDOUT_TAIL_CHARS;++const CHECK_BEFORE_RERUN = "Check before starting it again, for example with exec `pgrep -af '<part of the command>'` or by looking at the files it writes";+export const EXEC_LATE = "The command did not finish within this call's time limit. It may still be running on the cloud computer, so do not run it "+ + `again blindly: a second copy can collide with the first, for example by reading its half-written files. ${CHECK_BEFORE_RERUN}. `+ + "Start a command that may run long (downloads, installs, builds, data jobs) with background: true, then follow it with exec_status.";+const START_LATE = `The cloud computer did not confirm the start in time. The command may have started. ${CHECK_BEFORE_RERUN}.`;+const STATUS_LATE = "The cloud computer did not answer in time. Nothing was changed; call exec_status again.";+const OTHER_COMPUTER = "That process_id is not from this cloud computer. Use the process_id that exec with background: true returned on this computer.";+const UNKNOWN_PROCESS = "This cloud computer has no background command with that process_id; it may have restarted since. "+ + "Look at the files the command writes to see how far it got.";+const LOST = "The cloud computer restarted or lost track of this command, so its exit code may be unknown. Look at the files it writes to see how far it got.";+const CUT = "Only the end of the output is shown. Write long output to a file and read the part you need with exec.";++const text = (value: string, isError = false): CloudComputerResult => ({ ...(isError ? { isError } : {}), content: [{ type: "text", text: value }] });+const included = (cfg: AppConfig) => boatAccount(cfg)?.included === true;++/** Security: a process_id names the computer it was started on, so one read through another computer is refused rather+ * than answered with whatever process holds that number there. */+const computerTag = (boxId: string) => createHash("sha256").update(boxId).digest("hex").slice(0, 8);+export const processIdOn = (boxId: string, processId: number) => `bg-${processId}-${computerTag(boxId)}`;++function processIdFrom(boxId: string, value: string): number | null {+ const match = PROCESS_ID.exec(value);+ const processId = Number(match?.[1]);+ return match && match[2] === computerTag(boxId) && Number.isSafeInteger(processId) ? processId : null;+}++/** Never starts on a lone low surrogate: half a character is an invalid string some providers reject. */+function tail(value: unknown, chars: number): { text: string; cut: boolean } {+ const whole = typeof value === "string" ? value : "";+ if (whole.length <= chars) return { text: whole, cut: false };+ const kept = whole.slice(-chars);+ const first = kept.charCodeAt(0);+ return { text: first >= 0xdc00 && first <= 0xdfff ? kept.slice(1) : kept, cut: true };+}++/** An Admin relay that does not forward `detached` has Boat run the command to the end and answer with its result. */+function ranInForeground(body: any): CloudComputerResult {+ const stdout = tail(body.stdout, STDOUT_TAIL_CHARS), stderr = tail(body.stderr, STDERR_TAIL_CHARS);+ return text(JSON.stringify({+ status: "finished", exitCode: body.exitCode, stdout: stdout.text, stderr: stderr.text,+ ...(stdout.cut || stderr.cut ? { outputCut: CUT } : {}), note: "The cloud computer ran this command to the end instead of in the background.",+ }), body.exitCode !== 0);+}++export async function startInBackground(cfg: AppConfig, boxId: string, command: string, signal: AbortSignal): Promise<CloudComputerResult> {+ assertBoatNotDeleting(boxId);+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/commands`, {+ method: "POST", body: JSON.stringify({ command: isolatedRemoteCommand(command), detached: true }), signal,+ });+ const body: any = await response.json().catch(() => null);+ if (!response.ok) {+ const refusal = boatErrorMessage(response.status, "Starting the command", body, included(cfg));+ return text(response.status >= 500 ? `${refusal} The command may have started. ${CHECK_BEFORE_RERUN}.` : refusal, true);+ }+ const processId = body?.processId;+ if (Number.isInteger(body?.exitCode) && processId === undefined) return ranInForeground(body);+ if (!Number.isSafeInteger(processId) || processId < 1) return text(`The cloud computer did not say which process it started. The command may have started. ${CHECK_BEFORE_RERUN}.`, true);+ return text(JSON.stringify({ processId: processIdOn(boxId, processId), status: "running", next: "It keeps running after this call. Follow it with exec_status." }));+}++function describeStatus(processId: string, body: any): CloudComputerResult {+ const stdout = tail(body.stdout, STDOUT_TAIL_CHARS), stderr = tail(body.stderr, STDERR_TAIL_CHARS);+ const status = body.running ? "running" : body.status === "lost" ? "lost" : "finished";+ return text(JSON.stringify({+ processId, status, exitCode: body.running ? null : (Number.isInteger(body.exitCode) ? body.exitCode : null),+ ...(!body.running && typeof body.signal === "string" && body.signal ? { signal: body.signal } : {}),+ ...(body.oomKilled === true ? { outOfMemory: true } : {}),+ stdout: stdout.text, stderr: stderr.text,+ ...(stdout.cut || stderr.cut || body.stdoutTruncated === true || body.stderrTruncated === true ? { outputCut: CUT } : {}),+ ...(status === "lost" ? { note: LOST } : {}),+ }));+}++export async function backgroundStatus(+ cfg: AppConfig,+ boxId: string,+ args: { process_id: string; wait_seconds?: number },+ signal: AbortSignal,+): Promise<CloudComputerResult> {+ const processId = processIdFrom(boxId, args.process_id);+ if (processId === null) return text(OTHER_COMPUTER, true);+ const until = Date.now() + Math.min(args.wait_seconds ?? 0, STATUS_WAIT_MAX_SECONDS) * 1_000;+ for (;;) {+ assertBoatNotDeleting(boxId);+ const response = await boatFetch(cfg, `/sandboxes/${boxId}/commands/${processId}?tailBytes=${TAIL_BYTES}`, { signal });+ const body: any = await response.json().catch(() => null);+ if (response.status === 404) return text(UNKNOWN_PROCESS, true);+ if (!response.ok) return text(boatErrorMessage(response.status, "Reading the command's status", body, included(cfg)), true);+ if (typeof body?.running !== "boolean") return text("The cloud computer gave an unreadable answer about this command. Call exec_status again.", true);+ if (!body.running || Date.now() + POLL_MS > until) return describeStatus(args.process_id, body);+ await delay(POLL_MS, undefined, { signal });+ }+}++export function commandLateText(name: unknown, args: unknown): string | undefined {+ if (name === "exec_status") return STATUS_LATE;+ if (name !== "exec") return undefined;+ return (args as { background?: unknown }).background === true ? START_LATE : EXEC_LATE;+}diff --git a/server/cloud-computer-tools.test.ts b/server/cloud-computer-tools.test.tsindex 95b45814aa..576d8215f4 100644--- a/server/cloud-computer-tools.test.ts+++ b/server/cloud-computer-tools.test.ts@@ -47,10 +47,10 @@ const rpc = (request: unknown, gate: { held: boolean; reason?: "person"; blocked};describe("cloud computer tools", () => {- it("lists the same ten tools for every engine", async () => {+ it("lists the same eleven tools for every engine", async () => {const listed = await rpc({ method: "tools/list", params: {} }).done as { tools: Array<{ name: string }> };expect(listed.tools.map(tool => tool.name)).toEqual([- "screenshot", "get_screen_size", "click", "move", "drag", "type_text", "key_press", "scroll", "open_url", "exec",+ "screenshot", "get_screen_size", "click", "move", "drag", "type_text", "key_press", "scroll", "open_url", "exec", "exec_status",]);expect(calls).toEqual([]);});@@ -185,7 +185,7 @@ describe("cloud computer tools", () => {cfg, boxId: () => "bx_23456789", signal: new AbortController().signal, budgetMs: 600, assertActive: () => {},gate: async () => { await new Promise(resolve => setTimeout(resolve, 300)); return { held: false }; },});- expect(result).toEqual({ isError: true, content: [{ type: "text", text: tools.CLOUD_COMPUTER_LATE }] });+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: (await import("./cloud-computer-background.ts")).EXEC_LATE }] });expect(Date.now() - started).toBeGreaterThanOrEqual(550);expect(Date.now() - started).toBeLessThan(1_500);expect(calls.filter(entry => entry.path.endsWith("/commands"))).toHaveLength(1);diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.tsindex 4af20414a5..97e7fd18bf 100644--- a/server/cloud-computer-tools.ts+++ b/server/cloud-computer-tools.ts@@ -2,6 +2,9 @@import type { ValidateFunction } from "ajv";import { isolatedRemoteCommand, runCommand, screenshotBoat } from "./boat.ts";import { isRedditAddress, REDDIT_REFUSAL } from "./browser/egress/reddit.ts";+import {+ backgroundStatus, commandLateText, EXEC_LATE, PROCESS_ID_PATTERN, startInBackground, STATUS_WAIT_MAX_SECONDS, STDERR_TAIL_CHARS, STDOUT_TAIL_CHARS,+} from "./cloud-computer-background.ts";import type { AppConfig } from "./config.ts";import { controlRefusal, type ControlState } from "./control-client.ts";import { HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";@@ -20,7 +23,14 @@ export const CLOUD_COMPUTER_TOOLS = [tool("key_press", "Press an X11 key or shortcut.", { key: { type: "string", pattern: "^[A-Za-z0-9_+]+$", minLength: 1, maxLength: 100 } }, ["key"]),tool("scroll", "Scroll at a point on the cloud desktop.", { x: coordinate, y: coordinate, direction: { type: "string", enum: ["up", "down", "left", "right"] }, amount: { type: "integer", minimum: 1, maximum: 30 } }, ["x", "y", "direction"]),tool("open_url", "Request opening an HTTP or HTTPS URL in the cloud desktop browser; inspect the screen to confirm it loaded.", { url: { type: "string", pattern: "^https?://", maxLength: 2000 } }, ["url"]),- tool("exec", "Run a shell command on the assigned cloud computer.", { command: { type: "string", minLength: 1, maxLength: 4000 } }, ["command"]),+ tool("exec", "Run a shell command on the assigned cloud computer and wait for its result. For a command that may run long (downloads, installs, builds, data jobs), set background: true: it starts the command and answers at once with a process_id to follow with exec_status.", {+ command: { type: "string", minLength: 1, maxLength: 4000 },+ background: { type: "boolean", description: "Start the command and answer at once with a process_id, instead of waiting for it to finish." },+ }, ["command"]),+ tool("exec_status", `Check a command started with exec and background: true: running or finished, its exit code, and the end of its stdout and stderr (the last ${STDOUT_TAIL_CHARS.toLocaleString("en-US")} and ${STDERR_TAIL_CHARS.toLocaleString("en-US")} characters).`, {+ process_id: { type: "string", pattern: PROCESS_ID_PATTERN },+ wait_seconds: { type: "integer", minimum: 0, maximum: STATUS_WAIT_MAX_SECONDS, description: "Wait up to this many seconds for the command to finish before answering." },+ }, ["process_id"]),];/** A call the gate let through while no Boat had landed for the turn. */export const CLOUD_COMPUTER_NOT_READY = "The cloud computer is not ready. This call was not performed. Take a fresh screenshot in a moment.";@@ -77,12 +87,14 @@ export async function runCloudComputerTool(case "key_press": command = `xdotool key --clearmodifiers ${quote(String(a.key))}`; break;case "scroll": command = `${mouse} click --repeat ${a.amount ?? 3} --delay 80 ${scrollButtons[String(a.direction)]}`; break;case "open_url": command = `nohup xdg-open ${quote(String(a.url))} >/dev/null 2>&1 </dev/null &`; break;- case "exec": command = String(a.command); break;+ case "exec": if (a.background === true) return startInBackground(cfg, boxId, String(a.command), signal); command = String(a.command); break;+ case "exec_status": return backgroundStatus(cfg, boxId, a as { process_id: string; wait_seconds?: number }, signal);default: return { isError: true, content: [{ type: "text", text: "Unknown cloud computer tool." }] };}const result = await runCommand(cfg, boxId, isolatedRemoteCommand(command), { signal });signal.throwIfAborted();if (name === "open_url" && result.ok) return { content: [{ type: "text", text: "Browser launch requested. Page loading is not confirmed; inspect the screen before continuing." }] };+ if (name === "exec" && result.timedOut) return { isError: true, content: [{ type: "text", text: EXEC_LATE }] };return { isError: !result.ok, content: [{ type: "text", text: JSON.stringify(result) }] };}@@ -122,7 +134,7 @@ export async function cloudComputerRpc(result = await runCloudComputerTool(deps.cfg, boxId, params.name as string, args as Record<string, unknown>, AbortSignal.any([deps.signal, late]));} catch (error) {if (!late.aborted || deps.signal.aborted) throw error;- return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_LATE }] };+ return { isError: true, content: [{ type: "text", text: commandLateText(params.name, args) ?? CLOUD_COMPUTER_LATE }] };}deps.assertActive();return result;diff --git a/server/hosted-desktop.e2e.test.ts b/server/hosted-desktop.e2e.test.tsindex f69f9e1f55..a9e0fd50ce 100644--- a/server/hosted-desktop.e2e.test.ts+++ b/server/hosted-desktop.e2e.test.ts@@ -139,7 +139,7 @@ it("keeps the bot's own engine on the cloud computer, and a failed place never bconst client = mcpClient(computer);try {expect((await client.request("initialize", { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "fixture", version: "1" } })).result.serverInfo.name).toBe("openmausbot-computer");- expect((await client.request("tools/list")).result.tools).toHaveLength(10);+ expect((await client.request("tools/list")).result.tools).toHaveLength(11);const shot = await client.request("tools/call", { name: "screenshot", arguments: {} });expect(shot.result.content[0]).toMatchObject({ type: "image", mimeType: "image/jpeg" });const exec = await client.request("tools/call", { name: "exec", arguments: { command: "printf hosted-desktop" } });