Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud browser: only a running call or a person's take-over keeps a sandbox session open; a session ends when its sandbox is gone; caps from the relay
milind-soniab795d450ffd
diff --git a/server/browser/engines.ts b/server/browser/engines.tsindex 7cc773298b..00edc92e2b 100644--- a/server/browser/engines.ts+++ b/server/browser/engines.ts@@ -258,6 +258,8 @@ export interface RuntimeRouterOptions {afterCall?(session: string, spec: BrowserSpawnSpec, result: unknown): unknown;/** Where a page action that failed is counted; the server's own log when unset. */inputLog?: BrowserInputLog;+ /** A tool call that failed or threw, awaited before its answer: the session's host may check where its browser runs. */+ failedCall?(session: string, spec: BrowserSpawnSpec): Promise<void>;}const resultText = (result: unknown): string => {@@ -278,8 +280,10 @@ export class RuntimeRouter {readonly #annotate: RuntimeRouterOptions["annotate"];readonly #afterCall: RuntimeRouterOptions["afterCall"];readonly #log: BrowserInputLog;+ readonly #failedCall: RuntimeRouterOptions["failedCall"];constructor(old: BrowserRuntime, chrome: ChromeEngine, options: RuntimeRouterOptions = {}) {+ this.#failedCall = options.failedCall;this.#log = options.inputLog ?? browserInputLog;this.#old = old;this.#chrome = chrome;@@ -317,10 +321,14 @@ export class RuntimeRouter {if (error instanceof ClaimRefused) return refuse(error.message);const reason = botReason(error instanceof Error ? error.message : "");failed(reason === "engine_error" ? "threw" : reason);+ if (method === "tools/call") await this.#failedCall?.(session, spec).catch(() => undefined);throw error;}if (method !== "tools/call") return result;- if ((result as { isError?: unknown } | null)?.isError === true) failed(botReason(resultText(result)));+ if ((result as { isError?: unknown } | null)?.isError === true) {+ failed(botReason(resultText(result)));+ await this.#failedCall?.(session, spec).catch(() => undefined);+ }const annotated = this.#annotate ? this.#annotate(spec, result) : result;return this.#afterCall ? this.#afterCall(session, spec, annotated) : annotated;}diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.tsindex cc87e13510..4a3fe588c7 100644--- a/server/cloud-browser/cloud-browser.test.ts+++ b/server/cloud-browser/cloud-browser.test.ts@@ -146,18 +146,21 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>expect(cloud.report().resumes).toBe(1);});- it("on an Admin from before the browser sandbox, makes nothing at all and stays in the home for a week", async () => {+ it("on an Admin from before the browser sandbox, makes nothing at all, and asks again the next day or at the home's next start", async () => {fake.exists = false;fake.oldRelay = true;const cloud = browser();expect(await cloud.open(request())).toEqual({ home: "old-relay" });expect(fake.creates()).toBe(0);- clock += 6 * 24 * 60 * 60_000;+ clock += 60 * 60_000;const asked = fake.requests.length;expect(await cloud.open(request())).toEqual({ home: "old-relay" });- expect(fake.requests.length).toBe(asked);- clock += 24 * 60 * 60_000;+ expect(fake.requests.length, "not asked again the same day").toBe(asked);+ // The relay is updated meanwhile: a restarted home finds it at once.fake.oldRelay = false;+ urlOf(await browser().open(request("writer")));+ // And the running one, the next day.+ clock = Date.UTC(2026, 10, 25, 0, 0, 1);urlOf(await cloud.open(request()));});@@ -165,7 +168,7 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>fake.exists = false;// The probe answers, but the create comes back unmarked (an Admin rolled back between the two).const realProbe = providerOps(() => ({}) as AppConfig);- const ops = { ...realProbe, probe: async () => { fake.oldRelay = true; return { kind: "available" as const, boxId: null, chromes: null }; } };+ const ops = { ...realProbe, probe: async () => { fake.oldRelay = true; return { kind: "available" as const, boxId: null, chromes: null, caps: { resumes: null, awakeMinutes: null } }; } };const guarded = browser({ ops: () => ops });expect(await guarded.open(request())).toEqual({ home: "old-relay" });expect(fake.creates()).toBe(1);@@ -472,14 +475,66 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>urlOf(await cloud.open(request()));});- it("treats the relay's busy answer as the account's limit for the day", async () => {+ it("treats the relay's busy answer (a minute or hour window) as a back-off of minutes, not the rest of 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(await cloud.open(request())).toEqual({ home: "backoff" });+ expect(await cloud.open(request())).toEqual({ home: "backoff" });expect(fake.resumes()).toBe(1);+ clock += CLOUD_BROWSER_BACKOFF_MS;+ fake.startStatus = 200;+ fake.startBody = { ok: true };+ urlOf(await cloud.open(request()));+ });++ it("takes this Cloud's caps from the relay's answer, not its own table", async () => {+ fake.state = "archived";+ fake.caps = { resumesPerDay: 1, awakeMinutesPerDay: 720 };+ const cloud = browser();+ urlOf(await cloud.open(request()));+ expect(cloud.report()).toMatchObject({ budget: 1, awakeMinutesCap: 720 });+ clock += CLOUD_BROWSER_IDLE_MS;+ await cloud.closeIdle();+ fake.state = "archived";+ expect(await cloud.open(request())).toEqual({ home: "budget" });+ });++ it("ends a session whose sandbox stopped under it (a cap, the maximum age, an outage), so the next call opens again instead of failing", async () => {+ const cloud = browser();+ urlOf(await cloud.open(request()));+ expect(await cloud.failed("bot-scout"), "still there: the call's own failure").toBe(false);+ expect(cloud.active("bot-scout")).not.toBeNull();+ // The Admin stopped it (its minutes cap) while a turn held the browser.+ fake.state = "archived";+ expect(await cloud.failed("bot-scout")).toBe(true);+ expect(cloud.active("bot-scout")).toBeNull();+ expect(engineClosed).toEqual(["bot-scout"]);+ urlOf(await cloud.open(request()));+ expect(fake.resumes()).toBe(1);+ });++ it("stamps the provider deadline's push only when it moved, and tries a failed one again at the next sweep", async () => {+ const cloud = browser();+ urlOf(await cloud.open(request()));+ const pushes = () => fake.requests.filter((one) => one.method === "PATCH" && one.body?.ttlSeconds !== undefined).length;+ fake.patchStatus = 500;+ clock += 60_000;+ cloud.touch("bot-scout");+ await cloud.closeIdle();+ expect(pushes()).toBe(1);+ clock += 30_000;+ await cloud.closeIdle();+ expect(pushes(), "tried again soon").toBe(2);+ fake.patchStatus = 200;+ clock += 30_000;+ await cloud.closeIdle();+ expect(pushes()).toBe(3);+ clock += 30_000;+ cloud.touch("bot-scout");+ await cloud.closeIdle();+ expect(pushes(), "moved: not again for 10 minutes").toBe(3);});it("a session the caller rules out (a shared profile, another person's, a person's own key) makes no relay call", async () => {diff --git a/server/cloud-browser/door.ts b/server/cloud-browser/door.tsindex bac7f66de2..a11e76e7c3 100644--- a/server/cloud-browser/door.ts+++ b/server/cloud-browser/door.ts@@ -96,6 +96,8 @@ export class CloudBrowserDoors {}url(session: string): string | null { return this.#doors.get(session)?.url ?? null; }+ /** Where the session's door leads, for a check that it still answers. */+ target(session: string): DoorTarget | null { return this.#doors.get(session)?.target ?? 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; }diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.tsindex a1df61dcd6..457e1a5e54 100644--- a/server/cloud-browser/index.ts+++ b/server/cloud-browser/index.ts@@ -21,6 +21,8 @@ const LEVER_CLEANUP_GAP_MS = 60 * 60_000;export const SANDBOX_IDLE_TTL_SECONDS = 1_200;export const TTL_REFRESH_MS = 10 * 60_000;+const READY_STATES = new Set(["idle", "ready", "running"]);+export const cloudBrowserLever = (env: NodeJS.ProcessEnv = process.env): boolean => env.OMB_CLOUD_BROWSER?.trim() === "home";export interface CloudBrowserDeps {@@ -118,8 +120,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {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"; }+ // The account's start pool is busy for now (the relay's "busy", a minute or hour window): a few minutes, not the day.+ if (failure.status === 429) { rails.holdOff(); return "backoff"; }rails.failed();return "start-failed";}@@ -138,6 +140,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {if (said.kind === "old-relay") throw new OldRelay();if (said.kind === "unavailable") throw new Unavailable(said.reason, said.resetsAt);if (said.chromes !== null) chromesAllowed = said.chromes;+ rails.caps(said.caps.resumes, said.caps.awakeMinutes);}async function wake(ops: ComputerOps): Promise<{ id: string; started: boolean }> {@@ -299,13 +302,30 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {}/** The provider's auto-stop pushed ahead while some browser here was used since the last push. */+ /** Stamped only once the deadline really moved (or the Admin refused on purpose); a failed push is tried again at the+ * next sweep, well before the deadline it was meant to move. */async function refreshTtl(at: number): Promise<void> {const ops = deps.ops();if (!ops || !boxId || at - ttlRefreshedAt < TTL_REFRESH_MS) return;const used = [...lastUse.values()].some((at) => at > ttlRefreshedAt);if (!used) return;- ttlRefreshedAt = at;- await ops.refreshTtl(boxId, SANDBOX_IDLE_TTL_SECONDS).catch(() => undefined);+ const outcome = await ops.refreshTtl(boxId, SANDBOX_IDLE_TTL_SECONDS).catch(() => "failed" as const);+ if (outcome !== "failed") ttlRefreshedAt = at;+ }++ /** A call in a session on the sandbox failed: when the sandbox is no longer ready (stopped by a cap, the Admin's maximum+ * session age, an outage) or the door no longer answers, the session ends so the next call opens again, in the home if+ * the sandbox can't be had. A session never fails call after call on a dead sandbox. */+ async function failed(session: string): Promise<boolean> {+ const ops = deps.ops();+ if (!sessions.has(session) || !ops || !boxId) return false;+ const state = await ops.state(boxId).catch(() => null);+ const target = doors.target(session);+ const alive = state !== null && READY_STATES.has(state) && target !== null && await probeDoor(target, 5_000);+ if (alive) return false;+ log(`browser ${session}: its browser sandbox is ${state && !READY_STATES.has(state) ? `${state}` : "not answering"}; the session ends and the next call opens again`);+ await close(session);+ return true;}async function closeIdle(): Promise<void> {@@ -338,6 +358,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {close,closeIdle,dialed: (session: string): number => doors.dialed(session),+ failed,/** Lines for the session's next browser call (downloads that arrived, or could not). */takeNotes: (session: string): string[] => {const left = leftNotes.get(session) ?? [];diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.tsindex ace91ca01d..d6238308b8 100644--- a/server/cloud-browser/rails.ts+++ b/server/cloud-browser/rails.ts@@ -74,8 +74,8 @@ export interface CloudBrowserRailsOptions {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;+ let budget = options.budget ?? CLOUD_BROWSER_DAILY_RESUMES;+ let 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, oldRelayUntil: 0, unavailableUntil: 0, carried: {}, carryBad: {} };@@ -90,7 +90,8 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {accountUntil: number(saved.accountUntil), hoursUntil: number(saved.hoursUntil),noRouteDay: typeof saved.noRouteDay === "string" ? saved.noRouteDay : null,awakeSince: number(saved.awakeSince), leverSince: number(saved.leverSince),- oldRelayUntil: number(saved.oldRelayUntil), unavailableUntil: number(saved.unavailableUntil),+ // An older relay's hold is not kept across a restart: the home asks again, so a relay deployed meanwhile is found.+ oldRelayUntil: 0, unavailableUntil: number(saved.unavailableUntil),carried: Object.fromEntries(Object.entries(saved.carried && typeof saved.carried === "object" ? saved.carried : {}).filter(([key, at]) => /^bx_[a-z0-9]{8}:[a-f0-9]{16}$/.test(key) && typeof at === "number" && Number.isFinite(at))),carryBad: Object.fromEntries(Object.entries(saved.carryBad && typeof saved.carryBad === "object" ? saved.carryBad : {})@@ -149,6 +150,11 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {current.awakeSince = 0;save();},+ /** This Cloud's caps as the Admin said them for its plan: they replace the defaults here, which are only a backstop. */+ caps(resumes: number | null, awakeMinutes: number | null): void {+ if (resumes !== null && Number.isInteger(resumes) && resumes >= 0) budget = resumes;+ if (awakeMinutes !== null && Number.isFinite(awakeMinutes) && awakeMinutes >= 0) awakeCapMs = awakeMinutes * 60_000;+ },/** 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. */@@ -215,9 +221,9 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {today().carried[key] = at;save();},- /** An Admin from before the browser sandbox: asked again in a week. */+ /** An Admin from before the browser sandbox: asked again the next UTC day, or at the home's next start. */oldRelay(): void {- today().oldRelayUntil = now() + 7 * 24 * 60 * 60_000;+ today().oldRelayUntil = nextUtcMidnight(now());save();},/** The relay's no, until its `resetsAt` (the fleet's starts, this Cloud's, or switched off), else for the back-off. */diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.tsindex 6352bd230f..b8b166ea2b 100644--- a/server/cloud-browser/remote.ts+++ b/server/cloud-browser/remote.ts@@ -29,7 +29,7 @@ export const profileKey = (botId: string): string => createHash("sha256").update/** What the relay says before anything is started: whether a browser sandbox may start now, and until when it may not. */export type Availability =| { kind: "old-relay" }- | { kind: "available"; boxId: string | null; chromes: number | null }+ | { kind: "available"; boxId: string | null; chromes: number | null; caps: { resumes: number | null; awakeMinutes: number | null } }| { kind: "unavailable"; reason: string; resetsAt: string | null };/** What the browser needs from the relay; tests pass their own. */@@ -58,8 +58,9 @@ export interface ComputerOps {quit(boxId: string, key: string | null): Promise<void>;/** The door's port on a protected relay URL (one that needs its token); null where it is refused or unprotected. */host(boxId: string, port: number): Promise<string | null>;- /** Moves the provider's own auto-stop to now + `seconds`, so it stops the sandbox only after that long unused. */- refreshTtl(boxId: string, seconds: number): Promise<void>;+ /** Moves the provider's own auto-stop to now + `seconds`, so it stops the sandbox only after that long unused: "moved",+ * "refused" (the Admin's maximum session age: the deadline is left to run out on purpose) or "failed" (to try again soon). */+ refreshTtl(boxId: string, seconds: number): Promise<"moved" | "refused" | "failed">;/** Deletes it, journaled like every deletion (boat-delete-journal.ts), so a failed delete is retried and never leaks. */remove(boxId: string): Promise<boolean>;}@@ -136,7 +137,9 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {if (answer.status === 404) return { kind: "old-relay" };if (!answer.ok || typeof answer.body?.available !== "boolean") throw boatRefusal(answer.status, "asking about the browser sandbox", answer.body, true);const chromes = Number.isInteger(answer.body.chromes) && answer.body.chromes >= 1 && answer.body.chromes <= 4 ? answer.body.chromes as number : null;- if (answer.body.available) return { kind: "available", boxId: typeof answer.body.boxId === "string" ? answer.body.boxId : null, chromes };+ const count = (value: unknown) => (typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null);+ const caps = { resumes: count(answer.body.caps?.resumesPerDay), awakeMinutes: count(answer.body.caps?.awakeMinutesPerDay) };+ if (answer.body.available) return { kind: "available", boxId: typeof answer.body.boxId === "string" ? answer.body.boxId : null, chromes, caps };return { kind: "unavailable", reason: typeof answer.body.reason === "string" ? answer.body.reason : "unknown", resetsAt: typeof answer.body.resetsAt === "string" ? answer.body.resetsAt : null };},async find() {@@ -177,8 +180,9 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {return protectedUrl(answer.body?.url);},async refreshTtl(boxId, seconds) {- // A refusal (the Admin's maximum session age, say) leaves the deadline as it is: that is the point of it.- await json(cfg(), `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ ttlSeconds: ttlSecondsOf(seconds) }) });+ const answer = await json(cfg(), `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ ttlSeconds: ttlSecondsOf(seconds) }) }).catch(() => null);+ if (answer?.ok) return "moved";+ return answer?.status === 409 && (answer.body?.code ?? answer.body?.error?.code) === "max_age" ? "refused" : "failed";},async remove(boxId) {const name = await boatNameFor(BROWSER_SANDBOX_OWNER);diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.tsindex 09d21450b7..5a1e4c7f35 100644--- a/server/cloud-browser/testing/fake-computer.ts+++ b/server/cloud-browser/testing/fake-computer.ts@@ -29,6 +29,10 @@ export interface FakeComputer {hostRoute: boolean;unprotected: boolean;chromeStarts: boolean;+ /** The caps the probe says this Cloud's plan has. */+ caps: { resumesPerDay: number; awakeMinutesPerDay: number } | null;+ /** Status the PATCH of a sandbox answers with. */+ patchStatus: number;/** How many Chromes the probe says this Cloud's sandbox takes (by its plan's size). */chromes: number;/** A resume during `archiving` finds the machine already gone. */@@ -69,7 +73,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {let retired = true;const fake = {base: "", state: "ready", exists: true, startStatus: 200, startBody: { ok: true }, oldRelay: false, available: true, unavailableReason: "fleet_starts",- unavailableUntil: null, hostRoute: true, unprotected: false, chromeStarts: true, policy: true, takeBackFails: false, chromes: 2, requests: [], upgrades: [], frames: [], boxId: "bx_23456789",+ unavailableUntil: null, hostRoute: true, unprotected: false, chromeStarts: true, policy: true, takeBackFails: false, chromes: 2, caps: null, patchStatus: 200, requests: [], upgrades: [], frames: [], boxId: "bx_23456789",files: new Map(), cookies: new Map(), commands: [], failing: new Set(),} as unknown as FakeComputer;const watchers = new Map<string, Set<import("ws").WebSocket>>();@@ -102,7 +106,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {const rest = url.pathname.replace(/^\/api\/v1/, "");if (rest === "/browser-sandbox") {if (fake.oldRelay) return send(404, { ok: false, code: "not_found" });- return send(200, { ok: true, type: "browser.sandbox", available: fake.available, boxId: fake.exists ? boxId : null, sandboxType: fake.chromes > 2 ? "default" : "small", chromes: fake.chromes,+ return send(200, { ok: true, type: "browser.sandbox", available: fake.available, boxId: fake.exists ? boxId : null, sandboxType: fake.chromes > 2 ? "default" : "small", chromes: fake.chromes, ...(fake.caps ? { caps: fake.caps } : {}),...(fake.available ? {} : { reason: fake.unavailableReason, ...(fake.unavailableUntil ? { resetsAt: fake.unavailableUntil } : {}) }) });}if (rest === "/sandboxes" && req.method === "GET") return send(200, { ok: true, sandboxes: fake.exists ? [row] : [], pageInfo: { nextCursor: null } });@@ -114,7 +118,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {fake.state = "ready";return send(202, { ok: true, sandbox: { id: fake.boxId, state: "provisioning", ...(!fake.oldRelay && 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 === "PATCH") return body.ttlSeconds !== undefined && fake.patchStatus >= 300 ? send(fake.patchStatus, { ok: false }) : 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;diff --git a/server/host/browser-cloud-sandbox.test.ts b/server/host/browser-cloud-sandbox.test.tsindex 8042b77b58..9a1f28d850 100644--- a/server/host/browser-cloud-sandbox.test.ts+++ b/server/host/browser-cloud-sandbox.test.ts@@ -58,14 +58,14 @@ afterEach(async () => {await fake.close();});-function setup({ desktop = false, cloudBrowser = true, ownKey = false }: { desktop?: boolean; cloudBrowser?: boolean; ownKey?: boolean } = {}) {+function setup({ desktop = false, cloudBrowser = true, ownKey = false, turnHolds = false }: { desktop?: boolean; cloudBrowser?: boolean; ownKey?: boolean; turnHolds?: boolean } = {}) {const cfg = { features: { browser: true }, ...(ownKey ? { box: { token: "boat_persons-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: () => () => {} },+ turnResources: { free: () => !turnHolds, holder: () => undefined, onClaim: () => () => {} },activeInternalGenerationByThread: new Map([[turn.threadId, turn.generation]]),mintInternalCapability: () => "capability-token",DESKTOP_MANAGED: desktop,@@ -185,6 +185,7 @@ lines.on("line", (line) => {let result;if (m.method === "initialize") result = { protocolVersion: "2024-11-05", capabilities: { tools: {} } };else if (m.method === "tools/list") result = { tools: [{ name: "agent_browser_get_url", inputSchema: { type: "object" } }, { name: "agent_browser_open", inputSchema: { type: "object" } }] };+ else if (m.params.name === "agent_browser_fail") result = { isError: true, content: [{ type: "text", text: "Target closed" }] };else result = { content: [{ type: "text", text: where + ":" + m.params.name }] };process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: m.id, result }) + "\\n");});@@ -226,3 +227,44 @@ describe.skipIf(process.platform === "win32")("a turn's first browser call afterexpect(JSON.stringify(again)).toContain("home:agent_browser_get_url");});});++describe.skipIf(process.platform === "win32")("what keeps a session on the browser sandbox open, on the host's real rules", () => {+ let engineDir: string;+ beforeEach(() => {+ vi.mocked(BrowserRuntime.prototype.agentRpc).mockRestore();+ engineDir = mkdtempSync(join(tmpdir(), "fake-engine-"));+ const binary = join(engineDir, "agent-browser");+ writeFileSync(binary, FAKE_ENGINE);+ chmodSync(binary, 0o755);+ vi.mocked(browserEngineStatus).mockReturnValue({ kind: "ready", binaryPath: binary, version: "0.37.0", managed: false });+ });+ afterEach(() => { vi.useRealTimers(); rmSync(engineDir, { recursive: true, force: true }); });++ it("a turn that made one call and goes on for hours does not keep the sandbox awake: 3 minutes after its last call the session closes", async () => {+ vi.useFakeTimers({ toFake: ["Date"] });+ // The turn holds the browser for its whole life once it made a call, as the real route claims it.+ const { host } = setup({ turnHolds: true });+ const browser = (await host.browserIntegration(botId, undefined, undefined, "team", { opening: "agent_browser_get_url" }))!;+ await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", { name: "agent_browser_get_url", arguments: {} });+ expect(host.cloudBrowserBusy("browser")).toBe(true);+ vi.setSystemTime(Date.now() + 2 * 60_000);+ await host.cloudBrowserSweep();+ expect(host.cloudBrowserBusy("browser"), "2 minutes after the call").toBe(true);+ vi.setSystemTime(Date.now() + 60_000 + 1);+ await host.cloudBrowserSweep();+ expect(host.cloudBrowserBusy("browser"), "3 minutes after the call, the turn's hold notwithstanding").toBe(false);+ });++ it("a failed call on a sandbox that stopped under the session ends it, so the next call opens again", async () => {+ const { host } = setup();+ const browser = (await host.browserIntegration(botId, undefined, undefined, "team", { opening: "agent_browser_get_url" }))!;+ await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", { name: "agent_browser_get_url", arguments: {} });+ fake.state = "archived";+ const failed = await host.browserRuntime.agentRpc(browser.session, browser.spec, "tools/call", { name: "agent_browser_fail", arguments: {} });+ expect(failed).toHaveProperty("isError", true);+ expect(host.cloudBrowserBusy("browser")).toBe(false);+ const next = (await host.browserIntegration(botId, undefined, undefined, "team", { opening: "agent_browser_get_url" }))!;+ expect(JSON.stringify(await host.browserRuntime.agentRpc(next.session, next.spec, "tools/call", { name: "agent_browser_get_url", arguments: {} }))).toContain("sandbox:");+ expect(fake.resumes()).toBe(1);+ });+});diff --git a/server/host/browser.ts b/server/host/browser.tsindex 938c3a77f2..201d9d7fd1 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -127,6 +127,12 @@ function lentDevice(device: NonNullable<EgressSetup["device"]>, holder: (sessiontype 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 keeps a session on the browser sandbox open past its 3 quiet minutes: a call running in it, or a person driving it+ * (a take-over). Not a turn's claim on the browser, which lasts the whole turn after one call, and not an open view, which+ * streams even while hidden: each bot call already counts as use when it is made. */+export function sandboxInUse(runtime: Pick<BrowserRuntime, "working">, session: string): boolean {+ return runtime.working(session);+}/** What the upload tool answers while the bot's browser runs on its cloud computer. *//** 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. */@@ -254,6 +260,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {return lender.online ? null : lentChromeGuidance("offline", lender);},annotate: (spec, result) => passkeyAnnotation(chromeEngine.onPane(spec) ? "pane" : CLOUD_HOME ? "cloud" : DESKTOP_MANAGED ? "desktop" : "server")(spec, result),+ // A failed call in a session on the browser sandbox: a sandbox no longer there ends the session, so the next call reopens.+ failedCall: async (session) => { if (cloudBrowser?.attached(session)) await cloudBrowser.failed(session); },// agent-browser's own error names only the CDP connection; the door knows what went wrong on the way.afterCall: (session, spec, answer) => {cloudBrowser?.touch(session);@@ -291,8 +299,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {if (spec) await closeBrowser(session, spec);await agentBrowserRuntime.close(session);},- // Real use only: a turn holding the browser, a call running in it, or a person watching or driving it.- held: (session) => !turnResources.free(`browser:${session}`) || agentBrowserRuntime.working(session) || agentBrowserRuntime.spare(session) === null,+ held: (session) => sandboxInUse(agentBrowserRuntime, session),folder: (botId) => deps.cloudBrowser?.folder?.(botId) ?? null,// The home's saved sign-ins: agent-browser's encrypted restore file, under this server's key only.signIns: {@@ -853,5 +860,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {eraseAudienceBrowsers, browserOwners, closeCapBrowsers,cloudBrowserBusy: (owner: string) => cloudBrowser?.busy(owner) ?? false,cloudBrowserReport: () => cloudBrowser?.report() ?? null,+ /** The browser sandbox's idle sweep, run now (it runs on its own every 30 s while a session is open). */+ cloudBrowserSweep: () => cloudBrowser?.closeIdle() ?? Promise.resolve(),};}