Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Browser memory: fewer renderer processes per bot browser, and a ceiling on Linux servers (#6902)
Milind Soni399d6da901d9
diff --git a/server/browser-engine.test.ts b/server/browser-engine.test.tsindex 0ad095d3cc..9c067db5c1 100644--- a/server/browser-engine.test.ts+++ b/server/browser-engine.test.ts@@ -30,6 +30,7 @@ import {installAgentBrowserBinary,isMusl,isTemporaryBrowserSession,+ NO_BACK_FORWARD_CACHE,pinnedBinaryPath,prepareBrowserSessionState,resolveAgentBrowserBinary,@@ -931,7 +932,7 @@ describe("what a bot gets", () => {/** A saved session's browser: its own kept profile, behind no gate. */const keptNoGate = (session: string) => ({AGENT_BROWSER_PROXY: "socks5://127.0.0.1:0", AGENT_BROWSER_PROXY_BYPASS: "<-loopback>",- AGENT_BROWSER_PROFILE: browserProfileDirectory(session), AGENT_BROWSER_ARGS: [cacheArg, ...gateArgs].join("\n"),+ AGENT_BROWSER_PROFILE: browserProfileDirectory(session), AGENT_BROWSER_ARGS: [NO_BACK_FORWARD_CACHE, cacheArg, ...gateArgs].join("\n"),});it("gives each saved session a profile of its own that outlives Chrome, and a temporary or My Chrome browser none", () => {@@ -971,7 +972,7 @@ describe("what a bot gets", () => {it("launches Chrome only behind its egress gate, off the person's keychain, and never for the person's own Chrome", () => {const gated = agentBrowserIntegration({ binaryPath: "/x/agent-browser", session: "bot-1", encryptionKey: "k", env: { PATH: "/usr/bin" }, egressPort: 45123, platform: "darwin" });expect(gated.env).toMatchObject({ AGENT_BROWSER_PROXY: "socks5://127.0.0.1:45123", AGENT_BROWSER_PROXY_BYPASS: "<-loopback>" });- expect(gated.env.AGENT_BROWSER_ARGS!.split("\n")).toEqual([cacheArg, "--webrtc-ip-handling-policy=disable_non_proxied_udp", "--force-webrtc-ip-handling-policy=disable_non_proxied_udp", "--use-mock-keychain"]);+ expect(gated.env.AGENT_BROWSER_ARGS!.split("\n")).toEqual([NO_BACK_FORWARD_CACHE, cacheArg, "--webrtc-ip-handling-policy=disable_non_proxied_udp", "--force-webrtc-ip-handling-policy=disable_non_proxied_udp", "--use-mock-keychain"]);expect(agentBrowserIntegration({ binaryPath: "/x", session: "bot-1", encryptionKey: "k", env: {}, egressPort: 45123, platform: "linux" }).env.AGENT_BROWSER_ARGS).toContain("--password-store=basic");expect(agentBrowserIntegration({ binaryPath: "/x", session: "bot-1", encryptionKey: "k", env: {} }).env.AGENT_BROWSER_PROXY).toBe("socks5://127.0.0.1:0");const mine = agentBrowserIntegration({ binaryPath: "/x", session: "work", encryptionKey: "k", env: {}, attach: {}, egressPort: 45123 });@@ -988,7 +989,7 @@ describe("what a bot gets", () => {launcher: { ...launcher, AGENT_BROWSER_PROXY: "direct://", AGENT_BROWSER_PROXY_BYPASS: "*", AGENT_BROWSER_ARGS: "--lang=en-IN" },});expect(pushy.env).toMatchObject({ AGENT_BROWSER_EXECUTABLE_PATH: "/d/chrome-launcher.sh", ...gate });- expect(pushy.env.AGENT_BROWSER_ARGS!.split("\n")).toEqual(["--lang=en-IN", cacheArg, "--webrtc-ip-handling-policy=disable_non_proxied_udp", "--force-webrtc-ip-handling-policy=disable_non_proxied_udp", "--use-mock-keychain"]);+ expect(pushy.env.AGENT_BROWSER_ARGS!.split("\n")).toEqual(["--lang=en-IN", NO_BACK_FORWARD_CACHE, cacheArg, "--webrtc-ip-handling-policy=disable_non_proxied_udp", "--force-webrtc-ip-handling-policy=disable_non_proxied_udp", "--use-mock-keychain"]);});it("forwards the explicit Chrome path without copying arbitrary environment or overriding session isolation", () => {diff --git a/server/browser-engine.ts b/server/browser-engine.tsindex 248d6708a3..be955aa021 100644--- a/server/browser-engine.ts+++ b/server/browser-engine.ts@@ -562,6 +562,7 @@ export function browserEngineStatus(options: BrowserLookupOptions = {}): Browser}const PROFILE_CACHE_ARG = `--disk-cache-size=${64 * 1024 * 1024}`;+export const NO_BACK_FORWARD_CACHE = "--disable-back-forward-cache";/** agent-browser 0.37 relaunches a running Chrome without a word when a command's launch settings differ, so every* command for a session must carry these same ones. Chrome fails every connection through port 0. */@@ -635,7 +636,8 @@ export function agentBrowserIntegration(input: {}// The gate goes last, so nothing the launcher sets can route Chrome around it; launcher arguments are kept beside its own.if (!input.attach) {- const launch = { ...env, ...input.launcher };+ // Chrome keeps up to six pages a tab left alive for Back, each cross-site one in a renderer process of its own.+ const launch = { ...env, ...input.launcher, AGENT_BROWSER_ARGS: [input.launcher?.AGENT_BROWSER_ARGS, NO_BACK_FORWARD_CACHE].filter(Boolean).join("\n") };// A kept profile's disk cache would otherwise grow to Chrome's default of several hundred megabytes per profile.if (env.AGENT_BROWSER_PROFILE) launch.AGENT_BROWSER_ARGS = [launch.AGENT_BROWSER_ARGS, PROFILE_CACHE_ARG].filter(Boolean).join("\n");// agent-browser 0.37 adds this itself only where it recognises Docker, and a container platform leaves no such mark.diff --git a/server/browser/chrome/wrapper.test.ts b/server/browser/chrome/wrapper.test.tsindex cdcc524bdb..7d641dad7f 100644--- a/server/browser/chrome/wrapper.test.ts+++ b/server/browser/chrome/wrapper.test.ts@@ -5,7 +5,7 @@ import { join } from "node:path";import { afterAll, describe, expect, it } from "vitest";import { removeTempDir } from "../../testing/cleanup.ts";-import { batchQuote, browserLanguage, browserTimeZone, languageList, launcherFlags, launcherPath, launcherScript, primaryScreen, writeLauncher, type LauncherSettings } from "./wrapper.ts";+import { batchQuote, browserLanguage, browserTimeZone, HEADLESS_DISABLED_FEATURES, languageList, launcherFlags, launcherPath, launcherScript, primaryScreen, writeLauncher, type LauncherSettings } from "./wrapper.ts";const UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/153.0.0.0 Safari/537.36";const posix = process.platform !== "win32";@@ -44,10 +44,16 @@ describe("the launcher agent-browser runs instead of Chrome", () => {const out = join(folder, "argv");execFileSync(path, ENGINE_ARGS, { env: { PATH: "/usr/bin:/bin", ARGV_OUT: out, HOME: join(folder, "temporary-home") } });const argv = readFileSync(out, "utf8").split("\0").slice(0, -1);- expect(argv).toEqual([...ENGINE_ARGS, ...launcherFlags(settings, "darwin")]);+ expect(argv).toEqual([...ENGINE_ARGS, ...launcherFlags(settings, "darwin"), HEADLESS_DISABLED_FEATURES]);expect(argv).toContain(`--user-agent=${UA}`);+ // Chrome keeps the last --disable-features, so the engine's own Translate stays off.+ expect(argv.filter((arg) => arg.startsWith("--disable-features=")).at(-1)).toBe("--disable-features=Translate,WebUIOmniboxPopup,WebUIOmniboxAimPopup,WebUIReloadButton");expect(readFileSync(`${out}.tz`, "utf8")).toBe("America/New_York");expect(readFileSync(`${out}.home`, "utf8")).toBe("/Users/ada");+ // A browser with a window keeps Chrome's own features: its omnibox and reload button are seen.+ const headed = ENGINE_ARGS.filter((arg) => !arg.startsWith("--headless"));+ execFileSync(path, headed, { env: { PATH: "/usr/bin:/bin", ARGV_OUT: out, HOME: join(folder, "temporary-home") } });+ expect(readFileSync(out, "utf8").split("\0").slice(0, -1)).toEqual([...headed, ...launcherFlags(settings, "darwin")]);});it("writes a shell script that execs Chrome, so agent-browser keeps Chrome's own pid and process group", () => {@@ -56,7 +62,9 @@ describe("the launcher agent-browser runs instead of Chrome", () => {"#!/bin/sh","TZ='Asia/Kolkata'","export TZ",- `exec '/opt/it'\\''s/chrome' "$@" '--disable-blink-features=AutomationControlled' '--user-agent=${UA}' '--screen-info={1512x982}' '--lang=en-IN' '--password-store=basic'`,+ "headless=",+ `for arg in "$@"; do case "$arg" in --headless|--headless=*) headless='${HEADLESS_DISABLED_FEATURES}' ;; esac; done`,+ `exec '/opt/it'\\''s/chrome' "$@" '--disable-blink-features=AutomationControlled' '--user-agent=${UA}' '--screen-info={1512x982}' '--lang=en-IN' '--password-store=basic' $headless`,"",]);});@@ -93,7 +101,7 @@ describe("the launcher of a Team Cloud's boxed browsers", () => {const engine = ["--remote-debugging-port=0", "--headless=new", `--user-data-dir=${profile}`, "--x=it's $HOME"];execFileSync(path, engine, { env: { PATH: "/usr/bin:/bin", ARGV_OUT: out } });const argv = readFileSync(out, "utf8").split("\0").slice(0, -1);- expect(argv).toEqual(["--unshare-user", "--seccomp", "9", "--ro-bind", "/usr", "/usr", "--bind", profile, profile, "--setenv", "HOME", "/tmp", "--", "/opt/chrome/chrome", ...engine, ...launcherFlags(settings, "linux")]);+ expect(argv).toEqual(["--unshare-user", "--seccomp", "9", "--ro-bind", "/usr", "/usr", "--bind", profile, profile, "--setenv", "HOME", "/tmp", "--", "/opt/chrome/chrome", ...engine, ...launcherFlags(settings, "linux"), HEADLESS_DISABLED_FEATURES]);expect(statSync(profile).isDirectory(), "the profile exists before bubblewrap binds it").toBe(true);expect(readFileSync(`${out}.fd9`, "utf8")).toBe("FILTER");// bubblewrap's --die-with-parent follows the thread that started it; the launcher, not agent-browser's thread, is its parent.diff --git a/server/browser/chrome/wrapper.ts b/server/browser/chrome/wrapper.tsindex c0e3b97d09..4967eb363f 100644--- a/server/browser/chrome/wrapper.ts+++ b/server/browser/chrome/wrapper.ts@@ -34,6 +34,11 @@ export interface LauncherBox {/** agent-browser hands Chrome only stdio (it speaks to it over a port), so 9 is free for the filter. */export const LAUNCHER_SECCOMP_FD = 9;+/** Headless Chrome 152–156 still keeps a renderer for its WebUI omnibox popups and reload button, which it never shows.+ * agent-browser 0.37 passes --disable-features=Translate and Chrome keeps only the last value of a switch, so Translate+ * stays in the list; agent-browser splits AGENT_BROWSER_ARGS at commas, so only the launcher can pass a list. */+export const HEADLESS_DISABLED_FEATURES = "--disable-features=Translate,WebUIOmniboxPopup,WebUIOmniboxAimPopup,WebUIReloadButton";+/** Last on the command line, so they win over any switch of the same name: Chrome keeps the last value of a switch. A bot's* Chrome never touches the person's keychain or keyring (agent-browser 0.37 passes these too). */export function launcherFlags(settings: LauncherSettings, platform: NodeJS.Platform = process.platform): string[] {@@ -66,11 +71,14 @@ export function launcherScript(settings: LauncherSettings, platform: NodeJS.Platif (platform === "win32") {return ["@echo off", `${batchQuote(settings.chrome)} %* ${flags.map(batchQuote).join(" ")}`, ""].join("\r\n");}- const chrome = `${shellQuote(settings.chrome)} "$@" ${flags.map(shellQuote).join(" ")}`;+ // $headless holds one word without spaces or patterns, so it is expanded unquoted: nothing at all when Chrome has a window.+ const chrome = `${shellQuote(settings.chrome)} "$@" ${flags.map(shellQuote).join(" ")} $headless`;return ["#!/bin/sh",...(settings.home ? [`HOME=${shellQuote(settings.home)}`, "export HOME"] : []),...(settings.timeZone ? [`TZ=${shellQuote(settings.timeZone)}`, "export TZ"] : []),+ "headless=",+ `for arg in "$@"; do case "$arg" in --headless|--headless=*) headless=${shellQuote(HEADLESS_DISABLED_FEATURES)} ;; esac; done`,...(settings.box ? boxedLaunch(settings.box, chrome) : [`exec ${chrome}`]),"",].join("\n");diff --git a/server/browser/memory-ceiling.test.ts b/server/browser/memory-ceiling.test.tsnew file mode 100644index 0000000000..78feafe653--- /dev/null+++ b/server/browser/memory-ceiling.test.ts@@ -0,0 +1,109 @@+import { describe, expect, it } from "vitest";++import { ceilingLines, createBrowserCeiling, type BrowserCeilingDeps, type CeilingTab } from "./memory-ceiling.ts";++const MB = 1_048_576;++function harness(options: { sizes?: Record<number, number | null>; quiet?: boolean; tabs?: CeilingTab[] | null; closes?: boolean } = {}) {+ const sizes: Record<number, number | null> = options.sizes ?? { 10: 300 * MB, 11: 500 * MB };+ const state = { now: 0, quiet: options.quiet ?? true, tabs: options.tabs === undefined ? [+ { tabId: "t1", title: "Inbox", url: "https://mail.example/", active: false },+ { tabId: "t2", title: "Report", url: "https://example.com/report", active: true },+ { tabId: "t3", title: "", url: "https://news.example/a", active: false },+ ] : options.tabs };+ const closedTabs: string[] = [], closed: string[] = [], logs: string[] = [];+ const deps: BrowserCeilingDeps = {+ lines: { softBytes: 700 * MB, hardBytes: 1000 * MB },+ browsers: async () => [{ session: "bot-a", pids: Object.keys(sizes).map(Number) }],+ pss: (pid) => sizes[pid] ?? null,+ quiet: () => state.quiet,+ tabs: async () => state.tabs,+ closeTab: async (_session, tabId) => { closedTabs.push(tabId); return true; },+ close: async (session) => { closed.push(session); return options.closes ?? true; },+ log: (line) => logs.push(line),+ now: () => state.now,+ };+ return { ceiling: createBrowserCeiling(deps), state, sizes, closedTabs, closed, logs };+}++describe("a bot browser's memory ceiling", () => {+ it("is a share of the server's memory, never below a browser on one page", () => {+ expect(ceilingLines(2048 * MB)).toEqual({ softBytes: Math.round(2048 * MB / 3), hardBytes: 1024 * MB });+ expect(ceilingLines(8192 * MB)).toEqual({ softBytes: Math.round(8192 * MB / 3), hardBytes: 4096 * MB });+ expect(ceilingLines(1024 * MB)).toEqual({ softBytes: 600 * MB, hardBytes: 900 * MB });+ });++ it("leaves a browser under its soft line alone", async () => {+ const run = harness({ sizes: { 10: 300 * MB, 11: 300 * MB } });+ await run.ceiling.tick();+ expect(run.closedTabs).toEqual([]);+ expect(run.closed).toEqual([]);+ expect(run.ceiling.takeNote("bot-a")).toBeNull();+ });++ it("over its soft line closes only background tabs, between calls, and tells the bot once which", async () => {+ const run = harness();+ await run.ceiling.tick();+ expect(run.closedTabs).toEqual(["t1", "t3"]);+ expect(run.closed).toEqual([]);+ const note = run.ceiling.takeNote("bot-a")!;+ expect(note).toContain("800 MB");+ expect(note).toContain("Inbox (https://mail.example/)");+ expect(note).toContain("https://news.example/a");+ expect(note).not.toContain("Report");+ expect(note).toContain("take a new snapshot");+ expect(run.ceiling.takeNote("bot-a")).toBeNull();+ });++ it("waits while a call runs or a person holds the browser", async () => {+ const run = harness({ quiet: false });+ await run.ceiling.tick();+ expect(run.closedTabs).toEqual([]);+ run.state.quiet = true;+ await run.ceiling.tick();+ expect(run.closedTabs).toEqual(["t1", "t3"]);+ });++ it("acts on one browser at most once a minute", async () => {+ const run = harness();+ await run.ceiling.tick();+ run.closedTabs.length = 0;+ run.state.now = 30_000;+ await run.ceiling.tick();+ expect(run.closedTabs).toEqual([]);+ run.state.now = 61_000;+ await run.ceiling.tick();+ expect(run.closedTabs).toEqual(["t1", "t3"]);+ });++ it("over its hard line with no background tab to close, asks memory relief's close and logs what it kept", async () => {+ const run = harness({ sizes: { 10: 600 * MB, 11: 500 * MB }, tabs: [{ tabId: "t2", title: "Only", url: "https://example.com/", active: true }] });+ await run.ceiling.tick();+ expect(run.closed).toEqual(["bot-a"]);+ expect(run.logs.at(-1)).toMatch(/1100 MB, over its hard line of 1000 MB; closed it/u);+ const kept = harness({ sizes: { 10: 600 * MB, 11: 500 * MB }, tabs: [], closes: false });+ await kept.ceiling.tick();+ expect(kept.logs.at(-1)).toMatch(/kept open/u);+ });++ it("over its hard line closes background tabs first, and the browser only on a later look", async () => {+ const run = harness({ sizes: { 10: 600 * MB, 11: 500 * MB } });+ await run.ceiling.tick();+ expect(run.closedTabs).toEqual(["t1", "t3"]);+ expect(run.closed).toEqual([]);+ run.state.tabs = [{ tabId: "t2", title: "Report", url: "https://example.com/report", active: true }];+ run.state.now = 61_000;+ await run.ceiling.tick();+ expect(run.closed).toEqual(["bot-a"]);+ });++ it("measures nothing it cannot read, and survives a browser whose tabs do not answer", async () => {+ const unread = harness({ sizes: { 10: null } });+ await unread.ceiling.tick();+ expect(unread.closedTabs).toEqual([]);+ const silent = harness({ tabs: null });+ await silent.ceiling.tick();+ expect(silent.closedTabs).toEqual([]);+ expect(silent.ceiling.takeNote("bot-a")).toBeNull();+ });+});diff --git a/server/browser/memory-ceiling.ts b/server/browser/memory-ceiling.tsnew file mode 100644index 0000000000..b369c3caa5--- /dev/null+++ b/server/browser/memory-ceiling.ts@@ -0,0 +1,116 @@+// One bot browser never takes a Linux server's memory. Each running browser (agent-browser's daemon and its Chrome) is+// measured by proportional set size, shared pages counted once: a sum of RSS over Chrome's 10 to 30 processes counts+// the browser binary's pages in every one of them. Over its soft line, between calls, its background tabs close and the+// bot hears which on its next call. Over its hard line it is closed only through memory relief's own close, which keeps+// a browser a turn holds, one a call runs in, and one attached to the person's own Chrome.++const MB = 1_048_576;+export const CEILING_TICK_MS = 15_000;+/** A browser's tabs are closed at most this often, and a refused close is logged at most this often. */+const ACT_EVERY_MS = 60_000;++export interface CeilingLines { softBytes: number; hardBytes: number }++/** A third of the memory (at least 600 MB) and half of it (at least 900 MB): a 2 GB home's are 683 and 1024 MB. */+export function ceilingLines(memoryBytes: number): CeilingLines {+ return { softBytes: Math.max(600 * MB, Math.round(memoryBytes / 3)), hardBytes: Math.max(900 * MB, Math.round(memoryBytes / 2)) };+}++export interface CeilingBrowser { session: string; pids: readonly number[] }+export interface CeilingTab { tabId: string; title: string; url: string; active: boolean }++export interface BrowserCeilingDeps {+ lines: CeilingLines;+ /** Running browsers this server started, never one attached to the person's own Chrome, each with its process tree. */+ browsers(): Promise<CeilingBrowser[]>;+ pss(pid: number): number | null;+ /** No call runs in it and no person holds it, so its tabs may change now. */+ quiet(session: string): boolean;+ tabs(session: string): Promise<CeilingTab[] | null>;+ closeTab(session: string, tabId: string): Promise<boolean>;+ /** Memory relief's close; false when its rules keep the browser open. */+ close(session: string): Promise<boolean>;+ log?(line: string): void;+ now?(): number;+}++const mb = (bytes: number) => Math.round(bytes / MB);++function page(tab: CeilingTab): string {+ const title = tab.title.trim().slice(0, 80);+ return title ? `${title} (${tab.url})` : tab.url;+}++export function tabsClosedNote(usedBytes: number, closed: readonly CeilingTab[]): string {+ return `This browser was using ${mb(usedBytes)} MB of this computer's memory, so its other tabs were closed to keep everything else running: ${closed.map(page).join("; ")}. Open one again if you still need it. Earlier @eN refs are gone: take a new snapshot before acting.`;+}++export function createBrowserCeiling(deps: BrowserCeilingDeps) {+ const now = deps.now ?? Date.now;+ const log = deps.log ?? ((line: string) => console.warn(line));+ const notes = new Map<string, string>();+ const acted = new Map<string, number>();+ let running = false;++ function size(browser: CeilingBrowser): number | null {+ let total = 0, read = 0;+ for (const pid of browser.pids) {+ const bytes = deps.pss(pid);+ if (bytes === null) continue;+ total += bytes; read += 1;+ }+ return read ? total : null;+ }++ async function closeBackgroundTabs(session: string, used: number): Promise<boolean> {+ const tabs = await deps.tabs(session).catch(() => null);+ const background = tabs?.filter((tab) => !tab.active) ?? [];+ if (!tabs?.some((tab) => tab.active) || !background.length) return false;+ const closed: CeilingTab[] = [];+ for (const tab of background) {+ if (!deps.quiet(session)) break;+ if (await deps.closeTab(session, tab.tabId).catch(() => false)) closed.push(tab);+ }+ if (!closed.length) return false;+ notes.set(session, tabsClosedNote(used, closed));+ log(`browser ${session}: ${mb(used)} MB, over its soft line of ${mb(deps.lines.softBytes)} MB; closed ${closed.length} background tab(s)`);+ return true;+ }++ async function check(browser: CeilingBrowser): Promise<void> {+ const used = size(browser);+ const { session } = browser;+ if (used === null || used < deps.lines.softBytes) return;+ const at = now();+ if (at - (acted.get(session) ?? -Infinity) < ACT_EVERY_MS) return;+ if (used < deps.lines.hardBytes) {+ if (deps.quiet(session) && await closeBackgroundTabs(session, used)) acted.set(session, at);+ return;+ }+ acted.set(session, at);+ if (deps.quiet(session) && await closeBackgroundTabs(session, used)) return;+ if (await deps.close(session).catch(() => false)) log(`browser ${session}: ${mb(used)} MB, over its hard line of ${mb(deps.lines.hardBytes)} MB; closed it`);+ else log(`browser ${session}: ${mb(used)} MB, over its hard line of ${mb(deps.lines.hardBytes)} MB; kept open, a turn or a person is using it`);+ }++ return {+ async tick(): Promise<void> {+ if (running) return;+ running = true;+ try {+ const browsers = await deps.browsers();+ const live = new Set(browsers.map((browser) => browser.session));+ for (const session of acted.keys()) if (!live.has(session)) acted.delete(session);+ for (const browser of browsers) await check(browser).catch(() => undefined);+ } finally { running = false; }+ },+ /** What the bot is told on its next call in this browser, once. */+ takeNote(session: string): string | null {+ const note = notes.get(session) ?? null;+ notes.delete(session);+ return note;+ },+ };+}++export type BrowserCeiling = ReturnType<typeof createBrowserCeiling>;diff --git a/server/host/browser.ts b/server/host/browser.tsindex abc0bf5ee1..fc85cbe23a 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -42,12 +42,16 @@ import type { HostKind } from "../browser/chrome/flags.ts";import { browserEngineKind, type BrowserEngineKind } from "../browser/config.ts";import { parseSocks5Proxy } from "../browser/egress/policy.ts";import { ChromeEngine, chromeTarget, LiveRouter, profileKey, RuntimeRouter } from "../browser/engines.ts";+import { CEILING_TICK_MS, ceilingLines, createBrowserCeiling } from "../browser/memory-ceiling.ts";+import { browserProcessTree } from "../browser-processes.ts";+import { pssBytes } from "../bot-memory-cap.ts";+import { boxMemory } from "../box-memory.ts";import { CHROME_BROWSER_SYSTEM_PROMPT } from "../browser/prompt.ts";import { passkeyAnnotation } from "../browser/passkey-notice.ts";import { LentChromeDoors, lentChromeGuidance, type ChromeLender } from "../browser/lent-chrome.ts";import type { ChromeRoute } from "../device-links.ts";import type { EngineBrowsers } from "../engine-memory.ts";-import { createBrowserReclaim } from "./browser-reclaim.ts";+import { createBrowserReclaim, reclaimable } from "./browser-reclaim.ts";import { BROWSER_TASKS, processBudget } from "../process-room.ts";import { idleAfter } from "../drivers/session-idle.ts";import { augmentedPath } from "../env-path.ts";@@ -230,7 +234,8 @@ export function createBrowserHost(deps: BrowserHostDeps) {},annotate: passkeyAnnotation(CLOUD_HOME ? "cloud" : DESKTOP_MANAGED ? "desktop" : "server"),// agent-browser's own error names only the CDP connection; the door knows what went wrong on the way.- afterCall: (session, spec, result) => {+ afterCall: (session, spec, answer) => {+ const result = 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.@@ -280,22 +285,66 @@ export function createBrowserHost(deps: BrowserHostDeps) {running: (session) => browserRunning(session, usedBrowserSessions.get(session)),inUse: (session) => !turnResources.free(`browser:${session}`) || agentBrowserRuntime.working(session) });let gateTimer: ReturnType<typeof setInterval> | undefined;+ let ceilingTimer: ReturnType<typeof setInterval> | undefined;const browserSweep = {start() {gateTimer = setInterval(() => void releaseGates().catch(() => undefined), 60_000);gateTimer.unref?.();+ if (browserCeiling) {+ ceilingTimer = setInterval(() => void browserCeiling.tick().catch(() => undefined), CEILING_TICK_MS);+ ceilingTimer.unref?.();+ }agentBrowserSweep.start();chromeEngine.start({ inUse: browserEngineKind(cfg) === "chrome", prepare: builtInBrowserEnabled(cfg) });return browserSweep;},closeAll: () => {clearInterval(gateTimer);+ clearInterval(ceilingTimer);doors?.close();doorUrls.clear();leftovers.clear();return agentBrowserSweep.closeAll();},};+ // Linux servers only: there a browser's proportional size can be read, and its memory is the home's.+ const browserCeiling = process.platform === "linux" && !DESKTOP_MANAGED ? createBrowserCeiling({+ lines: ceilingLines(boxMemory().bytes),+ browsers: async () => (await Promise.all(browserOwners().map(async ({ pid, session }) => {+ const spec = usedBrowserSessions.get(session);+ const tree = spec ? await browserProcessTree(spec.command, pid, session) : null;+ return tree ? [{ session, pids: [...tree.members.keys()] }] : [];+ }))).flat(),+ pss: (pid) => pssBytes(pid),+ quiet: (session) => !agentBrowserRuntime.working(session),+ tabs: async (session) => {+ const tabs = (await inRunningSession(session, ["tab", "list"]))?.tabs;+ return Array.isArray(tabs) ? tabs.flatMap((tab: { tabId?: unknown; title?: unknown; url?: unknown; active?: unknown }) =>+ typeof tab.tabId === "string" ? [{ tabId: tab.tabId, title: String(tab.title ?? ""), url: String(tab.url ?? ""), active: tab.active === true }] : []) : null;+ },+ closeTab: async (session, tabId) => (await inRunningSession(session, ["tab", "close", tabId])) !== null,+ // Memory relief's rules under ordinary shortage; which bots have a turn running is not known here.+ close: async (session) => {+ const spec = usedBrowserSessions.get(session);+ if (!spec) return false;+ const working = agentBrowserRuntime.working(session), spare = agentBrowserRuntime.spare(session);+ const candidate = { session, held: !turnResources.free(`browser:${session}`), working, running: browserRunning(session, spec),+ attached: Boolean(chromeTarget(session, spec)) || attachesToChrome(spec.env), watched: spare === null && !working, turnRunning: false,+ savesSignIns: spare?.savesSignIns ?? spec.env.AGENT_BROWSER_RESTORE_SAVE === "auto" };+ return reclaimable(candidate, false) && browserRuntime.closeUnused(session, spec);+ },+ }) : null;+ function inRunningSession(session: string, args: string[]): Promise<Record<string, unknown> | null> {+ const spec = usedBrowserSessions.get(session);+ return spec ? inRunningBrowser(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session }), args).catch(() => null) : Promise.resolve(null);+ }+ /** 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;+ const note = Array.isArray(content) ? browserCeiling?.takeNote(session) : null;+ if (!note || !Array.isArray(content)) return result;+ return { ...(result as object), content: [...content, { type: "text", text: note }] };+ }// The viewer and the agent must address the SAME temporary browser.const temporaryBrowserSessions = new Map<string, string>();/** The suffix an audience gives a browser's name, remembered so a deletion erases every audience's browser. */