Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud browser: carry a bot's saved sign-ins into its sandbox profile and back, deliver downloads to its working folder, take uploads
milind-sonif1787072edf8
diff --git a/server/browser-sites.ts b/server/browser-sites.tsindex 7e4b836af9..9dc040a2b3 100644--- a/server/browser-sites.ts+++ b/server/browser-sites.ts@@ -2,7 +2,7 @@// it autosaves (`<restore key>-<session>.json.enc`, cli/src/native/state.rs: AES-256-GCM under SHA-256 of the key text,// 12-byte nonce first, 16-byte tag last); signing out clears all three. The key stays in this server process; no bot or page ever sees it.import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";-import { existsSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -191,6 +191,31 @@ function rewriteSavedState(directory: string, session: string, key: string, site}}+/** A session's saved sign-ins (its newest restore file) and when they last changed, for the Cloud's browser sandbox to carry+ * over (server/cloud-browser/sign-ins.ts): null when it has none, "unreadable" when the file is there but cannot be read+ * (a save under way, or another key), so the sandbox never opens signed out by mistake. */+export function readSignIns(directory: string, session: string, key: string): { state: SavedState; modified: number } | null | "unreadable" {+ for (const base of stateBases(session)) {+ const path = [".json.enc", ".json"].map((suffix) => join(directory, base + suffix)).filter(existsSync)+ .sort((a, b) => modified(b) - modified(a))[0];+ if (!path) continue;+ try { return { state: readState(path, key), modified: modified(path) }; }+ catch { return "unreadable"; }+ }+ return null;+}++/** The sandbox's cookies written back as the session's saved cookies (its storage kept), so a browser that opens in the+ * home sees the sign-ins made in the sandbox. Returns when the file changed. */+export function writeSignIns(directory: string, session: string, key: string, cookies: unknown[]): number {+ const current = readSignIns(directory, session, key);+ const origins = current && current !== "unreadable" ? current.state.origins : [];+ mkdirSync(directory, { recursive: true, mode: 0o700 });+ const path = join(directory, `${stateBases(session)[0]}.json.enc`);+ writeState(path, { cookies: cookies.filter(isCookie), origins }, key);+ return modified(path);+}+export function connectCdp(url: string, timeoutMs = 10_000, listeners: CdpListeners = {}): Promise<Cdp> {return new Promise((resolve, reject) => {const socket = new WebSocket(url);diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.tsindex 915e7bd8e8..cc61d03c9a 100644--- a/server/cloud-browser/cloud-browser.test.ts+++ b/server/cloud-browser/cloud-browser.test.ts@@ -1,6 +1,6 @@// The Cloud's browser sandbox, against a fake Admin relay and provider (testing/fake-computer.ts): no real provider is// called and no billable resource is made.-import { mkdtempSync, rmSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -8,7 +8,8 @@ import WebSocket from "ws";import type { AppConfig } from "../config.ts";import { ComputerIdleTimer } from "../computer-idle.ts";-import { DOWNLOAD_NOTE, downloadNote, LOCAL_SCHEME_REFUSAL, localSchemeRefusal } from "./guards.ts";+import { LOCAL_SCHEME_REFUSAL, localSchemeRefusal } from "./guards.ts";+import { UPLOAD_MAX_BYTES, type SignInStore } from "./companion.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, profileKey, providerOps } from "./remote.ts";@@ -91,9 +92,10 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>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);+ // One probe before the session was committed, the session's companion (sign-ins, downloads), and the engine's own+ // single connection for all five actions.+ expect(fake.upgrades).toHaveLength(3);+ expect(cloud.dialed("bot-scout")).toBe(2);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);@@ -112,7 +114,7 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>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);+ expect(cloud.dialed("bot-scout"), "only the companion's own connection").toBe(1);});it("two calls opening one session at once share the one open: a session never splits across two browsers", async () => {@@ -434,14 +436,149 @@ describe("what a browser in the sandbox is kept from", () => {expect(localSchemeRefusal({ name: "agent_browser_open", arguments: { url: "https://example.com/file:x" } })).toBeNull();expect(localSchemeRefusal({ name: "agent_browser_snapshot", arguments: {} })).toBeNull();});+});++/** The home's saved sign-ins, held in memory as the restore file would hold them. */+function memorySignIns(initial: { cookies: unknown[]; origins: unknown[] } | null | "unreadable") {+ let saved = initial;+ let modified = initial ? 1_000 : 0;+ const writes: unknown[][] = [];+ const store: SignInStore = {+ load: () => (saved === null || saved === "unreadable" ? saved : { state: saved, modified }),+ save: (_session, cookies) => { writes.push(cookies); saved = { cookies, origins: saved && saved !== "unreadable" ? saved.origins : [] }; modified += 1; return modified; },+ };+ return { store, writes, change(next: { cookies: unknown[]; origins: unknown[] } | "unreadable") { saved = next; modified += 10; } };+}++const SIGNED_IN = { name: "sid", value: "s1", domain: ".example.com", path: "/", expires: -1, size: 5, httpOnly: true, secure: true, session: true, sameSite: "Lax" };++describe("a bot's sign-ins between the home and its sandbox profile", () => {+ it("carries the home's saved sign-ins in on the first use, over the session's own connection, and not again while they are unchanged", async () => {+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [{ origin: "https://example.com", localStorage: [{ name: "token", value: "t" }] }] });+ const cloud = browser({ signIns: home.store });+ urlOf(await cloud.open(request()));+ expect(fake.cookies.get(profileKey("scout"))).toEqual([{ name: "sid", value: "s1", domain: ".example.com", path: "/", secure: true, httpOnly: true, sameSite: "Lax" }]);+ expect(fake.commands.filter((one) => one.method === "DOMStorage.setDOMStorageItem").map((one) => one.params)).toEqual([+ { storageId: { securityOrigin: "https://example.com", isLocalStorage: true }, key: "token", value: "t" },+ ]);+ expect(fake.cookies.get(profileKey("writer")), "never another bot's profile").toBeUndefined();+ clock += CLOUD_BROWSER_IDLE_MS;+ await cloud.closeIdle();+ const setsBefore = fake.commands.filter((one) => one.method === "Storage.setCookies").length;+ urlOf(await cloud.open(request()));+ expect(fake.commands.filter((one) => one.method === "Storage.setCookies").length, "unchanged at home: not carried again").toBe(setsBefore);+ });- it("says once, in the call's answer, that a download was not kept", () => {- const answer = { content: [{ type: "text", text: "Navigation failed: net::ERR_ABORTED" }] };- const noted = downloadNote(answer) as { content: Array<{ text: string }> };- expect(noted.content.at(-1)?.text).toBe(DOWNLOAD_NOTE);- expect(downloadNote(noted)).toBe(noted);- const page = { content: [{ type: "text", text: "button \"Download the app\"" }] };- expect(downloadNote(page), "a page's own words are not a download").toBe(page);+ it("opens in the home, never signed out, when the home's sign-ins cannot be read now, and carries them next time", async () => {+ const home = memorySignIns("unreadable");+ const cloud = browser({ signIns: home.store });+ expect(await cloud.open(request())).toEqual({ home: "sign-ins" });+ expect(cloud.active("bot-scout")).toBeNull();+ expect(cloud.report().fallbacks).toMatchObject({ "sign-ins": 1 });+ home.change({ cookies: [SIGNED_IN], origins: [] });+ urlOf(await cloud.open(request()));+ expect(fake.cookies.get(profileKey("scout"))).toHaveLength(1);+ });++ it("writes the sandbox's sign-ins back to the home on a clean close, so a browser that falls back to the home is signed in too", async () => {+ const home = memorySignIns(null);+ const cloud = browser({ signIns: home.store });+ urlOf(await cloud.open(request()));+ // The person signs in on a site in the sandbox.+ fake.cookies.set(profileKey("scout"), [{ name: "auth", value: "new", domain: "mail.example", path: "/", secure: true }]);+ clock += CLOUD_BROWSER_IDLE_MS;+ await cloud.closeIdle();+ expect(home.writes).toHaveLength(1);+ expect(home.writes[0]).toEqual([expect.objectContaining({ name: "auth", value: "new", domain: "mail.example" })]);+ // Written back, not carried in again on the next open.+ const sets = fake.commands.filter((one) => one.method === "Storage.setCookies").length;+ urlOf(await cloud.open(request()));+ expect(fake.commands.filter((one) => one.method === "Storage.setCookies").length).toBe(sets);+ });++ it("a sign-in made in the home while the sandbox was unavailable is carried in on the next sandbox use", async () => {+ const home = memorySignIns({ cookies: [SIGNED_IN], origins: [] });+ const cloud = browser({ signIns: home.store });+ urlOf(await cloud.open(request()));+ clock += CLOUD_BROWSER_IDLE_MS;+ await cloud.closeIdle();+ home.change({ cookies: [SIGNED_IN, { ...SIGNED_IN, name: "fallback", domain: "shop.example" }], origins: [] });+ urlOf(await cloud.open(request()));+ expect(fake.cookies.get(profileKey("scout"))?.map((cookie) => cookie.name)).toContain("fallback");+ });++ it("never puts a cookie value in the log", async () => {+ const lines: string[] = [];+ const cloud = browser({ signIns: memorySignIns({ cookies: [SIGNED_IN], origins: [] }).store, log: (line) => lines.push(line) });+ urlOf(await cloud.open(request()));+ clock += CLOUD_BROWSER_IDLE_MS;+ await cloud.closeIdle();+ expect(lines.join("\n")).not.toContain("s1");+ });+});++describe("downloads and uploads of a browser in the sandbox", () => {+ let folder: string;+ beforeEach(() => { folder = mkdtempSync(join(tmpdir(), "bot-folder-")); });+ afterEach(() => { rmSync(folder, { recursive: true, force: true }); });++ const downloadPath = (guid: string) => `/home/user/.omb-browser/.downloads/${profileKey("scout")}/${guid}`;+ const finish = async (guid: string, name: string, bytes: Buffer) => {+ fake.files.set(downloadPath(guid), bytes);+ fake.emit(profileKey("scout"), "Browser.downloadWillBegin", { guid, suggestedFilename: name, url: "https://files.example/x" });+ fake.emit(profileKey("scout"), "Browser.downloadProgress", { guid, totalBytes: bytes.length, receivedBytes: bytes.length, state: "completed" });+ };++ it("sends each finished download to the bot's working folder with its bytes, removes it from the sandbox, and tells the bot", async () => {+ const cloud = browser({ folder: () => folder });+ urlOf(await cloud.open(request()));+ expect(fake.commands.find((one) => one.method === "Browser.setDownloadBehavior")?.params)+ .toEqual({ behavior: "allowAndName", downloadPath: `/home/user/.omb-browser/.downloads/${profileKey("scout")}`, eventsEnabled: true });+ const bytes = Buffer.from("%PDF-1.7 report bytes");+ await finish("0f3e2a1b-guid", "report.pdf", bytes);+ await vi.waitFor(() => expect(existsSync(join(folder, "downloads", "report.pdf"))).toBe(true));+ expect(readFileSync(join(folder, "downloads", "report.pdf"))).toEqual(bytes);+ await vi.waitFor(() => expect(fake.files.has(downloadPath("0f3e2a1b-guid"))).toBe(false));+ expect(cloud.takeNotes("bot-scout")).toEqual([`Downloaded "report.pdf" into your working folder as ${join("downloads", "report.pdf")} (${bytes.length} bytes).`]);+ expect(cloud.takeNotes("bot-scout")).toEqual([]);+ // A second file of the same name is kept beside it, as a browser names a second copy.+ await finish("1a2b3c4d-guid", "report.pdf", Buffer.from("second"));+ await vi.waitFor(() => expect(existsSync(join(folder, "downloads", "report (2).pdf"))).toBe(true));+ });++ it("cancels a download over the in-home browser's size limit and says so", async () => {+ const cloud = browser({ folder: () => folder });+ urlOf(await cloud.open(request()));+ fake.emit(profileKey("scout"), "Browser.downloadWillBegin", { guid: "big-guid", suggestedFilename: "huge.iso" });+ fake.emit(profileKey("scout"), "Browser.downloadProgress", { guid: "big-guid", totalBytes: 2 * 1024 ** 3, receivedBytes: 10, state: "inProgress" });+ await vi.waitFor(() => expect(fake.commands.some((one) => one.method === "Browser.cancelDownload" && one.params.guid === "big-guid")).toBe(true));+ expect(cloud.takeNotes("bot-scout")).toEqual([`"huge.iso" was not downloaded: it is over 1 GiB, the most a browser download keeps.`]);+ });++ it("keeps a download it could not bring over in the sandbox, says so, and tries it again when the browser closes", async () => {+ let available = false;+ const cloud = browser({ folder: () => (available ? folder : null) });+ urlOf(await cloud.open(request()));+ await finish("retry-guid", "data.csv", Buffer.from("a,b\n1,2\n"));+ await vi.waitFor(() => expect(cloud.takeNotes("bot-scout")).toEqual([expect.stringContaining(`"data.csv" was downloaded in the browser but could not be brought to your working folder`)]));+ expect(fake.files.has(downloadPath("retry-guid")), "kept in the sandbox").toBe(true);+ available = true;+ await cloud.close("bot-scout");+ expect(readFileSync(join(folder, "downloads", "data.csv"), "utf8")).toBe("a,b\n1,2\n");+ expect(fake.files.has(downloadPath("retry-guid"))).toBe(false);+ });++ it("gives a page a file from the Cloud by copying it into the sandbox first, and refuses a large one in one line", async () => {+ const cloud = browser();+ urlOf(await cloud.open(request()));+ mkdirSync(join(folder, "in"), { recursive: true });+ writeFileSync(join(folder, "in", "cv.pdf"), "my cv");+ const given = await cloud.upload("bot-scout", join(folder, "in", "cv.pdf"), "Résumé.pdf", 5);+ const path = `/home/user/.omb-browser/.uploads/${profileKey("scout")}/Résumé.pdf`;+ expect(given).toEqual({ path });+ expect(fake.files.get(path)?.toString()).toBe("my cv");+ expect(await cloud.upload("bot-scout", join(folder, "in", "cv.pdf"), null, UPLOAD_MAX_BYTES + 1))+ .toEqual({ error: "cv.pdf is over 50 MiB, which this browser can't take from the Cloud yet. Tell the person in one sentence and ask them to upload it themselves." });});});diff --git a/server/cloud-browser/companion.ts b/server/cloud-browser/companion.tsnew file mode 100644index 0000000000..3e79be0b21--- /dev/null+++ b/server/cloud-browser/companion.ts@@ -0,0 +1,163 @@+// What rides beside a bot's browser session in the Cloud's browser sandbox, on one more connection through the same door:+// its sign-ins carried in from the home when they changed there, carried back to the home on a clean close, and its+// downloads brought to the bot's working folder as they finish. Uploads go the other way, one file at a time.+import { existsSync } from "node:fs";+import { basename, dirname, join } from "node:path";++import type { Cdp, CdpEvent } from "../browser-sites.ts";+import { DOWNLOAD_LIMITS, safeFileName } from "../browser/cdp/downloads.ts";+import type { CloudBrowserRails } from "./rails.ts";+import type { ComputerOps } from "./remote.ts";+import { carryIn, carryOut } from "./sign-ins.ts";++/** Where a download lands in the bot's working folder. */+export const DOWNLOADS_SUBFOLDER = "downloads";+/** The largest file an upload copies into the sandbox; a larger one fails that one action with a line. */+export const UPLOAD_MAX_BYTES = 50 * 1024 * 1024;++export interface SignInStore {+ /** The home's saved sign-ins for a session, when they last changed; null when none; "unreadable" when not readable now. */+ load(session: string): { state: { cookies: unknown[]; origins: unknown[] }; modified: number } | null | "unreadable";+ /** The sandbox's cookies saved as the session's; returns when the file changed. */+ save(session: string, cookies: unknown[]): number;+}++export interface CompanionDeps {+ session: string;+ botId: string;+ key: string;+ boxId: string;+ /** The sandbox's home folder, from its launch. */+ home: string;+ ops: ComputerOps;+ rails: CloudBrowserRails;+ signIns: SignInStore | null;+ /** The bot's working folder in the Cloud, or null when it has none now. */+ folder(botId: string): string | null;+ connect(url: string, listeners: { event(message: CdpEvent): void }): Promise<Cdp>;+ log(line: string): void;+}++/** The home's sign-ins could not be read now: the session opens in the home this time, and the carry is tried next time. */+export class SignInsUnreadable extends Error {}++interface Pending { guid: string; name: string }++export class SandboxCompanion {+ readonly #deps: CompanionDeps;+ #cdp: Cdp | null = null;+ readonly #names = new Map<string, string>();+ /** Finished downloads not yet in the bot's folder: kept in the sandbox (a day at most) and tried again at the close. */+ readonly #pending = new Map<string, Pending>();+ readonly #notes: string[] = [];+ #started = 0;+ #delivering: Promise<void> = Promise.resolve();++ constructor(deps: CompanionDeps) { this.#deps = deps; }++ get downloadDir(): string { return `${this.#deps.home}/.omb-browser/.downloads/${this.#deps.key}`; }++ /** Opens its connection, carries the home's sign-ins in when they changed since the last carry, and takes the session's+ * downloads. Throws SignInsUnreadable, or any failure, before the session is used: it then opens in the home. */+ async start(cdpUrl: string): Promise<void> {+ const { session, key, rails, signIns } = this.#deps;+ const loaded = signIns ? signIns.load(session) : null;+ if (loaded === "unreadable") throw new SignInsUnreadable();+ this.#cdp = await this.#deps.connect(cdpUrl, { event: (message) => this.#event(message) });+ if (loaded && loaded.modified > rails.carried(key)) {+ const carried = await carryIn(this.#cdp, loaded.state);+ rails.setCarried(key, loaded.modified);+ this.#deps.log(`browser ${session}: carried ${carried.cookies} saved cookies and ${carried.origins} sites' storage into the browser sandbox`);+ }+ await this.#cdp.send("Browser.setDownloadBehavior", { behavior: "allowAndName", downloadPath: this.downloadDir, eventsEnabled: true });+ }++ /** Lines for the bot's next browser call: downloads that arrived, or could not. */+ takeNotes(): string[] { return this.#notes.splice(0); }++ /** A file of the Cloud copied into the sandbox for a page's file input; returns its path there, or the line to say. */+ async upload(file: string, name: string | null, size: number): Promise<{ path: string } | { error: string }> {+ const shown = basename(file);+ if (size > UPLOAD_MAX_BYTES) return { error: `${shown} is over ${UPLOAD_MAX_BYTES / 1024 / 1024} MiB, which this browser can't take from the Cloud yet. Tell the person in one sentence and ask them to upload it themselves.` };+ const target = `${this.#deps.home}/.omb-browser/.uploads/${this.#deps.key}/${safeFileName(name ?? shown) || "upload"}`;+ const sent = await this.#deps.ops.sendFile(this.#deps.boxId, dirname(file), shown, target);+ return "error" in sent ? { error: `${shown} could not be given to the browser: ${sent.error}` } : { path: target };+ }++ /** A clean close: downloads still waiting are tried once more, and the sandbox's cookies are saved as the home's. */+ async stop(): Promise<void> {+ await this.#delivering;+ for (const pending of this.#pending.values()) await this.#deliver(pending);+ if (this.#cdp && this.#deps.signIns) {+ try {+ const cookies = await carryOut(this.#cdp);+ this.#deps.rails.setCarried(this.#deps.key, this.#deps.signIns.save(this.#deps.session, cookies));+ } catch (error) {+ this.#deps.log(`browser ${this.#deps.session}: could not save the browser sandbox's sign-ins in the home (${error instanceof Error ? error.name : "error"}); they stay in the sandbox`);+ }+ }+ this.close();+ }++ close(): void {+ this.#cdp?.close();+ this.#cdp = null;+ }++ #event(message: CdpEvent): void {+ const params = message.params ?? {};+ const guid = typeof params.guid === "string" && /^[A-Za-z0-9-]{1,64}$/.test(params.guid) ? params.guid : null;+ if (!guid) return;+ if (message.method === "Browser.downloadWillBegin") {+ if (this.#started >= DOWNLOAD_LIMITS.perOwner) {+ void this.#cdp?.send("Browser.cancelDownload", { guid }).catch(() => undefined);+ this.#notes.push(`A download was stopped: this browser keeps at most ${DOWNLOAD_LIMITS.perOwner} downloads per session.`);+ return;+ }+ this.#started += 1;+ this.#names.set(guid, safeFileName(String(params.suggestedFilename ?? "")) || "download");+ return;+ }+ if (message.method !== "Browser.downloadProgress") return;+ const name = this.#names.get(guid) ?? "download";+ const bytes = Math.max(Number(params.totalBytes) || 0, Number(params.receivedBytes) || 0);+ if (params.state === "inProgress" && bytes > DOWNLOAD_LIMITS.maxBytes) {+ void this.#cdp?.send("Browser.cancelDownload", { guid }).catch(() => undefined);+ this.#names.delete(guid);+ this.#notes.push(`"${name}" was not downloaded: it is over ${DOWNLOAD_LIMITS.maxBytes / 1024 ** 3} GiB, the most a browser download keeps.`);+ return;+ }+ if (params.state === "canceled") { this.#names.delete(guid); return; }+ if (params.state !== "completed") return;+ this.#names.delete(guid);+ const pending = { guid, name };+ this.#delivering = this.#delivering.then(() => this.#deliver(pending));+ }++ async #deliver(pending: Pending): Promise<void> {+ const { botId, boxId, key, ops } = this.#deps;+ const folder = this.#deps.folder(botId);+ const failed = (why: string) => {+ this.#pending.set(pending.guid, pending);+ this.#notes.push(`"${pending.name}" was downloaded in the browser but could not be brought to your working folder (${why}). It is kept in the browser sandbox for a day and is tried again when this browser closes.`);+ };+ if (!folder) return failed("your working folder is not available right now");+ const to = unusedName(folder, pending.name);+ const fetched = await ops.fetchFile(boxId, `${this.downloadDir}/${pending.guid}`, folder, to).catch((error: unknown) => ({ error: error instanceof Error ? error.message : "it failed" }));+ if ("error" in fetched) return failed(fetched.error);+ this.#pending.delete(pending.guid);+ await ops.removeDownload(boxId, key, pending.guid).catch(() => undefined);+ this.#notes.push(`Downloaded "${pending.name}" into your working folder as ${fetched.path} (${fetched.bytes} bytes).`);+ }+}++/** `downloads/<name>`, or `downloads/<name> (2)` and so on when that is taken, as a browser names a second copy. */+function unusedName(folder: string, name: string): string {+ const dot = name.lastIndexOf(".");+ const [stem, extension] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];+ for (let n = 1; n < 1_000; n++) {+ const candidate = join(DOWNLOADS_SUBFOLDER, n === 1 ? name : `${stem} (${n})${extension}`);+ if (!existsSync(join(folder, candidate))) return candidate;+ }+ return join(DOWNLOADS_SUBFOLDER, `${stem} (${Date.now()})${extension}`);+}diff --git a/server/cloud-browser/guards.ts b/server/cloud-browser/guards.tsindex 30219a6ce7..252576a00c 100644--- a/server/cloud-browser/guards.ts+++ b/server/cloud-browser/guards.ts@@ -1,5 +1,5 @@// What a browser in the Cloud's browser sandbox is kept from, at the home before a call reaches it: every bot's Chrome-// there runs as the same user, so a local page could read another bot's profile. Its downloads stay in the sandbox.+// there runs as the same user, so a local page could read another bot's profile./** Schemes that open what is on the sandbox's own disk or Chrome's own pages, never a website. */const LOCAL_SCHEME = /^\s*(file|chrome|chrome-untrusted|devtools|view-source|filesystem|chrome-extension):/i;@@ -17,17 +17,3 @@ function namesLocal(value: unknown, depth = 0): boolean {export function localSchemeRefusal(params: unknown): string | null {return namesLocal((params as { arguments?: unknown } | null)?.arguments) ? LOCAL_SCHEME_REFUSAL : null;}--export const DOWNLOAD_NOTE = "This browser runs in the Cloud's browser sandbox, which doesn't save downloads yet: if that action started a download, the file was not kept. Tell the person in one sentence and ask them to download it themselves.";--/** What the engine says when a navigation turned into a download (Chrome cancels the page load), not a page's own words. */-const DOWNLOAD_SIGNS = /net::ERR_ABORTED|\bdownload (?:started|began|will begin|was blocked)\b/i;--/** A call whose answer says a download started or a navigation was cut off by one gets the note, once, at its end. */-export function downloadNote(result: unknown): unknown {- const content = (result as { content?: unknown } | null)?.content;- if (!Array.isArray(content)) return result;- const text = content.map((part) => (typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "")).join("\n");- if (!DOWNLOAD_SIGNS.test(text) || text.includes(DOWNLOAD_NOTE)) return result;- return { ...(result as object), content: [...content, { type: "text", text: DOWNLOAD_NOTE }] };-}diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.tsindex cc557d6ad6..1dd501deb5 100644--- a/server/cloud-browser/index.ts+++ b/server/cloud-browser/index.ts@@ -7,6 +7,8 @@ import { randomBytes } from "node:crypto";import { cloudFailureOf } from "../boat-limit.ts";import { CloudBrowserDoors, dialable, probeDoor, type DoorTarget } from "./door.ts";+import { connectCdp } from "../browser-sites.ts";+import { SandboxCompanion, SignInsUnreadable, type CompanionDeps, type SignInStore } from "./companion.ts";import { createCloudBrowserRails, type CloudBrowserRails, type HomeReason } from "./rails.ts";import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, OldRelay, profileKey, StaysHome, wakeSandbox, type ComputerOps } from "./remote.ts";@@ -28,6 +30,12 @@ export interface CloudBrowserDeps {closeEngine(session: string): Promise<unknown>;/** A turn holds this session's browser now: it is not closed for being idle. */held(session: string): boolean;+ /** The home's saved sign-ins (agent-browser's restore file), carried in and back; null keeps them apart. */+ signIns?: SignInStore | null;+ /** The bot's working folder, where its downloads land. */+ folder?(botId: string): string | null;+ /** Tests: the companion's own connection through the door. */+ connect?: CompanionDeps["connect"];env?: NodeJS.ProcessEnv;now?: () => number;log?: (line: string) => void;@@ -69,6 +77,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {/** A session's open under way: a second call for the same session waits on it, so one session never splits in two. */const pendingSessions = new Map<string, Promise<Opened>>();const closing = new Set<string>();+ const companions = new Map<string, SandboxCompanion>();/** 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;@@ -138,7 +147,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {box = await wake(ops);const secret = randomBytes(24).toString("hex");const answer = await ops.launch(box.id, key, secret);- if (!answer.chrome) {+ if (!answer.chrome || !answer.home) {rails.failed();await quit();return home(request, "start-failed");@@ -157,6 +166,22 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {return home(request, "unreachable");}const cdpUrl = await doors.open(request.session, target);+ const companion = new SandboxCompanion({+ session: request.session, botId: request.botId, key, boxId: box.id, home: answer.home, ops, rails, signIns: deps.signIns ?? null,+ folder: (botId) => deps.folder?.(botId) ?? null, log,+ connect: deps.connect ?? ((url, listeners) => connectCdp(url, 10_000, listeners)),+ });+ try {+ await companion.start(cdpUrl);+ } catch (error) {+ companion.close();+ doors.close(request.session);+ await quit();+ if (error instanceof SignInsUnreadable) return home(request, "sign-ins");+ rails.failed();+ return home(request, "unreachable");+ }+ companions.set(request.session, companion);sessions.set(request.session, request.botId);rails.opened();startSweep();@@ -223,6 +248,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {if (!botId || closing.has(session)) return;closing.add(session);try {+ await companions.get(session)?.stop().catch(() => undefined);+ companions.delete(session);await deps.closeEngine(session).catch(() => undefined);doors.close(session);sessions.delete(session);@@ -260,6 +287,11 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {close,closeIdle,dialed: (session: string): number => doors.dialed(session),+ /** Lines for the session's next browser call (downloads that arrived, or could not). */+ takeNotes: (session: string): string[] => companions.get(session)?.takeNotes() ?? [],+ /** A file of the Cloud given to the session's browser for a page's file input: its path in the sandbox, or the line to say. */+ upload: (session: string, file: string, name: string | null, size: number) =>+ companions.get(session)?.upload(file, name, size) ?? Promise.resolve({ error: "This browser closed; try the upload again." }),/** 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: () => {@@ -274,6 +306,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {closeAll(): void {if (sweep) clearInterval(sweep);sweep = null;+ for (const companion of companions.values()) companion.close();+ companions.clear();doors.closeAll();sessions.clear();},diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.tsindex eef2cb7f2e..ae7651d65c 100644--- a/server/cloud-browser/rails.ts+++ b/server/cloud-browser/rails.ts@@ -16,7 +16,7 @@ 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" | "own-key" | "not-set-up" | "busy" | "lent-connection"+ | "lever" | "team" | "not-eligible" | "own-key" | "sign-ins" | "not-set-up" | "busy" | "lent-connection"| "old-relay" | "unavailable" | "budget" | "minutes-used" | "sandbox-full" | "backoff" | "account-limit" | "hours-used" | "at-once" | "no-route" | "start-failed" | "unreachable";interface Day {@@ -44,6 +44,8 @@ interface State extends Day {oldRelayUntil: number;/** The relay said no browser sandbox may start (the fleet's day spent, switched off): nothing is started before this. */unavailableUntil: number;+ /** Per bot's profile key: when the home's saved sign-ins last carried in (or were last written back), by file time. */+ carried: Record<string, number>;/** Since when the operator lever has kept every browser in the home; 0 when it does not. */leverSince: number;}@@ -73,7 +75,7 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {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, oldRelayUntil: 0, unavailableUntil: 0 };+ 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: {} };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);@@ -86,6 +88,8 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {noRouteDay: typeof saved.noRouteDay === "string" ? saved.noRouteDay : null,awakeSince: number(saved.awakeSince), leverSince: number(saved.leverSince),oldRelayUntil: number(saved.oldRelayUntil), unavailableUntil: number(saved.unavailableUntil),+ carried: Object.fromEntries(Object.entries(saved.carried && typeof saved.carried === "object" ? saved.carried : {})+ .filter(([key, at]) => /^[a-f0-9]{16}$/.test(key) && typeof at === "number" && Number.isFinite(at))),};} catch {// None yet, or unreadable: a fresh day. The holds it may have had end by the next day anyway.@@ -195,6 +199,11 @@ export function createCloudBrowserRails(options: CloudBrowserRailsOptions) {current.backoffUntil = Math.max(current.backoffUntil, now() + CLOUD_BROWSER_BACKOFF_MS);save();},+ carried: (key: string): number => today().carried[key] ?? 0,+ setCarried(key: string, at: number): void {+ today().carried[key] = at;+ save();+ },/** An Admin from before the browser sandbox: asked again in a week. */oldRelay(): void {today().oldRelayUntil = now() + 7 * 24 * 60 * 60_000;diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.tsindex 2c7969308e..de3561a0be 100644--- a/server/cloud-browser/remote.ts+++ b/server/cloud-browser/remote.ts@@ -9,6 +9,7 @@ import { createHash } from "node:crypto";import { boatAccount, boatFetch, boatNameFor, boatRefusal, deadBoatOf, findBoat, requestRecordedBoatDeletion, SLEEPING_BOAT_STATES } from "../boat.ts";import { beginBoatCreate, discardBoatCreate, rememberCreatedBoat, resolveBoatCreate } from "../boat-create-idempotency.ts";import { relayBody } from "../boat-relay.ts";+import { copyFromComputer, copyToComputer, type CopyOutcome } from "../cloud-computer-files.ts";import type { AppConfig } from "../config.ts";const READY = new Set(["idle", "ready", "running"]);@@ -44,8 +45,14 @@ export interface ComputerOps {/** One resume. Throws the relay's refusal (with its limit) on anything but a 2xx or a 409. */resume(boxId: string): Promise<void>;state(boxId: string): Promise<string | null>;- /** One bot's Chrome started on its profile, with this open's door secret. */- launch(boxId: string, key: string, secret: string): Promise<{ chrome: boolean }>;+ /** One bot's Chrome started on its profile, with this open's door secret; `home` is the sandbox's home folder. */+ launch(boxId: string, key: string, secret: string): Promise<{ chrome: boolean; home: string | null }>;+ /** A finished download (a sandbox path) brought into `folder` as `to`, with the cloud computers' copy checks and limits. */+ fetchFile(boxId: string, path: string, folder: string, to: string): Promise<CopyOutcome>;+ /** A file of the Cloud (`from`, inside `folder`) copied to a sandbox path for an upload. */+ sendFile(boxId: string, folder: string, from: string, path: string): Promise<CopyOutcome>;+ /** A download the sandbox no longer needs to keep. */+ removeDownload(boxId: string, key: string, name: string): Promise<void>;/** One bot's Chrome asked to quit (it writes its cookies); `key` null: every Chrome and the door. */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. */@@ -139,7 +146,15 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {},async launch(boxId, key, secret) {if (!HEX16.test(key) || !HEX48.test(secret)) throw new Error("bad browser profile key or door secret");- return { chrome: (await action(boxId, { action: "launch", key, secret }))?.chrome === true };+ const answer = await action(boxId, { action: "launch", key, secret });+ const home = typeof answer?.home === "string" && /^\/[^\0\n]*$/.test(answer.home) && !answer.home.split("/").includes("..") ? answer.home.replace(/\/+$/, "") : null;+ return { chrome: answer?.chrome === true, home };+ },+ fetchFile: (boxId, path, folder, to) => copyFromComputer(cfg(), boxId, folder, { path, to }, AbortSignal.timeout(10 * 60_000)),+ sendFile: (boxId, folder, from, path) => copyToComputer(cfg(), boxId, folder, { from, path }, AbortSignal.timeout(10 * 60_000)),+ async removeDownload(boxId, key, name) {+ if (!HEX16.test(key)) throw new Error("bad browser profile key");+ await action(boxId, { action: "remove-download", key, name });},async quit(boxId, key) {if (key !== null && !HEX16.test(key)) throw new Error("bad browser profile key");diff --git a/server/cloud-browser/sign-ins.ts b/server/cloud-browser/sign-ins.tsnew file mode 100644index 0000000000..860bc6885b--- /dev/null+++ b/server/cloud-browser/sign-ins.ts@@ -0,0 +1,90 @@+// A bot's sign-ins follow it between the home's browser and its profile in the Cloud's browser sandbox. The home keeps+// them in agent-browser's encrypted restore file (browser-sites.ts reads and writes it); the sandbox's Chrome keeps them in+// its own profile. They travel only over the session's own DevTools connection, through the authenticated door: never+// through a file another bot's Chrome could read, and never into a log.+import type { Cdp } from "../browser-sites.ts";++/** At most this many cookies, and this much storage, move either way at once: a sign-in fits many times over. */+export const MAX_COOKIES = 3_000;+export const MAX_STORAGE_ORIGINS = 200;+const MAX_STORAGE_BYTES = 5 * 1024 * 1024;++/** A cookie as agent-browser saves it: Chrome's own (`Network.getAllCookies`), so `session` marks one with no expiry. */+interface SavedCookie {+ name: string; value: string; domain: string; path: string; expires?: number; httpOnly?: boolean; secure?: boolean;+ session?: boolean; sameSite?: string; partitionKey?: unknown; sourceScheme?: string; sourcePort?: number; priority?: string;+}++const isSavedCookie = (value: unknown): value is SavedCookie => {+ const cookie = value as Partial<SavedCookie> | null;+ return typeof cookie?.name === "string" && typeof cookie.value === "string" && typeof cookie.domain === "string" && typeof cookie.path === "string";+};++/** Chrome's CookieParam for `Storage.setCookies`: a session cookie stays one. */+export function cookieParam(cookie: SavedCookie): Record<string, unknown> {+ const sameSite = cookie.sameSite === "Strict" || cookie.sameSite === "Lax" || cookie.sameSite === "None" ? cookie.sameSite : undefined;+ const expires = cookie.session || typeof cookie.expires !== "number" || cookie.expires < 0 ? undefined : cookie.expires;+ return {+ name: cookie.name, value: cookie.value, domain: cookie.domain, path: cookie.path,+ ...(cookie.secure === true ? { secure: true } : {}), ...(cookie.httpOnly === true ? { httpOnly: true } : {}),+ ...(sameSite ? { sameSite } : {}), ...(expires !== undefined ? { expires } : {}),+ ...(cookie.partitionKey && typeof cookie.partitionKey === "object" ? { partitionKey: cookie.partitionKey } : {}),+ };+}++interface Storage { origin: string; items: Array<{ name: string; value: string }> }++function storageOf(origins: readonly unknown[]): Storage[] {+ let bytes = 0;+ const kept: Storage[] = [];+ for (const entry of origins.slice(0, MAX_STORAGE_ORIGINS)) {+ const origin = (entry as { origin?: unknown }).origin;+ const items = (entry as { localStorage?: unknown }).localStorage;+ if (typeof origin !== "string" || !/^https?:\/\//.test(origin) || !Array.isArray(items)) continue;+ const pairs = items.filter((item): item is { name: string; value: string } => typeof item?.name === "string" && typeof item?.value === "string");+ bytes += pairs.reduce((sum, item) => sum + item.name.length + item.value.length, 0);+ if (bytes > MAX_STORAGE_BYTES) break;+ if (pairs.length) kept.push({ origin, items: pairs });+ }+ return kept;+}++/** The home's saved sign-ins set in the sandbox's Chrome: every cookie, then, as best it can, each site's local storage+ * through one blank page of its own (Chrome may want a page of that site first; a site it refuses keeps its cookies). A+ * cookie Chrome refuses fails the carry, so the session opens in the home instead of signed out. */+export async function carryIn(cdp: Cdp, state: { cookies: readonly unknown[]; origins: readonly unknown[] }): Promise<{ cookies: number; origins: number }> {+ const cookies = state.cookies.filter(isSavedCookie).slice(0, MAX_COOKIES).map(cookieParam);+ if (cookies.length) await cdp.send("Storage.setCookies", { cookies });+ const storage = storageOf(state.origins);+ let carried = 0;+ if (storage.length) {+ const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank", background: true }).catch(() => ({})) as { targetId?: string };+ if (typeof targetId !== "string") return { cookies: cookies.length, origins: 0 };+ try {+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true }) as { sessionId?: string };+ if (typeof sessionId !== "string") throw new Error("no page for the storage carry");+ await cdp.send("DOMStorage.enable", {}, sessionId);+ for (const { origin, items } of storage) {+ try {+ for (const item of items) {+ await cdp.send("DOMStorage.setDOMStorageItem", { storageId: { securityOrigin: origin, isLocalStorage: true }, key: item.name, value: item.value }, sessionId);+ }+ carried += 1;+ } catch {+ // This site's storage stays in the home; its cookies were carried.+ }+ }+ } catch {+ // No page for storage: the cookies were carried.+ } finally {+ await cdp.send("Target.closeTarget", { targetId }).catch(() => undefined);+ }+ }+ return { cookies: cookies.length, origins: carried };+}++/** The sandbox's cookies as the home saves them (Chrome's own shape, as agent-browser writes it), at most MAX_COOKIES. */+export async function carryOut(cdp: Cdp): Promise<unknown[]> {+ const { cookies } = await cdp.send("Storage.getCookies", {}) as { cookies?: unknown[] };+ return (cookies ?? []).filter(isSavedCookie).slice(0, MAX_COOKIES);+}diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.tsindex 9046b244c9..caadeeafc3 100644--- a/server/cloud-browser/testing/fake-computer.ts+++ b/server/cloud-browser/testing/fake-computer.ts@@ -33,6 +33,14 @@ export interface FakeComputer {upgrades: Array<{ path: string; host: string | undefined; origin: string | undefined }>;frames: string[];boxId: string;+ /** Files on the sandbox's disk by path (downloads the page made, uploads the home sent). */+ files: Map<string, Buffer>;+ /** Each bot's cookies in its sandbox Chrome, by profile key, as `Storage.setCookies` left them. */+ cookies: Map<string, Array<Record<string, unknown>>>;+ /** Every DevTools command the sandbox's Chromes got, with its profile key. */+ commands: Array<{ key: string; method: string; params: Record<string, unknown> }>;+ /** Sends a DevTools event to the connections of a profile that asked for download events. */+ emit(key: string, method: string, params: Record<string, unknown>): void;resumes(): number;creates(): number;launches(): number;@@ -52,13 +60,30 @@ export async function startFakeComputer(): Promise<FakeComputer> {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, requests: [], upgrades: [], frames: [], boxId: "bx_23456789",+ files: new Map(), cookies: new Map(), commands: [],} as unknown as FakeComputer;+ const watchers = new Map<string, Set<import("ws").WebSocket>>();+ const HOME = "/home/user";const server: Server = createServer((req, res) => {const url = new URL(req.url ?? "/", "http://fake");- let raw = "";- req.on("data", (chunk) => { raw += chunk; });+ const chunks: Buffer[] = [];+ req.on("data", (chunk: Buffer) => { chunks.push(chunk); });req.on("end", () => {- const body = raw ? JSON.parse(raw) as Record<string, unknown> : {};+ // The transfer links: no bearer, as the provider's signed links need none.+ if (url.pathname === "/file" && req.method === "GET") {+ const file = fake.files.get(url.searchParams.get("p") ?? "");+ res.writeHead(file ? 200 : 404, { "content-length": String(file?.length ?? 0), connection: "close" });+ res.end(file ?? "");+ return;+ }+ if (url.pathname === "/put" && req.method === "PUT") {+ fake.files.set(url.searchParams.get("p") ?? "", Buffer.concat(chunks));+ res.writeHead(200, { connection: "close" });+ res.end();+ return;+ }+ const raw = Buffer.concat(chunks).toString("utf8");+ const body = raw && !url.pathname.startsWith("/put") ? JSON.parse(raw) as Record<string, unknown> : {};fake.requests.push({ method: req.method ?? "GET", path: url.pathname, 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 ${RELAY_KEY}`) return send(401, { ok: false });@@ -98,11 +123,18 @@ export async function startFakeComputer(): Promise<FakeComputer> {if (rest === `/sandboxes/${boxId}/browser`) {if (body.action === "launch" && typeof body.key === "string" && typeof body.secret === "string") {secrets.set(body.key, body.secret);- return send(200, { ok: true, chrome: fake.chromeStarts, policy: true });+ return send(200, { ok: true, chrome: fake.chromeStarts, policy: true, home: HOME });}+ if (body.action === "remove-download") fake.files.delete(`${HOME}/.omb-browser/.downloads/${String(body.key)}/${String(body.name)}`);return send(200, { ok: true });}if (rest === `/sandboxes/${boxId}/commands`) return send(404, { ok: false, code: "not_found" });+ if (rest === `/sandboxes/${boxId}/files/download-url` || rest === `/sandboxes/${boxId}/files/upload-url`) {+ const path = String(body.path ?? "");+ const download = rest.endsWith("download-url");+ if (!new RegExp(`^${HOME}/\\.omb-browser/\\.${download ? "downloads" : "uploads"}/[a-f0-9]{16}/[^/.][^/]*$`).test(path)) return send(404, { ok: false, code: "not_found" });+ return send(200, { ok: true, url: `${fake.base}/${download ? "file" : "put"}?p=${encodeURIComponent(path)}`, method: download ? "GET" : "PUT", path });+ }if (rest === `/sandboxes/${boxId}/stop`) { fake.state = "archived"; return send(200, { ok: true }); }send(404, { ok: false, code: "not_found" });});@@ -116,7 +148,23 @@ export async function startFakeComputer(): Promise<FakeComputer> {return;}wss.handleUpgrade(req, socket, head, (ws) => {- ws.on("message", (data) => { const text = String(data); fake.frames.push(text); ws.send(`echo:${key}:${text}`); });+ ws.on("message", (data) => {+ const text = String(data);+ fake.frames.push(text);+ const message = JSON.parse(text) as { id?: number; method?: string; params?: Record<string, unknown>; sessionId?: string };+ // A DevTools command gets Chrome's answer; anything else (the engine's frames in these tests) comes back echoed.+ if (typeof message.method !== "string") { ws.send(`echo:${key}:${text}`); return; }+ const params = message.params ?? {};+ fake.commands.push({ key, method: message.method, params });+ let result: Record<string, unknown> = {};+ if (message.method === "Storage.setCookies") fake.cookies.set(key, [...(fake.cookies.get(key) ?? []), ...(params.cookies as Array<Record<string, unknown>>)]);+ if (message.method === "Storage.getCookies") result = { cookies: (fake.cookies.get(key) ?? []).map((cookie) => ({ ...cookie, size: 1, session: cookie.expires === undefined, expires: cookie.expires ?? -1 })) };+ if (message.method === "Browser.setDownloadBehavior") { const set = watchers.get(key) ?? new Set(); set.add(ws); watchers.set(key, set); }+ if (message.method === "Target.createTarget") result = { targetId: "page-1" };+ if (message.method === "Target.attachToTarget") result = { sessionId: "session-1" };+ ws.send(JSON.stringify({ id: message.id, result, ...(message.sessionId ? { sessionId: message.sessionId } : {}) }));+ });+ ws.on("close", () => watchers.get(key)?.delete(ws));});});await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));@@ -128,6 +176,7 @@ export async function startFakeComputer(): Promise<FakeComputer> {fake.quits = () => fake.requests.flatMap((request) => !request.path.endsWith("/browser") ? []: request.body?.action === "quit" ? [`quit:${String(request.body.key)}`] : request.body?.action === "quit-all" ? ["quit-all"] : []);fake.profiles = () => actions("launch").map((request) => String(request.body?.key));+ fake.emit = (key, method, params) => { for (const ws of watchers.get(key) ?? []) ws.send(JSON.stringify({ method, params })); };fake.close = async () => {for (const client of wss.clients) client.terminate();wss.close();diff --git a/server/host/browser-cloud-sandbox.test.ts b/server/host/browser-cloud-sandbox.test.tsindex abfcf59fbf..7101f0a00e 100644--- a/server/host/browser-cloud-sandbox.test.ts+++ b/server/host/browser-cloud-sandbox.test.ts@@ -1,18 +1,18 @@// 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 { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";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 { RELAY_KEY, startFakeComputer, type FakeComputer } from "../cloud-browser/testing/fake-computer.ts";import { LOCAL_SCHEME_REFUSAL } from "../cloud-browser/guards.ts";-import { CLOUD_BROWSER_NO_UPLOAD, createBrowserHost, type BrowserHostDeps } from "./browser.ts";+import { createBrowserHost, type BrowserHostDeps } from "./browser.ts";vi.mock("../browser-engine.ts", async (original) => {const actual = await original<typeof import("../browser-engine.ts")>();@@ -101,8 +101,16 @@ describe("a personal Cloud's bot browser opens in the Cloud's browser sandbox",// 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));+ // An upload from the Cloud's disk goes to the sandbox first, and the page gets its path there.+ const scratch = mkdtempSync(join(tmpdir(), "upload-"));+ try {+ writeFileSync(join(scratch, "a.txt"), "hello");+ const paths = await host.uploadPaths([{ file: join(scratch, "a.txt"), name: "notes.txt" }], browser.session, browser.spec);+ expect(paths).toEqual([expect.stringMatching(/^\/home\/user\/\.omb-browser\/\.uploads\/[a-f0-9]{16}\/notes\.txt$/)]);+ expect(fake.files.get(paths[0]!)?.toString()).toBe("hello");+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }expect(host.cloudBrowserBusy("browser")).toBe(true);expect(host.cloudBrowserBusy(botId)).toBe(false);expect(host.cloudBrowserReport()).toMatchObject({ sessions: { sandbox: 1, home: 0 } });diff --git a/server/host/browser.ts b/server/host/browser.tsindex fe4d08db50..b7e608c858 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -1,7 +1,7 @@// The bots' browser as the server hosts it: the engine's runtime and live view, which session a bot's browser is, and// the integration a turn mounts. browserEngine.engine picks agent-browser (the default) or the new Chrome engine; a// person's own Chrome (My Chrome) stays on agent-browser either way.-import { existsSync, readFileSync } from "node:fs";+import { existsSync, readFileSync, statSync } from "node:fs";import { join } from "node:path";import { setTimeout as sleep } from "node:timers/promises";@@ -61,7 +61,9 @@ import { createBrowserReclaim, reclaimable } from "./browser-reclaim.ts";import { createCloudBrowser, type HomeReason } from "../cloud-browser/index.ts";import { providerOps } from "../cloud-browser/remote.ts";import { boatAccount, boatConfigured } from "../boat.ts";-import { downloadNote, localSchemeRefusal } from "../cloud-browser/guards.ts";+import { localSchemeRefusal } from "../cloud-browser/guards.ts";+import { readSignIns, writeSignIns } from "../browser-sites.ts";+import { browserSessionsDirectory } from "../browser-engine.ts";import { BrowserUploadRefusal } from "../browser-upload.ts";import { BROWSER_TASKS, processBudget } from "../process-room.ts";import { idleAfter } from "../drivers/session-idle.ts";@@ -108,7 +110,7 @@ export interface BrowserHostDeps {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 };+ cloudBrowser?: { used(owner: string, windowMs: number): void; folder?(botId: string): string | null };}/** The lent computer's connection for a browser's pages, under the rule for everything it lends: only while the last@@ -126,7 +128,6 @@ type Spec = { command: string; args?: readonly string[]; env: Record<string, strtype 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;@@ -255,7 +256,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {annotate: (spec, result) => passkeyAnnotation(chromeEngine.onPane(spec) ? "pane" : CLOUD_HOME ? "cloud" : DESKTOP_MANAGED ? "desktop" : "server")(spec, result),// agent-browser's own error names only the CDP connection; the door knows what went wrong on the way.afterCall: (session, spec, answer) => {- const result = cloudBrowser?.attached(session) ? downloadNote(withCeilingNote(session, answer)) : withCeilingNote(session, answer);+ const result = withSandboxNotes(session, withCeilingNote(session, answer));const failed = result as { isError?: unknown; content?: unknown };const found = failed?.isError === true && viaDoor(session, spec) ? doors?.problem(session) : null;// A door refused under an earlier holder says nothing about a caller that may use it.@@ -285,7 +286,16 @@ export function createBrowserHost(deps: BrowserHostDeps) {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}`),+ 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: {+ load: (session) => readSignIns(sessionsDirectory(session), session, browserEngineEncryptionKey()),+ save: (session, cookies) => writeSignIns(sessionsDirectory(session), session, browserEngineEncryptionKey(), cookies),+ },}) : null;+ function sessionsDirectory(session: string): string {+ return browserSessionsDirectory(browserRuntimeEnv({ ...usedBrowserSessions.get(session)?.env, AGENT_BROWSER_SESSION: session }));+ }/** 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> {@@ -405,6 +415,13 @@ export function createBrowserHost(deps: BrowserHostDeps) {const spec = usedBrowserSessions.get(session);return spec ? inRunningBrowser(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session }), args).catch(() => null) : Promise.resolve(null);}+ /** What the browser sandbox has to say since the last call (downloads that arrived, or could not), added to this one. */+ function withSandboxNotes(session: string, result: unknown): unknown {+ const notes = cloudBrowser?.takeNotes(session) ?? [];+ const content = (result as { content?: unknown } | null)?.content;+ if (!notes.length || !Array.isArray(content)) return result;+ return { ...(result as object), content: [...content, ...notes.map((text) => ({ type: "text", text }))] };+ }/** The ceiling's word on what it closed, added to the bot's next call in that browser. */function withCeilingNote(session: string, result: unknown): unknown {const content = (result as { content?: unknown } | null)?.content;@@ -762,8 +779,18 @@ export function createBrowserHost(deps: BrowserHostDeps) {return (await Promise.all(requests.map((request) => eraseOneBrowser(request)))).every(Boolean);}/** Chrome receives private copies; a boxed agent-browser reads them from its own profile's folder. */+ /** In the Cloud's browser sandbox, each file goes there first and the page gets its path there. */+ async function sandboxUploadPaths(files: ReadonlyArray<{ file: string; name: string | null }>, session: string): Promise<string[]> {+ const paths: string[] = [];+ for (const { file, name } of files) {+ const given = await cloudBrowser!.upload(session, file, name, statSync(file).size);+ if ("error" in given) throw new BrowserUploadRefusal(given.error);+ paths.push(given.path);+ }+ return paths;+ }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));+ if (cloudBrowser?.attached(session)) return sandboxUploadPaths(files, session);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) });diff --git a/server/index.ts b/server/index.tsindex dc16decefc..bcbd9b6d19 100644--- a/server/index.ts+++ b/server/index.ts@@ -2353,7 +2353,7 @@ 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, 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 });+} = createBrowserHost({ cloudBrowser: CLOUD_PERSONAL ? { used: (owner, windowMs) => cloudComputerPower.used(owner, windowMs), folder: (botId) => { const bot = store.bot(botId); return bot ? bot.cwd || workspaceDir(bot.id) : null; } } : 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 }),