Skip to content

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

Cloud browser: a personal Cloud's bots browse in the Cloud's own browser sandbox, the home's browser only as fallback

milind-sonied0cfd442fcb
diff --git a/server/boat.ts b/server/boat.ts
index c6805db7fb..5dc45e9274 100644
--- a/server/boat.ts
+++ b/server/boat.ts
@@ -643,7 +643,7 @@ export async function listManagedBoats(
let owner: ManagedBoatOwner | null = null;
let legacyOwner = false;
if (SCOPED_MANAGED_BOAT_NAME.test(name) || SET_ASIDE_BOAT_NAME.test(name)) {
- if (!name.startsWith(scopedPrefix)) continue;
+ if (!name.startsWith(scopedPrefix) || name === `${scopedPrefix}browser-${boatBotNameParts("browser").hash}`) continue; // The Cloud's browser sandbox (cloud-browser/remote.ts) is no computer of a bot's.
owner = ownerByCurrentName.get(name) ?? null;
} else if (LEGACY_MANAGED_BOAT_NAME.test(name)) {
owner = ownerByLegacyName.get(name) ?? null;
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 15678d3341..7601efb287 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -17,7 +17,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_BUG_REPORT_URL", "OMB_CACHE_CAP_APP", "OMB_CACHE_CAP_TOOLS", "OMB_CACHE_ROOT", "OMB_CACHE_SWEEP", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",
"OMB_CLAUDE_INHERIT_USER_CONFIG", "OMB_CLAUDE_SESSION_IDLE_", "OMB_CLI_OWNER_STDIN", "OMB_CLI_PREFIX", "OMB_CLINE_PROVIDER",
"OMB_CLOUDFLARED_PATH", "OMB_CLOUD_", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_AI_TOKEN", "OMB_CLOUD_AI_URL",
- "OMB_CLOUD_BOAT_TOKEN", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_BOOTSTRAP_SECRET", "OMB_CLOUD_CAPS_DROPPED",
+ "OMB_CLOUD_BOAT_TOKEN", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_BROWSER", "OMB_CLOUD_BOOTSTRAP_SECRET", "OMB_CLOUD_CAPS_DROPPED",
"OMB_CLOUD_CLIENT_IP_HEADER", "OMB_CLOUD_COMPUTER_AUTO_REPLACE", "OMB_CLOUD_COMPUTER_DEAD_CONFIRM_MS", "OMB_CLOUD_COMPUTER_IDLE_MS", "OMB_CLOUD_COMPUTER_START_BUDGET_MS",
"OMB_CLOUD_CONNECTED_APPS_GRANT", "OMB_CLOUD_DECIDER_TOKEN", "OMB_CLOUD_DECIDER_URL", "OMB_CLOUD_EDGE_ACME_EMAIL",
"OMB_CLOUD_EDGE_ACME_FALLBACK_ONLY", "OMB_CLOUD_EDGE_BIN", "OMB_CLOUD_EDGE_CERT_ISSUERS",
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
new file mode 100644
index 0000000000..e1b7461738
--- /dev/null
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -0,0 +1,464 @@
+// The Cloud's browser sandbox, against a fake provider (testing/fake-computer.ts): no real provider is called and no
+// billable resource is made.
+import { spawn } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import WebSocket, { WebSocketServer } from "ws";
+
+import type { AppConfig } from "../config.ts";
+import { ComputerIdleTimer } from "../computer-idle.ts";
+import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, type CloudBrowserDeps } from "./index.ts";
+import { CLOUD_BROWSER_BACKOFF_MS, createCloudBrowserRails } from "./rails.ts";
+import {
+ BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, browserSandboxCreateBody, COMPUTER_BROWSER_DIR, doorSource, launchCommand, profileKey, providerOps, quitCommand, QUIT_ALL_COMMAND,
+} from "./remote.ts";
+import { OWN_KEY, RELAY_TOKEN, startFakeComputer, type FakeComputer } from "./testing/fake-computer.ts";
+
+let fake: FakeComputer;
+let dir: string;
+let clock: number;
+let used: Array<[string, number]>;
+let engineClosed: string[];
+let held: boolean;
+let browsers: ReturnType<typeof createCloudBrowser>[];
+
+beforeEach(async () => {
+ fake = await startFakeComputer();
+ vi.stubEnv("OMB_BOAT_API", `${fake.base}/api/v1`);
+ vi.stubEnv("OMB_CLOUD_BROWSER", undefined);
+ vi.stubEnv("OMB_CLOUD_BOAT_URL", undefined);
+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", undefined);
+ dir = mkdtempSync(join(tmpdir(), "cloud-browser-"));
+ clock = Date.UTC(2026, 10, 24, 10, 0, 0);
+ used = [];
+ engineClosed = [];
+ held = false;
+ browsers = [];
+});
+
+afterEach(async () => {
+ for (const browser of browsers) browser.closeAll();
+ vi.unstubAllEnvs();
+ await fake.close();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+function browser(overrides: Partial<CloudBrowserDeps> & { budget?: number; awakeMinutes?: number } = {}) {
+ const now = () => clock;
+ const cfg = { box: { token: OWN_KEY } } as AppConfig;
+ const { budget, awakeMinutes, ...rest } = overrides;
+ const created = createCloudBrowser({
+ dataDir: dir,
+ ops: () => providerOps(() => cfg),
+ used: (owner, windowMs) => { used.push([owner, windowMs]); },
+ closeEngine: async (closed) => { engineClosed.push(closed); },
+ held: () => held,
+ now,
+ log: () => {},
+ pollMs: 5,
+ rails: createCloudBrowserRails({ dataDir: dir, now, ...(budget ? { budget } : {}), ...(awakeMinutes ? { awakeMinutes } : {}) }),
+ ...rest,
+ });
+ browsers.push(created);
+ return created;
+}
+
+const request = (botId = "scout", refusal: null | "not-eligible" = null) => ({ session: `bot-${botId}`, botId, refusal });
+
+/** Opens a WebSocket through the session's address, as the browser engine does, and sends `count` messages over it. */
+async function act(cdpUrl: string, count: number): Promise<string[]> {
+ const socket = new WebSocket(cdpUrl);
+ await new Promise<void>((resolve, reject) => { socket.once("open", () => resolve()); socket.once("error", reject); });
+ const answers: string[] = [];
+ for (let i = 0; i < count; i++) {
+ const answer = new Promise<string>((resolve) => socket.once("message", (data) => resolve(String(data))));
+ socket.send(JSON.stringify({ id: i }));
+ answers.push(await answer);
+ }
+ await new Promise<void>((resolve) => { socket.once("close", () => resolve()); socket.close(); });
+ return answers;
+}
+
+const urlOf = (opened: { cdpUrl: string } | { home: string }): string => {
+ if (!("cdpUrl" in opened)) throw new Error(`expected the sandbox, got ${opened.home}`);
+ return opened.cdpUrl;
+};
+
+describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () => {
+ it("opens there and carries every action over one held connection, through the relay's token and the door's secret", async () => {
+ const cloud = browser();
+ const cdpUrl = urlOf(await cloud.open(request()));
+ expect(cdpUrl).toMatch(/^ws:\/\/127\.0\.0\.1:\d+\/devtools\/browser\/[a-f0-9]{64}$/);
+ const key = profileKey("scout");
+ expect(await act(cdpUrl, 5)).toEqual([0, 1, 2, 3, 4].map((id) => `echo:${key}:${JSON.stringify({ id })}`));
+ // One probe before the session was committed, then the session's own single connection for all five actions.
+ expect(fake.upgrades).toHaveLength(2);
+ expect(cloud.dialed("bot-scout")).toBe(1);
+ for (const upgrade of fake.upgrades) {
+ expect(upgrade.path).toMatch(new RegExp(`^/${key}/[a-f0-9]{48}$`));
+ expect(upgrade.host).toBe(new URL(fake.base).host);
+ expect(upgrade.origin).toBeUndefined();
+ }
+ const before = fake.requests.length;
+ await act(cdpUrl, 3);
+ expect(fake.requests.length, "no provider call per action").toBe(before);
+ expect(cloud.busy(BROWSER_SANDBOX_OWNER)).toBe(true);
+ expect(cloud.busy("scout"), "never a bot's own computer").toBe(false);
+ expect(cloud.report()).toMatchObject({ sessions: { sandbox: 1, home: 0 }, resumes: 0 });
+ });
+
+ it("refuses a connection to its address without the session's own token", async () => {
+ const cloud = browser();
+ const cdpUrl = urlOf(await cloud.open(request()));
+ await expect(act(cdpUrl.replace(/[a-f0-9]{64}$/, "0".repeat(64)), 1)).rejects.toThrow();
+ expect(cloud.dialed("bot-scout")).toBe(0);
+ });
+
+ it("makes the sandbox the first time a bot needs a browser: small, no environment, named, one start", async () => {
+ fake.exists = false;
+ const cloud = browser();
+ urlOf(await cloud.open(request()));
+ expect(fake.creates()).toBe(1);
+ const create = fake.requests.find((one) => one.method === "POST" && one.path === "/api/v1/sandboxes");
+ expect(create?.body).toEqual({ ttlSeconds: 7200, noEnv: true, type: "small" });
+ expect(fake.requests.find((one) => one.method === "PATCH")?.body?.name).toMatch(/^ogb-[a-f0-9]{12}-browser-[a-f0-9]{6}$/);
+ expect(cloud.report().resumes).toBe(1);
+ // Through the Cloud's relay the create says what it is, so the plan's computers and hours never count it.
+ expect(browserSandboxCreateBody(true)).toEqual({ ttlSeconds: 7200, noEnv: true, type: "small", purpose: "browser" });
+ });
+
+ it("through the Cloud's relay, keeps a sandbox only when the relay knows it is the browser's, and deletes one an older relay made", async () => {
+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `${fake.base}/api/v1`);
+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", OWN_KEY);
+ fake.exists = false;
+ fake.knowsPurpose = false;
+ const viaRelay = browser({ ops: () => providerOps(() => ({}) as AppConfig) });
+ expect(await viaRelay.open(request())).toEqual({ home: "no-route" });
+ expect(fake.requests.find((one) => one.method === "POST" && one.path === "/api/v1/sandboxes")?.body).toMatchObject({ purpose: "browser" });
+ expect(fake.requests.filter((one) => one.method === "DELETE")).toHaveLength(1);
+ expect(fake.exists).toBe(false);
+ expect(await viaRelay.open(request()), "no second create that day").toEqual({ home: "no-route" });
+ expect(fake.creates()).toBe(1);
+ });
+
+ it("through a relay that knows the browser sandbox, makes it and opens there", async () => {
+ vi.stubEnv("OMB_CLOUD_BOAT_URL", `${fake.base}/api/v1`);
+ vi.stubEnv("OMB_CLOUD_BOAT_TOKEN", OWN_KEY);
+ fake.exists = false;
+ urlOf(await browser({ ops: () => providerOps(() => ({}) as AppConfig) }).open(request()));
+ expect(fake.requests.filter((one) => one.method === "DELETE")).toEqual([]);
+ });
+
+ it("wakes a stopped sandbox with exactly one resume, then reads only", async () => {
+ fake.state = "archived";
+ const cloud = browser();
+ urlOf(await cloud.open(request()));
+ expect(fake.resumes()).toBe(1);
+ expect(fake.creates()).toBe(0);
+ expect(cloud.report().resumes).toBe(1);
+ });
+
+ it("gives each bot its own profile and Chrome, carries up to three at once, and keeps a fourth in the home", async () => {
+ fake.state = "archived";
+ const cloud = browser();
+ const bots = ["scout", "writer", "chief", "fourth"];
+ const opened = await Promise.all(bots.slice(0, BROWSER_SANDBOX_CHROMES).map((bot) => cloud.open(request(bot))));
+ expect(fake.resumes(), "bots opening together share one wake").toBe(1);
+ for (const [i, bot] of bots.slice(0, 3).entries()) expect(await act(urlOf(opened[i]!), 1)).toEqual([`echo:${profileKey(bot)}:{"id":0}`]);
+ expect(new Set(fake.profiles())).toEqual(new Set(bots.slice(0, 3).map(profileKey)));
+ expect(await cloud.open(request("fourth"))).toEqual({ home: "sandbox-full" });
+ });
+
+ it("keeps one profile per bot on the sandbox's disk, clearing a lock only when no Chrome of its own runs", () => {
+ const key = profileKey("scout");
+ expect(key).not.toBe(profileKey("writer"));
+ const command = launchCommand(key, "a".repeat(48));
+ expect(command).toContain(`K="$D/${key}"; P="$K/profile"`);
+ expect(command).toContain('--user-data-dir="$P"');
+ const guard = command.indexOf('if ! pgrep -f -- "--user-data-dir=$P"'), clear = command.indexOf('rm -f "$P/SingletonLock"');
+ expect(guard).toBeGreaterThan(-1);
+ expect(clear).toBeGreaterThan(guard);
+ expect(command).toMatch(/env -i HOME="\$HOME" PATH="[^"]+" setsid nohup "\$B"/);
+ expect(quitCommand(key)).toContain(`P="${COMPUTER_BROWSER_DIR}/${key}/profile"`);
+ expect(QUIT_ALL_COMMAND).toContain(`pkill -TERM -f -- "--user-data-dir=$D/"`);
+ expect(() => launchCommand("../../etc", "a".repeat(48))).toThrow();
+ expect(() => launchCommand(key, "not hex; rm -rf /")).toThrow();
+ });
+
+ it("reuses a bot's profile after the sandbox slept", async () => {
+ const cloud = browser();
+ await cloud.open(request());
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ fake.state = "archived";
+ urlOf(await cloud.open(request()));
+ expect(fake.profiles()).toEqual([profileKey("scout"), profileKey("scout")]);
+ expect(fake.resumes()).toBe(1);
+ });
+
+ it("closes a browser after 3 minutes without activity; the last one lets the sandbox sleep through the computers' idle path", async () => {
+ const cloud = browser();
+ const scout = urlOf(await cloud.open(request("scout")));
+ urlOf(await cloud.open(request("writer")));
+ await act(scout, 1);
+ clock += CLOUD_BROWSER_IDLE_MS - 1;
+ await cloud.closeIdle();
+ expect(engineClosed).toEqual([]);
+ held = true;
+ clock += 1;
+ await cloud.closeIdle();
+ expect(engineClosed, "a browser a turn holds stays").toEqual([]);
+ held = false;
+ await cloud.close("bot-writer");
+ expect(fake.requests.at(-1)?.command, "the other bot's Chrome keeps running").toBe(quitCommand(profileKey("writer")));
+ expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS]);
+ await cloud.closeIdle();
+ expect(engineClosed).toEqual(["bot-writer", "bot-scout"]);
+ expect(fake.requests.at(-1)?.command).toBe(QUIT_ALL_COMMAND);
+ expect(cloud.busy(BROWSER_SANDBOX_OWNER)).toBe(false);
+ expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, 1_000]);
+ });
+
+ it("spends at most the day's start budget (creates and resumes), then opens in the home without sending another", async () => {
+ fake.exists = false;
+ const cloud = browser({ budget: 2 });
+ for (let i = 0; i < 2; i++) {
+ urlOf(await cloud.open(request()));
+ clock += CLOUD_BROWSER_IDLE_MS;
+ await cloud.closeIdle();
+ fake.state = "archived";
+ }
+ expect(await cloud.open(request())).toEqual({ home: "budget" });
+ expect(fake.creates() + fake.resumes()).toBe(2);
+ expect(cloud.report()).toMatchObject({ resumes: 2, fallbacks: { budget: 1 } });
+ clock += 24 * 60 * 60_000;
+ urlOf(await cloud.open(request()));
+ expect(fake.resumes()).toBe(2);
+ });
+
+ it("stops after two failed starts in a row: 15 minutes in the home with no start sent, then tries again", async () => {
+ fake.state = "archived";
+ fake.startStatus = 500;
+ fake.startBody = { ok: false, message: "resume failed" };
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "start-failed" });
+ expect(await cloud.open(request())).toEqual({ home: "start-failed" });
+ expect(await cloud.open(request())).toEqual({ home: "backoff" });
+ clock += CLOUD_BROWSER_BACKOFF_MS - 1;
+ expect(await cloud.open(request())).toEqual({ home: "backoff" });
+ expect(fake.resumes()).toBe(2);
+ fake.startStatus = 200;
+ fake.startBody = { ok: true };
+ clock += 1;
+ urlOf(await cloud.open(request()));
+ expect(fake.resumes()).toBe(3);
+ expect(cloud.report().resumes, "refused resumes count too").toBe(3);
+ });
+
+ it("opens in the home once the relay says the sandbox's minutes are used up, until they reset, never as an error", async () => {
+ fake.state = "archived";
+ fake.startStatus = 429;
+ const resetsAt = new Date(Date.UTC(2026, 10, 25)).toISOString();
+ fake.startBody = { ok: false, code: "limit_reached", message: "used up", error: { code: "limit_reached", reason: "hours_used", limit: 240, used: 240, resetsAt } };
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "hours-used" });
+ expect(await cloud.open(request())).toEqual({ home: "hours-used" });
+ expect(fake.resumes()).toBe(1);
+ clock = Date.parse(resetsAt);
+ fake.startStatus = 200;
+ fake.startBody = { ok: true };
+ urlOf(await cloud.open(request()));
+ });
+
+ it("counts the sandbox's awake minutes itself and stops opening there past the day's cap, without cutting a running browser", async () => {
+ const cloud = browser({ awakeMinutes: 5 });
+ const scout = urlOf(await cloud.open(request("scout")));
+ clock += 5 * 60_000;
+ expect(await cloud.open(request("writer"))).toEqual({ home: "minutes-used" });
+ expect(cloud.active("bot-scout")).toBe(scout);
+ expect(cloud.report()).toMatchObject({ awakeMinutes: 5, awakeMinutesCap: 5, held: "minutes-used" });
+ clock = Date.UTC(2026, 10, 25, 0, 0, 0);
+ expect(cloud.report().awakeMinutes, "a new day counts from midnight").toBe(0);
+ });
+
+ it("holds every start until the next day when the account's starts are used up, with no retries", async () => {
+ fake.state = "archived";
+ fake.startStatus = 429;
+ fake.startBody = { ok: false, error: { code: "limit_reached", reason: "too_many_starts", window: "day" } };
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "account-limit" });
+ clock += 6 * 60 * 60_000;
+ expect(await cloud.open(request())).toEqual({ home: "account-limit" });
+ expect(fake.resumes()).toBe(1);
+ clock = Date.UTC(2026, 10, 25, 0, 0, 1);
+ fake.startStatus = 200;
+ fake.startBody = { ok: true };
+ urlOf(await cloud.open(request()));
+ });
+
+ it("treats the relay's busy answer, or the provider's own 429, as the account's limit for the day", async () => {
+ fake.state = "archived";
+ fake.startStatus = 429;
+ fake.startBody = { ok: false, code: "rate_limited", message: "Cloud computers are busy right now." };
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "account-limit" });
+ expect(await cloud.open(request())).toEqual({ home: "account-limit" });
+ expect(fake.resumes()).toBe(1);
+ });
+
+ it("a session the caller rules out (a shared profile, another person's) makes no provider call", async () => {
+ const cloud = browser();
+ expect(await cloud.open(request("scout", "not-eligible"))).toEqual({ home: "not-eligible" });
+ expect(fake.requests).toEqual([]);
+ });
+
+ it("with no way to reach the door's port, stays in the home for the rest of the day without another start", async () => {
+ fake.hostRoute = false;
+ fake.state = "archived";
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "no-route" });
+ expect(fake.quits()).toBe(1);
+ expect(used.at(-1)).toEqual([BROWSER_SANDBOX_OWNER, 1_000]);
+ const asked = fake.requests.length;
+ expect(await cloud.open(request())).toEqual({ home: "no-route" });
+ expect(fake.requests.length).toBe(asked);
+ });
+
+ it("uses the URL the sandbox printed when the provider's port route is refused", async () => {
+ fake.hostRoute = false;
+ fake.printUrl = true;
+ urlOf(await browser().open(request()));
+ });
+
+ it("a Chrome that does not start counts as a failure and opens in the home", async () => {
+ fake.chromeStarts = false;
+ expect(await browser().open(request())).toEqual({ home: "start-failed" });
+ expect(fake.upgrades).toEqual([]);
+ });
+
+ it("OMB_CLOUD_BROWSER=home keeps every browser in the home without one provider call, and deletes the sandbox after a day of it", async () => {
+ vi.stubEnv("OMB_CLOUD_BROWSER", "home");
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "lever" });
+ expect(cloud.report()).toMatchObject({ fallbacks: { lever: 1 } });
+ expect(fake.requests).toEqual([]);
+ clock += 24 * 60 * 60_000 + 1;
+ cloud.report();
+ await vi.waitFor(() => expect(fake.exists).toBe(false));
+ expect(fake.requests.filter((one) => one.method === "DELETE")).toHaveLength(1);
+ cloud.report();
+ expect(fake.requests.filter((one) => one.method === "DELETE"), "at most once an hour").toHaveLength(1);
+ });
+
+ it("a sandbox an earlier run left awake gets its idle window on the Admin's first health poll, not at start", async () => {
+ const first = browser();
+ urlOf(await first.open(request()));
+ first.closeAll();
+ used = [];
+ const again = browser();
+ expect(used).toEqual([]);
+ again.report();
+ expect(used).toEqual([[BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS]]);
+ again.report();
+ expect(used).toHaveLength(1);
+ });
+
+ it("keeps its day's counts and holds across a restart", async () => {
+ fake.state = "archived";
+ fake.startStatus = 429;
+ fake.startBody = { ok: false, error: { code: "limit_reached", reason: "too_many_starts", window: "day" } };
+ await browser().open(request());
+ const again = browser();
+ expect(await again.open(request())).toEqual({ home: "account-limit" });
+ expect(fake.resumes()).toBe(1);
+ expect(again.report()).toMatchObject({ resumes: 1, fallbacks: { "account-limit": 2 } });
+ });
+
+ it("the relay URL and the door's secret never reach the log", async () => {
+ const lines: string[] = [];
+ await browser({ log: (line) => lines.push(line) }).open(request());
+ expect(lines.join("\n")).not.toContain(RELAY_TOKEN);
+ expect(lines.join("\n")).not.toMatch(/[a-f0-9]{48}/);
+ });
+});
+
+describe("the sandbox's door, run as it runs there", () => {
+ let chrome: Server;
+ let folder: string;
+ afterEach(() => { chrome?.close(); rmSync(folder, { recursive: true, force: true }); });
+
+ it("lets a request with a profile's secret through to that profile's Chrome as a local DevTools connection, and nothing else", async () => {
+ folder = mkdtempSync(join(tmpdir(), "door-"));
+ const seen: Array<{ url: string | undefined; host: string | undefined; origin: string | undefined }> = [];
+ const wss = new WebSocketServer({ noServer: true });
+ chrome = createServer();
+ chrome.on("upgrade", (req, socket, head) => {
+ seen.push({ url: req.url, host: req.headers.host, origin: req.headers.origin });
+ wss.handleUpgrade(req, socket, head, (ws) => ws.on("message", (data) => ws.send(`chrome:${String(data)}`)));
+ });
+ await new Promise<void>((resolve) => chrome.listen(0, "127.0.0.1", resolve));
+ const chromePort = (chrome.address() as { port: number }).port;
+ const key = profileKey("scout"), secret = "b".repeat(48);
+ mkdirSync(join(folder, key, "profile"), { recursive: true });
+ writeFileSync(join(folder, key, "secret"), secret);
+ writeFileSync(join(folder, key, "profile", "DevToolsActivePort"), `${chromePort}\n/devtools/browser/abc-123\n`);
+ writeFileSync(join(folder, "door.mjs"), doorSource());
+ const probe = createServer();
+ await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
+ const doorPort = (probe.address() as { port: number }).port;
+ await new Promise<void>((resolve) => probe.close(() => resolve()));
+ const door = spawn(process.execPath, [join(folder, "door.mjs"), folder, String(doorPort)], { stdio: "ignore" });
+ try {
+ const open = async (path: string) => {
+ for (let tries = 0; ; tries++) {
+ const socket = new WebSocket(`ws://127.0.0.1:${doorPort}${path}`, { headers: { Origin: "https://evil.example", Host: "sandbox-39231.on.example" } });
+ try {
+ await new Promise<void>((resolve, reject) => { socket.once("open", () => resolve()); socket.once("error", reject); });
+ return socket;
+ } catch (error) {
+ if (tries > 40 || !String(error).includes("ECONNREFUSED")) throw error;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ }
+ };
+ const socket = await open(`/${key}/${secret}?_token=t`);
+ const answer = new Promise<string>((resolve) => socket.once("message", (data) => resolve(String(data))));
+ socket.send("hello");
+ expect(await answer).toBe("chrome:hello");
+ socket.close();
+ expect(seen).toEqual([{ url: "/devtools/browser/abc-123", host: `127.0.0.1:${chromePort}`, origin: undefined }]);
+ await expect(open(`/${key}/${"c".repeat(48)}`)).rejects.toThrow(/404/);
+ await expect(open(`/${profileKey("writer")}/${secret}`)).rejects.toThrow(/404/);
+ expect(seen).toHaveLength(1);
+ } finally {
+ door.kill();
+ }
+ });
+});
+
+describe("a computer's idle window with a browser's shorter one", () => {
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("a shorter window never cuts a longer one another use asked for, and a plain touch is unchanged", async () => {
+ vi.useFakeTimers();
+ const slept: number[] = [];
+ const timer = new ComputerIdleTimer(10_000, () => false, async () => { slept.push(Date.now()); });
+ const start = Date.now();
+ timer.touch();
+ timer.touch(1_000);
+ await vi.advanceTimersByTimeAsync(9_999);
+ expect(slept).toEqual([]);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(slept).toEqual([start + 10_000]);
+ const short = new ComputerIdleTimer(10_000, () => false, async () => { slept.push(Date.now()); });
+ const at = Date.now();
+ short.touch(3_000);
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(slept.at(-1)).toBe(at + 3_000);
+ timer.cancel();
+ short.cancel();
+ });
+});
diff --git a/server/cloud-browser/door.ts b/server/cloud-browser/door.ts
new file mode 100644
index 0000000000..07c2f92c74
--- /dev/null
+++ b/server/cloud-browser/door.ts
@@ -0,0 +1,152 @@
+// The home's end of a browser session on the bot's cloud computer: a loopback DevTools address the browser engine attaches
+// to (as it does to a lent Chrome, browser/lent-chrome.ts), whose connection is carried as one held-open WebSocket to the
+// computer's door through the provider's relay. Per action that adds one network round trip, never a provider API call.
+import { randomBytes, timingSafeEqual } from "node:crypto";
+import { connect as netConnect, createServer, type Server, type Socket } from "node:net";
+import { connect as tlsConnect } from "node:tls";
+
+const MAX_HEAD_BYTES = 16 * 1024;
+const HEAD_MS = 10_000;
+const PATH_PREFIX = "/devtools/browser/";
+const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
+
+/** Where the computer's door is: the relay's URL (with its access token) and this open's secret path. */
+export interface DoorTarget {
+ url: URL;
+ secret: string;
+}
+
+/** The relay URL, if it is one the home may dial: HTTPS, or plain HTTP to a loopback address (a test's computer). */
+export function dialable(raw: string): URL | null {
+ let url: URL;
+ try { url = new URL(raw); } catch { return null; }
+ if (url.username || url.password) return null;
+ if (url.protocol === "https:") return url;
+ return url.protocol === "http:" && LOOPBACK.has(url.hostname) ? url : null;
+}
+
+/** The request the computer's door gets: its secret path with the relay's token, the relay's host, and the engine's own
+ * WebSocket headers. Origin is dropped: Chrome refuses a DevTools connection that names one it was not told to allow. */
+export function rewrittenHead(head: Buffer, target: DoorTarget): Buffer {
+ const lines = head.toString("latin1").split("\r\n").filter(Boolean);
+ const kept = lines.slice(1).filter((line) => !/^(host|origin):/i.test(line));
+ const query = target.url.search;
+ return Buffer.from([`GET /${target.secret}${query} HTTP/1.1`, `Host: ${target.url.host}`, ...kept, "", ""].join("\r\n"), "latin1");
+}
+
+interface Door { server: Server; url: string; token: Buffer; target: DoorTarget; connections: Set<Socket>; lastActivity: number; dialed: number }
+
+function answer(socket: Socket, status: string): void {
+ socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`, () => socket.destroy());
+}
+
+function dial(url: URL): Socket {
+ const port = Number(url.port) || (url.protocol === "https:" ? 443 : 80);
+ const host = url.hostname.replace(/^\[|\]$/g, "");
+ return url.protocol === "https:" ? tlsConnect({ host, port, servername: host }) : netConnect({ host, port });
+}
+
+/** Proves a target answers a WebSocket upgrade with a 101 before a session is committed to it. */
+export function probeDoor(target: DoorTarget, timeoutMs = 10_000): Promise<boolean> {
+ return new Promise((resolve) => {
+ const socket = dial(target.url);
+ const ready = target.url.protocol === "https:" ? "secureConnect" : "connect";
+ let seen = Buffer.alloc(0);
+ const done = (ok: boolean) => { clearTimeout(timer); socket.destroy(); resolve(ok); };
+ const timer = setTimeout(() => done(false), timeoutMs);
+ timer.unref?.();
+ socket.once("error", () => done(false));
+ socket.on("data", (chunk: Buffer) => {
+ seen = Buffer.concat([seen, chunk]);
+ if (seen.length >= 12) done(seen.subarray(0, 12).toString("latin1") === "HTTP/1.1 101");
+ });
+ const key = randomBytes(16).toString("base64");
+ socket.once(ready, () => socket.write(rewrittenHead(Buffer.from(`GET / HTTP/1.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`, "latin1"), target)));
+ });
+}
+
+export class CloudBrowserDoors {
+ readonly #doors = new Map<string, Door>();
+ readonly #now: () => number;
+
+ constructor(now: () => number = Date.now) { this.#now = now; }
+
+ async open(session: string, target: DoorTarget): Promise<string> {
+ this.close(session);
+ const token = randomBytes(32);
+ const connections = new Set<Socket>();
+ const door: Door = { server: createServer(), url: "", token, target, connections, lastActivity: this.#now(), dialed: 0 };
+ door.server.on("connection", (socket) => {
+ connections.add(socket);
+ socket.on("close", () => connections.delete(socket));
+ socket.on("error", () => socket.destroy());
+ this.#serve(door, socket);
+ });
+ await new Promise<void>((resolve, reject) => {
+ door.server.once("error", reject);
+ door.server.listen(0, "127.0.0.1", () => { door.server.off("error", reject); door.server.on("error", () => {}); resolve(); });
+ });
+ const address = door.server.address();
+ const port = typeof address === "object" && address !== null ? address.port : 0;
+ door.url = `ws://127.0.0.1:${port}${PATH_PREFIX}${token.toString("hex")}`;
+ this.#doors.set(session, door);
+ return door.url;
+ }
+
+ url(session: string): string | null { return this.#doors.get(session)?.url ?? null; }
+ sessions(): string[] { return [...this.#doors.keys()]; }
+ /** When bytes last crossed this session's door either way: its browser's last activity. */
+ lastActivity(session: string): number | null { return this.#doors.get(session)?.lastActivity ?? null; }
+ /** How many connections to the computer this session's door has made. */
+ dialed(session: string): number { return this.#doors.get(session)?.dialed ?? 0; }
+
+ close(session: string): void {
+ const door = this.#doors.get(session);
+ if (!door) return;
+ this.#doors.delete(session);
+ for (const socket of door.connections) socket.destroy();
+ door.server.close();
+ }
+
+ closeAll(): void { for (const session of this.#doors.keys()) this.close(session); }
+
+ #serve(door: Door, socket: Socket): void {
+ let data = Buffer.alloc(0);
+ const timer = setTimeout(() => socket.destroy(), HEAD_MS);
+ timer.unref?.();
+ socket.once("close", () => clearTimeout(timer));
+ const onData = (chunk: Buffer) => {
+ data = Buffer.concat([data, chunk]);
+ const end = data.indexOf("\r\n\r\n");
+ if (end === -1) { if (data.length > MAX_HEAD_BYTES) socket.destroy(); return; }
+ socket.off("data", onData);
+ clearTimeout(timer);
+ const path = data.subarray(0, data.indexOf("\r\n")).toString("latin1").split(" ")[1] ?? "";
+ const given = Buffer.from(path.startsWith(PATH_PREFIX) ? path.slice(PATH_PREFIX.length) : "", "latin1");
+ const expected = Buffer.from(door.token.toString("hex"), "latin1");
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return answer(socket, "404 Not Found");
+ socket.pause();
+ this.#join(door, socket, data.subarray(0, end + 4), data.subarray(end + 4));
+ };
+ socket.on("data", onData);
+ }
+
+ #join(door: Door, socket: Socket, head: Buffer, rest: Buffer): void {
+ const upstream = dial(door.target.url);
+ door.dialed += 1;
+ door.connections.add(upstream);
+ const touch = () => { door.lastActivity = this.#now(); };
+ upstream.on("close", () => { door.connections.delete(upstream); socket.destroy(); });
+ upstream.on("error", () => upstream.destroy());
+ socket.on("close", () => upstream.destroy());
+ upstream.once(door.target.url.protocol === "https:" ? "secureConnect" : "connect", () => {
+ upstream.write(rewrittenHead(head, door.target));
+ if (rest.length) upstream.write(rest);
+ socket.on("data", touch);
+ upstream.on("data", touch);
+ socket.pipe(upstream);
+ upstream.pipe(socket);
+ socket.resume();
+ });
+ }
+}
diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.ts
new file mode 100644
index 0000000000..94930b09dc
--- /dev/null
+++ b/server/cloud-browser/index.ts
@@ -0,0 +1,257 @@
+// A personal Cloud's bots browse in the Cloud's own browser sandbox at the provider (remote.ts), so a page's memory and
+// CPU are not the home's. Decided once per browser session, when its browser opens; a session never moves while it runs.
+// Every case this cannot serve opens the home's browser exactly as before, with one log line naming why. A desktop
+// install never builds this. The one operator lever, never a product setting: OMB_CLOUD_BROWSER=home keeps every browser
+// in the home, and after a day of it the sandbox is deleted.
+import { randomBytes } from "node:crypto";
+
+import { cloudFailureOf } from "../boat-limit.ts";
+import { CloudBrowserDoors, dialable, probeDoor, type DoorTarget } from "./door.ts";
+import { createCloudBrowserRails, type CloudBrowserRails, type HomeReason } from "./rails.ts";
+import {
+ BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, launchAnswer, launchCommand, profileKey, quitCommand, QUIT_ALL_COMMAND,
+ OldRelay, StaysHome, wakeSandbox, type ComputerOps,
+} from "./remote.ts";
+
+/** A browser in the sandbox with no activity this long is closed; the sandbox sleeps once none is left. */
+export const CLOUD_BROWSER_IDLE_MS = 3 * 60_000;
+const SWEEP_MS = 30_000;
+const LAUNCH_MS = 25_000;
+const LEVER_CLEANUP_GAP_MS = 60 * 60_000;
+
+export const cloudBrowserLever = (env: NodeJS.ProcessEnv = process.env): boolean => env.OMB_CLOUD_BROWSER?.trim() === "home";
+
+export interface CloudBrowserDeps {
+ dataDir: string;
+ /** The provider, or null while this Cloud has no cloud computers set up. */
+ ops(): ComputerOps | null;
+ /** The cloud computers' own idle path (host/cloud-computer-power.ts), keyed by BROWSER_SANDBOX_OWNER: `windowMs` asks
+ * for a sleep that soon unless something keeps the sandbox on longer. */
+ used(owner: string, windowMs: number): void;
+ /** Closes the session's browser engine in the home (its connection to the sandbox goes with it). */
+ closeEngine(session: string): Promise<unknown>;
+ /** A turn holds this session's browser now: it is not closed for being idle. */
+ held(session: string): boolean;
+ env?: NodeJS.ProcessEnv;
+ now?: () => number;
+ log?: (line: string) => void;
+ rails?: CloudBrowserRails;
+ /** Tests: a shorter sweep and wake reads. */
+ sweepMs?: number;
+ pollMs?: number;
+}
+
+export interface OpenRequest {
+ session: string;
+ botId: string;
+ /** Why this session may not use the sandbox (the caller's rules), or null. */
+ refusal: HomeReason | null;
+}
+
+export type Opened = { cdpUrl: string } | { home: HomeReason };
+
+export function createCloudBrowser(deps: CloudBrowserDeps) {
+ const now = deps.now ?? Date.now;
+ const log = deps.log ?? ((line: string) => console.warn(line));
+ const rails = deps.rails ?? createCloudBrowserRails({ dataDir: deps.dataDir, now });
+ const doors = new CloudBrowserDoors(now);
+ /** Each running session's bot; one Chrome per bot's profile. */
+ const sessions = new Map<string, string>();
+ /** Bots whose browser is being opened now. */
+ const opening = new Set<string>();
+ const closing = new Set<string>();
+ /** One wake of the sandbox at a time, shared by every bot opening meanwhile. */
+ let waking: Promise<{ id: string; started: boolean }> | null = null;
+ let boxId: string | null = null;
+ let sweep: ReturnType<typeof setInterval> | null = null;
+ let leftAwakeArmed = false;
+ /** Woken (or found awake) by an open here and not yet let sleep. */
+ let awake = false;
+ let leverCleanupAt = -Infinity;
+
+ const home = (request: OpenRequest, reason: HomeReason): Opened => {
+ rails.home(reason);
+ log(`browser ${request.session}: opens in the home, not in the Cloud's browser sandbox (${reason})`);
+ return { home: reason };
+ };
+ const bots = () => new Set([...sessions.values(), ...opening]);
+
+ /** A refusal's own words decide: the account's starts, the sandbox's minutes, or a failure that counts toward the back-off. */
+ function refused(error: unknown): HomeReason {
+ const failure = cloudFailureOf(error);
+ const limit = failure.limit;
+ if (limit?.reason === "too_many_starts" && (limit.window === "day" || limit.window === undefined)) { rails.accountLimit(limit); return "account-limit"; }
+ if (limit?.reason === "hours_used") { rails.hoursUsed(limit); return "hours-used"; }
+ if (limit?.reason === "at_once") { rails.holdOff(); return "at-once"; }
+ if (limit) { rails.holdOff(); return "backoff"; }
+ // The account's start pool (the relay's "busy", or the provider's own limit met with a person's own key): the rest of the day.
+ if (failure.status === 429) { rails.accountLimit(undefined); return "account-limit"; }
+ rails.failed();
+ return "start-failed";
+ }
+
+ /** Once no browser is left in it: the sandbox's idle path may stop it within a second. */
+ function letSleep(): void {
+ if (!awake || bots().size > 0) return;
+ awake = false;
+ deps.used(BROWSER_SANDBOX_OWNER, 1_000);
+ rails.asleep();
+ }
+
+ async function wake(ops: ComputerOps): Promise<{ id: string; started: boolean }> {
+ waking ??= wakeSandbox(ops, {
+ mayStart: () => rails.refusal(true) === null,
+ starting: () => rails.resumed(),
+ ...(deps.pollMs ? { pollMs: deps.pollMs } : {}),
+ }).finally(() => { waking = null; });
+ const box = await waking;
+ boxId = box.id;
+ awake = true;
+ rails.awake();
+ // On from here: the idle path times it, whatever happens next.
+ deps.used(BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS);
+ return box;
+ }
+
+ async function launch(request: OpenRequest, ops: ComputerOps): Promise<Opened> {
+ const key = profileKey(request.botId);
+ let box: { id: string; started: boolean } | null = null;
+ const quit = async () => { if (box) await ops.run(box.id, quitCommand(key), 10_000).catch(() => undefined); };
+ try {
+ box = await wake(ops);
+ const secret = randomBytes(24).toString("hex");
+ const answer = launchAnswer(await ops.run(box.id, launchCommand(key, secret), LAUNCH_MS));
+ if (!answer.chrome) {
+ rails.failed();
+ await quit();
+ return home(request, "start-failed");
+ }
+ const relay = await ops.host(box.id, COMPUTER_DOOR_PORT).catch(() => null) ?? answer.url;
+ const url = relay ? dialable(relay) : null;
+ if (!url) {
+ rails.noRoute();
+ await quit();
+ return home(request, "no-route");
+ }
+ const target: DoorTarget = { url, secret: `${key}/${secret}` };
+ if (!await probeDoor(target)) {
+ rails.failed();
+ await quit();
+ return home(request, "unreachable");
+ }
+ const cdpUrl = await doors.open(request.session, target);
+ sessions.set(request.session, request.botId);
+ rails.opened();
+ startSweep();
+ log(`browser ${request.session}: opened in the Cloud's browser sandbox${box.started ? " (started for it)" : ""}`);
+ return { cdpUrl };
+ } catch (error) {
+ if (error instanceof StaysHome) return home(request, error.reason);
+ if (error instanceof OldRelay) { rails.noRoute(); return home(request, "no-route"); }
+ await quit();
+ return home(request, refused(error));
+ }
+ }
+
+ /** The lever held for a day: the sandbox is deleted (journaled, retried by the deletion journal if it fails). */
+ function leverCleanup(): void {
+ if (!rails.lever(true) || now() - leverCleanupAt < LEVER_CLEANUP_GAP_MS || bots().size > 0) return;
+ leverCleanupAt = now();
+ const ops = deps.ops();
+ if (!ops) return;
+ void (async () => {
+ const box = await ops.find();
+ if (!box) return;
+ const removed = await ops.remove(box.id);
+ log(`browser sandbox: ${removed ? "deleted" : "deletion requested and journaled"} after a day with every browser kept in the home`);
+ rails.asleep();
+ })().catch((error: unknown) => log(`browser sandbox: could not delete it yet (${error instanceof Error ? error.name : "error"}); retrying within the hour`));
+ }
+
+ /** Where the session's browser opens: in the sandbox (`cdpUrl`, the engine's address for it), or in the home. */
+ async function open(request: OpenRequest): Promise<Opened> {
+ const live = doors.url(request.session);
+ if (live) return { cdpUrl: live };
+ if (cloudBrowserLever(deps.env)) { leverCleanup(); return home(request, "lever"); }
+ rails.lever(false);
+ if (request.refusal) return home(request, request.refusal);
+ const ops = deps.ops();
+ if (!ops) return home(request, "not-set-up");
+ const held = rails.refusal(false);
+ if (held) return home(request, held);
+ // One Chrome per bot's profile: a second session of the same bot (another audience's) stays in the home.
+ if (bots().has(request.botId)) return home(request, "busy");
+ if (bots().size >= BROWSER_SANDBOX_CHROMES) return home(request, "sandbox-full");
+ opening.add(request.botId);
+ try {
+ return await launch(request, ops);
+ } finally {
+ opening.delete(request.botId);
+ letSleep();
+ }
+ }
+
+ /** The bot's Chrome quits cleanly (its cookies written), the engine's session ends, and the sandbox may sleep. */
+ async function close(session: string): Promise<void> {
+ const botId = sessions.get(session);
+ if (!botId || closing.has(session)) return;
+ closing.add(session);
+ try {
+ await deps.closeEngine(session).catch(() => undefined);
+ doors.close(session);
+ sessions.delete(session);
+ const ops = deps.ops();
+ if (ops && boxId) await ops.run(boxId, bots().size > 0 ? quitCommand(profileKey(botId)) : QUIT_ALL_COMMAND, 10_000).catch(() => undefined);
+ letSleep();
+ log(`browser ${session}: closed in the Cloud's browser sandbox after ${Math.round(CLOUD_BROWSER_IDLE_MS / 60_000)} minutes unused`);
+ } finally {
+ closing.delete(session);
+ }
+ }
+
+ async function closeIdle(): Promise<void> {
+ const at = now();
+ await Promise.all(doors.sessions().map(async (session) => {
+ const last = doors.lastActivity(session);
+ if (last !== null && at - last >= CLOUD_BROWSER_IDLE_MS && !deps.held(session)) await close(session);
+ }));
+ if (doors.sessions().length === 0 && sweep) { clearInterval(sweep); sweep = null; }
+ }
+
+ function startSweep(): void {
+ if (sweep) return;
+ sweep = setInterval(() => void closeIdle().catch(() => undefined), deps.sweepMs ?? SWEEP_MS);
+ sweep.unref?.();
+ }
+
+ return {
+ open,
+ /** The engine's address for a session running in the sandbox, or null. */
+ active: (session: string): string | null => doors.url(session),
+ attached: (session: string): boolean => doors.url(session) !== null,
+ /** A browser is open or opening in the sandbox: its idle path must not stop it. */
+ busy: (owner: string): boolean => owner === BROWSER_SANDBOX_OWNER && bots().size > 0,
+ close,
+ closeIdle,
+ dialed: (session: string): number => doors.dialed(session),
+ /** Today's counts for the health report. Read on the Admin's poll, never at start: a sandbox an earlier run of this
+ * server left awake gets its idle window here, and the lever's day-old cleanup runs here. */
+ report: () => {
+ if (!leftAwakeArmed && bots().size === 0 && rails.leftAwake()) {
+ leftAwakeArmed = true;
+ deps.used(BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS);
+ rails.asleep();
+ }
+ if (cloudBrowserLever(deps.env)) leverCleanup();
+ return rails.report();
+ },
+ closeAll(): void {
+ if (sweep) clearInterval(sweep);
+ sweep = null;
+ doors.closeAll();
+ sessions.clear();
+ },
+ };
+}
+export type CloudBrowser = ReturnType<typeof createCloudBrowser>;
+export type { HomeReason } from "./rails.ts";
diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.ts
new file mode 100644
index 0000000000..813ab0d22d
--- /dev/null
+++ b/server/cloud-browser/rails.ts
@@ -0,0 +1,214 @@
+// The cost and failure rails of a personal Cloud's browser on its bot's cloud computer (server/cloud-browser/index.ts).
+// Every start (a resume of a stopped computer) is counted here before it is sent, refused ones included, since the
+// provider bills a refused resume as a start. Kept on disk, so a restart neither forgets the day's count nor a hold.
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+
+import type { CloudLimit } from "../../shared/place-view.ts";
+
+/** Resumes a Cloud may spend on its bots' browsers in one UTC day; past it, every browser opens in the home. */
+export const CLOUD_BROWSER_DAILY_RESUMES = 30;
+/** Minutes the Cloud's browser sandbox may be awake in one UTC day; past it, every browser opens in the home. */
+export const CLOUD_BROWSER_DAILY_AWAKE_MINUTES = 240;
+/** Failed starts in a row before the back-off. */
+export const CLOUD_BROWSER_FAILURES_IN_ROW = 2;
+export const CLOUD_BROWSER_BACKOFF_MS = 15 * 60_000;
+
+/** Why a browser session opened in the home instead: names only, for the log and the health report. */
+export type HomeReason =
+ | "lever" | "team" | "not-eligible" | "not-set-up" | "busy" | "lent-connection"
+ | "budget" | "minutes-used" | "sandbox-full" | "backoff" | "account-limit" | "hours-used" | "at-once" | "no-route" | "start-failed" | "unreachable";
+
+interface Day {
+ day: string;
+ resumes: number;
+ /** Awake time of the sandbox this day, ended spells only (the running one is added when read). */
+ awakeMs: number;
+ computer: number;
+ home: number;
+ fallbacks: Partial<Record<HomeReason, number>>;
+}
+
+interface State extends Day {
+ failuresInRow: number;
+ backoffUntil: number;
+ /** The provider or the Admin said the account's starts are used up: no Cloud's start is sent before this. */
+ accountUntil: number;
+ /** This Cloud's cloud computer hours are used up. */
+ hoursUntil: number;
+ /** Neither way to reach a port on the computer worked today: no start is spent on it again before tomorrow. */
+ noRouteDay: string | null;
+ /** Since when the sandbox was woken here and not yet let sleep; 0 when asleep. */
+ awakeSince: number;
+ /** Since when the operator lever has kept every browser in the home; 0 when it does not. */
+ leverSince: number;
+}
+
+export const utcDay = (at: number): string => new Date(at).toISOString().slice(0, 10);
+const nextUtcMidnight = (at: number): number => {
+ const date = new Date(at);
+ return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate() + 1);
+};
+
+/** When a limit the Admin or the provider named lifts: its own `resetsAt` when it gave one in the future, else the next UTC day. */
+function liftsAt(limit: CloudLimit | undefined, now: number): number {
+ const said = limit?.resetsAt ? Date.parse(limit.resetsAt) : Number.NaN;
+ return Number.isFinite(said) && said > now ? said : nextUtcMidnight(now);
+}
+
+export interface CloudBrowserRailsOptions {
+ dataDir: string;
+ now?: () => number;
+ budget?: number;
+ awakeMinutes?: number;
+}
+
+export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {
+ const now = options.now ?? Date.now;
+ const budget = options.budget ?? CLOUD_BROWSER_DAILY_RESUMES;
+ const awakeCapMs = (options.awakeMinutes ?? CLOUD_BROWSER_DAILY_AWAKE_MINUTES) * 60_000;
+ const file = join(options.dataDir, "cloud-browser", "rails.json");
+ const fresh = (day: string): Day => ({ day, resumes: 0, awakeMs: 0, computer: 0, home: 0, fallbacks: {} });
+ let state: State = { ...fresh(utcDay(now())), failuresInRow: 0, backoffUntil: 0, accountUntil: 0, hoursUntil: 0, noRouteDay: null, awakeSince: 0, leverSince: 0 };
+ try {
+ const saved = JSON.parse(readFileSync(file, "utf8")) as Partial<State>;
+ const number = (value: unknown) => (typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0);
+ state = {
+ day: typeof saved.day === "string" ? saved.day : state.day,
+ resumes: number(saved.resumes), awakeMs: number(saved.awakeMs), computer: number(saved.computer), home: number(saved.home),
+ fallbacks: saved.fallbacks && typeof saved.fallbacks === "object" ? saved.fallbacks : {},
+ failuresInRow: number(saved.failuresInRow), backoffUntil: number(saved.backoffUntil),
+ accountUntil: number(saved.accountUntil), hoursUntil: number(saved.hoursUntil),
+ noRouteDay: typeof saved.noRouteDay === "string" ? saved.noRouteDay : null,
+ awakeSince: number(saved.awakeSince), leverSince: number(saved.leverSince),
+ };
+ } catch {
+ // None yet, or unreadable: a fresh day. The holds it may have had end by the next day anyway.
+ }
+
+ const today = (): State => {
+ const at = now(), day = utcDay(at);
+ if (state.day !== day) {
+ // A spell that runs over midnight: its part before midnight is yesterday's, and the new day counts from midnight.
+ if (state.awakeSince) state.awakeSince = Math.max(state.awakeSince, Date.parse(`${day}T00:00:00.000Z`));
+ state = { ...state, ...fresh(day) };
+ }
+ return state;
+ };
+ const awakeToday = (current: State) => current.awakeMs + (current.awakeSince ? Math.max(0, now() - current.awakeSince) : 0);
+ const save = () => {
+ try {
+ mkdirSync(dirname(file), { recursive: true });
+ writeFileSync(`${file}.tmp`, JSON.stringify(state));
+ renameSync(`${file}.tmp`, file);
+ } catch {
+ // The rails still hold in memory; only a restart would forget today's count.
+ }
+ };
+
+ return {
+ /** Why no start may be sent for a browser now, or null. `resume`: this open needs one (the computer is stopped). */
+ refusal(resume: boolean): HomeReason | null {
+ const current = today(), at = now();
+ if (at < current.accountUntil) return "account-limit";
+ if (at < current.hoursUntil) return "hours-used";
+ if (at < current.backoffUntil) return "backoff";
+ if (current.noRouteDay === current.day) return "no-route";
+ if (awakeToday(current) >= awakeCapMs) return "minutes-used";
+ if (resume && current.resumes >= budget) return "budget";
+ return null;
+ },
+ /** The sandbox is awake from now (woken or found awake here). */
+ awake(): void {
+ const current = today();
+ if (current.awakeSince) return;
+ current.awakeSince = now();
+ save();
+ },
+ /** It was let sleep: its spell ends now. */
+ asleep(): void {
+ const current = today();
+ if (!current.awakeSince) return;
+ current.awakeMs += Math.max(0, now() - current.awakeSince);
+ current.awakeSince = 0;
+ save();
+ },
+ /** Whether a spell is open, so a restarted server lets the sandbox sleep again. */
+ leftAwake: (): boolean => today().awakeSince > 0,
+ /** The operator lever's state; true once it has kept browsers in the home for more than a day. */
+ lever(on: boolean): boolean {
+ const current = today();
+ if (!on) {
+ if (current.leverSince) { current.leverSince = 0; save(); }
+ return false;
+ }
+ if (!current.leverSince) { current.leverSince = now(); save(); }
+ return now() - current.leverSince > 24 * 60 * 60_000;
+ },
+ /** Before the resume is sent: it counts whatever the answer. */
+ resumed(): void {
+ today().resumes += 1;
+ save();
+ },
+ opened(): void {
+ const current = today();
+ current.computer += 1;
+ current.failuresInRow = 0;
+ save();
+ },
+ home(reason: HomeReason): void {
+ const current = today();
+ current.home += 1;
+ current.fallbacks[reason] = (current.fallbacks[reason] ?? 0) + 1;
+ save();
+ },
+ /** A start or a launch that failed: two in a row hold every start off for CLOUD_BROWSER_BACKOFF_MS. */
+ failed(): void {
+ const current = today();
+ current.failuresInRow += 1;
+ if (current.failuresInRow >= CLOUD_BROWSER_FAILURES_IN_ROW) {
+ current.backoffUntil = now() + CLOUD_BROWSER_BACKOFF_MS;
+ current.failuresInRow = 0;
+ }
+ save();
+ },
+ /** The account's starts are used up (the Admin's `too_many_starts` for the day, or the provider's own 429). */
+ accountLimit(limit: CloudLimit | undefined): void {
+ today().accountUntil = liftsAt(limit, now());
+ save();
+ },
+ hoursUsed(limit: CloudLimit | undefined): void {
+ today().hoursUntil = liftsAt(limit, now());
+ save();
+ },
+ /** A refusal that is not this computer's fault and should not be asked again soon (the plan's computers at once, a
+ * minute or hour start limit, usage that cannot be checked): the same back-off as two failures. */
+ holdOff(): void {
+ const current = today();
+ current.backoffUntil = Math.max(current.backoffUntil, now() + CLOUD_BROWSER_BACKOFF_MS);
+ save();
+ },
+ noRoute(): void {
+ const current = today();
+ current.noRouteDay = current.day;
+ save();
+ },
+ /** Today's counts for the health report: numbers and reason names only. */
+ report() {
+ const current = today(), at = now();
+ return {
+ day: current.day,
+ sessions: { sandbox: current.computer, home: current.home },
+ resumes: current.resumes,
+ budget,
+ awakeMinutes: Math.floor(awakeToday(current) / 60_000),
+ awakeMinutesCap: Math.round(awakeCapMs / 60_000),
+ fallbacks: { ...current.fallbacks },
+ held: awakeToday(current) >= awakeCapMs ? "minutes-used" as const : at < current.accountUntil ? "account-limit" as const : at < current.hoursUntil ? "hours-used" as const
+ : at < current.backoffUntil ? "backoff" as const : current.noRouteDay === current.day ? "no-route" as const : null,
+ };
+ },
+ };
+}
+export type CloudBrowserRails = ReturnType<typeof createCloudBrowserRails>;
+export type CloudBrowserReport = ReturnType<CloudBrowserRails["report"]>;
diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.ts
new file mode 100644
index 0000000000..9bdadd088f
--- /dev/null
+++ b/server/cloud-browser/remote.ts
@@ -0,0 +1,270 @@
+// The Cloud's browser sandbox at the provider: one small sandbox per personal Cloud home, made the first time a bot needs
+// a browser, shared by that Cloud's bots, each with a profile of its own on its disk. It is not a bot's cloud computer:
+// no bot runs commands in it, the computer screens never list it, and on MausBot Cloud the Admin's relay keeps it out of
+// the plan's computers and hours (`purpose: "browser"`) under limits of its own.
+// Woken with ONE resume and then only reads, never the resume loop of boat.ts's waitReady: a refused resume is billed.
+import { createHash } from "node:crypto";
+
+import { boatAccount, boatFetch, boatNameFor, boatRefusal, findBoat, requestRecordedBoatDeletion, runCommand, SLEEPING_BOAT_STATES } from "../boat.ts";
+import { beginBoatCreate, discardBoatCreate, rememberCreatedBoat, resolveBoatCreate } from "../boat-create-idempotency.ts";
+import { relayBody } from "../boat-relay.ts";
+import type { CommandOutcome } from "../boat-command.ts";
+import type { AppConfig } from "../config.ts";
+
+const READY = new Set(["idle", "ready", "running"]);
+const TERMINAL = new Set(["error", "cancelled"]);
+/** The sandbox's owner key: its name is `ogb-<this installation>-browser-<hash>`, so operators tell it from a bot's computer. */
+export const BROWSER_SANDBOX_OWNER = "browser";
+/** The provider's smallest size that runs Chrome well: 2 vCPU, 4 GB. A heavy page measured 0.8–0.87 GB per Chrome. */
+export const BROWSER_SANDBOX_TYPE = "small";
+/** Chromes at once in one sandbox (one per bot browsing); past this a bot's browser opens in the home. */
+export const BROWSER_SANDBOX_CHROMES = 3;
+/** The provider stops it by itself after this long if every stop path here died. */
+const BROWSER_SANDBOX_TTL_SECONDS = 2 * 60 * 60;
+/** The port the sandbox's small door listens on, on its loopback only; the provider's relay reaches it there. */
+export const COMPUTER_DOOR_PORT = 39231;
+/** Where the browsers keep their profiles and the door on the sandbox's disk. */
+export const COMPUTER_BROWSER_DIR = "$HOME/.omb-browser";
+
+/** A bot's folder name in the sandbox: a hash, so the sandbox never holds a bot's id or name. */
+export const profileKey = (botId: string): string => createHash("sha256").update(`omb-browser:${botId}`).digest("hex").slice(0, 16);
+
+/** What the browser needs from the provider; tests pass their own. */
+export interface ComputerOps {
+ /** The Cloud's browser sandbox, or null when there is none yet. */
+ find(): Promise<{ id: string; state: string } | null>;
+ /** Makes it (once: the create is journaled under one idempotency key) and names it. Throws the provider's or the Admin's refusal. */
+ create(): Promise<{ id: string; state: string }>;
+ /** One resume. Throws the provider's or the Admin's refusal (with its limit) on anything but a 2xx or a 409. */
+ resume(boxId: string): Promise<void>;
+ state(boxId: string): Promise<string | null>;
+ run(boxId: string, command: string, timeoutMs: number): Promise<CommandOutcome>;
+ /** The provider's way to put the door's port on a URL; null where it is refused. */
+ host(boxId: string, port: number): Promise<string | null>;
+ /** Deletes it, journaled like every deletion (boat-delete-journal.ts), so a failed delete is retried and never leaks. */
+ remove(boxId: string): Promise<boolean>;
+}
+
+async function json(cfg: AppConfig, path: string, init: RequestInit = {}) {
+ const res = await boatFetch(cfg, path, { ...init, signal: init.signal ?? AbortSignal.timeout(20_000) });
+ const body: any = relayBody(boatAccount(cfg), await res.json().catch(() => null));
+ return { ok: res.ok && body?.ok !== false, status: res.status, body };
+}
+
+const included = (cfg: AppConfig) => boatAccount(cfg)?.included === true;
+
+/** `purpose` tells the Admin's relay this is the Cloud's browser sandbox, outside the plan's computers and hours; a
+ * person's own key goes to the provider, which takes no such field. */
+export const browserSandboxCreateBody = (viaRelay: boolean) =>
+ ({ ttlSeconds: BROWSER_SANDBOX_TTL_SECONDS, noEnv: true, type: BROWSER_SANDBOX_TYPE, ...(viaRelay ? { purpose: "browser" } : {}) });
+
+export function providerOps(cfg: () => AppConfig): ComputerOps {
+ async function create(): Promise<{ id: string; state: string }> {
+ const config = cfg();
+ const body = JSON.stringify(browserSandboxCreateBody(included(config)));
+ let request = beginBoatCreate(BROWSER_SANDBOX_OWNER, body).request;
+ let answer = request.boxId ? await json(config, `/sandboxes/${request.boxId}`) : null;
+ let posted = false;
+ if (!answer?.ok) {
+ posted = true;
+ answer = await json(config, "/sandboxes", { method: "POST", headers: { "Idempotency-Key": request.idempotencyKey }, body, signal: AbortSignal.timeout(45_000) });
+ // The relay already holds this Cloud's browser sandbox (a create whose answer was lost): that one is ours.
+ const existing = answer.body?.boxId ?? answer.body?.error?.boxId;
+ if (answer.status === 409 && (answer.body?.code ?? answer.body?.error?.code) === "browser_sandbox_exists" && typeof existing === "string") {
+ answer = { ok: true, status: 200, body: { sandbox: { id: existing, state: "unknown" } } };
+ posted = false;
+ }
+ }
+ const boxId = answer.body?.sandbox?.id;
+ if (!answer.ok || typeof boxId !== "string") {
+ if (answer.status < 500 && answer.status !== 409) discardBoatCreate(request);
+ throw boatRefusal(answer.status, "making the browser sandbox", answer.body, included(config));
+ }
+ request = rememberCreatedBoat(request, boxId);
+ // A relay from before the browser sandbox made a plan computer instead, which would take the plan's slot: deleted at once.
+ if (posted && included(config) && answer.body.sandbox.purpose !== "browser") {
+ resolveBoatCreate(request);
+ await requestRecordedBoatDeletion(config, { boxId, name: await boatNameFor(BROWSER_SANDBOX_OWNER), ownerBotId: BROWSER_SANDBOX_OWNER }).catch(() => "pending");
+ throw new OldRelay();
+ }
+ const named = await json(config, `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ name: await boatNameFor(BROWSER_SANDBOX_OWNER) }) });
+ if (!named.ok) throw boatRefusal(named.status, "naming the browser sandbox", named.body, included(config));
+ resolveBoatCreate(request);
+ return { id: boxId, state: typeof answer.body.sandbox.state === "string" ? answer.body.sandbox.state : "unknown" };
+ }
+ return {
+ async find() {
+ const found = await findBoat(cfg(), BROWSER_SANDBOX_OWNER);
+ return found && typeof found.id === "string" ? { id: found.id, state: typeof found.state === "string" ? found.state : "unknown" } : null;
+ },
+ create,
+ async resume(boxId) {
+ const answer = await json(cfg(), `/sandboxes/${boxId}/resume`, { method: "POST" });
+ // 409: a wake already under way; it is waited for like this one.
+ if (!answer.ok && answer.status !== 409) throw boatRefusal(answer.status, "waking the browser sandbox", answer.body, included(cfg()));
+ },
+ async state(boxId) {
+ const answer = await json(cfg(), `/sandboxes/${boxId}`);
+ const state = answer.body?.sandbox?.state;
+ return typeof state === "string" ? state : null;
+ },
+ run: (boxId, command, timeoutMs) => runCommand(cfg(), boxId, command, { timeoutMs }),
+ async host(boxId, port) {
+ const answer = await json(cfg(), `/sandboxes/${boxId}/host`, { method: "POST", body: JSON.stringify({ port, localhost: true }) });
+ return answer.ok && typeof answer.body?.url === "string" ? answer.body.url : null;
+ },
+ async remove(boxId) {
+ const name = await boatNameFor(BROWSER_SANDBOX_OWNER);
+ return (await requestRecordedBoatDeletion(cfg(), { boxId, name, ownerBotId: BROWSER_SANDBOX_OWNER })) === "confirmed";
+ },
+ };
+}
+
+/** The Cloud's relay does not know the browser sandbox yet (an Admin from before it): no route today. */
+export class OldRelay extends Error {}
+
+/** Not a failure of the sandbox: the browser opens in the home, and nothing is counted against it. */
+export class StaysHome extends Error {
+ readonly reason: "busy" | "budget";
+ constructor(reason: "busy" | "budget") {
+ super(reason);
+ this.reason = reason;
+ }
+}
+
+export interface WakeOptions {
+ /** Asked before the one start (a create or a resume) is sent: false keeps it unsent (the day's budget, a hold). */
+ mayStart(): boolean;
+ /** Called just before the start goes out, so it counts whatever the answer. */
+ starting(): void;
+ budgetMs?: number;
+ pollMs?: number;
+}
+
+/** The sandbox ready to take commands: made or woken with at most one start, then read until it says so. */
+export async function wakeSandbox(ops: ComputerOps, options: WakeOptions): Promise<{ id: string; started: boolean }> {
+ let found = await ops.find();
+ if (found && TERMINAL.has(found.state)) throw new Error("the browser sandbox is broken at the provider");
+ if (found && READY.has(found.state)) return { id: found.id, started: false };
+ // Archiving: its snapshot must land before it can be resumed, and another stop path owns it now.
+ if (found?.state === "archiving") throw new StaysHome("busy");
+ let started = false;
+ if (!found || SLEEPING_BOAT_STATES.has(found.state)) {
+ if (!options.mayStart()) throw new StaysHome("budget");
+ options.starting();
+ started = true;
+ if (!found) found = await ops.create();
+ else await ops.resume(found.id);
+ }
+ const id = found.id;
+ const deadline = Date.now() + (options.budgetMs ?? 45_000);
+ // Quick reads first: a resume after a short stop is ready in well under a second.
+ for (let reads = 0; Date.now() < deadline; reads++) {
+ await new Promise((resolve) => setTimeout(resolve, reads < 12 ? Math.min(250, options.pollMs ?? 250) : options.pollMs ?? 1_000));
+ const state = await ops.state(id).catch(() => null);
+ if (state && READY.has(state)) return { id, started };
+ if (state && TERMINAL.has(state)) break;
+ // Never a second start: a refused resume is billed as one too.
+ }
+ throw new Error("the browser sandbox did not become ready in time");
+}
+
+const DOOR_SOURCE = String.raw`
+import net from "node:net"; import fs from "node:fs"; import { timingSafeEqual } from "node:crypto";
+const D = process.argv[2], PORT = Number(process.argv[3]);
+const read = (f) => { try { return fs.readFileSync(D + f, "utf8"); } catch { return ""; } };
+const same = (a, b) => a.length === b.length && a.length > 0 && timingSafeEqual(Buffer.from(a), Buffer.from(b));
+net.createServer((s) => {
+ let buf = Buffer.alloc(0);
+ const t = setTimeout(() => s.destroy(), 10000);
+ s.on("error", () => s.destroy());
+ const on = (c) => {
+ buf = Buffer.concat([buf, c]);
+ const e = buf.indexOf("\r\n\r\n");
+ if (e < 0) { if (buf.length > 16384) s.destroy(); return; }
+ s.off("data", on); clearTimeout(t);
+ const head = buf.subarray(0, e).toString("latin1").split("\r\n"), rest = buf.subarray(e + 4);
+ const [, key = "", secret = ""] = /^\/([a-f0-9]{16})\/([a-f0-9]+)$/.exec((head[0].split(" ")[1] || "").split("?")[0]) || [];
+ const ports = key ? read("/" + key + "/profile/DevToolsActivePort").split("\n").map((x) => x.trim()) : [];
+ if (!key || !same(secret, read("/" + key + "/secret").trim()) || !ports[1]) { s.end("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"); return; }
+ const keep = head.slice(1).filter((h) => !/^(host|origin|forwarded|x-forwarded-[a-z-]*|x-real-ip):/i.test(h));
+ const up = net.connect(Number(ports[0]), "127.0.0.1", () => {
+ up.write(["GET " + ports[1] + " HTTP/1.1", "Host: 127.0.0.1:" + ports[0], ...keep, "", ""].join("\r\n"));
+ if (rest.length) up.write(rest);
+ s.pipe(up); up.pipe(s);
+ });
+ up.on("error", () => s.destroy()); up.on("close", () => s.destroy()); s.on("close", () => up.destroy());
+ };
+ s.on("data", on);
+}).listen(PORT, "127.0.0.1");
+`;
+
+/** The door's source, for its own test. */
+export const doorSource = (): string => DOOR_SOURCE;
+
+const check = (key: string, secret: string) => {
+ if (!/^[a-f0-9]{16}$/.test(key)) throw new Error("bad profile key");
+ if (!/^[a-f0-9]{32,128}$/.test(secret)) throw new Error("bad door secret");
+};
+
+/**
+ * One command: write this open's secret for one bot's profile, start that profile's Chrome unless it already runs
+ * (clearing a profile lock an earlier host left: nothing runs on it, so no live Chrome holds it), start the door unless it
+ * runs, and put the door on the provider's relay. Prints one JSON line: whether Chrome answers, and the relay's URL when
+ * the sandbox gave one. Chrome and the door start with an empty environment: no provider variable reaches a page. Each
+ * bot's profile is its own folder (its own user-data-dir and Chrome), so no bot's pages see another's cookies.
+ */
+export function launchCommand(key: string, secret: string, port = COMPUTER_DOOR_PORT): string {
+ check(key, secret);
+ const D = COMPUTER_BROWSER_DIR;
+ const clean = 'env -i HOME="$HOME" PATH="/usr/local/bin:/usr/bin:/bin" setsid nohup';
+ return [
+ `D="${D}"; K="$D/${key}"; P="$K/profile"; mkdir -p "$P"; chmod 700 "$D" "$K"`,
+ `umask 077; printf %s '${secret}' > "$K/secret"`,
+ `if ! pgrep -f -- "--user-data-dir=$P" >/dev/null 2>&1; then`,
+ ` rm -f "$P/SingletonLock" "$P/SingletonSocket" "$P/SingletonCookie" "$P/DevToolsActivePort"`,
+ ` B=$(command -v google-chrome || command -v google-chrome-stable || command -v chromium || command -v chromium-browser)`,
+ ` V=$("$B" --version 2>/dev/null | grep -o '[0-9][0-9.]*' | head -1)`,
+ ` ${clean} "$B" --headless=new --remote-debugging-address=127.0.0.1 --remote-debugging-port=0 --user-data-dir="$P" --no-first-run --no-default-browser-check --password-store=basic --use-mock-keychain --disable-dev-shm-usage --window-size=1280,800 --user-agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/$V Safari/537.36" about:blank >"$K/chrome.log" 2>&1 </dev/null &`,
+ "fi",
+ `for i in $(seq 1 80); do [ -s "$P/DevToolsActivePort" ] && break; sleep 0.1; done`,
+ `if ! pgrep -f -- "$D/door.mjs" >/dev/null 2>&1; then`,
+ ` cat > "$D/door.mjs" <<'OMB_DOOR'${DOOR_SOURCE}OMB_DOOR`,
+ ` ${clean} node "$D/door.mjs" "$D" ${port} >"$D/door.log" 2>&1 </dev/null &`,
+ "fi",
+ `(host ${port} --localhost >/dev/null 2>&1 || true)`,
+ `U=$(host url ${port} --localhost 2>/dev/null | grep -o 'https://[^[:space:]]*' | head -1)`,
+ `C=false; [ -s "$P/DevToolsActivePort" ] && C=true`,
+ `printf '{"chrome":%s,"url":"%s"}\\n' "$C" "$U"`,
+ ].join("\n");
+}
+
+/** One bot's Chrome asked to quit, so it writes its cookies; the others keep running. */
+export function quitCommand(key: string): string {
+ if (!/^[a-f0-9]{16}$/.test(key)) throw new Error("bad profile key");
+ return [
+ `P="${COMPUTER_BROWSER_DIR}/${key}/profile"`,
+ `pkill -TERM -f -- "--user-data-dir=$P" 2>/dev/null || true`,
+ `for i in $(seq 1 20); do pgrep -f -- "--user-data-dir=$P" >/dev/null 2>&1 || break; sleep 0.1; done`,
+ ].join("\n");
+}
+
+/** Every Chrome and the door asked to quit, before the sandbox stops. */
+export const QUIT_ALL_COMMAND = [
+ `D="${COMPUTER_BROWSER_DIR}"`,
+ `pkill -TERM -f -- "--user-data-dir=$D/" 2>/dev/null || true`,
+ `pkill -TERM -f -- "$D/door.mjs" 2>/dev/null || true`,
+ `for i in $(seq 1 30); do pgrep -f -- "--user-data-dir=$D/" >/dev/null 2>&1 || break; sleep 0.1; done`,
+].join("\n");
+
+/** The launch's answer: whether Chrome answers, and the relay URL the sandbox printed (a secret: never logged). */
+export function launchAnswer(outcome: CommandOutcome): { chrome: boolean; url: string | null } {
+ const line = outcome.stdout.trim().split("\n").at(-1) ?? "";
+ try {
+ const parsed = JSON.parse(line) as { chrome?: unknown; url?: unknown };
+ const url = typeof parsed.url === "string" && parsed.url ? parsed.url : null;
+ return { chrome: parsed.chrome === true, url };
+ } catch {
+ return { chrome: false, url: null };
+ }
+}
diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.ts
new file mode 100644
index 0000000000..f9ef1c712a
--- /dev/null
+++ b/server/cloud-browser/testing/fake-computer.ts
@@ -0,0 +1,120 @@
+// A fake provider for the Cloud's browser sandbox: the provider's API (list, create, name, resume, state, commands, host,
+// delete) and the sandbox's door behind its relay, which answers a WebSocket upgrade as Chrome would and echoes every
+// frame. Nothing here reaches a real provider or starts a real sandbox.
+import { createHash } from "node:crypto";
+import { createServer, type IncomingMessage, type Server } from "node:http";
+import type { Duplex } from "node:stream";
+import { WebSocketServer } from "ws";
+
+export const OWN_KEY = "boat_own-test-key";
+export const RELAY_TOKEN = "relay-token-123";
+
+type Request = { method: string; path: string; command?: string; body?: Record<string, unknown> };
+
+export interface FakeComputer {
+ base: string;
+ state: string;
+ /** Whether the sandbox exists yet; a create makes it. */
+ exists: boolean;
+ /** Status the next resumes and creates answer with (a 2xx makes the sandbox ready). */
+ startStatus: number;
+ startBody: Record<string, unknown>;
+ /** Whether the launch command prints the relay URL. */
+ printUrl: boolean;
+ /** Whether the provider's host route answers. */
+ hostRoute: boolean;
+ chromeStarts: boolean;
+ /** Plays a relay that knows the browser sandbox: its create answer carries `purpose`. */
+ knowsPurpose: boolean;
+ requests: Request[];
+ upgrades: Array<{ path: string; host: string | undefined; origin: string | undefined }>;
+ frames: string[];
+ resumes(): number;
+ creates(): number;
+ launches(): number;
+ quits(): number;
+ /** The profile folders the launches named, in order. */
+ profiles(): string[];
+ close(): Promise<void>;
+}
+
+const legacyName = (owner: string) => `ogb-${owner.slice(0, 8).toLowerCase().replace(/[^a-z0-9]/g, "")}-${createHash("sha256").update(owner).digest("hex").slice(0, 6)}`;
+
+export async function startFakeComputer(boxId = "bx_23456789"): Promise<FakeComputer> {
+ const secrets = new Map<string, string>();
+ const wss = new WebSocketServer({ noServer: true });
+ const fake = {
+ base: "", state: "ready", exists: true, startStatus: 200, startBody: { ok: true }, printUrl: false, hostRoute: true, chromeStarts: true, knowsPurpose: true,
+ requests: [], upgrades: [], frames: [],
+ } as unknown as FakeComputer;
+ const server: Server = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://fake");
+ let raw = "";
+ req.on("data", (chunk) => { raw += chunk; });
+ req.on("end", () => {
+ const body = raw ? JSON.parse(raw) as Record<string, unknown> : {};
+ fake.requests.push({ method: req.method ?? "GET", path: url.pathname, ...(typeof body.command === "string" ? { command: body.command } : {}), body });
+ const send = (status: number, payload: unknown) => { res.writeHead(status, { "content-type": "application/json", connection: "close" }); res.end(JSON.stringify(payload)); };
+ if (req.headers.authorization !== `Bearer ${OWN_KEY}`) return send(401, { ok: false });
+ const row = { id: boxId, name: legacyName("browser"), state: fake.state };
+ const rest = url.pathname.replace(/^\/api\/v1/, "");
+ if (rest === "/sandboxes" && req.method === "GET") return send(200, { ok: true, sandboxes: fake.exists ? [row] : [], pageInfo: { nextCursor: null } });
+ if (rest === "/sandboxes" && req.method === "POST") {
+ if (fake.startStatus >= 300) return send(fake.startStatus, fake.startBody);
+ fake.exists = true;
+ fake.state = "ready";
+ return send(202, { ok: true, sandbox: { id: boxId, state: "provisioning", ...(fake.knowsPurpose && body.purpose ? { purpose: body.purpose } : {}) } });
+ }
+ if (rest === `/sandboxes/${boxId}` && req.method === "PATCH") return send(200, { ok: true, sandbox: row });
+ if (rest === `/sandboxes/${boxId}` && req.method === "GET") return fake.exists ? send(200, { ok: true, sandbox: row }) : send(404, { ok: false });
+ if (rest === `/sandboxes/${boxId}` && req.method === "DELETE") { fake.exists = false; return send(200, { ok: true, operation: { id: `bdop_${"a".repeat(32)}`, status: "completed", kind: "sandbox", targetId: boxId } }); }
+ if (rest === `/sandboxes/${boxId}/resume`) {
+ if (fake.startStatus < 300) fake.state = "ready";
+ return send(fake.startStatus, fake.startBody);
+ }
+ if (rest === `/sandboxes/${boxId}/host`) return fake.hostRoute ? send(200, { ok: true, url: `${fake.base}/door?_token=${RELAY_TOKEN}` }) : send(404, { ok: false, code: "not_found" });
+ if (rest === `/sandboxes/${boxId}/commands`) {
+ const command = String(body.command ?? "");
+ const key = /K="\$D\/([a-f0-9]{16})"/.exec(command)?.[1], secret = /printf %s '([a-f0-9]+)'/.exec(command)?.[1];
+ if (key && secret) {
+ secrets.set(key, secret);
+ const printed = fake.printUrl ? `${fake.base}/door?_token=${RELAY_TOKEN}` : "";
+ return send(200, { exitCode: 0, stdout: `${JSON.stringify({ chrome: fake.chromeStarts, url: printed })}\n`, stderr: "" });
+ }
+ return send(200, { exitCode: 0, stdout: "", stderr: "" });
+ }
+ if (rest === `/sandboxes/${boxId}/stop`) { fake.state = "archived"; return send(200, { ok: true }); }
+ send(404, { ok: false, code: "not_found" });
+ });
+ });
+ server.on("upgrade", (req: IncomingMessage, socket: Duplex, head: Buffer) => {
+ const url = new URL(req.url ?? "/", "http://fake");
+ fake.upgrades.push({ path: url.pathname, host: req.headers.host, origin: req.headers.origin });
+ const [, key = "", secret = ""] = /^\/([a-f0-9]{16})\/([a-f0-9]+)$/.exec(url.pathname) ?? [];
+ if (!key || secrets.get(key) !== secret || url.searchParams.get("_token") !== RELAY_TOKEN) {
+ socket.end("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
+ return;
+ }
+ wss.handleUpgrade(req, socket, head, (ws) => {
+ ws.on("message", (data) => { const text = String(data); fake.frames.push(text); ws.send(`echo:${key}:${text}`); });
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ fake.base = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
+ const count = (test: (request: Request) => boolean) => fake.requests.filter(test).length;
+ fake.resumes = () => count((request) => request.method === "POST" && request.path.endsWith("/resume"));
+ fake.creates = () => count((request) => request.method === "POST" && request.path === "/api/v1/sandboxes");
+ fake.launches = () => count((request) => request.command?.includes("printf %s") === true);
+ fake.quits = () => count((request) => request.command?.includes("pkill -TERM") === true);
+ fake.profiles = () => fake.requests.flatMap((request) => {
+ const key = request.command?.includes("printf %s") ? /K="\$D\/([a-f0-9]{16})"/.exec(request.command)?.[1] : undefined;
+ return key ? [key] : [];
+ });
+ fake.close = async () => {
+ for (const client of wss.clients) client.terminate();
+ wss.close();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ };
+ return fake;
+}
diff --git a/server/cloud-health.ts b/server/cloud-health.ts
index 72dd73844c..3dcdaf04dc 100644
--- a/server/cloud-health.ts
+++ b/server/cloud-health.ts
@@ -7,6 +7,7 @@ import { failedTurnCause } from "../shared/failed-turn.ts";
import { PLACE_STATES } from "../shared/place-view.ts";
import { trialCreditKind } from "../shared/trial-credit.ts";
import type { BoxReport } from "./bot-box/box.ts";
+import type { CloudBrowserReport } from "./cloud-browser/rails.ts";
import type { RoomReport } from "./engine-memory.ts";
import type { FirstHourReport } from "./host/first-hour.ts";
import type { ValueReport } from "./host/value-ledger.ts";
@@ -261,7 +262,9 @@ export interface CloudHealthDeps {
image: string | undefined;
/** Null when connected apps are not set up here. */
connectors: () => Promise<Record<string, { connected: boolean; pending?: boolean }>> | null;
- browser: () => { available: boolean; installing: boolean; interrupted: number };
+ /** `cloudComputer`: a personal Cloud's bot browsers on their cloud computers today (server/cloud-browser/rails.ts):
+ * where sessions opened, resumes spent, and why a session stayed in the home, by reason name only. */
+ browser: () => { available: boolean; installing: boolean; interrupted: number; cloudComputer?: CloudBrowserReport | null };
/** The bot box (server/bot-box): whether turns run boxed here, and the last self-check's count. */
box?: () => BoxReport;
/** A personal Cloud's milestones since its first boot, and the work its Chief did: times and counts only. */
@@ -351,7 +354,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {
v: 1 as const, version, image, bootedAt: ledger.bootedAt, at: now(),
turns: read.turns, routines: guarded(() => deps.routines?.(ROUTINE_CAP) ?? [], []).filter((routine) => match(ID, routine.routineId)), schedule: guarded(() => deps.schedule?.() ?? null, null),
engines: engines(), connectors: connectorState(),
- browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },
+ browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted, ...(browser.cloudComputer ? { cloudComputer: browser.cloudComputer } : {}) },
box: boxSummary(deps.box?.()),
firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(), perf: perf(), ...storage(),
// The data checks of this version's first start: check ids and counts (server/doctor/start.ts).
diff --git a/server/computer-idle.ts b/server/computer-idle.ts
index 12ce239139..469f578513 100644
--- a/server/computer-idle.ts
+++ b/server/computer-idle.ts
@@ -6,6 +6,8 @@ const BUSY_CHECKS_PER_WINDOW = 10;
export class ComputerIdleTimer {
private timer: ReturnType<typeof setTimeout> | null = null;
private lastActivityAt = 0;
+ /** The end of the longest window any activity asked for. */
+ private quietAt = 0;
private failures = 0;
private busySeen = false;
/** Bumped by every cancel, so a stop still in flight from an earlier window neither re-arms nor reports. */
@@ -28,11 +30,15 @@ export class ComputerIdleTimer {
this.onFailure = onFailure;
}
- touch(): void {
- this.lastActivityAt = Date.now();
+ /** `windowMs`: this activity's own quiet window, shorter or longer than the timer's; a shorter one never cuts a window
+ * an earlier activity asked for. */
+ touch(windowMs: number = this.idleMs): void {
+ const at = Date.now();
+ this.lastActivityAt = at;
this.failures = 0;
this.busySeen = false;
- this.arm(this.idleMs);
+ this.quietAt = Math.max(this.quietAt, at + checkedIdleMs(windowMs));
+ this.arm(this.quietAt - at);
}
cancel(): void {
@@ -43,6 +49,7 @@ export class ComputerIdleTimer {
setIdleMs(idleMs: number): void {
this.idleMs = checkedIdleMs(idleMs);
+ this.quietAt = this.lastActivityAt + this.idleMs;
if (!this.timer) return;
this.arm(Math.max(0, this.lastActivityAt + this.idleMs - Date.now()));
}
diff --git a/server/host/browser-cloud-sandbox.test.ts b/server/host/browser-cloud-sandbox.test.ts
new file mode 100644
index 0000000000..32c0bfdb18
--- /dev/null
+++ b/server/host/browser-cloud-sandbox.test.ts
@@ -0,0 +1,154 @@
+// The bots' browser host on a personal Cloud, where a bot's browser opens in the Cloud's browser sandbox, against a fake
+// provider (cloud-browser/testing/fake-computer.ts): the switch's lever, a desktop install, and the rules kept for it.
+import { rmSync } from "node:fs";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { browserEngineStatus } from "../browser-engine.ts";
+import { BrowserRuntime } from "../browser-runtime.ts";
+import { BrowserUploadRefusal } from "../browser-upload.ts";
+import { REDDIT_REFUSAL } from "../browser/egress/reddit.ts";
+import { DATA_DIR, type AppConfig } from "../config.ts";
+import type { Store } from "../store.ts";
+import { OWN_KEY, startFakeComputer, type FakeComputer } from "../cloud-browser/testing/fake-computer.ts";
+import { CLOUD_BROWSER_NO_UPLOAD, createBrowserHost, type BrowserHostDeps } from "./browser.ts";
+
+vi.mock("../browser-engine.ts", async (original) => {
+ const actual = await original<typeof import("../browser-engine.ts")>();
+ return {
+ ...actual,
+ browserEngineStatus: vi.fn(actual.browserEngineStatus),
+ prepareBrowserSessionState: vi.fn(async () => undefined),
+ clearBrowserSessionState: vi.fn(async () => true),
+ closeBrowserSession: vi.fn(async () => true),
+ runningBrowserSessionNames: vi.fn(async () => []),
+ };
+});
+vi.mock("../browser-processes.ts", async (original) => ({
+ ...await original<typeof import("../browser-processes.ts")>(),
+ orphanedBrowsers: vi.fn(async () => []),
+}));
+
+const botId = "scout";
+const turn = { threadId: "thread-1", generation: "gen-1" };
+let fake: FakeComputer;
+type Host = ReturnType<typeof createBrowserHost>;
+const hosts: Host[] = [];
+
+beforeEach(async () => {
+ // Each test starts the day afresh: the rails keep their counts in the data folder.
+ rmSync(join(DATA_DIR, "cloud-browser"), { recursive: true, force: true });
+ fake = await startFakeComputer();
+ vi.stubEnv("OMB_BOAT_API", `${fake.base}/api/v1`);
+ vi.stubEnv("OMB_CLOUD_BROWSER", undefined);
+ vi.mocked(browserEngineStatus).mockReturnValue({ kind: "ready", binaryPath: "/usr/local/bin/agent-browser", version: "0.37.0", managed: false });
+ vi.spyOn(BrowserRuntime.prototype, "agentRpc").mockImplementation(async (_session, _spec, _method, _params, beforeDispatch) => {
+ beforeDispatch?.();
+ return { content: [{ type: "text", text: "page" }] };
+ });
+});
+
+afterEach(async () => {
+ await Promise.all(hosts.splice(0).map(async (host) => { host.browserSweep.closeAll(); await host.browserRuntime.closeAll(); }));
+ vi.restoreAllMocks();
+ vi.mocked(browserEngineStatus).mockReset();
+ vi.unstubAllEnvs();
+ await fake.close();
+});
+
+function setup({ desktop = false, cloudBrowser = true }: { desktop?: boolean; cloudBrowser?: boolean } = {}) {
+ const cfg = { features: { browser: true }, box: { token: OWN_KEY } } as unknown as AppConfig;
+ const bots = [{ id: botId, name: botId, browser: true }];
+ const used: Array<[string, number]> = [];
+ const deps: BrowserHostDeps = {
+ cfg,
+ store: () => ({ bots, bot: (id: string) => bots.find((bot) => bot.id === id), botByThread: () => bots[0] }) as unknown as Pick<Store, "bots" | "bot" | "botByThread">,
+ turnResources: { free: () => true, holder: () => undefined, onClaim: () => () => {} },
+ activeInternalGenerationByThread: new Map([[turn.threadId, turn.generation]]),
+ mintInternalCapability: () => "capability-token",
+ DESKTOP_MANAGED: desktop,
+ CLOUD_HOME: desktop ? null : { machineId: "m-1" },
+ PORT: 4100,
+ ...(cloudBrowser ? { cloudBrowser: { used: (owner: string, windowMs: number) => { used.push([owner, windowMs]); } } } : {}),
+ };
+ const host = createBrowserHost(deps);
+ hosts.push(host);
+ return { host, used };
+}
+
+const OPEN = "agent_browser_open";
+
+describe("a personal Cloud's bot browser opens in the Cloud's browser sandbox", () => {
+ it("attaches the session's engine to the sandbox when a tool call opens it, and keeps the Cloud's rules", async () => {
+ const { host, used } = setup();
+ const atTurnStart = await host.browserIntegration(botId, undefined, turn);
+ expect(atTurnStart?.spec.env.AGENT_BROWSER_CDP, "a turn's start never wakes the sandbox").toBeUndefined();
+ expect(fake.requests).toEqual([]);
+ const browser = (await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN }))!;
+ expect(browser.spec.env.AGENT_BROWSER_CDP).toMatch(/^ws:\/\/127\.0\.0\.1:\d+\/devtools\/browser\/[a-f0-9]{64}$/);
+ expect(browser.spec.env.AGENT_BROWSER_RESTORE_SAVE).toBe("never");
+ expect(used, "timed by the computers' idle path as the Cloud's sandbox, never as the bot's computer").toEqual([["browser", 3 * 60_000]]);
+ // The live view and the next call see the same browser; nothing moves while it runs.
+ host.usedBrowserSessions.clear();
+ expect((await host.currentBrowserSpec(botId, undefined))?.spec.env.AGENT_BROWSER_CDP).toBe(browser.spec.env.AGENT_BROWSER_CDP);
+ expect((await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN }))?.spec.env.AGENT_BROWSER_CDP).toBe(browser.spec.env.AGENT_BROWSER_CDP);
+ expect(fake.launches()).toBe(1);
+ // Reddit stays refused in the sandbox, as in the home.
+ expect(await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", { name: OPEN, arguments: { url: "https://www.reddit.com/" } }))
+ .toEqual({ isError: true, content: [{ type: "text", text: REDDIT_REFUSAL }] });
+ // An upload from the Cloud's disk says so in one line instead of failing on a missing file.
+ await expect(host.uploadPaths([{ file: "/tmp/a.txt", name: "a.txt" }], browser.session, browser.spec)).rejects.toThrow(new BrowserUploadRefusal(CLOUD_BROWSER_NO_UPLOAD));
+ expect(host.cloudBrowserBusy("browser")).toBe(true);
+ expect(host.cloudBrowserBusy(botId)).toBe(false);
+ expect(host.cloudBrowserReport()).toMatchObject({ sessions: { sandbox: 1, home: 0 } });
+ });
+
+ it("a closing call never opens the sandbox", async () => {
+ const { host } = setup();
+ await host.browserIntegration(botId, undefined, undefined, "team", { opening: "agent_browser_close" });
+ expect(fake.requests).toEqual([]);
+ });
+
+ it("a temporary or shared profile opens in the home: the sandbox keeps one profile per bot", async () => {
+ const { host } = setup();
+ const browser = await host.browserIntegration(botId, "guest", undefined, "team", { opening: OPEN });
+ expect(browser?.spec.env.AGENT_BROWSER_CDP).toBeUndefined();
+ expect(fake.requests).toEqual([]);
+ expect(host.cloudBrowserReport()).toMatchObject({ fallbacks: { "not-eligible": 1 } });
+ });
+
+ it("OMB_CLOUD_BROWSER=home: the session's spec is byte-identical to today's and no provider call is made", async () => {
+ vi.stubEnv("OMB_CLOUD_BROWSER", "home");
+ const { host } = setup();
+ const before = await host.browserIntegration(botId, undefined, turn);
+ const opened = await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN });
+ const today = setup({ cloudBrowser: false }).host;
+ const withoutFeature = await today.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN });
+ expect(JSON.stringify(opened?.spec)).toBe(JSON.stringify(before?.spec));
+ expect(JSON.stringify(opened?.spec)).toBe(JSON.stringify(withoutFeature?.spec));
+ expect(fake.requests).toEqual([]);
+ expect(fake.upgrades).toEqual([]);
+ });
+
+ it("on a desktop install everything about it is ignored", async () => {
+ const { host } = setup({ desktop: true });
+ const opened = await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN });
+ const today = setup({ desktop: true, cloudBrowser: false }).host;
+ const withoutFeature = await today.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN });
+ expect(JSON.stringify(opened?.spec)).toBe(JSON.stringify(withoutFeature?.spec));
+ expect(opened?.spec.env.AGENT_BROWSER_CDP).toBeUndefined();
+ expect(host.cloudBrowserReport()).toBeNull();
+ expect(host.cloudBrowserBusy(botId)).toBe(false);
+ expect(fake.requests).toEqual([]);
+ });
+
+ it("when the sandbox cannot be reached, the session opens in the home exactly as today", async () => {
+ fake.chromeStarts = false;
+ const { host } = setup();
+ const opened = await host.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN });
+ const today = setup({ cloudBrowser: false }).host;
+ const withoutFeature = await today.browserIntegration(botId, undefined, undefined, "team", { opening: OPEN });
+ expect(JSON.stringify(opened?.spec)).toBe(JSON.stringify(withoutFeature?.spec));
+ expect(host.cloudBrowserReport()).toMatchObject({ sessions: { sandbox: 0, home: 1 }, fallbacks: { "start-failed": 1 } });
+ });
+});
diff --git a/server/host/browser.ts b/server/host/browser.ts
index 361bfd9381..66490767a9 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -58,6 +58,10 @@ import { LentChromeDoors, lentChromeGuidance, type ChromeLender } from "../brows
import type { ChromeRoute } from "../device-links.ts";
import type { EngineBrowsers } from "../engine-memory.ts";
import { createBrowserReclaim, reclaimable } from "./browser-reclaim.ts";
+import { createCloudBrowser, type HomeReason } from "../cloud-browser/index.ts";
+import { providerOps } from "../cloud-browser/remote.ts";
+import { boatConfigured } from "../boat.ts";
+import { BrowserUploadRefusal } from "../browser-upload.ts";
import { BROWSER_TASKS, processBudget } from "../process-room.ts";
import { idleAfter } from "../drivers/session-idle.ts";
import { augmentedPath } from "../env-path.ts";
@@ -101,6 +105,9 @@ export interface BrowserHostDeps {
browserBox?(seccompFd: number, ro: readonly string[]): LauncherBox | null;
/** How many agent-browser browsers run at once; sized by this server's limits without it. */
browsersAtOnce?(): number;
+ /** A personal Cloud only: a bot's browser opens in the Cloud's browser sandbox (server/cloud-browser), the home's
+ * otherwise. `used`: the cloud computers' idle path, which times the sandbox too. */
+ cloudBrowser?: { used(owner: string, windowMs: number): void };
}
/** The lent computer's connection for a browser's pages, under the rule for everything it lends: only while the last
@@ -117,6 +124,8 @@ function lentDevice(device: NonNullable<EgressSetup["device"]>, holder: (session
type Spec = { command: string; args?: readonly string[]; env: Record<string, string> };
type LendRefusal = CloudLendingRefusal | "memory-changed" | "memory-changed-here";
const BOT_SESSION = /^bot-[A-Za-z0-9_.-]+$/;
+/** What the upload tool answers while the bot's browser runs on its cloud computer. */
+export const CLOUD_BROWSER_NO_UPLOAD = "File uploads don't work in this browser yet: it runs in this Cloud's browser sandbox, which can't take files from the Cloud yet. Tell the person in one sentence and ask them to upload the file themselves.";
/** However short of room the server is, a bot's browser stays this long after its last use: a turn's next browser call is
* seldom further apart. */
const BROWSER_IDLE_FLOOR_MS = 60_000;
@@ -227,7 +236,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
// A tool call that would open Reddit from MausBot Cloud is refused before it reaches the browser. My Chrome is the
// person's own, outside the egress gate too; on My Cloud a call that can't reach it now says why instead.
const browserRuntime = new RuntimeRouter(agentBrowserRuntime, chromeEngine, {
- refusal: (_session, spec, params) => (attachesToChrome(spec.env) ? null : browserEgress.callRefusal(params)),
+ refusal: (session, spec, params) => (attachesToChrome(spec.env) && !cloudBrowser?.attached(session) ? null : browserEgress.callRefusal(params)),
// The opt-in engine's browsers wait for the server's room here; agent-browser's wait in browserRoom above. The
// person's own Chrome runs outside this server, and a close frees room.
room: (session, spec, params) => (!processRoom || attachesToChrome(spec.env) || (params as { name?: unknown } | null)?.name === "agent_browser_close"
@@ -265,6 +274,32 @@ export function createBrowserHost(deps: BrowserHostDeps) {
});
const browserLive = new LiveRouter(agentBrowserLive, chromeEngine);
const usedBrowserSessions = new Map<string, Spec>();
+ // A personal Cloud's bots browse in the Cloud's browser sandbox, never a bot's own cloud computer; a desktop install never builds this.
+ const computerOps = providerOps(() => cfg);
+ const cloudBrowser = deps.cloudBrowser && CLOUD_HOME && !DESKTOP_MANAGED ? createCloudBrowser({
+ dataDir: DATA_DIR,
+ ops: () => (boatConfigured(cfg) ? computerOps : null),
+ used: (owner, windowMs) => deps.cloudBrowser?.used(owner, windowMs),
+ closeEngine: (session) => { const spec = usedBrowserSessions.get(session); return spec ? closeBrowser(session, spec) : Promise.resolve(true); },
+ held: (session) => !turnResources.free(`browser:${session}`),
+ }) : null;
+ /** Where a session's browser opens, decided once when it opens: in the Cloud's browser sandbox (its address returned),
+ * or in the home (undefined). A browser already running stays where it runs. */
+ async function cloudBrowserUrl(botId: string, profile: string | undefined, session: string, audience: Audience, opening: string | null | undefined): Promise<string | undefined> {
+ if (!cloudBrowser) return undefined;
+ const live = cloudBrowser.active(session);
+ if (live) return live;
+ if (!opening || opening === "agent_browser_close" || browserRunning(session, usedBrowserSessions.get(session))) return undefined;
+ const opened = await cloudBrowser.open({ session, botId, refusal: cloudBrowserRefusal(profile, session, audience) });
+ return "cdpUrl" in opened ? opened.cdpUrl : undefined;
+ }
+ /** The sessions this slice keeps in the home: a shared, temporary or someone else's profile (the sandbox keeps one
+ * profile per bot), and a session whose sites go out through the person's lent computer. */
+ function cloudBrowserRefusal(profile: string | undefined, session: string, audience: Audience): HomeReason | null {
+ if (profile || audienceBrowserSuffix(audience) !== "") return "not-eligible";
+ const lent = device?.(session);
+ return lent && "open" in lent ? "lent-connection" : null;
+ }
const audiences = new AudienceBrowsers(join(DATA_DIR, "browser", "audiences.json"));
const browserAudience = (threadId: string | undefined): Audience => (threadId && deps.audienceOf ? deps.audienceOf(threadId) : "team");
const device = deps.device && lentDevice(deps.device, (session) => turnResources.holder(`browser:${session}`), mayLend);
@@ -309,6 +344,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
clearInterval(gateTimer);
ceilingLoop?.stop();
doors?.close();
+ cloudBrowser?.closeAll();
doorUrls.clear();
leftovers.clear();
return agentBrowserSweep.closeAll();
@@ -444,14 +480,15 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return Boolean(profileId) && (myChromeAvailable() || lentChrome !== undefined)
&& cfg.browserProfiles?.some((profile) => profile.id === profileId && profile.browser === "chrome") === true;
}
- function browserSessionSpec(binaryPath: string, session: string, profile: string | undefined, egressPort?: number, cdpUrl?: string) {
+ /** `cloudUrl`: the session's browser runs on the bot's cloud computer, reached through this address. */
+ function browserSessionSpec(binaryPath: string, session: string, profile: string | undefined, egressPort?: number, cdpUrl?: string, cloudUrl?: string) {
const attachCdpUrl = cdpUrl ?? browserEngineAttachCdpUrl(cfg);
const locale = browserLanguage(process.env, deps.language?.());
return agentBrowserIntegration({
binaryPath, session, encryptionKey: browserEngineEncryptionKey(), persistent: profile !== "guest", egressPort,
env: { ...process.env, PATH: augmentedPath(), ...(locale ? { OMB_BROWSER_LANG: locale } : {}) },
launcher: chromeLauncher.env(),
- ...(usesMyChrome(profile) ? { attach: attachCdpUrl ? { cdpUrl: attachCdpUrl } : {} } : {}),
+ ...(cloudUrl ? { attach: { cdpUrl: cloudUrl } } : usesMyChrome(profile) ? { attach: attachCdpUrl ? { cdpUrl: attachCdpUrl } : {} } : {}),
});
}
function browserProfileIdOf(profile: string | undefined): string | undefined {
@@ -506,7 +543,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {
},
};
}
- async function browserIntegration(botId: string, profile: string | undefined, turn?: { threadId: string; generation: string }, audience = browserAudience(turn?.threadId)) {
+ /** `opening`: the name of a browser tool call about to run, which may open the session's browser. */
+ async function browserIntegration(botId: string, profile: string | undefined, turn?: { threadId: string; generation: string }, audience = browserAudience(turn?.threadId), options: { opening?: string | null } = {}) {
const profileTarget = profile && profile !== "guest" ? browserProfilePartitionTarget(cfg, profile) : null;
const partitionId = profile === "guest" ? "guest" : (profileTarget?.partitionId ?? "");
const browserProfileId = profileTarget?.profileId ?? profile;
@@ -521,8 +559,10 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return null;
}
const session = currentBrowserSession(botId, profile, audience);
- const cdpUrl = lentChromeSession(browserProfileId) ? await lentChromeDoor(session) : undefined;
- const spec = browserSessionSpec(status.binaryPath, session, browserProfileId, usesMyChrome(browserProfileId) ? undefined : await browserEgress.open(session), cdpUrl);
+ const lent = lentChromeSession(browserProfileId);
+ const cdpUrl = lent ? await lentChromeDoor(session) : undefined;
+ const cloudUrl = lent ? undefined : await cloudBrowserUrl(botId, profile, session, audience, options.opening);
+ const spec = browserSessionSpec(status.binaryPath, session, browserProfileId, usesMyChrome(browserProfileId) || cloudUrl ? undefined : await browserEgress.open(session), cdpUrl, cloudUrl);
usedBrowserSessions.set(session, spec);
await prepareBrowserSessionState(status.binaryPath, session, { env: spec.env, persistent: profile !== "guest" && !attachesToChrome(spec.env), isCurrent: () => {
const current = store.bot(botId);
@@ -543,7 +583,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {
if (used) return { session, spec: used };
const profileId = browserProfileIdOf(profile);
const cdpUrl = lentChromeSession(profileId) ? await lentChromeDoor(session) : undefined;
- return { session, spec: browserSessionSpec(engine.binaryPath, session, profileId, usesMyChrome(profileId) ? undefined : await browserEgress.open(session), cdpUrl) };
+ const cloudUrl = cloudBrowser?.active(session) ?? undefined;
+ return { session, spec: browserSessionSpec(engine.binaryPath, session, profileId, usesMyChrome(profileId) || cloudUrl ? undefined : await browserEgress.open(session), cdpUrl, cloudUrl) };
}
/** fill_login's reads and typing, on whichever engine runs the session. */
function loginInput(session: string, spec: Spec, env: NodeJS.ProcessEnv): Pick<FillLoginDeps, "engine" | "insertText" | "press" | "click"> {
@@ -718,6 +759,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
}
/** Chrome receives private copies; a boxed agent-browser reads them from its own profile's folder. */
function uploadPaths(files: ReadonlyArray<{ file: string; name: string | null }>, session: string, spec: Spec): Promise<string[]> {
+ if (cloudBrowser?.attached(session)) return Promise.reject(new BrowserUploadRefusal(CLOUD_BROWSER_NO_UPLOAD));
const chrome = chromeTarget(session, spec);
const folder = boxed && !chrome ? join(browserProfileDirectory(session), "omb-uploads") : join(DATA_DIR, "browser-uploads");
return namedUploadPaths(files, folder, Date.now(), { everyFile: boxed || Boolean(chrome) });
@@ -768,5 +810,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {
browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, signedInSitesRefusal, closeBrowser, browserEngineSwitched,
eraseDeletedBrowser, engineSummary, engineBrowsers, browserAudience, browserSessionsOf, signedInSitesTarget, uploadPaths,
eraseAudienceBrowsers, browserOwners, closeCapBrowsers,
+ cloudBrowserBusy: (owner: string) => cloudBrowser?.busy(owner) ?? false,
+ cloudBrowserReport: () => cloudBrowser?.report() ?? null,
};
}
diff --git a/server/host/cloud-computer-power.ts b/server/host/cloud-computer-power.ts
index bc61d83e38..17221b8541 100644
--- a/server/host/cloud-computer-power.ts
+++ b/server/host/cloud-computer-power.ts
@@ -116,8 +116,9 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {
deps.log(`cloud computer ${owner}: asleep after ${Math.round(CLOUD_COMPUTER_IDLE_MS / 1_000)}s idle`);
}
- /** Starts, or restarts, this owner's idle window. */
- function used(owner: string): void {
+ /** Starts, or restarts, this owner's idle window; `windowMs` asks for a shorter or longer one (the browser's), which
+ * never cuts a longer window another use asked for. */
+ function used(owner: string, windowMs?: number): void {
if (closed || !boat.boatConfigured(cfg)) return;
let timer = timers.get(owner);
if (!timer) {
@@ -127,7 +128,7 @@ export function createCloudComputerPower(deps: CloudComputerPowerDeps) {
});
timers.set(owner, timer);
}
- timer.touch();
+ timer.touch(windowMs);
}
/** Before the wake, so a start that fails or outlives its turn still leaves the computer timed. */
diff --git a/server/index.ts b/server/index.ts
index e1c11d9c82..dc16decefc 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -2352,8 +2352,8 @@ function cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): Dir
const {
browserRuntime, browserLive, usedBrowserSessions, browserSweep, temporaryBrowserSessions,
currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, usesMyChrome, lentChromeSummary, browserSessionSpec, browserIntegration,
- browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners, closeCapBrowsers,
-} = createBrowserHost({ cfg, language: appLanguage, store: () => store, turnResources, activeInternalGenerationByThread, mintInternalCapability, DESKTOP_MANAGED, CLOUD_HOME, HOSTED_WORKSPACE, PORT, engineMemory, audienceOf: teamHost.browserAudience, ...(CLOUD_TEAM ? { browserBox: (fd: number, ro: readonly string[]) => botBox.browserBox(fd, ro) } : {}), lendRefusal: (turn) => cloudLendingRefusal({ botId: store.botByThread(turn.threadId)?.id ?? "", threadId: turn.threadId, generation: turn.generation }), device: () => deviceLinks.route(CLOUD_HOME_LENDER) ?? sharedComputers.internetAway(CLOUD_HOME_LENDER) ?? { unshared: true as const }, lentChrome: CLOUD_PERSONAL ? { route: () => deviceLinks.chromeRoute(CLOUD_HOME_LENDER), lender: () => sharedComputers.chromeLender(CLOUD_HOME_LENDER) } : undefined });
+ browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners, closeCapBrowsers, cloudBrowserBusy, cloudBrowserReport,
+} = createBrowserHost({ cloudBrowser: CLOUD_PERSONAL ? { used: (owner, windowMs) => cloudComputerPower.used(owner, windowMs) } : undefined, cfg, language: appLanguage, store: () => store, turnResources, activeInternalGenerationByThread, mintInternalCapability, DESKTOP_MANAGED, CLOUD_HOME, HOSTED_WORKSPACE, PORT, engineMemory, audienceOf: teamHost.browserAudience, ...(CLOUD_TEAM ? { browserBox: (fd: number, ro: readonly string[]) => botBox.browserBox(fd, ro) } : {}), lendRefusal: (turn) => cloudLendingRefusal({ botId: store.botByThread(turn.threadId)?.id ?? "", threadId: turn.threadId, generation: turn.generation }), device: () => deviceLinks.route(CLOUD_HOME_LENDER) ?? sharedComputers.internetAway(CLOUD_HOME_LENDER) ?? { unshared: true as const }, lentChrome: CLOUD_PERSONAL ? { route: () => deviceLinks.chromeRoute(CLOUD_HOME_LENDER), lender: () => sharedComputers.chromeLender(CLOUD_HOME_LENDER) } : undefined });
const dataSheets = new DataSheetRegistry({
broadcast: (frame) => broadcast({ ...frame }),
@@ -2783,7 +2783,7 @@ const cloudPlanTier = createCloudPlanTier({ dataDir: DATA_DIR, cloudHome: Boolea
const teamWelcome = createTeamWelcomeStore(DATA_DIR); const { cloudHealth, cloudSigned } = createCloudSignedHost({ cloudHome: CLOUD_HOME, sessions, power: () => cloudPower, box: () => botBox.report(), teamAdmin: teamAdminHost(), policyChanged: nudgeCloudTeamPolicy, invited: (email, by) => teamWelcome.invited(personKey({ id: "", email }), by), memberBrowserOff: () => managedPolicy.remoteAccessRefusal() !== undefined, plan: (cancelled) => routineHolds?.plan(cancelled), planTier: (tier) => cloudPlanTier.set(tier), memberLeft: (email) => leaveTeam ? leaveTeam(email).then((result) => { botApi.manager.revokeMintedBy(personKey({ id: "", email })); teamOwners.left(email); teamMessages.inbox.forget(personKey({ id: "", email })); forgetSetupPresser(store, personKey({ id: "", email })); devsReports.forget(personKey({ id: "", email })); teamSlack?.memberLeft(personKey({ id: "", email })); return result; }) : Promise.reject(new Error("not a team")), health: { store, bus, perf: perf.health, storage: () => withCacheCounters(perf.storage(), cacheSweeper), dataDir: DATA_DIR, eventsDir: EVENTS_DIR, version: serverVersion(), image: process.env.OMB_CLOUD_IMAGE, routines: (cap) => routines?.health(cap) ?? [], schedule: () => routines?.scheduleReport() ?? null,
engines: () => registry.instances().map((instance) => ({ instanceId: instance.instanceId, driverKind: instance.driverKind, snapshot: registry.knownSnapshot(instance.instanceId) })),
connectors: () => emailHost.health(composio.configured(cfg) ? composio.connectedServices(cfg) : null),
- browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.roomReport() } : {}) } });
+ browser: () => ({ available: browserReady(undefined), installing: Boolean(browserEngineInstall), interrupted: browserRuntime.interruptedCount(), cloudComputer: cloudBrowserReport() }), firstHour: () => firstHourHooks.health(), ...(engineMemory.enabled ? { room: () => engineMemory.roomReport() } : {}) } });
const teamComputers = new TeamComputers(join(DATA_DIR, "team-computers.json"), ENVIRONMENT_ID);
let followupsReady = false;
const sendSequencer = new SendSequencer();
@@ -5608,7 +5608,7 @@ 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() ?? [], wakeTimedOut: (owner, boxId, ctx) => boatRecovery.wakeTimedOut(owner, boxId, ctx),
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),
+ busy: owner => computerProviderConfigTransitions.has("box") || boatLifecycleBusyBots.has(owner) || cloudBrowserBusy(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, usedByOther: (owner, boxId, asking) => usedByAnotherBot(owner, boxId, { holder: resource => turnResources.holder(resource), botOfThread: threadId => store.botByThread(threadId)?.id ?? null }, asking), created: owner => cloudComputerPower.used(owner), turnWaiting: boxId => cloudComputerPower.waiting(boxId), tell: (owner, key, vars) => { 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], { ...vars, 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) });
@@ -12900,7 +12900,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (!bot || bot.browser === false || bot.computer === "off" || !builtInBrowserEnabled(cfg)) {
return json(res, 403, { error: "browser tools are not enabled for this bot" });
}
- const browser = await browserIntegration(bot.id, bot.browserProfile, undefined, teamHost.browserAudience(internalCapability.threadId));
+ const browser = await browserIntegration(bot.id, bot.browserProfile, undefined, teamHost.browserAudience(internalCapability.threadId), { opening: body?.method === "tools/call" ? String(body?.params?.name ?? "") || null : null });
if (!browser || browser.session !== internalCapability.browserSession) {
return json(res, 409, { error: "this browser profile changed; start a new turn" });
}