Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud computer: wait out a slow wake, replace one that never answers, and let calls wait for a recovery
milind-sonife03f46024ef
diff --git a/server/auto-vm-claims.ts b/server/auto-vm-claims.tsindex 90265146a9..7958fc2562 100644--- a/server/auto-vm-claims.ts+++ b/server/auto-vm-claims.ts@@ -80,6 +80,21 @@ export function startAutoVmClaim(table: AutoVmClaimTable, threadId: string, geneslot.begin = begin;}+/** The turn's cloud computer `replacedBoxId` was replaced: the slot claims again, which starts the owner's new computer,+ * and this waits for that until `until`. The new computer's id once it answers; null while it is still starting (the+ * claim goes on, and the turn's next call waits for it), or when the claim failed or this slot never claimed one. */+export async function reclaimAutoVm(table: AutoVmClaimTable, owner: AutoVmClaimOwner, replacedBoxId: string, until: number, signal?: AbortSignal): Promise<string | null> {+ const slot = table.get(owner.threadId);+ if (!slot || slot.owner.generation !== owner.generation || !slot.lazy || !slot.startsComputer) return null;+ // Only the first call to see the replacement starts the claim again; later ones wait on that same claim.+ if (slot.claimed && slot.boxId === replacedBoxId) {+ Object.assign(slot, { claimed: false, begin: undefined, attempts: 0, boxId: undefined, retryReason: undefined });+ }+ startAutoVmClaim(table, owner.threadId, owner.generation);+ if (!slot.claimed) await settledWithin(slot.begin ?? null, until - Date.now(), signal);+ return slot.claimed && slot.boxId && slot.boxId !== replacedBoxId ? slot.boxId : null;+}+/** 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" | "limit" | "startsComputer" | "backOnAuto">): string {const label = slot.label ?? "this computer";diff --git a/server/boat-health.ts b/server/boat-health.tsindex b8aeb33b23..7211a07584 100644--- a/server/boat-health.ts+++ b/server/boat-health.ts@@ -17,8 +17,10 @@ export const DEAD_COMPUTER = {witnessMs: 10 * 60_000,/** At most this many automatic replacements per computer owner in an hour; after that it stops and says so. */replacementsPerHour: 1,+ /** And in a day, so a provider that keeps handing out broken computers cannot use up the plan's computers or hours. */+ replacementsPerDay: 3,/** And at most this many automatic deletes per installation in an hour, whoever's computers they are. */- installationDeletesPerHour: 1,+ installationDeletesPerHour: 3,/** The provider's `error` must be seen on two reads at least this far apart before a computer is deleted for it. */deadConfirmMs: process.env.OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS?.trim() ? Math.max(0, Number(process.env.OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS) || 0) : 30 * 60_000,/** At most one automatic restart per installation in this long. */diff --git a/server/boat-ready.test.ts b/server/boat-ready.test.tsindex ba103e1c08..9d7bcd5965 100644--- a/server/boat-ready.test.ts+++ b/server/boat-ready.test.ts@@ -84,12 +84,37 @@ describe("waiting for a cloud computer to answer", () => {it("gives up after a minute and a half when the provider gives no reason for the silence", async () => {const h = harness(() => false);- const answer = await h.readiness.awaitAnswer(cfg, BOX, { woke: true });+ h.health.answered(BOX);+ h.advance(READY_WAIT.freshMs + 1);+ const answer = await h.readiness.awaitAnswer(cfg, BOX);expect(answer).toMatchObject({ ok: false, phase: "waking" });expect(answer.waitedMs).toBeLessThanOrEqual(READY_WAIT.answerPatienceMs + READY_WAIT.probeTimeoutMs);expect(answer.waitedMs).toBeGreaterThan(READY_WAIT.answerPatienceMs - READY_WAIT.probeTimeoutMs - READY_WAIT.probeGapMs);});+ it("after a wake, waits three minutes with longer and longer gaps before it gives up", async () => {+ const gaps: number[] = [];+ const h = harness(() => false);+ const readiness = createBoatReadiness({+ probe: async () => { h.advance(READY_WAIT.probeTimeoutMs); return false; },+ read: async () => ({ state: "idle", health: "ok" }), health: h.health, counters: h.counters, now: h.now,+ sleep: async (ms) => { gaps.push(ms); h.advance(ms); },+ });+ const answer = await readiness.awaitAnswer(cfg, BOX, { woke: true });+ expect(answer).toMatchObject({ ok: false, phase: "waking" });+ expect(answer.waitedMs).toBeGreaterThan(READY_WAIT.wakePatienceMs - READY_WAIT.probeTimeoutMs - 20_000);+ expect(answer.waitedMs).toBeLessThanOrEqual(READY_WAIT.wakePatienceMs + READY_WAIT.probeTimeoutMs);+ expect(gaps.slice(0, 5)).toEqual([...READY_WAIT.wakeGapsMs]);+ expect(gaps.slice(5).every((gap) => gap === 20_000)).toBe(true);+ });++ it("after a wake, a computer silent for two and a half minutes is still waited for, and answers", async () => {+ const h = harness((at) => at >= h.start + 150_000);+ const answer = await h.readiness.awaitAnswer(cfg, BOX, { woke: true });+ expect(answer.ok).toBe(true);+ expect(answer.waitedMs).toBeGreaterThanOrEqual(150_000);+ });+it("waits up to ten minutes while the provider says the disk is being restored, and reports that", async () => {const restoring = { state: "idle", health: "ok", hydrated: false, lastSnapshotStatus: "in_progress" };const slow = harness((at) => at >= slow.start + 6 * 60_000, () => restoring);diff --git a/server/boat-ready.ts b/server/boat-ready.tsindex ccc1783e8c..3dff9c2e42 100644--- a/server/boat-ready.ts+++ b/server/boat-ready.ts@@ -25,6 +25,11 @@ export const READY_WAIT = {freshMs: 60_000,/** With the provider saying ready and giving no reason for the silence: a resume takes about 8 s, so this is ten of them. */answerPatienceMs: 90_000,+ /** Right after a wake, a create or a restart, the same silence is given longer: resumed computers were seen to time+ * out every command for several minutes and then answer. Past this the computer may be replaced (boat-recovery.ts). */+ wakePatienceMs: 3 * 60_000,+ /** Between probes after a wake, longer as the silence goes on; the last one repeats. */+ wakeGapsMs: [3_000, 5_000, 8_000, 13_000, 20_000],/** With the provider saying the disk is still being restored. Restores of 5 to 30 minutes were seen; past ten the* computer is restarted instead, once. */restorePatienceMs: 10 * 60_000,@@ -137,11 +142,12 @@ export function createBoatReadiness(overrides: Partial<BoatReadinessDeps> = {})failures += 1;deps.health.unanswered(boxId);enter(boatSignals(await deps.read(cfg, boxId)).restoring === true ? "restoring" : phase);- const patience = phase === "restoring" ? READY_WAIT.restorePatienceMs : READY_WAIT.answerPatienceMs;+ const patience = phase === "restoring" ? READY_WAIT.restorePatienceMs : opts.woke ? READY_WAIT.wakePatienceMs : READY_WAIT.answerPatienceMs;+ const gap = opts.woke ? READY_WAIT.wakeGapsMs[Math.min(failures, READY_WAIT.wakeGapsMs.length) - 1]! : READY_WAIT.probeGapMs;// The patience may be overrun by one probe; the caller's deadline never is.- const next = deps.now() + READY_WAIT.probeGapMs;+ const next = deps.now() + gap;if (next >= started + patience || next + READY_WAIT.probeTimeoutMs > hardStop) return done({ ok: false, phase, waitedMs: deps.now() - started });- await deps.sleep(READY_WAIT.probeGapMs, opts.signal);+ await deps.sleep(gap, opts.signal);}}diff --git a/server/boat-recovery.test.ts b/server/boat-recovery.test.tsindex facf9e560b..ff873aae82 100644--- a/server/boat-recovery.test.ts+++ b/server/boat-recovery.test.ts@@ -250,20 +250,18 @@ describe("a cloud computer the provider reports in error", () => {expect(deletes()).toHaveLength(2);});- it("is deleted by itself at most once an hour for the whole installation, whoever's computer it is", async () => {- const first = await botWith("error");- const second = await botWith("error");- await boat.findBoat(cfg, first.botId);- await boat.findBoat(cfg, second.botId);- await expect(boat.provisionBoat(cfg, first.botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_DEAD_WAITING);- await expect(boat.provisionBoat(cfg, second.botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_DEAD_WAITING);+ it("is deleted by itself at most three times an hour for the whole installation, whoever's computers they are", async () => {+ const dead = [await botWith("error"), await botWith("error"), await botWith("error"), await botWith("error")];+ for (const { botId } of dead) await boat.findBoat(cfg, botId);+ for (const { botId } of dead) await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_DEAD_WAITING);at += DEAD_CONFIRM;- await expect(boat.provisionBoat(cfg, first.botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });- await expect(boat.provisionBoat(cfg, second.botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NEEDS_PERSON);- expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([first.box.id]);+ for (const { botId } of dead.slice(0, 3)) await expect(boat.provisionBoat(cfg, botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ const last = dead[3]!;+ await expect(boat.provisionBoat(cfg, last.botId, "Bot")).rejects.toThrow(words.CLOUD_COMPUTER_NEEDS_PERSON);+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual(dead.slice(0, 3).map(({ box }) => box.id));at += 61 * 60_000;- await expect(boat.provisionBoat(cfg, second.botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });- expect(deletes()).toHaveLength(2);+ await expect(boat.provisionBoat(cfg, last.botId, "Bot")).rejects.toMatchObject({ code: journal.BOAT_DELETION_FINISHED });+ expect(deletes()).toHaveLength(4);});it("finishes after a crash between the delete and the new computer, telling each side once", async () => {@@ -348,19 +346,17 @@ describe("a cloud computer that says it is ready but does not answer", () => {expect(deletes()).toHaveLength(0);});- it("is restarted, which keeps its files, but never deleted when no other computer answers: it then waits for the person", async () => {+ it("with no other computer to compare against, is restarted, then replaced as soon as the restart's wake gets no answer", async () => {const { botId, box } = await botWith("ready");commandStatus.set(box.id, 502);await boat.findBoat(cfg, botId);stopsAnswering(box.id);- await until(() => recovery.status(botId)?.state === "needs-person");+ await until(() => recovery.status(botId)?.state === "replaced");expect(stops().map((request) => request.path)).toEqual([`/boxes/${box.id}/stop`]);expect(recovery.verdict(botId)).toBe("restart-failed");- expect(deletes()).toHaveLength(0);- expect(told).toEqual([[botId, "needsPerson"]]);- expect(recovery.refusal(box.id, "after")).toBe(words.CLOUD_COMPUTER_NEEDS_PERSON);- expect(recovery.refusal(box.id, "before")).toBeNull();- expect(recovery.stuck(botId)).toBe(true);+ expect(deletes().map((request) => request.headers["x-ascii-confirm-delete"])).toEqual([box.id]);+ expect(told).toEqual([[botId, "replaced"]]);+ expect(recovery.replaced(box.id)).toBe(true);});it("is neither restarted nor deleted while the provider's list fails", async () => {@@ -585,6 +581,7 @@ describe("why a silent computer was left as it is", () => {});it("says a restart did not help, and keeps saying that while the computer stays silent", async () => {+ autoOn = false;const { botId, box } = await botWith("ready");commandStatus.set(box.id, 502);await boat.findBoat(cfg, botId);@@ -599,6 +596,7 @@ describe("why a silent computer was left as it is", () => {});it("says it was restarted too recently when it goes silent again within the hour, and nothing once it answers", async () => {+ autoOn = false;const { botId, box } = await botWith("ready");commandStatus.set(box.id, 502);resumeAnswers.add(box.id);@@ -752,17 +750,20 @@ describe("a start the Admin refuses right after a replacement", () => {});});-describe("with automatic replacement off, the default", () => {- beforeEach(() => { autoOn = false; });-- it("is off unless the environment or config.json turns it on, and the environment wins", () => {+describe("automatic replacement", () => {+ it("is on unless the environment or config.json turns it off, and the environment wins", () => {const on = recoveryModule.cloudComputerAutoReplace;- expect(on({}, {})).toBe(false);- expect(on({ features: { cloudComputerAutoReplace: true } }, {})).toBe(true);- expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "1" })).toBe(true);+ expect(on({}, {})).toBe(true);+ expect(on({ features: { cloudComputerAutoReplace: false } }, {})).toBe(false);+ expect(on({ features: { cloudComputerAutoReplace: false } }, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "1" })).toBe(true);expect(on({ features: { cloudComputerAutoReplace: true } }, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "0" })).toBe(false);- expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "yes" })).toBe(false);+ expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "0" })).toBe(false);+ expect(on({}, { OMB_CLOUD_COMPUTER_AUTO_REPLACE: "yes" })).toBe(true);});+});++describe("with automatic replacement switched off", () => {+ beforeEach(() => { autoOn = false; });it("never deletes a computer the provider reports in error: the bot and the person hear it once", async () => {const { botId } = await botWith("error");diff --git a/server/boat-recovery.ts b/server/boat-recovery.tsindex 051964559b..c576a800c7 100644--- a/server/boat-recovery.ts+++ b/server/boat-recovery.ts@@ -1,6 +1,8 @@-// A cloud computer that stopped answering: waited for while the provider is still restoring its disk, restarted once, then-// replaced (its deletion frees the plan's place, and the next use creates a new one) or, with automatic replacement off,-// left for the person. The bot and the person are told once. Nothing here asks the person anything.+// A cloud computer that stopped answering: waited for while the provider is still restoring its disk, restarted once,+// then replaced (its deletion frees the plan's place, and the next use creates a new one) or, with automatic replacement+// switched off, left for the person. A computer woken for a turn that stays silent past the wake's patience is replaced+// at once (wakeTimedOut), so the turn goes on on a new one. The bot and the person are told once. Nothing here asks the+// person anything.import { existsSync, readFileSync } from "node:fs";import { join } from "node:path";@@ -46,14 +48,14 @@ interface Replacement {toldPerson?: true;}-/** Whether a dead computer is deleted and replaced without the person. Off unless OMB_CLOUD_COMPUTER_AUTO_REPLACE is "1" or- * config.json has `"features": {"cloudComputerAutoReplace": true}`; the environment, "1" or "0", wins. Off by default until- * the provider confirms that deleting a computer whose host is unreachable is safe for the rest of the account. */+/** Whether a dead or silent computer is deleted and replaced without the person. On unless OMB_CLOUD_COMPUTER_AUTO_REPLACE+ * is "0" or config.json has `"features": {"cloudComputerAutoReplace": false}`; the environment, "1" or "0", wins. Off, a+ * silent computer waits for the person's Replace computer, as before. */export function cloudComputerAutoReplace(cfg: Pick<AppConfig, "features">, env: NodeJS.ProcessEnv = process.env): boolean {const override = env.OMB_CLOUD_COMPUTER_AUTO_REPLACE?.trim();if (override === "1") return true;if (override === "0") return false;- return cfg.features?.cloudComputerAutoReplace === true;+ return cfg.features?.cloudComputerAutoReplace !== false;}export interface BoatRecoveryDeps {@@ -66,6 +68,8 @@ export interface BoatRecoveryDeps {eligible?(owner: string): boolean;/** A person is driving or viewing this owner's desktop now. */personActive?(owner: string): boolean;+ /** A running turn of another bot holds this computer: it is never replaced by itself then. */+ usedByOther?(owner: string, boxId: string): boolean;file?: string;now?: () => number;health?: BoatHealth;@@ -83,6 +87,21 @@ export type RecoveryVerdict = "restart-failed" | "person-busy" | "restart-limitetype Dead = { boxId: string; name: string };type ReplaceOutcome = "confirmed" | "pending" | "kept" | "held" | "waiting" | "capped" | "failed";+/** What became of a computer that was woken for a turn and stayed silent past the wake's patience. `answers`: a last probe+ * got through after all. `gone`: it no longer exists, so the next start makes a new one. `off`: automatic replacement is+ * switched off, so nothing was done. `kept`: it was left as it is, and `why` says so in a few words for the turn. */+export type WakeTimeoutOutcome = { kind: "answers" | "replaced" | "gone" | "off" } | { kind: "kept"; why: string };++const KEPT_WHY: Partial<Record<ReplaceOutcome | "unreachable", string>> = {+ capped: "it was already replaced recently, and MausBot replaces a bot's computer at most once an hour and three times a day",+ held: "it could not be replaced by itself right now (a person or another bot is using it, or this installation already replaced computers in the last hour)",+ failed: "replacing it failed: the old computer's deletion was not confirmed",+ unreachable: "the cloud computer service itself can't be reached right now",+ waiting: "the provider reports it broken, and it is replaced if it stays that way",+};+const keptWhy = (outcome: keyof typeof KEPT_WHY): WakeTimeoutOutcome =>+ ({ kind: "kept", why: `the cloud computer did not answer after waking, and ${KEPT_WHY[outcome] ?? "it was left as it is"}. Nothing else was changed; trying again later is fine` });+export function createBoatRecovery(deps: BoatRecoveryDeps) {const health = deps.health ?? boatHealth;const now = deps.now ?? Date.now;@@ -229,13 +248,14 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {return "held";}if (!fenced) {- if (personBusy(owner, target.boxId)) { needsPerson(owner, target.boxId); return "held"; }+ if (personBusy(owner, target.boxId) || deps.usedByOther?.(owner, target.boxId) === true) { needsPerson(owner, target.boxId); return "held"; }if (opts.dead && !deadConfirmed(target.boxId)) { needsPerson(owner, target.boxId); return "waiting"; }if (!(await listWorks(cfg))) { unreachable(owner, target.boxId); return "held"; }const automatic = entries.filter((entry) => !entry.manual && entry.boxId !== target.boxId && now() - entry.at < HOUR_MS);- if (automatic.filter((entry) => entry.owner === owner).length >= DEAD_COMPUTER.replacementsPerHour) {+ const today = entries.filter((entry) => !entry.manual && entry.boxId !== target.boxId && entry.owner === owner && now() - entry.at < DAY_MS);+ if (automatic.filter((entry) => entry.owner === owner).length >= DEAD_COMPUTER.replacementsPerHour || today.length >= DEAD_COMPUTER.replacementsPerDay) {tellOnce(owner, target.boxId, "capped", "capped");- deps.log(`cloud computer ${owner}: ${target.boxId} was already replaced in the last hour; left as it is`);+ deps.log(`cloud computer ${owner}: ${target.boxId} was already replaced in the last hour, or three times today; left as it is`);return "capped";}if (automatic.length >= DEAD_COMPUTER.installationDeletesPerHour) {@@ -272,9 +292,10 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {}/** A fresh probe that got no answer, with the provider's list working; false when that is not so (the outcome is- * reported). `witness`: before a delete, another computer of this installation must have answered as well. A restart- * keeps the files, so the provider's own list answering is enough for it: an installation with one computer in use has- * no witness, and would otherwise never be restarted. */+ * reported). `witness`: before a delete, the installation's other computers must not all be silent as well: that is+ * the provider's own outage, which a new computer would not fix. An installation with no other computer in use has no+ * one to compare against; its list answering, a restart that did not help and the hourly and daily limits stand for+ * that, or a lone computer would never be replaced. */async function stillDown(owner: string, boxId: string, cfg: AppConfig, witness = true): Promise<boolean> {const probe = await boat.probeBoat(cfg, boxId);if (probe !== false) {@@ -283,14 +304,16 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {return false;}if (!(await listWorks(cfg))) { unreachable(owner, boxId); return false; }- // An installation whose other computers do not answer either cannot tell a dead machine from its own outage.- if (witness && !health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs)) { needsPerson(owner, boxId); return false; }+ if (witness && !health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs) && health.othersSilentWithin(boxId, DEAD_COMPUTER.witnessMs)) {+ unreachable(owner, boxId);+ return false;+ }return true;}- /** After the restart: replaced once the provider says the machine is gone, or after DEAD_COMPUTER.replaceAfterMs of no- * answers while another computer of this installation answers (else the provider itself may be down). */- async function decide(owner: string, boxId: string): Promise<void> {+ /** After the restart: replaced once the provider says the machine is gone, at once when the restart's own wake got no+ * answer in its patience (`restartFailed`), or else after DEAD_COMPUTER.replaceAfterMs of no answers. */+ async function decide(owner: string, boxId: string, restartFailed = false): Promise<void> {timers.delete(owner);const cfg = deps.cfg();const since = health.notRespondingSince(boxId);@@ -299,7 +322,7 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {if (!seen.identity || !(await boat.boatNameMatchesBot(owner, seen.identity.name))) return clear(owner, boxId);if (seen.identity.state === "error") return void await replace(owner, seen.identity, { dead: true });if (since === null || !READY.has(seen.identity.state)) return clear(owner, boxId);- const left = since + DEAD_COMPUTER.replaceAfterMs - now();+ const left = restartFailed ? 0 : since + DEAD_COMPUTER.replaceAfterMs - now();if (left > 0) {set(owner, boxId, "not-responding");const timer = setTimeout(() => void lane(owner, () => decide(owner, boxId)).catch((error) => deps.log(`cloud computer ${owner}: ${String(error)}`)), left);@@ -372,10 +395,38 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {}judge(owner, boxId, "restart-failed");deps.log(`cloud computer ${owner}: ${boxId} still does not answer after a restart`);+ return decide(owner, boxId, restarted === "no-answer");}return decide(owner, boxId);}+ /** A computer woken, created or restarted for a turn that did not answer in the wake's patience. Every guard of a+ * replacement holds; one that is merely slow but answers a last probe is kept. */+ async function wakeTimedOut(owner: string, boxId: string): Promise<WakeTimeoutOutcome> {+ if (!autoReplace()) return { kind: "off" };+ if (!eligible(owner)) { needsPerson(owner, boxId); return keptWhy("held"); }+ const cfg = deps.cfg();+ const seen = await boat.inspectBoatIdentity(cfg, boxId);+ if (!seen.available) { unreachable(owner, boxId); return keptWhy("unreachable"); }+ if (!seen.identity || !(await boat.boatNameMatchesBot(owner, seen.identity.name))) return { kind: "gone" };+ if (seen.identity.state !== "error") {+ const probe = await boat.probeBoat(cfg, boxId);+ if (probe !== false) {+ if (probe) health.answered(boxId);+ clear(owner, boxId);+ return { kind: "answers" };+ }+ if (!(await listWorks(cfg))) { unreachable(owner, boxId); return keptWhy("unreachable"); }+ if (!health.otherAnsweredWithin(boxId, DEAD_COMPUTER.witnessMs) && health.othersSilentWithin(boxId, DEAD_COMPUTER.witnessMs)) {+ unreachable(owner, boxId);+ return keptWhy("unreachable");+ }+ }+ deps.log(`cloud computer ${owner}: ${boxId} did not answer within ${Math.round(READY_WAIT.wakePatienceMs / 60_000)} minutes of waking; replacing it`);+ const outcome = await replace(owner, seen.identity, seen.identity.state === "error" ? { dead: true } : {});+ return outcome === "confirmed" || outcome === "pending" ? { kind: "replaced" } : outcome === "kept" ? { kind: "answers" } : keptWhy(outcome);+ }+const unsubscribe = health.onNotResponding((boxId) => {const owner = boat.boatOwnerOf(boxId);if (!owner || closed) return;@@ -431,6 +482,23 @@ export function createBoatRecovery(deps: BoatRecoveryDeps) {if (found?.boxId === boxId && found.state === "needs-person") return eligible(owner!) ? CLOUD_COMPUTER_NEEDS_PERSON : CLOUD_COMPUTER_TEAM_NOT_RESPONDING;return health.notRespondingSince(boxId) === null ? null : CLOUD_COMPUTER_NOT_RESPONDING;},+ wakeTimedOut: (owner: string, boxId: string): Promise<WakeTimeoutOutcome> => lane(owner, () => wakeTimedOut(owner, boxId)),+ /** Resolves once no restart or replacement of this computer is under way, or at `until`: a call waits that out instead+ * of being refused at once, so a recovery in progress is not taken for one failure after another. */+ async settle(boxId: string, until: number, signal?: AbortSignal): Promise<void> {+ const owner = boat.boatOwnerOf(boxId);+ if (!owner) return;+ const underWay = () => {+ const found = states.get(owner);+ return retired.has(boxId) ? lanes.has(owner) : found?.boxId === boxId && recoveryUnderWay(found.state) && (lanes.has(owner) || timers.has(owner));+ };+ // `until` is the caller's own clock, the wall clock.+ while (underWay() && Date.now() < until && !signal?.aborted && !closed) {+ await Promise.race([lanes.get(owner)?.catch(() => undefined), wait(Math.max(1, Math.min(pollMs, until - Date.now())))]);+ }+ },+ /** This computer was deleted by a replacement: the turn that used it goes on on the owner's new one. */+ replaced: (boxId: string): boolean => retired.has(boxId),/** Told once, with the first call on the owner's computer after a replacement or a restart. */notice(boxId: string): string | null {const owner = boat.boatOwnerOf(boxId);diff --git a/server/cloud-computer-lazy.e2e.test.ts b/server/cloud-computer-lazy.e2e.test.tsindex fdd354b914..200530dfcb 100644--- a/server/cloud-computer-lazy.e2e.test.ts+++ b/server/cloud-computer-lazy.e2e.test.ts@@ -348,7 +348,8 @@ describe("a cloud computer starts only when the bot uses it", () => {.filter((frame: any) => frame.kind === "notify" && frame.notification?.botId === botId && frame.notification.kind === "notice").map((frame: any) => frame.notification.body);- it("by default a computer whose machine is gone is never deleted by itself: the bot and the person are told once, and Replace computer replaces it", async () => {+ it("with automatic replacement switched off, a computer whose machine is gone is never deleted by itself: the bot and the person are told once, and Replace computer replaces it", async () => {+ await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: false } });const bot = await cloudBot("Waiting");await apiOk("POST", `/api/bots/${bot.id}/computer/provision`);const dead = rows.at(-1)!;@@ -376,11 +377,11 @@ describe("a cloud computer starts only when the bot uses it", () => {expect(creates()).toBe(made + 1);await finish(bot.id);expect(await recoveryLines(bot.id)).toHaveLength(1);+ await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: true } });await apiOk("DELETE", `/api/bots/${bot.id}`);}, 60_000);- it("with automatic replacement on, a computer whose machine is gone is replaced on its next use, and the bot and the person are told once", async () => {- await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: true } });+ it("by default, a computer whose machine is gone is replaced on its next use, and the bot and the person are told once", async () => {const bot = await cloudBot("Stranded");// Made from the panel, so no command has answered on it lately: one that has is kept for a few minutes.await apiOk("POST", `/api/bots/${bot.id}/computer/provision`);@@ -413,7 +414,6 @@ describe("a cloud computer starts only when the bot uses it", () => {const line = "Stranded's cloud computer stopped responding, so MausBot replaced it with a new one. Files that were only on the old computer are gone.";expect(await recoveryLines(bot.id)).toEqual([`recovery: ${waiting}`, `recovery: ${line}`]);expect(inboxNotices(bot.id)).toEqual([waiting, line]);- await apiOk("PATCH", "/api/config", { features: { cloudComputerAutoReplace: false } });await apiOk("DELETE", `/api/bots/${bot.id}`);}, 60_000);diff --git a/server/cloud-computer-tools.ts b/server/cloud-computer-tools.tsindex 2385fc3773..8127ea1175 100644--- a/server/cloud-computer-tools.ts+++ b/server/cloud-computer-tools.ts@@ -13,8 +13,8 @@ import { controlRefusal, type ControlState } from "./control-client.ts";import { COMPUTER_COPY_BUDGET_MS, HARNESS_CALL_BUDGET_MS } from "./harness-budget.ts";import { compileToolSchema } from "./mcp-schema-validator.ts";import {- CLOUD_COMPUTER_ANSWER_LOST, CLOUD_COMPUTER_EXEC_ANSWER_LOST, CLOUD_COMPUTER_NO_ANSWER, CLOUD_COMPUTER_STILL_RESTORING, CLOUD_COMPUTER_STILL_WAKING,- CLOUD_COMPUTER_UNREACHABLE,+ CLOUD_COMPUTER_ANSWER_LOST, CLOUD_COMPUTER_EXEC_ANSWER_LOST, CLOUD_COMPUTER_NO_ANSWER, CLOUD_COMPUTER_REPLACEMENT_STARTING, CLOUD_COMPUTER_STILL_RESTORING,+ CLOUD_COMPUTER_STILL_WAKING, CLOUD_COMPUTER_UNREACHABLE,} from "../shared/cloud-computer-recovery.ts";const coordinate = { type: "integer", minimum: 0, maximum: 32767 };@@ -62,6 +62,9 @@ export const EXEC_STOPPED_AT_LIMIT = "The cloud computer's provider stopped this+ "no longer running; what it had done up to then stays. Start it again with background: true, then follow it with exec_status.";/** Pointer moves, clicks, keys and the like take well under a second; this ends five seconds before the provider would stop a direct command at 30 s. */const QUICK_CALL_MS = 25_000;+/** A call that waits out a restart or replacement of its computer stops waiting this long before its own time is up,+ * so the call itself, or the line that says to repeat it, still gets through. */+const RECOVERY_WAIT_RESERVE_MS = 30_000;const COPY_TOOLS = new Set(["copy_from_computer", "copy_to_computer"]);export const cloudComputerCallBudgetMs = (name: unknown): number =>typeof name === "string" && COPY_TOOLS.has(name) ? COMPUTER_COPY_BUDGET_MS : HARNESS_CALL_BUDGET_MS;@@ -184,8 +187,16 @@ export async function cloudComputerRpc(signal: AbortSignal;/** The whole call, the gate's wait included, answers within this. */budgetMs?: number;- /** A computer that stopped answering (server/boat-recovery.ts): what the bot is told instead, and once after it was replaced. */- recovery?: { refusal(boxId: string, phase: "before" | "after"): string | null; notice(boxId: string): string | null };+ /** A computer that stopped answering (server/boat-recovery.ts): what the bot is told instead, and once after it was+ * replaced. `settle` waits out a restart or replacement under way; `replaced` says this computer was replaced. */+ recovery?: {+ refusal(boxId: string, phase: "before" | "after"): string | null; notice(boxId: string): string | null;+ settle?(boxId: string, until: number, signal?: AbortSignal): Promise<void>; replaced?(boxId: string): boolean;+ };+ /** Moves the turn onto the owner's new computer once `replacedBoxId` was replaced; its id, or null while it is still starting. */+ reclaim?(replacedBoxId: string, until: number, signal?: AbortSignal): Promise<string | null>;+ /** The call is waiting on its computer's recovery: the person's status line says the computer is waking. */+ waiting?(): void;/** The computer's disk (server/cloud-computer-disk.ts): told when each call begins and ends, and asked for a note to end the result with. */disk?: { began(cfg: AppConfig, boxId: string): void; ended(cfg: AppConfig, boxId: string): void; after(cfg: AppConfig, boxId: string, texts: readonly string[], failed: boolean): Promise<string | null> };/** Whether the computer answered this call: a call refused before it was sent, or one that got no answer, did not. */@@ -208,13 +219,28 @@ export async function cloudComputerRpc(// 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();+ let boxId = deps.boxId();if (!boxId) return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_NOT_READY }] };const refused = (phase: "before" | "after"): CloudComputerResult | null => {- const text = deps.recovery?.refusal(boxId, phase);+ const text = deps.recovery?.refusal(boxId!, phase);return text ? { isError: true, content: [{ type: "text", text }] } : null;};- const before = refused("before");+ let before = refused("before");+ if (before && deps.recovery?.settle) {+ // A restart or replacement under way is waited for here, not refused at once: a bot refused straight away repeats+ // the call, is refused again, and gives up while its computer is still being brought back.+ const until = deadline - RECOVERY_WAIT_RESERVE_MS;+ deps.waiting?.();+ await deps.recovery.settle(boxId, until, deps.signal);+ deps.assertActive();+ if (deps.recovery.replaced?.(boxId) && deps.reclaim) {+ const next = await deps.reclaim(boxId, until, deps.signal);+ deps.assertActive();+ if (!next) { deps.settled?.(false); return { isError: true, content: [{ type: "text", text: CLOUD_COMPUTER_REPLACEMENT_STARTING }] }; }+ boxId = next;+ }+ before = refused("before");+ }if (before) { deps.settled?.(false); return before; }const late = AbortSignal.timeout(Math.max(1, deadline - Date.now()));deps.disk?.began(deps.cfg, boxId);diff --git a/server/cloud-computer-unattended.test.ts b/server/cloud-computer-unattended.test.tsindex 09dfae2e8f..8bfef37b0e 100644--- a/server/cloud-computer-unattended.test.ts+++ b/server/cloud-computer-unattended.test.ts@@ -90,7 +90,8 @@ async function world(watched = false) {const readiness = createBoatReadiness({ health, counters, now,// A little real time passes with each wait, so the test's clock cannot run through the run's twenty minutes while// the recovery's own steps (real requests, a real pause between two reads of a waking computer) are still under way.- sleep: async (ms) => { at += ms; await new Promise((resolve) => setTimeout(resolve, 25)); },+ // A longer wait (the gaps grow after a wake) takes a little longer, so the ratio stays about the same.+ sleep: async (ms) => { at += ms; await new Promise((resolve) => setTimeout(resolve, Math.max(25, Math.ceil(ms / 120)))); },});const told: string[] = [];const logged: string[] = [];diff --git a/server/cloud-computer-wake.test.ts b/server/cloud-computer-wake.test.tsnew file mode 100644index 0000000000..2412322549--- /dev/null+++ b/server/cloud-computer-wake.test.ts@@ -0,0 +1,330 @@+// A cloud computer woken for a turn that is slow to answer, or never answers: the turn waits for it patiently, and one+// that stays silent past the wake's patience is replaced, once, within its limits, and the turn goes on on the new one.+// A loopback stand-in for the Cloud's relay plays the provider. No network, no real computer; the data folder is the+// test's own, and the clock the waits read is the test's.+import { mkdtempSync, rmSync } from "node:fs";+import { createServer, type Server } from "node:http";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import type { AppConfig } from "./config.ts";+import type { BotRecord } from "./store.ts";++type Box = { id: string; name: string; state: string };++const ALPHABET = "23456789abcdefghjkmnpqrstuvwxyz";+let made = 0;+const newId = () => `bx_${String(made++).padStart(8, "0").split("").map((digit) => ALPHABET[Number(digit)]).join("")}`;+const opId = (boxId: string) => `bdop_${Buffer.from(boxId.padEnd(16, "x")).toString("hex").slice(0, 32)}`;++let server: Server;+let boxes: Box[] = [];+let requests: Array<{ method: string; path: string; command?: string }> = [];+/** Until when, on the test's clock, each computer leaves every command unanswered (the gateway's 502). */+let silentUntil = new Map<string, number>();+/** A computer made from now on is silent for this long, on the test's clock. */+let newSilentMs = 0;+let deleteStatus = 202;+let deleteDelayMs = 0;+let at = 50_000_000;+const now = () => at;++const send = (res: import("node:http").ServerResponse, status: number, body: unknown) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(body));+};++beforeAll(async () => {+ server = createServer((req, res) => {+ let raw = "";+ req.on("data", (chunk) => { raw += chunk; });+ req.on("end", () => {+ const url = new URL(req.url ?? "/", "http://relay.test");+ const path = url.pathname.replace(/^\/relay\/api\/box\/v1/, "");+ const body = raw ? JSON.parse(raw) : {};+ const method = req.method ?? "GET";+ requests.push({ method, path, ...(typeof body.command === "string" ? { command: body.command } : {}) });+ if (path === "/boxes" && method === "GET") return send(res, 200, { ok: true, boxes, pageInfo: { nextCursor: null } });+ if (path === "/boxes" && method === "POST") {+ const box = { id: newId(), name: "", state: "ready" };+ boxes.push(box);+ if (newSilentMs) silentUntil.set(box.id, at + newSilentMs);+ return send(res, 200, { ok: true, box });+ }+ const operation = /^\/deletion-operations\/([^/]+)$/.exec(path);+ if (operation && method === "GET") return send(res, 200, { ok: true, operation: { id: operation[1], kind: "box", targetId: "", status: "completed" } });+ const match = /^\/boxes\/([^/]+)(?:\/(stop|resume|commands|desktop))?$/.exec(path);+ const box = match ? boxes.find((candidate) => candidate.id === match[1]) : undefined;+ if (!match || !box) return send(res, 404, { ok: false, code: "not_found", message: "That cloud computer does not exist." });+ const action = match[2];+ if (!action && method === "GET") return send(res, 200, { ok: true, box });+ if (!action && method === "PATCH") { box.name = body.name; return send(res, 200, { ok: true, box }); }+ if (!action && method === "DELETE") {+ setTimeout(() => {+ if (deleteStatus >= 400) return send(res, deleteStatus, { ok: false, code: "upstream_error", message: "The delete failed." });+ boxes = boxes.filter((candidate) => candidate.id !== box.id);+ send(res, 202, { ok: true, operation: { id: opId(box.id), kind: "box", targetId: box.id, status: "completed" } });+ }, deleteDelayMs);+ return;+ }+ if (action === "stop") { box.state = "archived"; return send(res, 200, { ok: true, box }); }+ if (action === "resume") { box.state = "ready"; return send(res, 200, { ok: true, box }); }+ if (action === "commands") {+ if ((silentUntil.get(box.id) ?? -Infinity) > at) return send(res, 502, { ok: false, code: "upstream_unavailable", message: "Cloud computers could not be reached." });+ return send(res, 200, { exitCode: 0, stdout: "captured", stderr: "" });+ }+ if (action === "desktop") return send(res, 200, { desktopUrl: "https://desktop.test/view" });+ return send(res, 404, { ok: false });+ });+ });+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const { port } = server.address() as { port: number };+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `http://127.0.0.1:${port}/relay/api/box/v1`);+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", "box_omb_synthetic");+});+afterAll(async () => {+ vi.unstubAllEnvs();+ server.closeAllConnections();+ await new Promise<void>((resolve) => server.close(() => resolve()));+});++const cfg = {} as AppConfig;+let boat: typeof import("./boat.ts");+let words: typeof import("../shared/cloud-computer-recovery.ts");+let tools: typeof import("./cloud-computer-tools.ts");+let claims: typeof import("./auto-vm-claims.ts");+let power: ReturnType<typeof import("./host/cloud-computer-power.ts").createCloudComputerPower>;+let recovery: import("./boat-recovery.ts").BoatRecovery;+let health: import("./boat-health.ts").BoatHealth;+let told: Array<[string, string]>;+let hooks: string[];+let autoOn: boolean;+let inUseByOther: Set<string>;+let dir: string;++beforeEach(async () => {+ boxes = []; requests = []; silentUntil = new Map(); newSilentMs = 0; deleteStatus = 202; deleteDelayMs = 0;+ at += 7 * 24 * 60 * 60_000;+ told = []; hooks = []; autoOn = true; inUseByOther = new Set();+ dir = mkdtempSync(join(tmpdir(), "omb-wake-"));+ vi.resetModules();+ boat = await import("./boat.ts");+ words = await import("../shared/cloud-computer-recovery.ts");+ tools = await import("./cloud-computer-tools.ts");+ claims = await import("./auto-vm-claims.ts");+ const { createBoatHealth } = await import("./boat-health.ts");+ const { createBoatReadiness } = await import("./boat-ready.ts");+ const { createBoatRecovery } = await import("./boat-recovery.ts");+ const { createCloudComputerCounters } = await import("./cloud-computer-counters.ts");+ const { createCloudComputerPower } = await import("./host/cloud-computer-power.ts");+ health = createBoatHealth(now);+ // Each wait moves the test's clock instead of passing real time. The waits keep their own health record, so the+ // background recovery (restart, then replace, on three silent probes) stays out of these scenarios: they are about+ // the turn's own wait.+ const readiness = createBoatReadiness({ health: createBoatHealth(now), counters: createCloudComputerCounters(now), now, sleep: async (ms) => { at += ms; } });+ recovery = createBoatRecovery({+ cfg: () => cfg, tell: (owner, line) => told.push([owner, line]), log: () => {}, file: join(dir, "boat-replacements.json"), now, health,+ pollMs: 5, recheckMs: 20, readiness, autoReplace: () => autoOn, usedByOther: (owner) => inUseByOther.has(owner),+ });+ power = createCloudComputerPower({+ cfg, busy: () => false, claim: () => () => {}, owners: () => [], routines: () => [], routineComputer: () => null,+ broadcast: () => {}, log: () => {}, readiness, wakeTimedOut: (owner, boxId) => recovery.wakeTimedOut(owner, boxId),+ });+});+afterEach(() => {+ recovery.close();+ power.close();+ rmSync(dir, { recursive: true, force: true });+});++let bots = 0;+/** A bot whose computer went to sleep, and stays silent for `silentMs` once it is woken. */+async function asleep(silentMs: number) {+ const botId = `bot-wake-${bots++}`;+ const box = { id: newId(), name: await boat.boatNameFor(botId), state: "archived" };+ boxes.push(box);+ silentUntil.set(box.id, silentMs === Infinity ? Infinity : at + silentMs);+ return { bot: { id: botId, name: "Scout" } as BotRecord, box };+}+const turn = (threadId = "thread-1") => ({ threadId, generation: "g1" });+const ready = (bot: BotRecord) => power.ready(bot, turn(), {+ budgetMs: 30_000, onWaking: () => hooks.push("waking"), onReplacing: () => hooks.push("replacing"), onRestoring: () => hooks.push("restoring"),+});+const deletes = () => requests.filter((request) => request.method === "DELETE");+const creates = () => requests.filter((request) => request.method === "POST" && request.path === "/boxes");+/** One computer call as the bot makes it, through the same route a turn's calls take. */+const call = (boxId: () => string, extra: Partial<Parameters<typeof tools.cloudComputerRpc>[1]> = {}) =>+ tools.cloudComputerRpc({ method: "tools/call", params: { name: "exec", arguments: { command: "echo hi" } } }, {+ cfg, signal: new AbortController().signal, boxId, gate: async () => ({ held: false }), assertActive: () => {}, recovery, ...extra,+ });+const ranEcho = () => requests.filter((request) => request.command?.includes("echo hi")).length;++describe("a woken cloud computer that is slow to answer", () => {+ it("is waited for inside the wake's patience: the bot's command runs once, nothing is replaced, and no error is shown", async () => {+ const { bot, box } = await asleep(150_000);+ const machine = await ready(bot);+ expect(machine?.id).toBe(box.id);+ expect(hooks).toEqual(["waking"]);+ const result = await call(() => box.id);+ expect(result).toMatchObject({ content: [{ type: "text" }] });+ expect((result as { isError?: boolean }).isError).toBeFalsy();+ expect(ranEcho()).toBe(1);+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([]);+ });+});++describe("a woken cloud computer that never answers", () => {+ it("is replaced once, the turn goes on on the new one, and the bot and the person each hear it once", async () => {+ const { bot, box } = await asleep(Infinity);+ const machine = await ready(bot);+ expect(machine?.id).not.toBe(box.id);+ expect(hooks).toEqual(["waking", "replacing"]);+ expect(deletes().map((request) => request.path)).toEqual([`/boxes/${box.id}`]);+ expect(creates()).toHaveLength(1);+ expect(told).toEqual([[bot.id, "replaced"]]);++ const first = await call(() => machine!.id as string);+ expect((first as { isError?: boolean }).isError).toBeFalsy();+ expect((first as { content: unknown[] }).content[0]).toEqual({ type: "text", text: words.CLOUD_COMPUTER_REPLACED });+ expect(words.CLOUD_COMPUTER_REPLACED).toMatch(/install again/);+ expect(ranEcho()).toBe(1);+ const second = await call(() => machine!.id as string);+ expect((second as { content: unknown[] }).content).toHaveLength(1);+ expect(told).toHaveLength(1);+ });++ it("is kept when a last probe gets through: a computer that is only slow is never replaced", async () => {+ const { bot, box } = await asleep(0);+ box.state = "ready";+ await boat.findBoat(cfg, bot.id);+ await expect(recovery.wakeTimedOut(bot.id, box.id)).resolves.toEqual({ kind: "answers" });+ expect(deletes()).toHaveLength(0);+ expect(told).toEqual([]);+ });++ it("is replaced at most once an hour and three times a day per bot", async () => {+ newSilentMs = 1e12;+ const { bot } = await asleep(Infinity);+ await expect(ready(bot)).rejects.toThrow(/new one did not answer in time either/);+ expect(deletes()).toHaveLength(1);+ expect(told).toEqual([[bot.id, "replaced"]]);++ // Within the hour: left as it is, and the turn says why.+ const current = () => boxes.find((box) => box.name)!;+ current().state = "archived";+ await expect(ready(bot)).rejects.toThrow(/at most once an hour and three times a day/);+ expect(deletes()).toHaveLength(1);+ expect(told.filter(([, line]) => line === "capped")).toHaveLength(1);++ for (let replaced = 2; replaced <= 3; replaced++) {+ at += 61 * 60_000;+ current().state = "archived";+ await expect(ready(bot)).rejects.toThrow(/new one did not answer/);+ expect(deletes()).toHaveLength(replaced);+ }+ at += 61 * 60_000;+ current().state = "archived";+ await expect(ready(bot)).rejects.toThrow(/three times a day/);+ expect(deletes()).toHaveLength(3);+ });++ it("fails the turn with a clear reason when the replacement itself fails, and makes no new computer", async () => {+ deleteStatus = 500;+ const { bot } = await asleep(Infinity);+ const failed = await ready(bot).then(() => null, (error: unknown) => error);+ expect(failed).toBeInstanceOf(Error);+ expect((failed as Error).message).toMatch(/did not answer after waking, and replacing it failed.*trying again later is fine/);+ expect(claims.transientClaimFailure(failed)).toBe(false);+ expect(creates()).toHaveLength(0);+ });++ it("is not replaced while another bot's running turn uses it", async () => {+ const { bot } = await asleep(Infinity);+ inUseByOther.add(bot.id);+ await expect(ready(bot)).rejects.toThrow(/could not be replaced by itself right now/);+ expect(deletes()).toHaveLength(0);+ expect(creates()).toHaveLength(0);+ expect(told).toEqual([[bot.id, "needsPerson"]]);+ });++ it("is not replaced while the installation's other computers are silent too: that is the provider's outage", async () => {+ const { bot } = await asleep(Infinity);+ health.unanswered("bx_someoneelse");+ await expect(ready(bot)).rejects.toThrow(/service itself can't be reached/);+ expect(deletes()).toHaveLength(0);+ });++ it("with automatic replacement switched off, keeps today's behaviour: nothing is replaced and the claim may be tried again", async () => {+ autoOn = false;+ const { bot } = await asleep(Infinity);+ const failed = await ready(bot).then(() => null, (error: unknown) => error);+ expect((failed as Error).message).toBe("the cloud computer is awake but is not answering yet");+ expect(claims.transientClaimFailure(failed)).toBe(true);+ expect(deletes()).toHaveLength(0);+ expect(creates()).toHaveLength(0);+ expect(told).toEqual([]);+ });+});++describe("a computer call made while its computer is being replaced", () => {+ it("waits for the replacement and runs on the new computer, instead of being refused again and again", async () => {+ const { bot, box } = await asleep(Infinity);+ box.state = "ready";+ await boat.findBoat(cfg, bot.id);+ deleteDelayMs = 300;+ const replacing = recovery.wakeTimedOut(bot.id, box.id);+ await vi.waitFor(() => expect(recovery.refusal(box.id, "before")).not.toBeNull());+ let current = box.id;+ let reclaims = 0;+ const result = await call(() => current, {+ reclaim: async (replacedBoxId) => {+ reclaims++;+ expect(replacedBoxId).toBe(box.id);+ const machine = await power.ready(bot, turn(), { budgetMs: 30_000 });+ current = machine!.id as string;+ return current;+ },+ });+ await replacing;+ expect(reclaims).toBe(1);+ expect(current).not.toBe(box.id);+ expect((result as { isError?: boolean }).isError).toBeFalsy();+ expect((result as { content: unknown[] }).content[0]).toEqual({ type: "text", text: words.CLOUD_COMPUTER_REPLACED });+ expect(ranEcho()).toBe(1);+ });++ it("says the new computer is still starting, and that the call was not performed, when it is not up in time", async () => {+ const { bot, box } = await asleep(Infinity);+ box.state = "ready";+ await boat.findBoat(cfg, bot.id);+ await recovery.wakeTimedOut(bot.id, box.id);+ const result = await call(() => box.id, { reclaim: async () => null });+ expect(result).toEqual({ isError: true, content: [{ type: "text", text: words.CLOUD_COMPUTER_REPLACEMENT_STARTING }] });+ expect(ranEcho()).toBe(0);+ });+});++describe("moving a turn's claim onto the replacement", () => {+ it("claims again once, however many calls see the replacement, and hands back the new computer", async () => {+ const table: import("./auto-vm-claims.ts").AutoVmClaimTable = new Map();+ let next = 1;+ const slot: import("./auto-vm-claims.ts").AutoVmClaimSlot = {+ owner: { threadId: "t", generation: "g" }, lazy: true, startsComputer: true,+ claim: async () => { await new Promise((resolve) => setTimeout(resolve, 20)); slot.boxId = `bx_new${next++}`; },+ };+ table.set("t", slot);+ claims.startAutoVmClaim(table, "t", "g");+ await slot.begin;+ expect(slot).toMatchObject({ claimed: true, boxId: "bx_new1" });+ const until = Date.now() + 5_000;+ const [a, b] = await Promise.all([+ claims.reclaimAutoVm(table, slot.owner, "bx_new1", until),+ claims.reclaimAutoVm(table, slot.owner, "bx_new1", until),+ ]);+ expect([a, b]).toEqual(["bx_new2", "bx_new2"]);+ expect(await claims.reclaimAutoVm(table, slot.owner, "bx_new1", until)).toBe("bx_new2");+ expect(next).toBe(3);+ expect(await claims.reclaimAutoVm(table, { threadId: "t", generation: "older" }, "bx_new2", until)).toBeNull();+ });+});diff --git a/server/config.ts b/server/config.tsindex 74c67a5289..fcbed51c48 100644--- a/server/config.ts+++ b/server/config.ts@@ -245,7 +245,7 @@ const featureConfigSchema = z.object({/** Room jobs to several members run side by side, each in a thread of its own. On unless false. */parallelRoomJobs: z.boolean().optional(),acpPlanLines: z.boolean().optional(), // An ACP agent's plan as activity lines. Off unless true.-}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional() }); // cloudComputerAutoReplace: delete and replace a dead cloud computer by itself, off unless true (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)+}).extend({ agentsToolBridge: z.boolean().optional(), savedSteps: z.boolean().optional(), usbPhoneTakeover: z.boolean().optional(), cloudComputerAutoReplace: z.boolean().optional(), phonePush: z.boolean().optional() }); // cloudComputerAutoReplace: delete and replace a dead or silent cloud computer by itself, on unless false (OMB_CLOUD_COMPUTER_AUTO_REPLACE wins); agentsToolBridge: the find_tool / use_tool bridge, off unless true; savedSteps: repeat a computer task from its saved steps, on unless false; usbPhoneTakeover: watch and take over the bots' USB phone, off unless true; phonePush: wake a paired phone whose app is closed through the hosted push relay, off unless true (OMB_PHONE_PUSH wins)const onboardingConfigSchema = z.object({completedAt: z.string().trim().max(40).optional(),version: z.number().int().min(0).max(1000).optional(),diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.tsindex 161ec63bb8..5aa3b08b61 100644--- a/server/host/cloud-computer-power.ts+++ b/server/host/cloud-computer-power.ts@@ -4,7 +4,9 @@import * as boat from "../boat.ts";import { boatCreateRecoverySnapshot } from "../boat-create-idempotency.ts";import { BOAT_DELETING, BOAT_DELETION_FINISHED, hasPendingBoatDeletionForBot } from "../boat-delete-journal.ts";-import { boatReadiness, type BoatReadiness } from "../boat-ready.ts";+import { boatReadiness, type BoatAnswer, type BoatReadiness } from "../boat-ready.ts";+import type { WakeTimeoutOutcome } from "../boat-recovery.ts";+import { withinBudget } from "../auto-vm-claims.ts";import { backgroundCommandRunning } from "../cloud-computer-background.ts";import { ComputerIdleTimer } from "../computer-idle.ts";import type { AppConfig } from "../config.ts";@@ -44,6 +46,18 @@ export interface CloudComputerPowerDeps {broadcast(payload: Record<string, unknown>): void;log(line: string): void;readiness?: Pick<BoatReadiness, "awaitAnswer">;+ /** A computer woken or created for a turn stayed silent past the wake's patience: replace it, within every guard+ * (server/boat-recovery.ts). Absent, such a computer is only reported, as with automatic replacement switched off. */+ wakeTimedOut?(owner: string, boxId: string): Promise<WakeTimeoutOutcome>;+}++/** How a turn's start went, for the line the bot hears meanwhile. */+export interface CloudComputerReadyHooks {+ onRestoring?(): void;+ /** Woken and silent: the wait goes on. */+ onWaking?(): void;+ /** Silent past the wake's patience, and being replaced with a new computer. */+ onReplacing?(): void;}export function createCloudComputerPower(deps: CloudComputerPowerDeps) {@@ -187,22 +201,58 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {}}- /** After a start, before the turn's first call is sent: the computer has to answer a command, not only be reported- * ready. One that answered moments ago is not asked again. The failure is passing, so the turn's next call tries again. */- async function answering(boxId: string, opts: { woke?: boolean; onRestoring?: () => void } = {}): Promise<void> {+ const notAnswering = (answer: Extract<BoatAnswer, { ok: false }>) =>+ Object.assign(new Error(answer.phase === "restoring" ? CLOUD_COMPUTER_DISK_NOT_BACK_YET : CLOUD_COMPUTER_NOT_ANSWERING_YET), { status: 503, transient: true });++ /** Waits for the computer to answer a command, not only be reported ready; one that answered moments ago is not asked+ * again. After a wake the wait is patient (READY_WAIT.wakePatienceMs, longer while the provider says its disk is restored). */+ async function awaitAnswer(boxId: string, opts: { woke?: boolean } & CloudComputerReadyHooks): Promise<BoatAnswer & { woke: boolean }> {+ const woke = opts.woke === true || unheard.has(boxId);const answer = await readiness.awaitAnswer(cfg, boxId, {- woke: opts.woke === true || unheard.has(boxId),- onPhase: (phase) => { if (phase === "restoring") opts.onRestoring?.(); },+ woke,+ onPhase: (phase) => { if (phase === "restoring") opts.onRestoring?.(); else opts.onWaking?.(); },});- if (!answer.ok) {- throw Object.assign(new Error(answer.phase === "restoring" ? CLOUD_COMPUTER_DISK_NOT_BACK_YET : CLOUD_COMPUTER_NOT_ANSWERING_YET), { status: 503, transient: true });+ if (answer.ok) unheard.delete(boxId);+ return { ...answer, woke };+ }++ /** After a start, before the turn's first call is sent. The failure is passing, so the turn's next call tries again. */+ async function answering(boxId: string, opts: { woke?: boolean; onRestoring?: () => void } = {}): Promise<void> {+ const answer = await awaitAnswer(boxId, opts);+ if (!answer.ok) throw notAnswering(answer);+ }++ /** A bot's own computer for a turn: started (woken, or created) within `budgetMs`, then waited on until it answers. One+ * woken or created here that stays silent past the wake's patience is replaced, once, and the turn goes on on the new+ * one; the old one's files are gone, which the recovery tells the bot and the person. Null when `existingOnly` and the+ * bot has none. */+ async function ready(bot: BotRecord, turn: TurnOwner, opts: { existingOnly?: boolean; budgetMs: number } & CloudComputerReadyHooks) {+ for (let replaced = false; ; replaced = true) {+ // The replacement stands in for the computer the bot already had, so it is made even where a first one would not be.+ const machine = await withinBudget(start(bot, turn, { existingOnly: !replaced && opts.existingOnly, budgetMs: opts.budgetMs }), opts.budgetMs, CLOUD_COMPUTER_DID_NOT_START);+ if (!machine) {+ if (replaced) throw new Error("the cloud computer did not answer after waking, so it was replaced, but its replacement could not be found. Trying again later is fine");+ return null;+ }+ const boxId = machine.id as string;+ const answer = await awaitAnswer(boxId, opts);+ if (answer.ok) return machine;+ // A computer this process did not wake keeps today's short wait: the recovery restarts it, then replaces it.+ if (!answer.woke || !deps.wakeTimedOut) throw notAnswering(answer);+ if (replaced) throw new Error("the cloud computer did not answer after waking, so it was replaced with a new one, but the new one did not answer in time either. Trying again later is fine");+ opts.onReplacing?.();+ const outcome = await deps.wakeTimedOut(bot.id, boxId);+ if (outcome.kind === "answers") return machine;+ if (outcome.kind === "off") throw notAnswering(answer);+ if (outcome.kind === "kept") throw new Error(outcome.why);+ deps.log(`cloud computer ${bot.id}: ${boxId} ${outcome.kind === "gone" ? "is gone" : "was replaced"} after it did not answer its wake; starting a new one for the turn`);}- unheard.delete(boxId);}return {start,answering,+ ready,attached,released,used,diff --git a/server/index.ts b/server/index.tsindex 963d592123..a52390c1fa 100644--- a/server/index.ts+++ b/server/index.ts@@ -94,7 +94,7 @@ import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";import { finishedWithoutSummaryLine, ROOM_SUMMARY_REASK, roomTurnNarrationIds, roomTurnReply } from "./room-reply.ts";import { chosenPlace, pickComputer } from "./computer-selection.ts";import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";-import { cloudComputerRpc } from "./cloud-computer-tools.ts"; import { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES, CLOUD_COMPUTER_RESTORING, RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts"; import { boatReadiness } from "./boat-ready.ts"; import { createRunComputerGate } from "./host/cloud-computer-run-gate.ts"; import { cloudComputerDisk } from "./cloud-computer-disk.ts"; import { runComputerMemory } from "./host/cloud-computer-run-memory.ts";+import { cloudComputerRpc } from "./cloud-computer-tools.ts"; import { createBoatRecovery } from "./boat-recovery.ts"; import { CLOUD_COMPUTER_PERSON_LINES, CLOUD_COMPUTER_REPLACING, CLOUD_COMPUTER_RESTORING, CLOUD_COMPUTER_WAKING, RUN_COMPUTER_LINES } from "../shared/cloud-computer-recovery.ts"; import { boatReadiness } from "./boat-ready.ts"; import { createRunComputerGate } from "./host/cloud-computer-run-gate.ts"; import { cloudComputerDisk } from "./cloud-computer-disk.ts"; import { runComputerMemory } from "./host/cloud-computer-run-memory.ts";import { chartRenderer, compileChart, dataEngine, validateVegaLite } from "./data/deps.ts";import { DATA_INTERNAL_MCP_PATH, dataRpc } from "./data/rpc.ts";import { removeRetiredAppFiles } from "./retired-apps.ts"; import { createEmailRoutes } from "./routes/email.ts"; import { createEmailHost, EMAIL_INTERNAL_MCP_PATH, emailAccess } from "./email/host.ts"; import { createEmailService } from "./email/service.ts"; import { createPostizRoutes } from "./routes/postiz.ts"; import { createPostiz } from "./postiz/service.ts";@@ -428,7 +428,7 @@ import { createLocalVmUpdater, LOCAL_VM_UPDATING_PROBLEM, recoverLocalVms, VPS_Oimport { keepInstalledAppsBeforeRemove } from "./local-vm-profiles.ts";import { localVmStopReason, recordLocalVmIdleStop } from "./local-vm-stop-reason.ts";import { ComputerIdleTimer } from "./computer-idle.ts";-import { CLOUD_COMPUTER_DID_NOT_START, CLOUD_COMPUTER_START_BUDGET_MS, CLOUD_COMPUTER_STARTING, createCloudComputerPower } from "./host/cloud-computer-power.ts"; import { ownCloudComputer, resetBotCloudComputer } from "./host/cloud-computer-reset.ts"; import { createCloudComputerResetAsks, noOwnCloudComputer } from "./host/cloud-computer-reset-asks.ts";+import { CLOUD_COMPUTER_DID_NOT_START, CLOUD_COMPUTER_START_BUDGET_MS, CLOUD_COMPUTER_STARTING, createCloudComputerPower, type CloudComputerReadyHooks } from "./host/cloud-computer-power.ts"; import { ownCloudComputer, resetBotCloudComputer } from "./host/cloud-computer-reset.ts"; import { createCloudComputerResetAsks, noOwnCloudComputer } from "./host/cloud-computer-reset-asks.ts";import { LocalVmLease, LocalVmLeasePool } from "./local-vm-lease.ts";import { LocalVmSeatPool, type LocalVmSeatHolder } from "./local-vm-seat-pool.ts";import { loopGuardSettings } from "./host/loop-guard.ts"; import { createUnattendedTurns, personDriven } from "./host/unattended-turns.ts"; import { createPersonFirst } from "./host/person-first.ts"; import { createRunOwners, runActorOf } from "./host/run-owner.ts";@@ -504,7 +504,7 @@ import { OrgLibrary } from "./org-library.ts";import { newBotWorksOn, shouldMountLocalComputer } from "./local-routing.ts";import { autoLocalVmAttachable, type ContainerComputerStatus } from "./container-computer.ts";import { startStoppedPodmanMachine } from "./podman-machine.ts";-import { keepTransient, lazyClaimFailedText, lazyClaimRetryText, settledWithin, startAutoVmClaim, withinBudget, type AutoVmClaimSlot, type AutoVmClaimTable } from "./auto-vm-claims.ts";+import { keepTransient, lazyClaimFailedText, lazyClaimRetryText, reclaimAutoVm, 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";@@ -5629,11 +5629,11 @@ const localVmIdleMs = () => localVmIdleTimeoutMinutes(cfg) * 60_000;const LOCAL_VM_DESKTOP_WAIT_MS = 90_000;const localVmIdles = new Map<string, ComputerIdleTimer>();const meetingsHost = createMeetingsHost({ cfg, dataDir: DATA_DIR, store, startTurn: (botId, text, opts) => startTurn(botId, text, opts), threadBusy, power: () => cloudComputerPower, computerOwner: (bot) => botComputerControlKey(bot), routines: () => routines, log: (line) => console.warn(line) }, () => ({ personName: personNameIn, sendsFreely: (botId, threadId) => roomTurnLevels.forRequest(threadId, botId, () => sourceApprovalMode(botId, threadId)) === "full", outbound: () => outboundHold, markOutside: (threadId) => outsideLineage.mark(threadId), folder: (botId, threadId) => messageFileRootsForThread(botId, threadId).filter((root) => root !== ATTACHMENTS_DIR)[0] ?? null })); const cloudComputerPower = createCloudComputerPower({- cfg, owners: managedBoatOwners, broadcast, log: line => console.warn(line), routines: () => routines?.listRoutines() ?? [],+ cfg, owners: managedBoatOwners, broadcast, log: line => console.warn(line), routines: () => routines?.listRoutines() ?? [], wakeTimedOut: (owner, boxId) => boatRecovery.wakeTimedOut(owner, boxId),routineComputer: routine => { const bot = store.bot(routine.botId); return bot && turnProvider(bot, routine.runOn) === "box" ? botComputerControlKey(bot) : null; },busy: owner => computerProviderConfigTransitions.has("box") || boatLifecycleBusyBots.has(owner) || managedBoatOwners().some(entry => entry.botId === owner && entry.inUse) || meetingsHost.keepsAwake(owner),claim: owner => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); return team ? claimTeamComputerLifecycle(team) : claimBotComputerLifecycle(owner); },-}); const boatRecovery = createBoatRecovery({ cfg: () => cfg, log: line => console.warn(line), eligible: owner => { const bot = store.bot(owner); return Boolean(bot) && botComputerControlKey(bot!) === owner; }, personActive: owner => computerControl.snapshot(owner).held || desktopViewer.viewing(owner) > 0, tell: (owner, key) => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); if (team) { teamComputers.setProblem(team.id, serverLine(appLanguage(), CLOUD_COMPUTER_PERSON_LINES.teamNotResponding, { name: team.name })); return; } const bot = store.bot(owner); if (!bot) return; const text = serverLine(conversationLanguage(bot.threadId), CLOUD_COMPUTER_PERSON_LINES[key], { name: bot.name }); store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${text}`, ok: true } }); notify(buildNoticeNotification(bot, bot.threadId, text)); } }); const runComputers = createRunComputerGate({ computerOf: (run) => { const bot = store.bot(run.botId); return bot && turnProvider(bot, run.runOn as RoutineRunOn | undefined) === "box" ? botComputerControlKey(bot) : null; }, find: (owner) => boat.findBoat(cfg, owner), wake: (owner, budgetMs) => boat.readyBoat(cfg, owner, budgetMs), awaitAnswer: (boxId, opts) => boatReadiness.awaitAnswer(cfg, boxId, opts), verdict: (owner, since) => boatRecovery.verdict(owner, since), recoveryState: (owner) => boatRecovery.status(owner)?.state ?? null, used: (owner) => cloudComputerPower.used(owner), disk: (boxId, signal) => cloudComputerDisk.beforeRun(cfg, boxId, signal), remember: runComputerMemory(join(DATA_DIR, "routine-computers.json")), routineOf: (botId, threadId) => { const run = routines?.activeRunForBot(botId); return run?.threadId === threadId ? run.routineId : null; }, log: (line) => console.warn(line) });+}); const boatRecovery = createBoatRecovery({ cfg: () => cfg, log: line => console.warn(line), eligible: owner => { const bot = store.bot(owner); return Boolean(bot) && botComputerControlKey(bot!) === owner; }, personActive: owner => computerControl.snapshot(owner).held || desktopViewer.viewing(owner) > 0, usedByOther: (owner, boxId) => [`computer:box-bot:${owner}`, `computer:box:${boxId}`].some(resource => { const holder = turnResources.holder(resource); return holder !== undefined && store.botByThread(holder.threadId)?.id !== owner; }), tell: (owner, key) => { const team = teamComputers.list().find(entry => teamComputerOwner(entry.id) === owner); if (team) { teamComputers.setProblem(team.id, serverLine(appLanguage(), CLOUD_COMPUTER_PERSON_LINES.teamNotResponding, { name: team.name })); return; } const bot = store.bot(owner); if (!bot) return; const text = serverLine(conversationLanguage(bot.threadId), CLOUD_COMPUTER_PERSON_LINES[key], { name: bot.name }); store.appendMessage(bot.threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${text}`, ok: true } }); notify(buildNoticeNotification(bot, bot.threadId, text)); } }); const runComputers = createRunComputerGate({ computerOf: (run) => { const bot = store.bot(run.botId); return bot && turnProvider(bot, run.runOn as RoutineRunOn | undefined) === "box" ? botComputerControlKey(bot) : null; }, find: (owner) => boat.findBoat(cfg, owner), wake: (owner, budgetMs) => boat.readyBoat(cfg, owner, budgetMs), awaitAnswer: (boxId, opts) => boatReadiness.awaitAnswer(cfg, boxId, opts), verdict: (owner, since) => boatRecovery.verdict(owner, since), recoveryState: (owner) => boatRecovery.status(owner)?.state ?? null, used: (owner) => cloudComputerPower.used(owner), disk: (boxId, signal) => cloudComputerDisk.beforeRun(cfg, boxId, signal), remember: runComputerMemory(join(DATA_DIR, "routine-computers.json")), routineOf: (botId, threadId) => { const run = routines?.activeRunForBot(botId); return run?.threadId === threadId ? run.routineId : null; }, log: (line) => console.warn(line) });function inheritedTeamComputer(bot: Pick<BotRecord, "section" | "computer" | "cloudBackend">): TeamComputerRecord | undefined {return teamComputers.forBot(bot);@@ -5860,7 +5860,7 @@ function mountBotBoat(try {attached = await attachBotBoat(bot, owner, {budgetMs: CLOUD_COMPUTER_START_BUDGET_MS,- onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }, onRestoring: () => { slot.pendingReason = CLOUD_COMPUTER_RESTORING; }, existingOnly: opts.existingOnly,+ onSeated: () => { slot.pendingReason = CLOUD_COMPUTER_STARTING; }, onRestoring: () => { slot.pendingReason = CLOUD_COMPUTER_RESTORING; }, existingOnly: opts.existingOnly, onWaking: () => { slot.pendingReason = CLOUD_COMPUTER_WAKING; }, onReplacing: () => { slot.pendingReason = CLOUD_COMPUTER_REPLACING; },});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) {@@ -5882,12 +5882,12 @@ function claimedBoatId(capability: InternalCapability): string | undefined {}/** The Cloud place is the consent boundary to create or wake a Boat (which un-pauses billing); Auto never reaches here. */-async function attachBotBoat(bot: BotRecord, owner: TurnOwner, start: { budgetMs: number; onSeated: () => void; onRestoring?: () => void; existingOnly?: boolean }) {+async function attachBotBoat(bot: BotRecord, owner: TurnOwner, start: { budgetMs: number; onSeated: () => void; existingOnly?: boolean } & CloudComputerReadyHooks) {// 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, budgetMs: start.budgetMs }), start.budgetMs, CLOUD_COMPUTER_DID_NOT_START);- if (!machine) return null; await cloudComputerPower.answering(machine.id as string, { onRestoring: start.onRestoring });+ const machine = await cloudComputerPower.ready(bot, owner, start); // Woken and silent past its patience: replaced once, and the turn goes on.+ if (!machine) return null;await bindTurnComputer(owner, `computer:box:${machine.id}`);return {boxId: machine.id as string,@@ -13059,7 +13059,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {cfg, signal: abort.signal, folder: () => messageFileRootsForThread(internalCapability.botId, internalCapability.threadId)[0],boxId: () => internalCapability.boxId ?? claimedBoatId(internalCapability),gate: () => computerCallGate(internalCapability, abort.signal),- assertActive: requireActiveInternalCapability, recovery: boatRecovery, disk: cloudComputerDisk, settled: (answered) => runComputers.callSettled(internalCapability.botId, internalCapability.threadId, answered),+ assertActive: requireActiveInternalCapability, recovery: boatRecovery, disk: cloudComputerDisk, settled: (answered) => runComputers.callSettled(internalCapability.botId, internalCapability.threadId, answered), reclaim: (replaced, until, signal) => reclaimAutoVm(autoVmClaims, internalCapability, replaced, until, signal), waiting: () => broadcast({ kind: "computer", botId: internalCapability.botId, state: "waking", place: "cloud" }),}) });}// DuckDB runs here on the bot's own database; the agent process holds only the turn's capability.diff --git a/shared/cloud-computer-recovery.ts b/shared/cloud-computer-recovery.tsindex a30edd376c..78ee82fc14 100644--- a/shared/cloud-computer-recovery.ts+++ b/shared/cloud-computer-recovery.ts@@ -36,9 +36,19 @@ export interface CloudComputerDisk {spaceClearedAt?: number;}-/** What the bot is told, in place of a computer call, while its computer is being restarted or replaced. */+/** What the bot is told, in place of a computer call, while its computer is being restarted or replaced and the call+ * waited for that as long as it could. */export const CLOUD_COMPUTER_NOT_RESPONDING =- "This bot's cloud computer isn't responding; MausBot is replacing it. Try again in a minute. Do not retry now.";+ "This bot's cloud computer isn't responding yet. MausBot is restarting or replacing it by itself, and this turn continues on it once it answers. This call was not performed. Repeat it in a minute.";+/** The computer did not answer after waking, so a new one is being made for this turn. */+export const CLOUD_COMPUTER_REPLACING =+ "This bot's cloud computer did not answer after waking, so MausBot is replacing it with a new one. This call was not performed. Repeat it in a minute.";+/** The turn's computer was replaced while this call waited, and the new one is not up yet. */+export const CLOUD_COMPUTER_REPLACEMENT_STARTING =+ "This bot's cloud computer stopped responding and was replaced with a new one, which is still starting. This call was not performed. Repeat it in a minute.";+/** Woken and not answering yet, inside the wake's patience: the call is not counted against the computer. */+export const CLOUD_COMPUTER_WAKING =+ "The cloud computer is awake but not answering yet; MausBot keeps waiting for it. This call was not performed. Repeat it in a moment.";/** While it is being stopped and started again, which keeps its files. */export const CLOUD_COMPUTER_RESTARTING ="This bot's cloud computer stopped responding and MausBot is restarting it; its files are kept. This call was not performed. Try again in a minute.";@@ -49,7 +59,7 @@ export const CLOUD_COMPUTER_RESTORING ="This bot's cloud computer is awake but still restoring its disk, so it is not answering yet. This call was not performed. Try again in a minute.";/** Told once, on the bot's first computer call after the replacement. */export const CLOUD_COMPUTER_REPLACED =- "This bot's cloud computer stopped responding and was replaced with a new one. Files that were only on the old computer are gone.";+ "This bot's cloud computer stopped responding and was replaced with a new one. Files and programs that were only on the old computer are gone: clone, download or install again what this task needs.";export const CLOUD_COMPUTER_REPLACED_BY_PERSON ="This bot's cloud computer was replaced with a new one. Files that were only on the old computer are gone.";export const CLOUD_COMPUTER_RESTARTED =