Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud computer: a failed start answers the waiting call with its reason (#4709)
Milind Soni07d5e152a90a
diff --git a/server/auto-vm-claims.test.ts b/server/auto-vm-claims.test.tsindex b5e4d18466..bd50b8c30b 100644--- a/server/auto-vm-claims.test.ts+++ b/server/auto-vm-claims.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vitest";-import { keepTransient, lazyClaimRetryText, MAX_CLAIM_ATTEMPTS, startAutoVmClaim, transientClaimFailure, type AutoVmClaimSlot, type AutoVmClaimTable } from "./auto-vm-claims.ts";+import { keepTransient, lazyClaimFailedText, lazyClaimRetryText, MAX_CLAIM_ATTEMPTS, startAutoVmClaim, transientClaimFailure, type AutoVmClaimSlot, type AutoVmClaimTable } from "./auto-vm-claims.ts";const slot = (claim: () => Promise<void>, generation = "gen-1"): AutoVmClaimSlot => ({owner: { threadId: "t1", generation },@@ -194,3 +194,21 @@ describe("startAutoVmClaim", () => {expect(onRejected).not.toHaveBeenCalled();});});++describe("lazyClaimFailedText", () => {+ const boat = { label: "the cloud computer", startsComputer: true as const, failure: "Miso's cloud desktop didn't start. This conversation is back on Auto. Send your message again." };++ it("gives the bot the computer's own reason, and says the conversation is back on Auto only when it is", () => {+ expect(lazyClaimFailedText({ ...boat, cause: "the cloud computer could not be created or reached", backOnAuto: true })).toBe(+ "The cloud computer could not be started: the cloud computer could not be created or reached. This call was not performed. " ++ "This conversation is back on Auto. Do not retry computer work in this turn; tell the person what you could not do.");+ expect(lazyClaimFailedText({ ...boat, cause: "the cloud computer didn't start in time." })).toBe(+ "The cloud computer could not be started: the cloud computer didn't start in time. This call was not performed. " ++ "Do not retry computer work in this turn; tell the person what you could not do.");+ });++ it("keeps the claim wording for a computer the turn does not start", () => {+ expect(lazyClaimFailedText({ label: "the Local VM", failure: "the Local VM is not ready" })).toBe(+ "This turn could not claim the Local VM (the Local VM is not ready). This call was not performed. Do not retry computer work in this turn; tell the person what you could not do.");+ });+});diff --git a/server/auto-vm-claims.ts b/server/auto-vm-claims.tsindex cd5d08e34a..c35530a6cf 100644--- a/server/auto-vm-claims.ts+++ b/server/auto-vm-claims.ts@@ -14,6 +14,10 @@ export interface AutoVmClaimSlot {/** The fired claim rejected; the slot stays so the gate keeps refusing screen calls instead of forwarding them to an unclaimed VM. */failed?: boolean;failure?: string;+ /** What went wrong in the computer's own words, when `failure` is the line the person sees. */+ cause?: string;+ /** The failure took the conversation's automatic pick off this computer. */+ backOnAuto?: boolean;/** The last claim failed on the network; the next screen call claims again. */retryReason?: string;attempts?: number;@@ -74,6 +78,17 @@ export function startAutoVmClaim(table: AutoVmClaimTable, threadId: string, geneslot.begin = begin;}+/** What every screen call hears for the rest of a turn whose computer could not be claimed. */+export function lazyClaimFailedText(slot: Pick<AutoVmClaimSlot, "label" | "failure" | "cause" | "startsComputer" | "backOnAuto">): string {+ const label = slot.label ?? "this computer";+ const why = (slot.cause ?? slot.failure)?.trim().replace(/[\s.]+$/, "");+ if (!slot.startsComputer) {+ return `This turn could not claim ${label}${why ? ` (${why})` : ""}. This call was not performed. Do not retry computer work in this turn; tell the person what you could not do.`;+ }+ return `${label.charAt(0).toUpperCase()}${label.slice(1)} could not be started${why ? `: ${why}` : ""}. This call was not performed.` ++ `${slot.backOnAuto ? " This conversation is back on Auto." : ""} Do not retry computer work in this turn; tell the person what you could not do.`;+}+export function lazyClaimRetryText(slot: Pick<AutoVmClaimSlot, "label" | "retryReason">): string {return `This turn could not reach ${slot.label ?? "this computer"} just now (${slot.retryReason}). This call was not performed; try it again in a moment.`;}diff --git a/server/boat-delete-journal.ts b/server/boat-delete-journal.tsindex a0d1dff21d..259d9042e1 100644--- a/server/boat-delete-journal.ts+++ b/server/boat-delete-journal.ts@@ -17,6 +17,9 @@ const BOAT_ID = /^bx_[23456789abcdefghjkmnpqrstuvwxyz]{8}$/;const OPERATION_ID = /^bdop_[a-f0-9]{32}$/;const PROVIDER_STATUSES = new Set(["pending", "processing", "blocked", "completed"]);+/** Codes of a create refused while the bot's previous computer is being removed, or right after its removal finished. */+export const BOAT_DELETING = "computer_deleting", BOAT_DELETION_FINISHED = "previous_deletion_finished";+export type BoatDeletionPhase = "prepared" | "accepted" | "blocked";export type BoatDeletionStatus = "pending" | "processing" | "blocked" | "completed";diff --git a/server/boat.ts b/server/boat.tsindex 8cea6a5dfc..81db0b50b4 100644--- a/server/boat.ts+++ b/server/boat.ts@@ -26,7 +26,7 @@ import {type BoatCreateRequest,} from "./boat-create-idempotency.ts";import {- boatDeletionSnapshot,+ BOAT_DELETING, BOAT_DELETION_FINISHED, boatDeletionSnapshot,getBoatDeletion,hasPendingBoatDeletionForBot,markBoatDeletionAccepted,@@ -718,7 +718,7 @@ function inventoryFailure(inventory: ManagedBoatInventory): Error & { status: nufunction deletionFenceError(): Error & { status: number } {return Object.assign(new Error("this cloud computer is being deleted — wait for it to finish, or retry Delete if it needs attention"),- { status: 409 },+ { status: 409, code: BOAT_DELETING },);}@@ -1055,7 +1055,7 @@ async function finishPriorDeletionBeforeProvision(cfg: AppConfig, botId: string)}throw Object.assign(new Error("the previous cloud computer deletion finished — retry to create a new computer"),- { status: 409 },+ { status: 409, code: BOAT_DELETION_FINISHED },);}diff --git a/server/cloud-computer-slow-start.e2e.test.ts b/server/cloud-computer-slow-start.e2e.test.tsindex 25df677e49..2f546d7795 100644--- a/server/cloud-computer-slow-start.e2e.test.ts+++ b/server/cloud-computer-slow-start.e2e.test.ts@@ -32,8 +32,8 @@ describe("a slow cloud computer start", () => {const requests: string[] = [];/** The relay keeps a new computer "provisioning" while this is set, never* answers a desktop link request while `desktop` is set, and cuts off this- * many computer listings before answering, as a dropped connection does. */- const hold = { provisioning: false, desktop: false, dropLists: 0 };+ * many computer listings before answering, as a dropped connection does, and refuses every create while `refuseCreate` is set. */+ const hold = { provisioning: false, desktop: false, dropLists: 0, refuseCreate: false };const held: ServerResponse[] = [];const api = async (method: string, path: string, body?: unknown) => {@@ -98,6 +98,7 @@ describe("a slow cloud computer start", () => {if (req.headers.authorization !== `Bearer ${INCLUDED}`) return send(401, { ok: false, code: "unauthorized" });if (path === "/boxes" && req.method === "GET" && hold.dropLists > 0) { hold.dropLists--; return void req.socket.destroy(); }if (path === "/boxes" && req.method === "GET") return send(200, { ok: true, boxes: rows, pageInfo: { nextCursor: null } });+ if (path === "/boxes" && req.method === "POST" && hold.refuseCreate) return send(422, { ok: false, message: "the sandbox image is unavailable" });if (path === "/boxes" && req.method === "POST") {const row = { id: `bx_${"23456789abcdefgh"[rows.length]}3456789`, state: "provisioning" };rows.push(row);@@ -242,4 +243,21 @@ describe("a slow cloud computer start", () => {hold.desktop = false;}}, 60_000);++ it("a start that fails while a call waits on it answers that call with the reason, not a refusal for an ended turn", async () => {+ hold.refuseCreate = true;+ try {+ const bot = await cloudBot("Refused starter");+ const sent = await startTurn(bot.id, "Open the cloud desktop");+ const answer = await screenshot(sent);+ expect(answer.isError).toBe(true);+ expect(answer.content[0]?.text).toMatch(/^The cloud computer could not be started: .*the sandbox image is unavailable.*\. This call was not performed\./);+ const [row] = await until(() => failedRows(bot.id), found => found.length > 0);+ expect(row.tool.place).toMatchObject({ params: { bot: "Refused starter" } });+ await until(() => task(bot.id), current => current?.busy === false, 20_000);+ await api("DELETE", `/api/bots/${bot.id}`);+ } finally {+ hold.refuseCreate = false;+ }+ }, 45_000);});diff --git a/server/cloud-computer-tools.test.ts b/server/cloud-computer-tools.test.tsindex 7dc522ddb6..1f7a894c0b 100644--- a/server/cloud-computer-tools.test.ts+++ b/server/cloud-computer-tools.test.ts@@ -166,6 +166,16 @@ describe("cloud computer tools", () => {await expect(rpc({ method: "resources/read" }).done).rejects.toMatchObject({ status: 400 });});+ it("answers a call the gate refused with the refusal, even when the turn ended while it waited", async () => {+ const ended = () => { throw Object.assign(new Error("This bot turn has already ended"), { status: 401 }); };+ const blockedReason = "The cloud computer could not be started: the cloud computer didn't start in time. This call was not performed.";+ const result = await tools.cloudComputerRpc({ method: "tools/call", params: { name: "screenshot", arguments: {} } }, {+ cfg, boxId: () => null, signal: new AbortController().signal, gate: async () => ({ held: true, blockedReason }), assertActive: ended,+ });+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: expect.stringContaining(blockedReason) }] });+ expect(calls).toHaveLength(0);+ });+it("aborts an in-flight Boat command without retrying it", async () => {holdCommand = true;const started = new Promise<void>(resolve => { commandStarted = resolve; });diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.tsindex 2dddd6060e..79f8f76d42 100644--- a/server/cloud-computer-tools.ts+++ b/server/cloud-computer-tools.ts@@ -149,8 +149,9 @@ export async function cloudComputerRpc(const problem = cloudComputerCallProblem(params.name, args);if (problem) return { isError: true, content: [{ type: "text", text: problem }] };const control = await deps.gate();- deps.assertActive();+ // A refusal acts on no Boat, so it answers even when the turn has ended meanwhile.if (control.held) return { isError: true, content: [{ type: "text", text: controlRefusal(control) }] };+ deps.assertActive();const boxId = deps.boxId();if (!boxId) return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_NOT_READY }] };const late = AbortSignal.timeout(Math.max(1, deadline - Date.now()));diff --git a/server/host/cloud-computer-power.test.ts b/server/host/cloud-computer-power.test.tsindex 57b4ae69c3..490a0eae2e 100644--- a/server/host/cloud-computer-power.test.ts+++ b/server/host/cloud-computer-power.test.ts@@ -302,6 +302,34 @@ describe("cloud computer power", () => {expect(fake.provisionBoat).not.toHaveBeenCalled();});+ it("waking a stopped computer waits the whole start budget, not a shorter wait of its own", async () => {+ fake.states.set("asleep", "archived");+ await power.start(bot("asleep"), turn("t1"), { budgetMs: 150_000 });+ expect(fake.readyBoat.mock.calls[0]![2]).toBeGreaterThan(140_000);+ });++ it("a create that meets the previous computer still being removed waits for the removal, then creates", async () => {+ const refusals = [{ code: "computer_deleting" }, { code: "computer_deleting" }, { code: "previous_deletion_finished" }];+ fake.provisionBoat = vi.fn(async (_cfg, owner: string) => {+ const refusal = refusals.shift();+ if (refusal) throw Object.assign(new Error("the previous cloud computer is still being removed"), refusal);+ fake.states.set(owner, "ready");+ });+ const started = power.start(bot("again"), turn("t1"), { budgetMs: 150_000 });+ await vi.advanceTimersByTimeAsync(10_000);+ await expect(started).resolves.toMatchObject({ state: "ready" });+ expect(fake.provisionBoat).toHaveBeenCalledTimes(4);+ });++ it("a removal that outlasts the start budget fails the start with its own reason", async () => {+ fake.provisionBoat = vi.fn(async () => { throw Object.assign(new Error("this cloud computer is being deleted"), { code: "computer_deleting" }); });+ const started = power.start(bot("stuck"), turn("t1"), { budgetMs: 20_000 });+ const failed = expect(started).rejects.toThrow("is being deleted");+ await vi.advanceTimersByTimeAsync(20_000);+ await failed;+ expect(fake.provisionBoat.mock.calls.length).toBeLessThanOrEqual(8);+ });+it("a start that outlives its turn keeps the computer on until the start is done", async () => {let created!: () => void;fake.provisionBoat = vi.fn(() => new Promise<void>(resolve => { created = () => { fake.states.set("new", "ready"); resolve(); }; }));diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.tsindex c89bee8501..8bf713ef57 100644--- a/server/host/cloud-computer-power.ts+++ b/server/host/cloud-computer-power.ts@@ -3,7 +3,7 @@// while a computer is on, up to its own eight-hour auto-stop.import * as boat from "../boat.ts";import { boatCreateRecoverySnapshot } from "../boat-create-idempotency.ts";-import { hasPendingBoatDeletionForBot } from "../boat-delete-journal.ts";+import { BOAT_DELETING, BOAT_DELETION_FINISHED, hasPendingBoatDeletionForBot } from "../boat-delete-journal.ts";import { backgroundCommandRunning } from "../cloud-computer-background.ts";import { ComputerIdleTimer } from "../computer-idle.ts";import type { AppConfig } from "../config.ts";@@ -21,6 +21,7 @@ const MAX_LISTING_RETRY_MS = 60 * 60_000;export const CLOUD_COMPUTER_START_BUDGET_MS = Math.max(1_000, Number(process.env.OMB_CLOUD_COMPUTER_START_BUDGET_MS) || 150_000);export const CLOUD_COMPUTER_STARTING = "The cloud computer is still starting. This call was not performed. Take a fresh screenshot in a moment.";export const CLOUD_COMPUTER_DID_NOT_START = "the cloud computer didn't start in time";+const REMOVAL_POLL_MS = 3_000;type ScheduledRoutine = Pick<Routine, "botId" | "runOn" | "enabled" | "nextRunAt">;@@ -111,12 +112,13 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {used(held.owner);}- /** `existingOnly`: wake or attach the bot's computer, but never create one (null when it has none). */- async function start(bot: BotRecord, turn: TurnOwner, opts: { existingOnly?: boolean } = {}) {+ /** `existingOnly`: wake or attach the bot's computer, but never create one (null when it has none). Every wait inside+ * fits `budgetMs`. */+ async function start(bot: BotRecord, turn: TurnOwner, opts: { existingOnly?: boolean; budgetMs?: number } = {}) {attached(turn, bot.id);starting.set(bot.id, (starting.get(bot.id) ?? 0) + 1);try {- return await startBotBoat(bot, opts.existingOnly === true);+ return await startBotBoat(bot, opts.existingOnly === true, Date.now() + (opts.budgetMs ?? CLOUD_COMPUTER_START_BUDGET_MS));} finally {const left = (starting.get(bot.id) ?? 1) - 1;if (left > 0) starting.set(bot.id, left);@@ -124,26 +126,40 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {}}- async function startBotBoat(bot: BotRecord, existingOnly: boolean) {+ async function startBotBoat(bot: BotRecord, existingOnly: boolean, deadline: number) {let b = await boat.findBoat(cfg, bot.id);const lifecycleOf = () => boat.boatTurnLifecycleAction(typeof b?.state === "string" ? b.state : null);let lifecycle = lifecycleOf();if (lifecycle === "provision" && existingOnly) return null;if (lifecycle === "provision") {broadcast({ kind: "computer", botId: bot.id, state: "provisioning", place: "cloud" });- await boat.provisionBoat(cfg, bot.id, bot.name);+ await provisionOnceRemoved(bot, deadline);b = await boat.findBoat(cfg, bot.id);lifecycle = lifecycleOf();}// An archived Boat answers every action with an error until it resumes: wake it once here.if (lifecycle === "wake") {broadcast({ kind: "computer", botId: bot.id, state: "waking", place: "cloud" });- b = (await boat.readyBoat(cfg, bot.id)) ?? b;+ b = (await boat.readyBoat(cfg, bot.id, Math.max(1_000, deadline - Date.now()))) ?? b;lifecycle = lifecycleOf();}return b && lifecycle === "attach" ? b : null;}+ /** A start that failed removes the computer it created, so the next one can meet that removal still under way. */+ async function provisionOnceRemoved(bot: BotRecord, deadline: number): Promise<void> {+ for (;;) {+ try {+ await boat.provisionBoat(cfg, bot.id, bot.name);+ return;+ } catch (error) {+ const code = (error as { code?: unknown } | null)?.code;+ if ((code !== BOAT_DELETING && code !== BOAT_DELETION_FINISHED) || closed || Date.now() + REMOVAL_POLL_MS >= deadline) throw error;+ if (code === BOAT_DELETING) await new Promise(resolve => setTimeout(resolve, REMOVAL_POLL_MS));+ }+ }+ }+/** At startup: what a previous run left on gets the same window. Orphans (no owner left) stay for Settings → Computers. */async function armRunning(retryInMs = CLOUD_COMPUTER_IDLE_MS): Promise<void> {if (closed || !boat.boatConfigured(cfg)) return;diff --git a/server/index.ts b/server/index.tsindex e66544cd19..4b7a78afc8 100644--- a/server/index.ts+++ b/server/index.ts@@ -510,7 +510,7 @@ import { OrgLibrary } from "./org-library.ts";import { shouldMountLocalComputer } from "./local-routing.ts";import { autoLocalVmAttachable, type ContainerComputerStatus } from "./container-computer.ts";import { startStoppedPodmanMachine } from "./podman-machine.ts";-import { keepTransient, lazyClaimRetryText, settledWithin, startAutoVmClaim, withinBudget, type AutoVmClaimSlot, type AutoVmClaimTable } from "./auto-vm-claims.ts";+import { keepTransient, lazyClaimFailedText, lazyClaimRetryText, settledWithin, startAutoVmClaim, withinBudget, type AutoVmClaimSlot, type AutoVmClaimTable } from "./auto-vm-claims.ts";import { CONTROL_ACT_WITHIN_MS, CONTROL_BUSY, CONTROL_HANDED_BACK, CONTROL_WAIT_MS, CONTROL_WAITED, controlRefusal, type ControlState } from "./control-client.ts";import { computerFreeAfterText, computerParkedText, computerPersonAwayText, computerStoppedWaitingText, computerWaitingText, type ComputerHolder } from "./computer-wait.ts";import { modelContextWindow } from "./model-context-window.ts";@@ -1878,11 +1878,11 @@ class ComputerWaitParked extends Error {this.generation = generation;}}-function clearFailedAutoPin(botId: string, threadId: string, place: Surface): void {+function clearFailedAutoPin(botId: string, threadId: string, place: Surface): boolean {const pinned = store.taskByThread(botId, threadId);- if (pinned?.surface === place && pinned.surfaceSource === "auto") {- store.patchTask(botId, threadId, { surface: undefined, surfaceSource: undefined });- }+ if (pinned?.surface !== place || pinned.surfaceSource !== "auto") return false;+ store.patchTask(botId, threadId, { surface: undefined, surfaceSource: undefined });+ return true;}async function asPlaceFailure(@@ -5715,10 +5715,7 @@ async function computerCallGate(internalCapability: InternalCapability, signal?:held = { held: true, helpOpen, reason: "person" };} else if (lazyClaim?.failed) {// A rejected lazy claim refuses every screen call for the rest of the generation: never forward onto a desktop this turn never claimed.- return {- held: true, helpOpen: false,- blockedReason: `This turn could not claim ${lazyClaim.label ?? "this computer"}${lazyClaim.failure ? ` (${lazyClaim.failure})` : ""}. This call was not performed. Do not retry computer work in this turn; tell the person what you could not do.`,- };+ return { held: true, helpOpen: false, blockedReason: lazyClaimFailedText(lazyClaim) };} else if (lazyClaim?.lazy && !lazyClaim.claimed) {startAutoVmClaim(autoVmClaims, threadId, generation, call);if (lazyClaim.begin && Date.now() < deadline && !signal?.aborted) {@@ -5921,6 +5918,7 @@ function mountBotBoat(});if (!attached) throw new Error(opts.existingOnly ? "this bot no longer has a cloud computer of its own" : "the cloud computer could not be created or reached");} catch (error) {+ slot.cause = error instanceof Error ? error.message : String(error);throw keepTransient(error, opts.source ? await asPlaceFailure(error, "cloud", opts.source, bot, "box") : error);}slot.boxId = attached.boxId;@@ -5941,7 +5939,7 @@ async function attachBotBoat(bot: BotRecord, owner: TurnOwner, start: { budgetMs// Claim before any network await so setup itself cannot race another turn.await bindTurnComputer(owner, `computer:box-bot:${bot.id}`, true);start.onSeated();- const machine = await withinBudget(cloudComputerPower.start(bot, owner, { existingOnly: start.existingOnly }), start.budgetMs, CLOUD_COMPUTER_DID_NOT_START);+ const machine = await withinBudget(cloudComputerPower.start(bot, owner, { existingOnly: start.existingOnly, budgetMs: start.budgetMs }), start.budgetMs, CLOUD_COMPUTER_DID_NOT_START);if (!machine) return null;await bindTurnComputer(owner, `computer:box:${machine.id}`);return {@@ -8078,7 +8076,8 @@ async function beginTurn(return;}const placeFailure = error instanceof PlaceUnavailableError ? error : undefined;- if (placeFailure) clearFailedAutoPin(bot.id, threadId, placeFailure.place);+ const slot = autoVmClaims.get(threadId);+ if (placeFailure && clearFailedAutoPin(bot.id, threadId, placeFailure.place) && slot?.owner.generation === resourceOwner.generation) slot.backOnAuto = true;const message = placeFailure?.message ?? `computer unavailable — ${label} could not be claimed for this turn (${failure})`;store.appendMessage(threadId, {role: "bot",