Skip to content

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

Idle engines close sooner under pressure; a memory cap per bot

milind-soni0c885a280732
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 9415fac6a0..176c37de75 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -589,6 +589,27 @@ once as "shared", never against any one bot. The report shows the ten bots
using the most memory; `GET /api/diagnostics/bots` (admin only) lists every
bot. Bot ids and numbers only.
+**Idle engines close sooner when room runs short.** A conversation's engine
+stays loaded after its turn (10 minutes by default, `OMB_SESSION_IDLE_MS`;
+30 seconds for work nobody is watching), a bot's browser stays open for its
+idle time, and a process several bots share is recycled a minute after its
+last session. Where turns wait for room, each of these times shrinks as
+memory or the process limit fills, down to a tenth (never below its floor),
+and what is already loaded is looked at again every few seconds. Before a
+new turn or browser waits for room, the engine idle longest is closed.
+
+**One bot's memory.** Where turns wait for room, one bot may use at most
+twice its fair share of the server's memory (the memory over the turns that
+may run at once), at least 1,900 MB and at most 80% of it. A bot over that
+for two checks in a row (every 5 seconds), or 50% over it once, has its
+engine stopped and its own browser closed; its running turn ends with a line
+saying which bot used more memory than this server allows for one bot.
+Engines and browsers several bots share are never stopped this way. Set
+`OMB_BOT_MEMORY_MAX_MB` to a number of MB, or to `off`; the desktop app has
+no cap unless it is set. The server enforces the cap itself by reading its
+process list; it logs at start whether the host also offers a systemd scope
+or a delegated cgroup, which are not used yet.
+
**Bots' cloud computers do not count.** A bot's cloud computer runs at the
provider that hosts it, not in this container, so its desktop and browser
use none of the container's processes or memory. Only the built-in browser
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index e19ac6d987..0c146bb54e 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -11,7 +11,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_ACP_QUIET_TICK_MS", "OMB_ACP_SESSION_IDLE_", "OMB_ACP_SHARED_RECYCLE_MS", "OMB_ADMIN_", "OMB_ADMIN_MEMBERSHIP",
"OMB_ADMIN_URL", "OMB_ADMIN_WORKSPACE", "OMB_AGENT_BROWSER_PATH", "OMB_AI_CHECKS", "OMB_ANTHROPIC_API_KEY",
"OMB_ANTHROPIC_API_URL", "OMB_APP_VERSION", "OMB_ATTACHMENTS_MAX_BYTES", "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT",
- "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BOAT_API", "OMB_BOT_BOX", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
+ "OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BOAT_API", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
"OMB_BROWSER_CONNECTION", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL",
"OMB_BROWSER_MAX_RUNNING", "OMB_BROWSER_SANDBOX", "OMB_BROWSER_SCREEN", "OMB_BROWSER_TIMEZONE", "OMB_BROWSER_TIMING",
"OMB_BUG_REPORT_URL", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",
diff --git a/server/bot-memory-cap.ts b/server/bot-memory-cap.ts
new file mode 100644
index 0000000000..f7ee0888a4
--- /dev/null
+++ b/server/bot-memory-cap.ts
@@ -0,0 +1,285 @@
+// One bot may use only so much of the server's memory: past its cap, that bot's engine is stopped (its running turn ends
+// with a line saying why) and its browser closed, before it can take memory every other bot needs. The design's ladder
+// is a systemd scope, then a delegated cgroup v2, then this server's own watchdog, then nothing (the desktop). The kernel
+// rungs are probed and reported but not used yet: putting each bot's processes in a cgroup of its own needs the server
+// moved into a leaf of its own first, which nothing here has verified on a real host. The watchdog is what enforces the
+// cap: every few seconds it reads the process list (no spawn), sums each bot's processes as the per-bot footprint
+// attributes them (perf/bot-footprint.ts: never another bot's, never a shared process), checks a bot over its cap by
+// proportional set size (shared pages counted once), and stops that bot's processes once it stays over, or at once far
+// over. A process several bots share is never stopped.
+import { accessSync, constants, existsSync, readFileSync } from "node:fs";
+
+import { boxMemory } from "./box-memory.ts";
+import { noticeFailure } from "./chat-notices.ts";
+import { newEventId, type ProviderAdapter, type ProviderInstance, type RuntimeEvent } from "./contracts.ts";
+import { BROWSER_BYTES, ENGINE_DEFAULT_BYTES } from "./engine-memory.ts";
+import { attributeRows, type BotTally, type FootprintOwner } from "./perf/bot-footprint.ts";
+import type { ProcessRow } from "./perf/process-buckets.ts";
+import type { GateHost } from "./process-room.ts";
+
+export const BOT_MEMORY_ENV = "OMB_BOT_MEMORY_MAX_MB";
+const MB = 1_048_576;
+/** No cap is set below a busy engine at its largest (engine-memory's ENGINE_MAX_BYTES) with its browser open. */
+export const BOT_CAP_FLOOR_BYTES = 1500 * MB + BROWSER_BYTES;
+/** Nor above this share of the server's memory: one bot never takes most of it. */
+const CAP_SHARE = 0.8;
+/** The fair share of a bot is the memory over the turns that may run at once; one bot may use twice that. */
+const FAIR_SHARES = 2;
+/** An explicit cap below this is taken as this: an engine alone needs more. */
+const SMALLEST_CAP_BYTES = 256 * MB;
+export const WATCHDOG_MS = 5_000;
+/** Over its cap in this many reads in a row (a few seconds apart), or this far over in one, and a bot is stopped. */
+const STRIKES = 2, FAR_OVER = 1.5;
+const STOP_GRACE_MS = 3_000;
+/** A turn that fails this long after its bot was stopped for memory says so. */
+const EXPLAIN_FOR_MS = 60_000;
+
+export interface CapInputs {
+ /** Where turns wait for room (process-room.ts gateHost): a Cloud home or a self-hosted Linux server; null on the desktop. */
+ gate: GateHost;
+ /** The memory the server may use: its container's limit, else the machine's. */
+ memoryBytes: number;
+ /** The most turns that run at once, where known. */
+ turns?: number;
+}
+
+/** OMB_BOT_MEMORY_MAX_MB: a number of MB; "off" or 0 for no cap; unset or "auto" for the default, which is on wherever
+ * turns wait for room (never on the desktop): twice one bot's fair share of the memory (the memory over the turns that
+ * may run at once), at least an engine at its largest with its browser, at most 80% of the memory. */
+export function botMemoryCapBytes(env: NodeJS.ProcessEnv, inputs: CapInputs, warn: (line: string) => void = () => undefined): number | null {
+ const raw = env[BOT_MEMORY_ENV]?.trim().toLowerCase();
+ if (raw === "off" || raw === "0") return null;
+ if (raw && /^\d+$/.test(raw)) return Math.max(SMALLEST_CAP_BYTES, Number(raw) * MB);
+ if (raw && raw !== "auto") warn(`${BOT_MEMORY_ENV}=${JSON.stringify(env[BOT_MEMORY_ENV])} is not a number of MB, "auto" or "off", so the default is used`);
+ if (inputs.gate === null || !(inputs.memoryBytes > 0)) return null;
+ const turns = Math.max(1, inputs.turns ?? Math.floor(inputs.memoryBytes / ENGINE_DEFAULT_BYTES));
+ const fair = (FAIR_SHARES * inputs.memoryBytes) / turns;
+ return Math.round(Math.min(inputs.memoryBytes * CAP_SHARE, Math.max(BOT_CAP_FLOOR_BYTES, fair)));
+}
+
+export type CapRung = "systemd-scope" | "cgroup" | "watchdog" | "none";
+type Read = (path: string) => string | null;
+const readText: Read = (path) => { try { return readFileSync(path, "utf8"); } catch { return null; } };
+const writable = (path: string) => { try { accessSync(path, constants.W_OK); return true; } catch { return false; } };
+
+/** Which rungs of the ladder this host offers, best first, and the one in use (the watchdog wherever a cap is set and a
+ * process list can be read: Linux). */
+export function capLadder(capBytes: number | null, deps: { platform?: NodeJS.Platform; read?: Read; writable?: (path: string) => boolean; exists?: (path: string) => boolean } = {}): { rung: CapRung; offered: CapRung[] } {
+ const platform = deps.platform ?? process.platform, read = deps.read ?? readText, canWrite = deps.writable ?? writable, exists = deps.exists ?? existsSync;
+ if (platform !== "linux") return { rung: "none", offered: [] };
+ const offered: CapRung[] = [];
+ const own = /^0::(\/.*)$/m.exec(read("/proc/self/cgroup") ?? "")?.[1];
+ const dir = own === undefined ? null : `/sys/fs/cgroup${own === "/" ? "" : own}`;
+ const memory = dir !== null && /(^|\s)memory(\s|$)/.test(read(`${dir}/cgroup.controllers`) ?? "");
+ if (memory && exists("/run/systemd/system") && /\.(service|scope)$/.test(own ?? "")) offered.push("systemd-scope");
+ if (memory && dir !== null && canWrite(`${dir}/cgroup.subtree_control`) && canWrite(`${dir}/cgroup.procs`)) offered.push("cgroup");
+ offered.push("watchdog");
+ return { rung: capBytes === null ? "none" : "watchdog", offered };
+}
+
+/** A process's proportional set size from /proc/<pid>/smaps_rollup; null where it can't be read. */
+export function pssBytes(pid: number, read: Read = readText): number | null {
+ const found = /^Pss:\s+(\d+) kB$/m.exec(read(`/proc/${pid}/smaps_rollup`) ?? "");
+ return found ? Number(found[1]) * 1024 : null;
+}
+
+export interface CapStop { botId: string; at: number; usedBytes: number; capBytes: number; pids: number[] }
+
+export interface WatchdogOptions {
+ cap: () => number | null;
+ list: () => readonly ProcessRow[];
+ owners: () => readonly FootprintOwner[];
+ pss?: (pid: number) => number | null;
+ /** Closes the bot's browser the way an idle close does (its sign-ins saved); resolves once it is closed or given up. */
+ closeBrowsers?: (botId: string) => Promise<void>;
+ signal?: (pid: number, signal: NodeJS.Signals) => void;
+ /** What each pid's start is now (Linux's start tick), to signal only the process that was read. */
+ startOf?: (pid: number) => string | null;
+ log?: (line: string) => void;
+ now?: () => number;
+ intervalMs?: number;
+ graceMs?: number;
+}
+
+export class BotMemoryWatchdog {
+ readonly #options: WatchdogOptions;
+ readonly #strikes = new Map<string, number>();
+ readonly #stops = new Map<string, CapStop>();
+ /** Engine pids stopped, and when: a pid the system later gives to another engine is not one of them for long. */
+ readonly #stoppedPids = new Map<number, number>();
+ #stopping = new Set<string>();
+ #timer: ReturnType<typeof setInterval> | null = null;
+ #running = false;
+ #count = 0;
+
+ constructor(options: WatchdogOptions) { this.#options = options; }
+
+ start(): void {
+ if (this.#timer || this.#options.cap() === null) return;
+ this.#timer = setInterval(() => void this.check(), this.#options.intervalMs ?? WATCHDOG_MS);
+ this.#timer.unref?.();
+ }
+
+ stop(): void { if (this.#timer) clearInterval(this.#timer); this.#timer = null; }
+
+ /** One look at every bot; resolves with the bots stopped. */
+ async check(): Promise<CapStop[]> {
+ const cap = this.#options.cap();
+ if (cap === null || this.#running) return [];
+ this.#running = true;
+ try {
+ const rows = this.#options.list();
+ const starts = new Map(rows.map((row) => [row.pid, row.start]));
+ const { bots } = attributeRows(rows, this.#options.owners());
+ for (const id of this.#strikes.keys()) if (!bots.has(id)) this.#strikes.delete(id);
+ const over: Array<{ id: string; tally: BotTally; used: number }> = [];
+ for (const [id, tally] of bots) {
+ if (tally.rssBytes <= cap || this.#stopping.has(id)) { this.#strikes.delete(id); continue; }
+ // Resident pages count what several processes share once each; their proportional share counts it once.
+ const used = tally.pids.reduce((sum, pid) => sum + (this.#options.pss?.(pid) ?? rowRss(rows, pid)), 0);
+ if (used <= cap) { this.#strikes.delete(id); continue; }
+ const strikes = (this.#strikes.get(id) ?? 0) + 1;
+ this.#strikes.set(id, strikes);
+ if (strikes >= STRIKES || used >= cap * FAR_OVER) over.push({ id, tally, used });
+ }
+ return await Promise.all(over.map(({ id, tally, used }) => this.#stopBot(id, tally, used, cap, starts)));
+ } finally { this.#running = false; }
+ }
+
+ async #stopBot(botId: string, tally: BotTally, usedBytes: number, capBytes: number, starts: ReadonlyMap<number, string>): Promise<CapStop> {
+ const now = this.#options.now ?? Date.now, signal = this.#options.signal ?? ((pid, value) => process.kill(pid, value));
+ const startOf = this.#options.startOf ?? (() => null);
+ const stop: CapStop = { botId, at: now(), usedBytes, capBytes, pids: [...tally.pids] };
+ this.#stopping.add(botId);
+ this.#strikes.delete(botId);
+ this.#stops.set(botId, stop);
+ this.#count += 1;
+ const browser = new Set(tally.browserPids);
+ const engine = tally.pids.filter((pid) => !browser.has(pid));
+ for (const [pid, at] of this.#stoppedPids) if (stop.at - at > EXPLAIN_FOR_MS) this.#stoppedPids.delete(pid);
+ for (const pid of engine) this.#stoppedPids.set(pid, stop.at);
+ (this.#options.log ?? ((line) => console.warn(line)))(`memory: bot ${botId} used ${Math.round(usedBytes / MB)} MB, more than the ${Math.round(capBytes / MB)} MB this server allows one bot; stopping its engine (${engine.length} processes)${browser.size ? " and closing its browser" : ""}`);
+ // Only a process still the one that was read: a pid the system has given to another since is left alone.
+ const same = (pid: number) => { const start = startOf(pid); return start === null || start === starts.get(pid); };
+ const send = (pids: readonly number[], value: NodeJS.Signals) => { for (const pid of pids) if (same(pid)) try { signal(pid, value); } catch {} };
+ try {
+ send(engine, "SIGTERM");
+ const closing = browser.size ? this.#options.closeBrowsers?.(botId).catch(() => undefined) : undefined;
+ await new Promise((resolve) => { const timer = setTimeout(resolve, this.#options.graceMs ?? STOP_GRACE_MS); timer.unref?.(); });
+ send(engine, "SIGKILL");
+ await closing;
+ // A browser that would not close (a turn still held it after its engine was gone) goes as the engine did.
+ if (browser.size && !this.#options.closeBrowsers) send([...browser], "SIGKILL");
+ } finally { this.#stopping.delete(botId); }
+ return stop;
+ }
+
+ /** The last stop of this bot for memory, while a turn that failed because of it should say so. */
+ stopOf(botId: string, at: number = Date.now()): CapStop | null {
+ const stop = this.#stops.get(botId);
+ if (!stop) return null;
+ if (at - stop.at > EXPLAIN_FOR_MS) { this.#stops.delete(botId); return null; }
+ return stop;
+ }
+
+ /** Whether this engine process was stopped for its bot's memory: its driver does not start it again at once. */
+ stoppedPid(pid: number | undefined, at: number = Date.now()): boolean {
+ const when = pid === undefined ? undefined : this.#stoppedPids.get(pid);
+ return when !== undefined && at - when <= EXPLAIN_FOR_MS;
+ }
+
+ /** Bots stopped since the server started. */
+ stops(): number { return this.#count; }
+}
+
+const rowRss = (rows: readonly ProcessRow[], pid: number) => rows.find((row) => row.pid === pid)?.rssBytes ?? 0;
+
+/** The line a turn ends with when its bot was stopped for using more memory than one bot may. */
+export function capStopFailure(botName: string, stop: CapStop): ReturnType<typeof noticeFailure> {
+ return noticeFailure("chat.notice.botMemoryCap", { bot: botName, used: String(Math.round(stop.usedBytes / MB)), cap: String(Math.round(stop.capBytes / MB)) });
+}
+
+let watchdog: BotMemoryWatchdog | null = null;
+let nameOf: (botId: string) => string = (botId) => botId;
+
+/** The server's one watchdog, once started (host/bot-memory-cap-host.ts). */
+export function useBotMemoryWatchdog(dog: BotMemoryWatchdog | null, botName?: (botId: string) => string): void {
+ watchdog = dog;
+ if (botName) nameOf = botName;
+}
+
+/** Whether this engine (`pid`) was stopped for its bot's memory (session-idle.ts stoppedForRoom). */
+export const stoppedForBotMemory = (pid?: number): boolean => watchdog?.stoppedPid(pid) === true;
+
+/**
+ * Every engine's adapter: a turn of a bot the watchdog stopped for memory fails with that reason, never in silence or
+ * as the engine's own failure. The instance is changed in place, as withEngineMemory does.
+ */
+export function withBotMemoryCap(instance: ProviderInstance, dog: () => BotMemoryWatchdog | null = () => watchdog, name: (botId: string) => string = (botId) => nameOf(botId),
+ now: () => number = Date.now): ProviderInstance {
+ const adapter = instance.adapter;
+ const turns = new Map<string, { botId: string; at: number }>();
+ const explained = new Set<string>();
+ const stopFor = (threadId: string) => {
+ const turn = turns.get(threadId), stop = turn ? dog()?.stopOf(turn.botId, now()) ?? null : null;
+ return turn && stop && stop.at >= turn.at ? stop : null;
+ };
+ const present = (item: RuntimeEvent): RuntimeEvent[] => {
+ if (item.type !== "runtime.error" && item.type !== "turn.completed") return [item];
+ const stop = stopFor(item.threadId);
+ if (stop && item.type === "runtime.error" && !explained.has(item.threadId)) {
+ explained.add(item.threadId);
+ return [{ ...item, ...capStopFailure(name(stop.botId), stop) }];
+ }
+ if (stop && item.type === "turn.completed" && !item.ok && item.stopReason !== "interrupted" && !explained.has(item.threadId)) {
+ explained.add(item.threadId);
+ const failure = capStopFailure(name(stop.botId), stop);
+ return [{ eventId: newEventId(), provider: instance.driverKind, threadId: item.threadId, createdAt: new Date().toISOString(), turnId: item.turnId, type: "runtime.error", ...failure } as RuntimeEvent, item];
+ }
+ return [item];
+ };
+ adapter.onEvent((item) => {
+ if (item.type !== "turn.completed") return;
+ queueMicrotask(() => { turns.delete(item.threadId); explained.delete(item.threadId); });
+ });
+ (instance as { adapter: ProviderAdapter }).adapter = {
+ ...adapter,
+ onEvent: (listener) => adapter.onEvent((item) => { for (const shown of present(item)) listener(shown); }),
+ sendTurn: async (input) => {
+ if (input.botId) turns.set(input.threadId, { botId: input.botId, at: now() });
+ explained.delete(input.threadId);
+ return adapter.sendTurn(input);
+ },
+ };
+ return instance;
+}
+
+export interface CapReport { mb: number | null; rung: CapRung; offered: CapRung[]; stops: number }
+let report: () => CapReport = () => ({ mb: null, rung: "none", offered: [], stops: 0 });
+
+/** Starts the server's watchdog where a cap is set and a process list can be read (Linux): the cap is worked out again
+ * each look, as the most turns at once may change (a plan's limit arrives after start). */
+export function startBotMemoryCap(deps: {
+ gate: GateHost; turns: () => number | undefined; owners: () => readonly FootprintOwner[]; botName: (botId: string) => string;
+ closeBrowsers: (botId: string) => Promise<void>; list: () => readonly ProcessRow[]; startOf: (pid: number) => string | null;
+ env?: NodeJS.ProcessEnv; memoryBytes?: number; log?: (line: string) => void; platform?: NodeJS.Platform;
+}): BotMemoryWatchdog | null {
+ const env = deps.env ?? process.env, log = deps.log ?? ((line: string) => console.warn(line));
+ let warned = false;
+ const cap = () => botMemoryCapBytes(env, { gate: deps.gate, memoryBytes: deps.memoryBytes ?? boxMemory().bytes, ...(deps.turns() === undefined ? {} : { turns: deps.turns() }) },
+ (line) => { if (!warned) { warned = true; log(`memory: ${line}`); } });
+ const first = cap(), ladder = capLadder(first, { platform: deps.platform ?? process.platform });
+ const dog = ladder.rung === "watchdog" ? new BotMemoryWatchdog({ cap, list: deps.list, owners: deps.owners, pss: (pid) => pssBytes(pid), closeBrowsers: deps.closeBrowsers, startOf: deps.startOf, log }) : null;
+ report = () => ({ mb: dog ? Math.round((cap() ?? 0) / MB) || null : null, rung: dog ? ladder.rung : "none", offered: ladder.offered, stops: dog?.stops() ?? 0 });
+ useBotMemoryWatchdog(dog, deps.botName);
+ if (dog) {
+ dog.start();
+ const others = ladder.offered.filter((rung) => rung !== "watchdog");
+ log(`memory: one bot may use up to ${Math.round((first ?? 0) / MB)} MB (${env[BOT_MEMORY_ENV]?.trim() ? BOT_MEMORY_ENV : "the default for this server's memory and turns"}); `
+ + `this server checks every ${Math.round(WATCHDOG_MS / 1000)} s${others.length ? `; also offered here, not used yet: ${others.join(", ")}` : ""}`);
+ }
+ return dog;
+}
+
+/** The cap in force, how it is enforced and how often it stopped a bot: for the health report. */
+export const botMemoryCapReport = (): CapReport => report();
diff --git a/server/chat-notices.ts b/server/chat-notices.ts
index 14cce420b9..10ff0afbb3 100644
--- a/server/chat-notices.ts
+++ b/server/chat-notices.ts
@@ -150,6 +150,8 @@ export const CHAT_NOTICE = {
"chat.notice.computerAiUnsupported": "this bot's AI can't use this computer — pick another AI for this bot, or choose another place for it to work",
"chat.notice.memoryReclaimedBrowser": "Ran out of room, so I closed the browser to keep everything else running.",
"chat.notice.memoryReclaimedTask": "Ran out of room, so I stopped this task to keep everything else running.",
+ "chat.notice.botMemoryCap":
+ "{bot} used more memory than this server allows for one bot ({used} MB of {cap} MB), so I stopped this task to keep the other bots running. Send the message again to start over; if it keeps happening, give this task less to do at once, or give the server more memory.",
"chat.notice.memoryReclaimedBrowserDetail": "Ran out of room, so I closed the browser to keep everything else running. ({detail})",
"chat.notice.memoryReclaimedTaskDetail": "Ran out of room, so I stopped this task to keep everything else running. ({detail})",
"chat.notice.outOfProcesses": "There is no room to start another program ({code}), so this task could not run. Nothing was sent to the AI. It starts again by itself when there is room.",
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index ba995722ab..c5989d4a92 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -458,14 +458,14 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
for (const link of host.links) closeSession(link.threadId, "recycle");
}
host.recycle = null;
- }, envOr("OMB_ACP_SHARED_RECYCLE_MS", 60_000));
+ }, envOr("OMB_ACP_SHARED_RECYCLE_MS", 60_000)); // shared: a process several conversations used, recycled once none is left
host.recycle.unref?.();
};
const armIdle = (threadId: string) => {
const session = sessions.get(threadId);
if (!session) return;
if (session.idleTimer) clearTimeout(session.idleTimer);
- session.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, engineIdleMs(threadId, sessionIdle), { close: () => closeSession(threadId, "idle"),
+ session.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, engineIdleMs(threadId, sessionIdle), { close: () => closeSession(threadId, "idle"), threadId, policy: sessionIdle, // per-chat
idle: () => sessions.get(threadId) === session && !session.closing && !session.current });
};
// Session allows the driver keeps when the agent offered no `allow_always`: exact operations per
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index e40267fa95..32a92915cc 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -934,8 +934,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (!s) return;
if (s.idleTimer) clearTimeout(s.idleTimer);
const held = (warmHolds.get(threadId) ?? 0) - Date.now();
- s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, "idle"),
- idle: () => sessions.get(threadId) === s && !s.closing && !s.turn && !active.has(threadId) && (warmHolds.get(threadId) ?? 0) <= Date.now() });
+ s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, "idle"), threadId, policy: sessionIdle, // per-chat
+ idle: () => sessions.get(threadId) === s && !s.closing && !s.turn && !active.has(threadId), held: () => (warmHolds.get(threadId) ?? 0) > Date.now() });
};
// Keep-warm pings and warm summaries fork a thread's session with its live launch contract (claude-warm-summary.ts).
const forks = claudeForks({ cli: config.cli, contracts: warmContracts, holds: warmHolds, armIdle, supports: (flag) => cliVersion === null || claudeCliSupports(cliVersion, flag),
diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.ts
index d7170bd2af..a2512e8ae9 100644
--- a/server/drivers/session-idle.ts
+++ b/server/drivers/session-idle.ts
@@ -1,7 +1,27 @@
+// The one idle policy for what the server keeps loaded between turns. Each kept thing has a scope, named as such here and
+// at each call site:
+// per-chat a conversation's engine session (Claude's stream, an ACP session in a process of its own), kept for that
+// conversation's next turn: OMB_SESSION_IDLE_MS (10 minutes; 150 s on a box of 1.5 GB or less), 30 s for a
+// conversation no person has in front of them, and while a person asked a prompt-cache keep-warm, until then.
+// per-bot a bot's browser, kept for any of its conversations: the browser idle time (Settings, 10 minutes on the
+// desktop, 3 on a Cloud home; host/browser.ts).
+// shared a process several bots' conversations use (a shared ACP process): recycled 60 s after its last session.
+// Where turns wait for room (a Cloud home, a self-hosted Linux server), every one of these times shrinks as memory or the
+// pids limit fills (EngineMemory.roomFactor: the signals admission reads), down to a tenth and never below its floor, and
+// what is already kept is looked at again every couple of seconds (sweepIdleEngines), not only when it went idle. Short
+// of room, a keep-warm hold yields too. Before admission makes a new engine wait it stops the engine idle longest
+// (engine-memory.ts), and a browser with no room to open asks for the same first (host/browser.ts).
import { availableMemory, boxMemory, type BoxMemory } from "../box-memory.ts";
+import { stoppedForBotMemory } from "../bot-memory-cap.ts";
import { engineMemory, type EngineMemory } from "../engine-memory.ts";
import { seenWithin } from "../thread-presence.ts";
+export type IdleScope = "per-chat" | "per-bot" | "shared";
+
+/** What the room allows of an idle time: the time scaled by `factor` (1 with room to spare, down to 0.1), never below
+ * `minimumMs`. */
+export const idleAfter = (baseMs: number, minimumMs: number, factor: number): number => Math.max(minimumMs, Math.round(baseMs * Math.min(1, Math.max(0.1, factor))));
+
export interface SessionIdlePolicy {
idleMs: number;
minimumMs: number;
@@ -50,9 +70,14 @@ export function idleEnginesAllowed(box: Pick<BoxMemory, "bytes">, availableBytes
}
export interface WarmEngine {
- /** Still idle and free to close: no turn running, no hold keeping it up. */
+ /** Still idle and free to close: no turn running. */
idle: () => boolean;
close: () => void;
+ /** A per-chat engine's conversation and policy: the sweep works its idle time out again as the room changes. */
+ threadId?: string;
+ policy?: SessionIdlePolicy;
+ /** Kept on purpose until a time (a prompt-cache keep-warm): only a shortage of room closes it before then. */
+ held?: () => boolean;
}
/** Idle engines of every driver, the longest idle first. */
@@ -65,7 +90,7 @@ export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "
if (box.bytes > SMALL_BOX_BYTES && most === Infinity) return;
warmEngines.delete(key);
warmEngines.set(key, engine);
- for (const [other, warm] of warmEngines) if (other !== key && !warm.idle()) warmEngines.delete(other);
+ for (const [other, warm] of warmEngines) if (other !== key && (!warm.idle() || warm.held?.())) warmEngines.delete(other);
const extra = warmEngines.size - idleEnginesAllowed(box, available(), most);
if (extra <= 0) return;
for (const [other, warm] of [...warmEngines].slice(0, extra)) {
@@ -74,10 +99,15 @@ export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "
}
}
-/** Closes an idle engine after `ms`, or sooner on a small box once another engine goes idle after it. */
-export function armIdleClose(key: string, ms: number, engine: WarmEngine): ReturnType<typeof setTimeout> {
- const timer = setTimeout(engine.close, ms);
+/** Every per-chat engine idle now, with when it went idle: what the sweep looks at again. */
+const armed = new Map<string, { engine: WarmEngine; since: number }>();
+
+/** Closes an idle per-chat engine after `ms`, sooner on a small box once another engine goes idle after it, and sooner
+ * still once the room shrinks its idle time (sweepIdleEngines). */
+export function armIdleClose(key: string, ms: number, engine: WarmEngine, now: number = Date.now()): ReturnType<typeof setTimeout> {
+ const timer = setTimeout(() => { armed.delete(key); engine.close(); }, ms);
timer.unref?.();
+ armed.set(key, { engine, since: now });
keepWarm(key, engine);
return timer;
}
@@ -85,7 +115,27 @@ export function armIdleClose(key: string, ms: number, engine: WarmEngine): Retur
export function stopIdleClose(key: string, timer: ReturnType<typeof setTimeout> | null): void {
if (timer) clearTimeout(timer);
warmEngines.delete(key);
+ armed.delete(key);
+}
+
+/** Closes each idle per-chat engine kept past what the room allows now; short of room, a keep-warm hold too. Runs on
+ * engine-memory's tick. Returns how many it closed. */
+export function sweepIdleEngines(memory: Pick<EngineMemory, "enabled" | "headroom" | "roomFactor" | "shortOfRoom"> = engineMemory, now: number = Date.now()): number {
+ if (!memory.enabled || !armed.size) return 0;
+ const factor = memory.roomFactor(), short = memory.shortOfRoom();
+ if (factor >= 1 && !short) return 0;
+ let closed = 0;
+ for (const [key, { engine, since }] of armed) {
+ if (!engine.threadId || !engine.policy || !engine.idle() || (engine.held?.() && !short)) continue;
+ if (now - since < engineIdleMs(engine.threadId, engine.policy, { enabled: true, headroom: () => factor, roomFactor: () => factor }, now)) continue;
+ armed.delete(key);
+ warmEngines.delete(key);
+ engine.close();
+ closed += 1;
+ }
+ return closed;
}
+engineMemory.useIdleSweep(() => void sweepIdleEngines());
export function warmEngineKeys(): string[] {
return [...warmEngines.keys()];
@@ -97,17 +147,18 @@ const WATCHED_MS = 30 * 60_000;
export const UNWATCHED_IDLE_MS = 30_000;
/**
- * How long one thread's idle engine stays up after a turn. Where turns wait for room (a Cloud home, a self-hosted Linux
- * server): briefly for a thread no person has had in front of them lately, and for the one they have, the configured time
- * scaled by the memory left (down to a tenth). Elsewhere the configured time.
+ * How long one conversation's idle engine (per-chat) stays up after a turn. Where turns wait for room (a Cloud home, a
+ * self-hosted Linux server): briefly for a thread no person has had in front of them lately, and for the one they have,
+ * the configured time scaled by the room left (memory and, under a pids limit, processes; down to a tenth). Elsewhere the
+ * configured time.
*/
-export function engineIdleMs(threadId: string, policy: SessionIdlePolicy, memory: Pick<EngineMemory, "enabled" | "headroom"> = engineMemory,
- now: number = Date.now()): number {
+export function engineIdleMs(threadId: string, policy: SessionIdlePolicy,
+ memory: Pick<EngineMemory, "enabled" | "headroom"> & Partial<Pick<EngineMemory, "roomFactor">> = engineMemory, now: number = Date.now()): number {
if (!memory.enabled) return policy.idleMs;
if (!seenWithin(threadId, WATCHED_MS, now)) return Math.max(policy.minimumMs, Math.min(policy.idleMs, UNWATCHED_IDLE_MS));
- return Math.max(policy.minimumMs, Math.round(policy.idleMs * memory.headroom()));
+ return idleAfter(policy.idleMs, policy.minimumMs, memory.roomFactor?.() ?? memory.headroom());
}
-/** Whether this thread's engine (`pid`, the process that exited) was just stopped to make room, or for want of it: a
- * driver does not start it again at once, into the same shortage. */
-export const stoppedForRoom = (threadId: string, pid?: number): boolean => engineMemory.stoppedForRoom(threadId, pid);
+/** Whether this thread's engine (`pid`, the process that exited) was just stopped to make room, or for want of it, or for
+ * its bot's memory cap (bot-memory-cap.ts): a driver does not start it again at once, into the same shortage. */
+export const stoppedForRoom = (threadId: string, pid?: number): boolean => engineMemory.stoppedForRoom(threadId, pid) || stoppedForBotMemory(pid);
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index d961ba1575..48c8207d25 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -250,6 +250,7 @@ export class EngineMemory {
private readonly turns: TurnsSetting;
private readonly processes: ProcessBudget | null;
private serverTurns: { at: number; most: number | undefined } | null = null;
+ private idleSweep: (() => void) | null = null;
constructor(options: EngineMemoryOptions) {
this.enabled = options.enabled;
@@ -572,6 +573,7 @@ export class EngineMemory {
/** Every couple of seconds while engines run: notes short memory against the running turns, and stops an engine before
* the machine runs out: an idle one first, else the newest of two or more busy ones. */
tick(): void {
+ try { this.idleSweep?.(); } catch (error) { this.log(`idle sweep failed: ${error instanceof Error ? error.message : String(error)}`); }
const memory = this.read();
if (!memory) return;
if ((memory.fullStall10 ?? 0) >= STALL_PERCENT) this.ledger.note(this.now(), "stalled");
@@ -601,6 +603,33 @@ export class EngineMemory {
return Math.min(1, Math.max(0.1, (this.free(memory) - this.floor(memory)) / (memory.totalBytes / 2)));
}
+ /** How much of an idle engine's keep-alive the server's room allows (idle-policy.ts): the lower of memory's headroom and,
+ * on a server under a pids limit, its processes'; 1 where the gate is off. The same signals admission reads. */
+ roomFactor(): number {
+ if (!this.enabled) return 1;
+ return Math.min(this.headroom(), this.processes?.headroom() ?? 1);
+ }
+
+ /** Whether admission would hold a new engine back now: memory below the floor, or no room for one more engine's
+ * processes. Then even an engine kept warm on purpose (a prompt-cache keep-warm hold) is closed once idle. */
+ shortOfRoom(): boolean {
+ if (!this.enabled) return false;
+ if (this.processes?.short(ENGINE_TASKS, 0)) return true;
+ const memory = this.read();
+ return memory !== null && this.free(memory) < this.floor(memory);
+ }
+
+ /** Stops the engine idle longest, if any: what a browser that has no room to open asks before it is refused. */
+ async reclaimIdle(): Promise<boolean> {
+ const idle = this.enabled ? this.idle() : null;
+ if (!idle) return false;
+ await this.stop(idle, "idle");
+ return true;
+ }
+
+ /** Runs on every tick (every couple of seconds while engines run): the idle policy closes what it kept too long. */
+ useIdleSweep(sweep: () => void): void { this.idleSweep = sweep; }
+
/** Memory the server, Chrome and the page cache keep: below it a machine without swap starts to thrash. */
private floor(memory: HostMemory): number { return Math.max(320 * MB, memory.totalBytes * 0.1); }
diff --git a/server/harness/registry.ts b/server/harness/registry.ts
index efd1b63de6..d599235856 100644
--- a/server/harness/registry.ts
+++ b/server/harness/registry.ts
@@ -3,6 +3,7 @@ import { findCliCandidates } from "../env-path.ts";
import { installNpmEngine, npmAvailable, serverInstallFor, standaloneLookupPath } from "../engine-install.ts";
import { installStandaloneEngine, isAppStandaloneCopy, type StandaloneInstalled } from "../engine-standalone.ts";
import { pinnedNpmVersion } from "../engine-versions.ts";
+import { withBotMemoryCap } from "../bot-memory-cap.ts";
import { withEngineMemory } from "../engine-memory.ts";
import { withEngineHomes } from "../engine-homes/engine-homes.ts";
import { withLocalContext } from "../drivers/local-inject.ts";
@@ -194,13 +195,13 @@ export class ProviderRegistry {
// The RAW config: decodeConfig fills in the driver default, which would flag every instance as overridden.
const rawCli = cliOfRaw(entry.config);
if (rawCli) this.cliByInstance.set(instanceId, rawCli);
- const live = withLocalContext(withUnaskedStops(withEngineHomes(withEngineMemory(withTurnScope(await driver.create({
+ const live = withLocalContext(withUnaskedStops(withEngineHomes(withBotMemoryCap(withEngineMemory(withTurnScope(await driver.create({
instanceId,
displayName: entry.displayName ?? driver.metadata.displayName,
environment: entry.environment ?? {},
enabled: entry.enabled ?? true,
config,
- }))))));
+ })))))));
this.shareSnapshot(live);
return { instanceId, live: decorate ? decorate(live) : live };
} catch (e) {
diff --git a/server/host/bot-memory-cap-host.ts b/server/host/bot-memory-cap-host.ts
new file mode 100644
index 0000000000..b1a0ec17f3
--- /dev/null
+++ b/server/host/bot-memory-cap-host.ts
@@ -0,0 +1,20 @@
+// Starts the per-bot memory cap (bot-memory-cap.ts) with this server's process list, bots and browsers.
+import { readFileSync } from "node:fs";
+
+import { startBotMemoryCap, type BotMemoryWatchdog } from "../bot-memory-cap.ts";
+import { engineMemory } from "../engine-memory.ts";
+import type { FootprintOwner } from "../perf/bot-footprint.ts";
+import { parseProcStat } from "../perf/process-buckets.ts";
+import { linuxProcessList } from "../perf/process-sampler.ts";
+import { gateHost } from "../process-room.ts";
+
+const startOf = (pid: number): string | null => {
+ try { return parseProcStat(pid, readFileSync(`/proc/${pid}/stat`, "utf8"))?.start ?? null; } catch { return null; }
+};
+
+export function startBotMemoryCapHost(deps: { owners: () => readonly FootprintOwner[]; botName: (botId: string) => string | undefined; closeBrowsers: (botId: string) => Promise<void> }): BotMemoryWatchdog | null {
+ return startBotMemoryCap({
+ gate: gateHost(), turns: () => engineMemory.most(), owners: deps.owners, botName: (botId) => deps.botName(botId) ?? "This bot",
+ closeBrowsers: deps.closeBrowsers, list: () => linuxProcessList().rows, startOf,
+ });
+}
diff --git a/server/host/browser.ts b/server/host/browser.ts
index b097a9bf5e..e3b2a46d6e 100644
--- a/server/host/browser.ts
+++ b/server/host/browser.ts
@@ -46,7 +46,8 @@ 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 { processBudget } from "../process-room.ts";
+import { BROWSER_TASKS, processBudget } from "../process-room.ts";
+import { idleAfter } from "../drivers/session-idle.ts";
import { augmentedPath } from "../env-path.ts";
import { harnessMcpTokenEnv } from "../harness-mcp-token.ts";
import type { FillLoginDeps } from "../login-fill.ts";
@@ -80,7 +81,7 @@ export interface BrowserHostDeps {
lentChrome?: { route(): ChromeRoute | null; lender(): ChromeLender | null };
/** The engine memory guard, told which browsers each thread's turn starts or holds. */
/** `selfHosted`: turns wait for room on this server, under its pids limit, and so do its bots' browsers. */
- engineMemory?: { useBrowsers(browsers: EngineBrowsers): void; selfHosted?(): boolean };
+ engineMemory?: { useBrowsers(browsers: EngineBrowsers): void; selfHosted?(): boolean; roomFactor?(): number; reclaimIdle?(): Promise<boolean> };
/** Whose browser a conversation's turns use on a Team Cloud: the member's, the group chat's or the team's. Every
* browser is the bot's own without it. */
audienceOf?(threadId: string): Audience;
@@ -104,6 +105,9 @@ function lentDevice(device: NonNullable<EgressSetup["device"]>, holder: (session
type Spec = { command: string; args?: readonly string[]; env: Record<string, string> };
type LendRefusal = CloudLendingRefusal | "memory-changed" | "memory-changed-here";
const BOT_SESSION = /^bot-[A-Za-z0-9_.-]+$/;
+/** 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;
export function createBrowserHost(deps: BrowserHostDeps) {
const { cfg, turnResources, activeInternalGenerationByThread, mintInternalCapability, DESKTOP_MANAGED, CLOUD_HOME, PORT } = deps;
@@ -119,7 +123,11 @@ export function createBrowserHost(deps: BrowserHostDeps) {
max: deps.browsersAtOnce ?? (() => defaultBrowserRoomSize()),
spare: (session) => spareForRoom(agentBrowserRuntime.spare(session), { holds: !turnResources.free(`browser:${session}`), idleMs: idleMs() }),
close: (session) => agentBrowserRuntime.closeIfIdle(session, 1),
- ...(processRoom ? { admit: (session: string) => processRoom.enter(session) } : {}),
+ // Short of room for its processes, an idle engine goes before this browser waits or is refused (session-idle.ts).
+ ...(processRoom ? { admit: async (session: string) => {
+ if (processBudget.short(BROWSER_TASKS, 0)) await deps.engineMemory?.reclaimIdle?.().catch(() => false);
+ return processRoom.enter(session);
+ } } : {}),
});
const agentBrowserRuntime: BrowserRuntime = new BrowserRuntime({
closeBrowser: (session, spec) => closeBrowserSession(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session })),
@@ -147,7 +155,11 @@ export function createBrowserHost(deps: BrowserHostDeps) {
url: (port) => relay(port, { action: "cdp_url" }, { timeoutMs: 5_000, maxBytes: 65_536 }).then((answer) => answer.data?.cdpUrl),
} });
const host: HostKind = DESKTOP_MANAGED ? "desktop" : CLOUD_HOME || existsSync("/.dockerenv") ? "container" : "server";
- const idleMs = () => browserIdleMs(cfg, { cloudHome: Boolean(CLOUD_HOME) });
+ // per-bot: a bot's browser, kept for any of its conversations; shorter as the server runs short of room (session-idle.ts).
+ const idleMs = () => {
+ const configured = browserIdleMs(cfg, { cloudHome: Boolean(CLOUD_HOME) });
+ return idleAfter(configured, Math.min(configured, BROWSER_IDLE_FLOOR_MS), deps.engineMemory?.roomFactor?.() ?? 1);
+ };
const chromeEngine = new ChromeEngine({
dataDir: DATA_DIR,
host,
@@ -481,6 +493,16 @@ export function createBrowserHost(deps: BrowserHostDeps) {
return [{ pid, botIds, kind: "browser" as const }];
});
}
+ /** Closes the browsers that are this bot's alone (never a profile another bot uses), as one stopped for memory is. */
+ async function closeBotBrowsers(botId: string): Promise<void> {
+ const bot = store.bot(botId);
+ if (!bot) return;
+ const shared = (session: string) => store.bots.some((other) => other.id !== botId && browserSessionsOf(other.id, other.browserProfile).includes(session));
+ await Promise.all(browserSessionsOf(bot.id, bot.browserProfile).flatMap((session) => {
+ const spec = usedBrowserSessions.get(session);
+ return spec && !chromeTarget(session, spec) && !shared(session) ? [closeForMemory(session, spec)] : [];
+ }));
+ }
/** The browser a thread's bot would start; a temporary one has no session until its first call. My Chrome is the person's own. */
function threadBrowser(threadId: string): { session: string | undefined; spec: Spec | undefined } | null {
const bot = store.botByThread(threadId);
@@ -617,6 +639,6 @@ export function createBrowserHost(deps: BrowserHostDeps) {
currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, lentChromeSummary, usesMyChrome, browserSessionSpec, browserIntegration,
browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, signedInSitesRefusal, closeBrowser, browserEngineSwitched,
eraseDeletedBrowser, engineSummary, engineBrowsers, browserAudience, browserSessionsOf, signedInSitesTarget, uploadPaths,
- eraseAudienceBrowsers, browserOwners,
+ eraseAudienceBrowsers, browserOwners, closeBotBrowsers,
};
}
diff --git a/server/idle-and-cap.test.ts b/server/idle-and-cap.test.ts
new file mode 100644
index 0000000000..da7cff5508
--- /dev/null
+++ b/server/idle-and-cap.test.ts
@@ -0,0 +1,351 @@
+// The one idle policy (drivers/session-idle.ts) and the per-bot memory cap (bot-memory-cap.ts).
+import type { ChildProcess } from "node:child_process";
+import { EventEmitter } from "node:events";
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ BOT_CAP_FLOOR_BYTES, BotMemoryWatchdog, botMemoryCapBytes, capLadder, pssBytes, useBotMemoryWatchdog, withBotMemoryCap,
+} from "./bot-memory-cap.ts";
+import type { ProviderInstance, RuntimeEvent, RuntimeEventListener, SendTurnInput } from "./contracts.ts";
+import { armIdleClose, engineIdleMs, idleAfter, stopIdleClose, stoppedForRoom, sweepIdleEngines, type WarmEngine } from "./drivers/session-idle.ts";
+import { EngineMemory, type HostMemory } from "./engine-memory.ts";
+import type { FootprintOwner } from "./perf/bot-footprint.ts";
+import type { ProcessRow } from "./perf/process-buckets.ts";
+import { ProcessBudget } from "./process-room.ts";
+import { forgetPresence, sawThread } from "./thread-presence.ts";
+
+const MB = 1024 * 1024, GB = 1024 * MB;
+const settle = () => new Promise((resolve) => setTimeout(resolve, 25));
+
+class FakeChild extends EventEmitter {
+ exitCode: number | null = null;
+ signalCode: NodeJS.Signals | null = null;
+ readonly pid: number;
+ constructor(pid: number) { super(); this.pid = pid; }
+ exit(signal: NodeJS.Signals | null = null) {
+ if (signal) this.signalCode = signal; else this.exitCode = 0;
+ this.emit("exit", this.exitCode, signal);
+ }
+}
+
+/** A self-hosted server under a pids limit (each engine 44 tasks) with `available` memory, or memory that can't be read. */
+function server(options: { pids?: number; available?: number | null; total?: number } = {}) {
+ let clock = 1_800_000_000_000, nextPid = 1000;
+ const children = new Map<number, FakeChild>();
+ const signals: string[] = [];
+ const state = { base: 26, available: options.available === undefined ? 60 * GB : options.available, extraTasks: 0 };
+ const total = options.total ?? 64 * GB;
+ const budget = new ProcessBudget({ read: () => ({ max: options.pids ?? 512, current: state.base + state.extraTasks + children.size * 44 }), now: () => clock, log: () => {} });
+ const memory = new EngineMemory({
+ enabled: true, host: "server", turns: 100, processes: budget, tickMs: 5,
+ tree: () => null,
+ read: (): HostMemory | null => (state.available === null ? null : { totalBytes: total, availableBytes: Math.max(0, state.available - children.size * 300 * MB), swapFreeBytes: 0, oomKills: 0, fullStall10: 0 }),
+ groups: () => new Map([...children.keys()].map((pid) => [pid, 300 * MB])),
+ now: () => clock, log: () => {},
+ signal: (pid, signal) => {
+ signals.push(`${signal} -${pid}`);
+ const child = children.get(pid);
+ if (child && child.exitCode === null && child.signalCode === null) queueMicrotask(() => child.exit(signal));
+ },
+ });
+ const spawn = (threadId: string) => memory.within(threadId, () => {
+ const child = new FakeChild(nextPid++);
+ children.set(child.pid, child);
+ child.once("exit", () => children.delete(child.pid));
+ memory.track(child as unknown as ChildProcess);
+ return child;
+ });
+ /** A finished turn whose engine stays loaded. */
+ const idleEngine = async (threadId: string) => {
+ memory.turnStarted(threadId);
+ spawn(threadId);
+ memory.turnEnded(threadId);
+ };
+ return { memory, budget, children, signals, state, spawn, idleEngine, advance: (ms: number) => { clock += ms; } };
+}
+
+describe("one idle policy, shorter as the server runs short of room", () => {
+ afterEach(forgetPresence);
+
+ it("scales a time by the room left, down to a tenth, never below its floor", () => {
+ expect(idleAfter(600_000, 10_000, 1)).toBe(600_000);
+ expect(idleAfter(600_000, 10_000, 0.5)).toBe(300_000);
+ expect(idleAfter(600_000, 10_000, 0)).toBe(60_000);
+ expect(idleAfter(600_000, 90_000, 0.1)).toBe(90_000);
+ expect(idleAfter(600_000, 10_000, 3)).toBe(600_000);
+ });
+
+ it("reads the room for processes the way admission does: free below the margin over half the limit", () => {
+ let current = 26;
+ let clock = 0;
+ const budget = new ProcessBudget({ read: () => ({ max: 1000, current }), now: () => clock, log: () => {} });
+ expect(budget.headroom()).toBe(1);
+ current = 600; // 1000 - 100 margin - 600 = 300 free, of 500
+ expect(budget.headroom()).toBeCloseTo(0.6, 5);
+ current = 890;
+ expect(budget.headroom()).toBe(0.1);
+ current = 26;
+ budget.spawnFailed("EAGAIN");
+ expect(budget.headroom()).toBe(0.1);
+ clock += 31_000;
+ expect(budget.headroom()).toBe(1);
+ expect(new ProcessBudget({ read: () => ({ max: null, current: null }), log: () => {} }).headroom()).toBe(1);
+ });
+
+ it("takes the lower of memory's and processes' room, and calls the server short when admission would hold an engine back", async () => {
+ const h = server({ pids: 1000 });
+ expect(h.memory.roomFactor()).toBe(1);
+ expect(h.memory.shortOfRoom()).toBe(false);
+ h.state.extraTasks = 574; // 600 tasks of 1000
+ expect(h.memory.roomFactor()).toBeCloseTo(0.6, 5);
+ h.state.extraTasks = 830; // 856 tasks: one more engine's 60 would not fit under 900
+ expect(h.memory.shortOfRoom()).toBe(true);
+ h.state.extraTasks = 0;
+ h.state.available = 500 * MB; // below the 6.4 GB floor of a 64 GB machine
+ expect(h.memory.shortOfRoom()).toBe(true);
+ expect(h.memory.roomFactor()).toBe(0.1);
+ expect(new EngineMemory({ enabled: false, read: () => null }).roomFactor()).toBe(1);
+ // A Cloud home has no pids limit to read: memory alone.
+ expect(new EngineMemory({ enabled: true, host: "cloud", read: () => ({ totalBytes: 4 * GB, availableBytes: 3.4 * GB, swapFreeBytes: 0, oomKills: 0, fullStall10: 0 }) }).roomFactor()).toBe(1);
+ });
+
+ it("gives a watched conversation's engine (per-chat) less time as the pids limit fills, as it already did for memory", () => {
+ const now = 1_800_000_000_000;
+ sawThread("open", now - 60_000);
+ const policy = { idleMs: 10 * 60_000, minimumMs: 10_000 };
+ expect(engineIdleMs("open", policy, { enabled: true, headroom: () => 1, roomFactor: () => 0.25 }, now)).toBe(150_000);
+ expect(engineIdleMs("open", policy, { enabled: true, headroom: () => 0.5 }, now)).toBe(300_000);
+ expect(engineIdleMs("open", policy, { enabled: false, headroom: () => 0.1, roomFactor: () => 0.1 }, now)).toBe(600_000);
+ });
+
+ it("closes engines already kept too long once room shrinks, keeps a keep-warm hold until the server is short, and never a busy one", () => {
+ const start = 1_800_000_000_000;
+ sawThread("t1", start); sawThread("t2", start); sawThread("t3", start);
+ const policy = { idleMs: 10 * 60_000, minimumMs: 10_000 };
+ const closed: string[] = [];
+ const busy = { t3: true } as Record<string, boolean>;
+ const warm = (threadId: string, held = false): WarmEngine => ({ threadId, policy, idle: () => !busy[threadId], held: () => held, close: () => closed.push(threadId) });
+ const timers = [armIdleClose("k1", 600_000, warm("t1"), start), armIdleClose("k2", 600_000, warm("t2", true), start), armIdleClose("k3", 600_000, warm("t3"), start)];
+ try {
+ const room = { factor: 1, short: false };
+ const memory = { enabled: true, headroom: () => room.factor, roomFactor: () => room.factor, shortOfRoom: () => room.short };
+ // Three minutes on, with room to spare: nothing closes before its ten minutes.
+ expect(sweepIdleEngines(memory, start + 3 * 60_000)).toBe(0);
+ // Room shrinks to a fifth: two minutes is the time now, and t1 has been idle three.
+ room.factor = 0.2;
+ expect(sweepIdleEngines(memory, start + 3 * 60_000)).toBe(1);
+ expect(closed).toEqual(["t1"]);
+ // Short of room: the keep-warm hold yields too; the busy engine stays.
+ room.short = true;
+ expect(sweepIdleEngines(memory, start + 3 * 60_000)).toBe(1);
+ expect(closed).toEqual(["t1", "t2"]);
+ // Off where turns don't wait for room.
+ expect(sweepIdleEngines({ ...memory, enabled: false }, start + 60 * 60_000)).toBe(0);
+ } finally {
+ for (const [index, timer] of timers.entries()) stopIdleClose(`k${index + 1}`, timer);
+ }
+ });
+
+ it("runs the sweep on every tick of the gate", () => {
+ const h = server();
+ let swept = 0;
+ h.memory.useIdleSweep(() => { swept += 1; });
+ h.memory.tick();
+ h.memory.useIdleSweep(() => { throw new Error("boom"); });
+ expect(() => h.memory.tick()).not.toThrow();
+ expect(swept).toBe(1);
+ });
+});
+
+describe("an idle engine goes before admission makes new work wait", () => {
+ it("when memory is short", async () => {
+ const h = server({ total: 4 * GB, available: 2 * GB });
+ await h.idleEngine("old");
+ h.advance(91_000);
+ h.state.available = 0.9 * GB; // 600 MB free with the idle engine: 190 MB above the floor, less than one more engine
+ const admitted = h.memory.admit("new", new AbortController().signal, () => {});
+ await settle();
+ expect(h.signals).toEqual(["SIGTERM -1000"]);
+ expect(await admitted).toBe(true);
+ });
+
+ it("when the pids limit is full", async () => {
+ const h = server({ pids: 512 });
+ // Nine idle engines: 422 tasks, and one more engine's 60 would pass the 461 kept below the limit.
+ for (const thread of ["a", "b", "c", "d", "e", "f", "g", "h", "i"]) await h.idleEngine(thread);
+ h.memory.turnStarted("busy");
+ const admitted = h.memory.admit("new", new AbortController().signal, () => {});
+ await settle();
+ expect(h.signals[0]).toBe("SIGTERM -1000");
+ expect(await admitted).toBe(true);
+ });
+
+ it("when memory can't be read and the pids limit is full", async () => {
+ const h = server({ pids: 512, available: null });
+ for (const thread of ["a", "b", "c", "d", "e", "f", "g", "h", "i"]) await h.idleEngine(thread);
+ h.memory.turnStarted("busy");
+ const admitted = h.memory.admit("new", new AbortController().signal, () => {});
+ await settle();
+ expect(h.signals[0]).toBe("SIGTERM -1000");
+ expect(await admitted).toBe(true);
+ });
+
+ it("and a browser that has no room to open asks for the same", async () => {
+ const h = server();
+ expect(await h.memory.reclaimIdle()).toBe(false);
+ await h.idleEngine("a");
+ await h.idleEngine("b");
+ expect(await h.memory.reclaimIdle()).toBe(true);
+ expect(h.signals).toEqual(["SIGTERM -1000"]);
+ });
+});
+
+describe("a memory cap per bot", () => {
+ const inputs = (memoryBytes: number, turns?: number) => ({ gate: "server" as const, memoryBytes, ...(turns === undefined ? {} : { turns }) });
+
+ it("is off on the desktop and where set off, a set number of MB where given, else twice a bot's fair share within bounds", () => {
+ const warned: string[] = [];
+ expect(botMemoryCapBytes({}, { gate: null, memoryBytes: 16 * GB })).toBeNull();
+ expect(botMemoryCapBytes({ OMB_BOT_MEMORY_MAX_MB: "3000" }, { gate: null, memoryBytes: 16 * GB })).toBe(3000 * MB);
+ expect(botMemoryCapBytes({ OMB_BOT_MEMORY_MAX_MB: "off" }, inputs(8 * GB, 10))).toBeNull();
+ expect(botMemoryCapBytes({ OMB_BOT_MEMORY_MAX_MB: "0" }, inputs(8 * GB, 10))).toBeNull();
+ expect(botMemoryCapBytes({ OMB_BOT_MEMORY_MAX_MB: "10" }, inputs(8 * GB, 10))).toBe(256 * MB);
+ // 8 GB and 10 turns: a fair share is 819 MB, twice that 1,638 MB, below an engine at its largest with its browser.
+ expect(botMemoryCapBytes({}, inputs(8 * GB, 10))).toBe(BOT_CAP_FLOOR_BYTES);
+ expect(BOT_CAP_FLOOR_BYTES).toBe(1900 * MB);
+ // 32 GB and 8 turns: 8 GB.
+ expect(botMemoryCapBytes({ OMB_BOT_MEMORY_MAX_MB: "auto" }, inputs(32 * GB, 8))).toBe(8 * GB);
+ // 2 GB: never more than 80% of the memory.
+ expect(botMemoryCapBytes({}, inputs(2 * GB, 2))).toBe(Math.round(1.6 * GB));
+ // Without a number of turns: as many as fit at an engine's usual 700 MB.
+ expect(botMemoryCapBytes({}, inputs(64 * GB))).toBe(BOT_CAP_FLOOR_BYTES);
+ expect(botMemoryCapBytes({}, inputs(64 * GB, 16))).toBe(8 * GB);
+ expect(botMemoryCapBytes({ OMB_BOT_MEMORY_MAX_MB: "lots" }, inputs(8 * GB, 10), (line) => warned.push(line))).toBe(BOT_CAP_FLOOR_BYTES);
+ expect(warned).toEqual(['OMB_BOT_MEMORY_MAX_MB="lots" is not a number of MB, "auto" or "off", so the default is used']);
+ });
+
+ it("reports the ladder's rungs this host offers, and enforces with the watchdog", () => {
+ expect(capLadder(GB, { platform: "darwin" })).toEqual({ rung: "none", offered: [] });
+ const files: Record<string, string> = { "/proc/self/cgroup": "0::/system.slice/openmausbot.service\n", "/sys/fs/cgroup/system.slice/openmausbot.service/cgroup.controllers": "cpu io memory pids\n" };
+ const read = (path: string) => files[path] ?? null;
+ expect(capLadder(GB, { platform: "linux", read, writable: () => true, exists: () => true })).toEqual({ rung: "watchdog", offered: ["systemd-scope", "cgroup", "watchdog"] });
+ // A container's read-only cgroup: only the watchdog.
+ expect(capLadder(GB, { platform: "linux", read: (path) => (path === "/proc/self/cgroup" ? "0::/\n" : path === "/sys/fs/cgroup/cgroup.controllers" ? "memory pids\n" : null), writable: () => false, exists: () => false }))
+ .toEqual({ rung: "watchdog", offered: ["watchdog"] });
+ expect(capLadder(null, { platform: "linux", read, writable: () => false, exists: () => false })).toEqual({ rung: "none", offered: ["watchdog"] });
+ expect(pssBytes(7, (path) => (path === "/proc/7/smaps_rollup" ? "Rss: 2048 kB\nPss: 1024 kB\n" : null))).toBe(MB);
+ expect(pssBytes(7, () => null)).toBeNull();
+ });
+
+ /** Bot A: engine 200 and its tool server 201. Bot B: engine 300, tool server 301, and its browser 500 with Chrome 501
+ * (100 MB). Shared: an engine 400 both bots use. The sizes are each bot's engine and tool server together. */
+ function processes(sizes: { a?: number; b?: number; shared?: number } = {}) {
+ const row = (pid: number, ppid: number, mb: number, pgid = pid): ProcessRow => ({ pid, ppid, name: "x", cpuMs: 0, rssBytes: mb * MB, start: `s${pid}`, pgid, sid: pgid });
+ return [
+ row(100, 1, 200),
+ row(200, 100, (sizes.a ?? 1200) - 200), row(201, 200, 200, 200),
+ row(300, 100, (sizes.b ?? 600) - 100), row(301, 300, 100, 300),
+ row(500, 1, 40), row(501, 500, 60, 500),
+ row(400, 100, sizes.shared ?? 5000),
+ ];
+ }
+ const owners: FootprintOwner[] = [
+ { pid: 200, botIds: ["bot_a"], kind: "engine" }, { pid: 300, botIds: ["bot_b"], kind: "engine" },
+ { pid: 500, botIds: ["bot_b"], kind: "browser" }, { pid: 400, botIds: ["bot_a", "bot_b"], kind: "engine" },
+ ];
+ function dog(rows: () => ProcessRow[], pss: (pid: number) => number | null = () => null, startOf: (pid: number) => string | null = (pid) => `s${pid}`) {
+ const signals: string[] = [], closed: string[] = [], logs: string[] = [];
+ let clock = 1_800_000_000_000;
+ const watchdog = new BotMemoryWatchdog({ cap: () => 1000 * MB, list: rows, owners: () => owners, pss, startOf, graceMs: 0, now: () => clock,
+ signal: (pid, value) => signals.push(`${value} ${pid}`), closeBrowsers: async (botId) => { closed.push(botId); }, log: (line) => logs.push(line) });
+ return { watchdog, signals, closed, logs, advance: (ms: number) => { clock += ms; }, now: () => clock };
+ }
+
+ it("stops a bot that stays over its cap: its engine's processes and its own browser, never another bot's or a shared process", async () => {
+ let sizes = { a: 900, b: 1200 };
+ const h = dog(() => processes(sizes));
+ expect(await h.watchdog.check()).toEqual([]);
+ expect(h.signals).toEqual([]);
+ const [stop] = await h.watchdog.check();
+ expect(stop).toMatchObject({ botId: "bot_b", usedBytes: 1300 * MB, capBytes: 1000 * MB });
+ expect(h.signals).toEqual(["SIGTERM 300", "SIGTERM 301", "SIGKILL 300", "SIGKILL 301"]);
+ expect(h.closed).toEqual(["bot_b"]);
+ expect(h.logs).toEqual(["memory: bot bot_b used 1300 MB, more than the 1000 MB this server allows one bot; stopping its engine (2 processes) and closing its browser"]);
+ expect(h.watchdog.stopOf("bot_b")).toMatchObject({ botId: "bot_b" });
+ expect(h.watchdog.stoppedPid(300)).toBe(true);
+ expect(h.watchdog.stoppedPid(200)).toBe(false);
+ expect(h.watchdog.stops()).toBe(1);
+ // A bot that dips back under its cap starts counting again.
+ sizes = { a: 1100, b: 500 };
+ expect(await h.watchdog.check()).toEqual([]);
+ sizes = { a: 900, b: 500 };
+ expect(await h.watchdog.check()).toEqual([]);
+ sizes = { a: 1100, b: 500 };
+ expect(await h.watchdog.check()).toEqual([]);
+ expect(h.signals).toHaveLength(4);
+ });
+
+ it("stops a bot far over its cap at once, and counts shared pages once (by proportional size) before stopping anything", async () => {
+ const far = dog(() => processes({ a: 1600 }));
+ expect((await far.watchdog.check()).map((stop) => stop.botId)).toEqual(["bot_a"]);
+ expect(far.signals).toEqual(["SIGTERM 200", "SIGTERM 201", "SIGKILL 200", "SIGKILL 201"]);
+ expect(far.closed).toEqual([]);
+ // Resident 1,600 MB, but 700 MB of it pages shared with other processes: 900 MB its own share, under the cap.
+ const shared = dog(() => processes({ a: 1600 }), (pid) => (pid === 200 ? 700 * MB : pid === 201 ? 200 * MB : null));
+ expect(await shared.watchdog.check()).toEqual([]);
+ expect(await shared.watchdog.check()).toEqual([]);
+ expect(shared.signals).toEqual([]);
+ });
+
+ it("leaves alone a pid the system gave to another process since it was read", async () => {
+ const h = dog(() => processes({ a: 1600 }), () => null, (pid) => (pid === 201 ? "later" : `s${pid}`));
+ await h.watchdog.check();
+ expect(h.signals).toEqual(["SIGTERM 200", "SIGKILL 200"]);
+ });
+
+ it("ends the stopped bot's turn with a line that says why, and only that bot's turn that ran then", async () => {
+ const h = dog(() => processes({ b: 1600 }));
+ const listeners = new Set<RuntimeEventListener>();
+ const instance = withBotMemoryCap({
+ instanceId: "i", driverKind: "claudeAgent", displayName: "x", enabled: true,
+ adapter: { sendTurn: async () => ({ turnId: "t" }), onEvent: (listener: RuntimeEventListener) => { listeners.add(listener); return () => listeners.delete(listener); } },
+ } as unknown as ProviderInstance, () => h.watchdog, (botId) => (botId === "bot_b" ? "Researcher" : botId), h.now);
+ const seen: RuntimeEvent[] = [];
+ instance.adapter.onEvent((event) => seen.push(event));
+ const emit = (event: Partial<RuntimeEvent>) => { for (const listener of listeners) listener({ eventId: "e", provider: "claudeAgent", createdAt: "", ...event } as RuntimeEvent); };
+ const shown = () => seen.map((event) => (event.type === "runtime.error" ? event.message : event.type));
+ await instance.adapter.sendTurn({ threadId: "tb", botId: "bot_b", text: "go" } as SendTurnInput);
+ await instance.adapter.sendTurn({ threadId: "tc", botId: "bot_b", text: "go" } as SendTurnInput);
+ await instance.adapter.sendTurn({ threadId: "ta", botId: "bot_a", text: "go" } as SendTurnInput);
+ h.advance(1_000);
+ await h.watchdog.check();
+ emit({ threadId: "tb", turnId: "t", type: "runtime.error", message: "the process running this turn's AI ended" });
+ emit({ threadId: "tb", turnId: "t", type: "turn.completed", ok: false, stopReason: "exit_before_result" });
+ emit({ threadId: "ta", turnId: "t", type: "runtime.error", message: "something else" });
+ const line = "Researcher used more memory than this server allows for one bot (1700 MB of 1000 MB), so I stopped this task to keep the other bots running. "
+ + "Send the message again to start over; if it keeps happening, give this task less to do at once, or give the server more memory.";
+ expect(shown()).toEqual([line, "turn.completed", "something else"]);
+ expect(seen[0]).toMatchObject({ text: { key: "chat.notice.botMemoryCap", params: { bot: "Researcher", used: "1700", cap: "1000" } } });
+ // A turn that ends without an error of its own still says why, first.
+ seen.length = 0;
+ emit({ threadId: "tc", turnId: "t", type: "turn.completed", ok: false, stopReason: "exit_before_result" });
+ expect(shown()).toEqual([line, "turn.completed"]);
+ await settle();
+ // A turn started after the stop fails for its own reasons.
+ seen.length = 0;
+ h.advance(1_000);
+ await instance.adapter.sendTurn({ threadId: "tb", botId: "bot_b", text: "again" } as SendTurnInput);
+ emit({ threadId: "tb", turnId: "t2", type: "runtime.error", message: "its own failure" });
+ expect(shown()).toEqual(["its own failure"]);
+ });
+
+ it("keeps a driver from starting the stopped engine again at once", async () => {
+ const h = dog(() => processes({ b: 1600 }));
+ await h.watchdog.check();
+ useBotMemoryWatchdog(h.watchdog);
+ try {
+ expect(stoppedForRoom("tb", 300)).toBe(true);
+ expect(stoppedForRoom("ta", 200)).toBe(false);
+ } finally { useBotMemoryWatchdog(null); }
+ });
+});
diff --git a/server/index.ts b/server/index.ts
index 3f9c195cbc..8f7c36d4f0 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -642,7 +642,7 @@ import { createPersonReplies } from "./person-replies.ts";
import { lendingPerson, lendingPersonKey, personKey, relayedPersonKey } from "./person-key.ts";
import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";
import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";
-import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
+import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";
import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";
import { createThreadRoutes } from "./routes/threads.ts";
import { createWebhookRoutes } from "./routes/webhooks.ts";
@@ -2377,7 +2377,7 @@ function cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): Dir
const {
browserRuntime, browserLive, usedBrowserSessions, browserSweep, temporaryBrowserSessions,
currentBrowserSession, forgetTemporaryBrowser, myChromeAvailable, usesMyChrome, lentChromeSummary, browserSessionSpec, browserIntegration,
- browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners,
+ browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners, closeBotBrowsers,
} = createBrowserHost({ cfg, language: appLanguage, store: () => store, turnResources, activeInternalGenerationByThread, mintInternalCapability, DESKTOP_MANAGED, CLOUD_HOME, HOSTED_WORKSPACE, PORT, engineMemory, audienceOf: teamHost.browserAudience, ...(CLOUD_TEAM ? { browserBox: (fd: number, ro: readonly string[]) => botBox.browserBox(fd, ro) } : {}), lendRefusal: (turn) => cloudLendingRefusal({ botId: store.botByThread(turn.threadId)?.id ?? "", threadId: turn.threadId, generation: turn.generation }), device: () => deviceLinks.route(CLOUD_HOME_LENDER) ?? sharedComputers.internetAway(CLOUD_HOME_LENDER) ?? { unshared: true as const }, lentChrome: CLOUD_PERSONAL ? { route: () => deviceLinks.chromeRoute(CLOUD_HOME_LENDER), lender: () => sharedComputers.chromeLender(CLOUD_HOME_LENDER) } : undefined });
const dataSheets = new DataSheetRegistry({
@@ -2789,7 +2789,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPers
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }), pruneOwners: (inUse) => engineOwners.prune(inUse), wholeMachine: Boolean(CLOUD_HOME) }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (inUse) => engineOwners.prune(inUse), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeBotBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
diff --git a/server/perf/bot-footprint.ts b/server/perf/bot-footprint.ts
index 1547d8b723..99977e4a65 100644
--- a/server/perf/bot-footprint.ts
+++ b/server/perf/bot-footprint.ts
@@ -31,6 +31,8 @@ export interface BotTally {
engines: number;
browsers: number;
pids: number[];
+ /** Those of `pids` that belong to it through a browser (its daemon and Chrome), not an engine. */
+ browserPids: number[];
}
export interface Attribution {
@@ -39,7 +41,7 @@ export interface Attribution {
shared: BotTally;
}
-const emptyTally = (): BotTally => ({ procs: 0, threads: 0, rssBytes: 0, cpuMs: 0, cpuDeltaMs: 0, engines: 0, browsers: 0, pids: [] });
+const emptyTally = (): BotTally => ({ procs: 0, threads: 0, rssBytes: 0, cpuMs: 0, cpuDeltaMs: 0, engines: 0, browsers: 0, pids: [], browserPids: [] });
/** Whose each row is: a bot's id, SHARED, or undefined for none (the server, its own helpers, anything else). */
export const SHARED = "\0shared";
@@ -61,28 +63,31 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Foot
roots.set(owner.pid, { label: known && known.label !== label ? SHARED : label, kind: owner.kind });
if (!owner.exited) live.add(owner.pid);
}
- const labels = new Map<number, string | null>();
- const labelOf = (row: ProcessRow, depth: number): string | null => {
+ type Label = { label: string; kind: FootprintOwner["kind"] } | null;
+ const labels = new Map<number, Label>();
+ const labelOf = (row: ProcessRow, depth: number): Label => {
const known = labels.get(row.pid);
if (known !== undefined) return known;
labels.set(row.pid, null);
// Its own record first, then the nearest recorded ancestor, then (for what outlived its parent and was adopted by an
// init) the session and group it still runs in.
- let label: string | null = live.has(row.pid) ? roots.get(row.pid)?.label ?? null : null;
+ let label: Label = live.has(row.pid) ? roots.get(row.pid) ?? null : null;
if (label === null && row.ppid !== row.pid && depth < 64) {
const parent = byPid.get(row.ppid);
if (parent) label = labelOf(parent, depth + 1);
}
- if (label === null && row.sid !== undefined && row.sid !== row.pid) label = roots.get(row.sid)?.label ?? null;
- if (label === null && row.pgid !== undefined && row.pgid !== row.pid) label = roots.get(row.pgid)?.label ?? null;
+ if (label === null && row.sid !== undefined && row.sid !== row.pid) label = roots.get(row.sid) ?? null;
+ if (label === null && row.pgid !== undefined && row.pgid !== row.pid) label = roots.get(row.pgid) ?? null;
labels.set(row.pid, label);
return label;
};
const out: Attribution = { bots: new Map(), shared: emptyTally() };
for (const row of rows) {
- const label = labelOf(row, 0);
- if (label === null) continue;
+ const found = labelOf(row, 0);
+ if (found === null) continue;
+ const label = found.label;
const tally = label === SHARED ? out.shared : out.bots.get(label) ?? out.bots.set(label, emptyTally()).get(label)!;
+ if (found.kind === "browser") tally.browserPids.push(row.pid);
tally.procs += 1;
tally.threads = tally.threads === null || row.threads === undefined ? null : tally.threads + row.threads;
tally.rssBytes += row.rssBytes;
@@ -118,6 +123,8 @@ export interface BotFootprintReport {
/** The bots using the most memory first. */
shown: BotFootprintRow[];
shared: Omit<BotFootprintRow, "id" | "peakMB">;
+ /** The memory one bot may use (bot-memory-cap.ts): MB or null for none, how it is enforced, and bots stopped since start. */
+ cap?: { mb: number | null; rung: string; stops: number };
}
const MB = 1_048_576;
@@ -188,6 +195,7 @@ export function botFootprintLines(report: BotFootprintReport): string[] {
const shared = report.shared;
return [
`Per bot (${report.bots} with processes running; most memory first): ${report.shown.length ? report.shown.map(one).join("; ") : "none"}`,
+ ...(report.cap ? [` Memory one bot may use: ${report.cap.mb === null ? "no limit" : `${report.cap.mb} MB (${report.cap.rung}); bots stopped for it since start: ${report.cap.stops}`}`] : []),
` Shared by several bots: ${shared.procs} processes${threads(shared.threads)}, ${shared.rssMB} MB, ${shared.engines} engines, ${shared.browsers} browsers`,
];
}
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
index 4fcaa7e061..ca11d1c088 100644
--- a/server/perf/perf-host.ts
+++ b/server/perf/perf-host.ts
@@ -41,6 +41,8 @@ export interface PerfHostDeps {
owners?: () => readonly FootprintOwner[];
/** After each sample: the process groups and sessions still in use, so records of exited engines can go. */
pruneOwners?: (inUse: ReadonlySet<number>) => void;
+ /** The memory one bot may use and how it is enforced (bot-memory-cap.ts). */
+ cap?: () => { mb: number | null; rung: string; stops: number };
}
/** The health report shows this many bots, the ones using the most memory first; the admin's read shows every one. */
@@ -94,6 +96,7 @@ export function createPerfHost(deps: PerfHostDeps) {
/** Its two warnings are said once each for the life of the server. */
const processes = deps.processes ?? createProcessHealth({ warn: (kind, line) => say(kind, line) });
const footprints: BotFootprints = createBotFootprints({ owners: () => deps.owners?.() ?? [], ...(deps.pruneOwners ? { prune: deps.pruneOwners } : {}), now });
+ const botReport = (limit?: number): BotFootprintReport => ({ ...footprints.report(limit), ...(deps.cap ? { cap: deps.cap() } : {}) });
const sampler = deps.sampler ?? createProcessSampler({
list: linux ? () => linuxProcessList() : psProcessList, intervalMs: linux ? LINUX_SAMPLE_MS : OTHER_SAMPLE_MS,
scope: deps.wholeMachine && linux ? "all" : "tree", utilization: nodeUtilization(), now, engines: enginePids,
@@ -106,13 +109,13 @@ export function createPerfHost(deps: PerfHostDeps) {
if (deps.timer !== false && linux) guarded("limits", () => (deps.log ?? ((line: string) => console.warn(line)))(processes.startLine()), undefined);
const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null), processes: processes.report(),
- bots: windows ? null : guarded("bots", () => footprints.report(BOTS_IN_HEALTH), null) });
+ bots: windows ? null : guarded("bots", () => botReport(BOTS_IN_HEALTH), null) });
return {
timings,
sampler,
footprints,
/** Every bot's footprint at the last sample, for the admin's read (routes/perf-diagnostics.ts). */
- bots: (): BotFootprintReport | null => (windows ? null : guarded("bots", () => footprints.report(), null)),
+ bots: (): BotFootprintReport | null => (windows ? null : guarded("bots", () => botReport(), null)),
noteHeld: (threadId: string, why: "plan-limit" | "memory") => guarded("held", () => timings.noteHeld(threadId, why), undefined),
noteFailover: (threadId: string, why: FailoverWhy) => guarded("failover", () => timings.noteFailover(threadId, why), undefined),
noteNotStarted: (threadId: string, turnId: string | null, refusal?: Refusal) => guarded("refused", () => timings.noteNotStarted(threadId, turnId, refusal), undefined),
diff --git a/server/process-room.ts b/server/process-room.ts
index 7398adf051..8dc3d9b207 100644
--- a/server/process-room.ts
+++ b/server/process-room.ts
@@ -28,6 +28,8 @@ const BROWSER_WAIT_MS = 20_000;
export const BROWSER_NO_ROOM = "This server is close to its limit on running programs, so another browser cannot open now. " +
"Try the browser again in a few minutes, or carry on without it.";
+const MIN_HEADROOM = 0.1;
+
/** Kept below the limit for what nobody counts ahead: a command's own children, a probe, a thread pool growing. */
export const margin = (limit: number) => Math.max(32, Math.round(limit * 0.1));
/** How many engines fit under a pids limit. */
@@ -99,6 +101,15 @@ export class ProcessBudget {
return limit !== null && current !== null && current + held + this.browsersHeld() + tasks > limit - margin(limit);
}
+ /** How much room for processes is left, for how long an idle engine stays loaded (idle-policy.ts): 1 with half the limit
+ * or more free below its margin, down to a tenth as it fills; 1 where no limit is known. */
+ headroom(): number {
+ if (this.now() < this.holdUntil) return MIN_HEADROOM;
+ const limit = this.limit(), { current } = this.state();
+ if (limit === null || current === null) return 1;
+ return Math.min(1, Math.max(MIN_HEADROOM, (limit - margin(limit) - this.browsersHeld() - current) / (limit / 2)));
+ }
+
/** What the browsers let in still hold against the limit beyond what the count shows of them: each counts at its full
* size for as long as it runs, so one opened after its turn was let in (on a bot's first browser call) is never missed,
* and one still starting or loading a page has its room kept. */
diff --git a/src/locales/en.json b/src/locales/en.json
index 3cd4ae1bec..0bd6ac40bf 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10167,6 +10167,7 @@
"native.home.bringUnavailable": "Your bots can't be brought together there now.",
"chat.notice.memoryReclaimedBrowser": "Ran out of room, so I closed the browser to keep everything else running.",
"chat.notice.memoryReclaimedTask": "Ran out of room, so I stopped this task to keep everything else running.",
+ "chat.notice.botMemoryCap": "{bot} used more memory than this server allows for one bot ({used} MB of {cap} MB), so I stopped this task to keep the other bots running. Send the message again to start over; if it keeps happening, give this task less to do at once, or give the server more memory.",
"chat.notice.memoryReclaimedBrowserDetail": "Ran out of room, so I closed the browser to keep everything else running. ({detail})",
"chat.notice.memoryReclaimedTaskDetail": "Ran out of room, so I stopped this task to keep everything else running. ({detail})",
"chat.notice.outOfProcesses": "There is no room to start another program ({code}), so this task could not run. Nothing was sent to the AI. It starts again by itself when there is room.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index d1ec2b17d6..12ee3ccb77 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10079,6 +10079,7 @@
"native.home.bringUnavailable": "Não é possível reunir seus bots lá agora.",
"chat.notice.memoryReclaimedBrowser": "Faltou memória, então fechei o navegador para manter o restante funcionando.",
"chat.notice.memoryReclaimedTask": "Faltou memória, então interrompi esta tarefa para manter o restante funcionando.",
+ "chat.notice.botMemoryCap": "{bot} usou mais memória do que este servidor permite para um bot ({used} MB de {cap} MB), então interrompi esta tarefa para manter os outros bots funcionando. Envie a mensagem de novo para recomeçar; se continuar acontecendo, dê menos trabalho de uma vez a esta tarefa ou mais memória ao servidor.",
"chat.notice.memoryReclaimedBrowserDetail": "Faltou memória, então fechei o navegador para manter o restante funcionando. ({detail})",
"chat.notice.memoryReclaimedTaskDetail": "Faltou memória, então interrompi esta tarefa para manter o restante funcionando. ({detail})",
"chat.notice.outOfProcesses": "Não há espaço para iniciar outro programa ({code}), então esta tarefa não pôde rodar. Nada foi enviado à IA. Ela começa de novo sozinha quando houver espaço.",