Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cap: watch only by default; an opt-in number acts only under pressure, on the largest bot, in steps
milind-soni3ef92e71aeec
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex d166730f1b..5f49be8d08 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -593,22 +593,34 @@ bot. Bot ids and numbers only.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 itsidle 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 computer 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.+last session (`OMB_ACP_SHARED_RECYCLE_MS`; this one stays fixed). Where turns+wait for room, a conversation's engine time and a browser's idle time shrink+as memory or the process limit fills, down to a tenth (never below their+floor), and engines already kept are 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, the server watches how+much memory each bot uses against twice its fair share (the memory over+the turns that may run at once), at least 1,900 MB and at most 80% of it,+for each engine the bot runs (a bot with several conversations open may use+that much for each). By default it only writes down a bot that stays over+(for 30 seconds, or sooner while memory is short): the bot's id, the memory+it used and how it was measured, the limit, its engines and the room left+go to the server log and the health report. Nothing is stopped. To have the+server act, set `OMB_BOT_MEMORY_MAX_MB` to a number of MB (any Linux host,+the desktop app included); `auto` is the default (watch only) and `off` turns+the watching off. Even then it acts only while the server is short of+memory, only on the bot using the most, and in steps: first what the bot+left running and its idle engines; then, measured again and still over, its+largest busy engine or browser. A turn whose engine is stopped ends with a+line saying the bot used more memory than this computer allows for one bot.+Engines and browsers several bots share, and a process other conversations+may join, are never stopped this way; on a Team Cloud only the browser that+was over is closed, never the same bot's browsers for other members. The+server watches 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 theprovider that hosts it, not in this container, so its desktop and browserdiff --git a/server/bot-memory-cap-live.test.ts b/server/bot-memory-cap-live.test.tsindex 6f3d65d3c5..8636b79dba 100644--- a/server/bot-memory-cap-live.test.ts+++ b/server/bot-memory-cap-live.test.ts@@ -1,4 +1,5 @@-// The memory cap on real processes (Linux): stand-in engines started as spawnCli starts them, each leading its own+// The memory cap on real processes (Linux): watch only by default, and an opt-in cap under (injected) memory pressure.+// Stand-in engines started as spawnCli starts them, each leading its own// session with two tool-server children and a child its shell left behind (adopted by init, still in the engine's// session); the watchdog reads /proc as the server does: stat lines, proportional set sizes, start ticks, real signals.import { spawn, type ChildProcess } from "node:child_process";@@ -6,6 +7,7 @@ import { readFileSync } from "node:fs";import { afterEach, describe, expect, it } from "vitest";import { BotMemoryWatchdog, pssBytes } from "./bot-memory-cap.ts";+import type { FootprintOwner } from "./perf/bot-footprint.ts";import { parseProcStat } from "./perf/process-buckets.ts";import { linuxProcessList } from "./perf/process-sampler.ts";@@ -38,25 +40,46 @@ async function until(done: () => boolean, ms = 15_000): Promise<boolean> {const session = (sid: number) => linuxProcessList().rows.filter((row) => row.sid === sid && row.state !== "Z").map((row) => row.pid);describe("the memory cap on real processes", () => {- it.runIf(process.platform === "linux")("stops only the bot over its cap, the child its shell left included, and leaves the other bot running", async () => {+ const owners = (big: ChildProcess, small: ChildProcess): FootprintOwner[] => [+ { pid: big.pid!, botIds: ["bot_big"], kind: "engine", threads: ["t_big"] }, { pid: small.pid!, botIds: ["bot_small"], kind: "engine", threads: ["t_small"] },+ ];++ it.runIf(process.platform === "linux")("by default only writes the bot down: nothing is signalled", async () => {+ const big = engine(300), small = engine(10);+ await Promise.all([ready(big), ready(small)]);+ expect(await until(() => session(big.pid!).length === 4 && session(small.pid!).length === 4)).toBe(true);+ const signals: string[] = [];+ const dog = new BotMemoryWatchdog({+ cap: () => ({ mode: "log", bytes: 200 * MB }), list: () => linuxProcessList().rows, pss: (pid) => pssBytes(pid), startOf, graceMs: 2_000, owners: () => owners(big, small),+ pressure: () => ({ room: 0.1, short: true, freeBytes: 100 * MB }), busy: () => true, signal: (pid, value) => { signals.push(`${value} ${pid}`); process.kill(pid, value); }, log: () => {},+ });+ let events = await dog.check();+ if (!events.length) events = await dog.check();+ expect(events.map((event) => [event.botId, event.action])).toEqual([["bot_big", "logged"]]);+ expect(events[0]!.usedMB).toBeGreaterThan(300);+ expect(signals).toEqual([]);+ expect(session(big.pid!).every(alive)).toBe(true);+ }, 60_000);++ it.runIf(process.platform === "linux")("set to a number, with memory short: stops only the bot over its cap, the child its shell left included, and leaves the other bot running", async () => {const big = engine(300), small = engine(10);await Promise.all([ready(big), ready(small)]);// Both sessions are whole: the engine, two tool servers and the left-behind sleep.expect(await until(() => session(big.pid!).length === 4 && session(small.pid!).length === 4)).toBe(true);- const smallPids = session(small.pid!);+ const smallPids = session(small.pid!), bigPids = session(big.pid!);const signals: string[] = [];const dog = new BotMemoryWatchdog({- cap: () => 200 * MB, list: () => linuxProcessList().rows, pss: (pid) => pssBytes(pid), startOf, graceMs: 2_000,- owners: () => [{ pid: big.pid!, botIds: ["bot_big"], kind: "engine" }, { pid: small.pid!, botIds: ["bot_small"], kind: "engine" }],+ cap: () => ({ mode: "enforce", bytes: 200 * MB }), list: () => linuxProcessList().rows, pss: (pid) => pssBytes(pid), startOf, graceMs: 2_000, owners: () => owners(big, small),+ pressure: () => ({ room: 0.1, short: true, freeBytes: 100 * MB }), busy: () => true,signal: (pid, value) => { signals.push(`${value} ${pid}`); process.kill(pid, value); }, log: () => {},});- let stops = await dog.check();- // 300 MB of its own pages against 200 MB is past one and a half times the cap: one look is enough. Allow a second- // where the share read below that the first time.- if (!stops.length) stops = await dog.check();- expect(stops.map((stop) => stop.botId)).toEqual(["bot_big"]);- expect(stops[0]!.usedBytes).toBeGreaterThan(300 * MB);- expect(stops[0]!.pids.length).toBeGreaterThanOrEqual(4);+ // 300 MB of its own pages against 200 MB is past one and a half times the cap with memory short: one look is enough.+ // Allow a second where the share read below that the first time.+ let events = await dog.check();+ if (!events.length) events = await dog.check();+ expect(events.map((event) => [event.botId, event.action])).toEqual([["bot_big", "engine"]]);+ expect(events[0]!.usedMB).toBeGreaterThan(300);+ expect(bigPids.every((pid) => signals.includes(`SIGTERM ${pid}`))).toBe(true);expect(await until(() => session(big.pid!).length === 0)).toBe(true);expect(signals.some((line) => smallPids.includes(Number(line.split(" ")[1])))).toBe(false);expect(smallPids.every(alive)).toBe(true);diff --git a/server/bot-memory-cap.test.ts b/server/bot-memory-cap.test.tsnew file mode 100644index 0000000000..76d9a8ba0b--- /dev/null+++ b/server/bot-memory-cap.test.ts@@ -0,0 +1,340 @@+// The per-bot memory cap (bot-memory-cap.ts): watch only by default; a set number acts, only under pressure, on the bot+// using the most, in steps.+import { describe, expect, it } from "vitest";++import {+ BOT_CAP_FLOOR_BYTES, BotMemoryWatchdog, botMemoryCap, capLadder, OVER_FOR_MS, pssBytes, useBotMemoryWatchdog, withBotMemoryCap,+ type CapPressure, type CapSetting,+} from "./bot-memory-cap.ts";+import type { ProviderInstance, RuntimeEvent, RuntimeEventListener, SendTurnInput } from "./contracts.ts";+import { stoppedForRoom } from "./drivers/session-idle.ts";+import { memoryStopped } from "./engine-memory.ts";+import { hostFaultOf, retryCannotFix } from "./host-fault.ts";+import { capPressure } from "./host/bot-memory-cap-host.ts";+import type { FootprintOwner } from "./perf/bot-footprint.ts";+import type { ProcessRow } from "./perf/process-buckets.ts";+import { perfHealth, PERF_HEALTH_MAX_BYTES } from "./perf/perf-report.ts";+import { createTurnTimings } from "./perf/turn-timings.ts";+import { namesOwnCause } from "./process-shortage.ts";+import { retriesTeammateThread } from "./routine-recovery.ts";++const MB = 1024 * 1024, GB = 1024 * MB;+const settle = () => new Promise((resolve) => setTimeout(resolve, 25));++describe("the cap's setting", () => {+ const inputs = (memoryBytes: number, turns?: number) => ({ gate: "server" as const, memoryBytes, ...(turns === undefined ? {} : { turns }) });++ it("watches only by default, enforces only a set number, and is off where set off or on the desktop unless set", () => {+ const warned: string[] = [];+ expect(botMemoryCap({}, { gate: null, memoryBytes: 16 * GB })).toBeNull();+ expect(botMemoryCap({ OMB_BOT_MEMORY_MAX_MB: "3000" }, { gate: null, memoryBytes: 16 * GB })).toEqual({ mode: "enforce", bytes: 3000 * MB });+ expect(botMemoryCap({ OMB_BOT_MEMORY_MAX_MB: "off" }, inputs(8 * GB, 10))).toBeNull();+ expect(botMemoryCap({ OMB_BOT_MEMORY_MAX_MB: "0" }, inputs(8 * GB, 10))).toBeNull();+ expect(botMemoryCap({ OMB_BOT_MEMORY_MAX_MB: "10" }, inputs(8 * GB, 10))).toEqual({ mode: "enforce", bytes: 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(botMemoryCap({}, inputs(8 * GB, 10))).toEqual({ mode: "log", bytes: BOT_CAP_FLOOR_BYTES });+ expect(BOT_CAP_FLOOR_BYTES).toBe(1900 * MB);+ // "auto" is the default: watch only, with the computed value. 32 GB and 8 turns: 8 GB.+ expect(botMemoryCap({ OMB_BOT_MEMORY_MAX_MB: "auto" }, inputs(32 * GB, 8))).toEqual({ mode: "log", bytes: 8 * GB });+ expect(botMemoryCap({}, inputs(2 * GB, 2))?.bytes).toBe(Math.round(1.6 * GB));+ expect(botMemoryCap({}, inputs(64 * GB))?.bytes).toBe(BOT_CAP_FLOOR_BYTES);+ expect(botMemoryCap({ OMB_BOT_MEMORY_MAX_MB: "lots" }, inputs(8 * GB, 10), (line) => warned.push(line))).toEqual({ mode: "log", bytes: 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 (watch only) is used']);+ });++ it("reports the ladder's rungs this host offers, and watches with the watchdog", () => {+ const log: CapSetting = { mode: "log", bytes: GB };+ expect(capLadder(log, { 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(log, { platform: "linux", read, writable: () => true, exists: () => true })).toEqual({ rung: "watchdog", offered: ["systemd-scope", "cgroup", "watchdog"] });+ expect(capLadder(log, { 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();+ });++ it("reads pressure from engine-memory where the gate runs, else from memory directly", () => {+ const host = (availableGB: number) => () => ({ totalBytes: 16 * GB, availableBytes: availableGB * GB, swapFreeBytes: 0, oomKills: 0, fullStall10: 0 });+ expect(capPressure({ enabled: true, roomFactor: () => 0.2, shortOfRoom: () => true }, host(1))).toEqual({ room: 0.2, short: true, freeBytes: GB });+ expect(capPressure({ enabled: false, roomFactor: () => 1, shortOfRoom: () => false }, host(12))).toMatchObject({ room: 1, short: false });+ // 1 GB free of 16 GB: below the 1.6 GB floor, so short; a tenth of the room.+ expect(capPressure({ enabled: false, roomFactor: () => 1, shortOfRoom: () => false }, host(1))).toMatchObject({ room: 0.1, short: true });+ expect(capPressure({ enabled: false, roomFactor: () => 1, shortOfRoom: () => false }, () => null)).toEqual({ room: 1, short: false, freeBytes: null });+ });+});++/** Bot A: engine 200 (conversation ta) and its tool server 201 (900 MB: under its cap). Bot B: engine 300 (tb) with tool server 301, its browser+ * 500 (session bot-b) with Chrome 501; with `two`, a second engine 310 (tc) and its tool server 311; with `orphan`,+ * what an exited engine 320 left in its session (321). Shared: an engine 400 both bots use. Sizes in MB. */+function processes(sizes: { a?: number; b?: number; b2?: number; orphan?: number; browser?: 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 });+ const browser = sizes.browser ?? 100;+ return [+ row(100, 1, 200),+ row(200, 100, (sizes.a ?? 900) - 200), row(201, 200, 200, 200),+ row(300, 100, (sizes.b ?? 600) - 100), row(301, 300, 100, 300),+ ...(sizes.b2 ? [row(310, 100, sizes.b2 - 100), row(311, 310, 100, 310)] : []),+ ...(sizes.orphan ? [row(321, 1, sizes.orphan, 320)] : []),+ row(500, 1, browser * 0.4), row(501, 500, browser * 0.6, 500),+ row(400, 100, sizes.shared ?? 5000),+ ];+}+const OWNERS: FootprintOwner[] = [+ { pid: 200, botIds: ["bot_a"], kind: "engine", threads: ["ta"] }, { pid: 300, botIds: ["bot_b"], kind: "engine", threads: ["tb"] },+ { pid: 310, botIds: ["bot_b"], kind: "engine", threads: ["tc"] }, { pid: 320, botIds: ["bot_b"], kind: "engine", threads: ["td"], exited: true },+ { pid: 500, botIds: ["bot_b"], kind: "browser", session: "bot-b" }, { pid: 400, botIds: ["bot_a", "bot_b"], kind: "engine", threads: ["ta", "tb"] },+];+const ROOMY: CapPressure = { room: 1, short: false, freeBytes: 40 * GB };+const SHORT: CapPressure = { room: 0.1, short: true, freeBytes: 300 * MB };++/** A watchdog over `rows` with a 1,000 MB cap per engine. Every process's proportional size reads as its resident size. */+function dog(rows: () => ProcessRow[], options: {+ mode?: CapSetting["mode"]; pressure?: () => CapPressure; busy?: ReadonlySet<string>; owners?: () => FootprintOwner[];+ pss?: (pid: number) => number | null; startOf?: (pid: number) => string | null;+} = {}) {+ const signals: string[] = [], closed: string[] = [], logs: string[] = [];+ let clock = 1_800_000_000_000, pssReads = 0;+ const pss = options.pss ?? ((pid: number) => rows().find((row) => row.pid === pid)?.rssBytes ?? null);+ const watchdog = new BotMemoryWatchdog({+ cap: () => ({ mode: options.mode ?? "enforce", bytes: 1000 * MB }), list: rows, owners: options.owners ?? (() => OWNERS), pressure: options.pressure ?? (() => SHORT),+ pss: (pid) => { pssReads += 1; return pss(pid); }, startOf: options.startOf ?? ((pid) => `s${pid}`), graceMs: 0, now: () => clock,+ busy: (threadId) => (options.busy ?? new Set(["tb", "ta"])).has(threadId),+ signal: (pid, value) => signals.push(`${value} ${pid}`), closeBrowser: async (session) => { closed.push(session); }, log: (line) => logs.push(line),+ });+ return { watchdog, signals, closed, logs, pssReads: () => pssReads, advance: (ms: number) => { clock += ms; }, now: () => clock };+}++describe("watch only, the default", () => {+ it("writes down a bot over its cap (once while it stays over) and sends no signal, closes no browser, explains nothing", async () => {+ // Bot B at 1,700 MB against 1,000 MB, memory short: an opt-in cap would act.+ let sizes = { b: 1600 };+ const h = dog(() => processes(sizes), { mode: "log" });+ const [event] = await h.watchdog.check();+ expect(event).toEqual({ at: h.now(), botId: "bot_b", usedMB: 1700, measured: "pss", capMB: 1000, engines: 1, room: 0.1, freeMB: 300, pressure: true, action: "logged" });+ expect(h.logs).toEqual(["memory: bot bot_b uses 1700 MB (proportional), over the 1000 MB one bot may use with 1 engine running; room 0.1, 300 MB free: "+ + "watch only, nothing stopped (set OMB_BOT_MEMORY_MAX_MB to a number of MB to enforce)"]);+ for (let look = 0; look < 30; look++) { h.advance(10_000); expect(await h.watchdog.check()).toEqual([]); }+ expect(h.signals).toEqual([]);+ expect(h.closed).toEqual([]);+ expect(h.watchdog.stops()).toBe(0);+ expect(h.watchdog.flagged()).toBe(1);+ expect(h.watchdog.stopFor("tb", h.now())).toBeNull();+ expect(h.watchdog.stoppedEngine("tb", 300, h.now())).toBe(false);+ useBotMemoryWatchdog(h.watchdog);+ try { expect(stoppedForRoom("tb", 300)).toBe(false); } finally { useBotMemoryWatchdog(null); }+ // Back under, then over again past the window: a second event.+ sizes = { b: 500 };+ h.advance(20_000);+ await h.watchdog.check();+ sizes = { b: 1300 };+ h.advance(20_000);+ expect(await h.watchdog.check()).toEqual([]);+ h.advance(OVER_FOR_MS);+ expect((await h.watchdog.check()).map((noted) => noted.action)).toEqual(["logged"]);+ expect(h.watchdog.events().map((noted) => noted.usedMB)).toEqual([1700, 1400]);+ expect(h.signals).toEqual([]);+ });++ it("puts its events in the health report's perf part, trimmed with the bots", () => {+ const timings = createTurnTimings({ now: () => 1_800_000_000_000 });+ const event = { at: 1, botId: "bot_b", usedMB: 1700, measured: "pss", capMB: 1000, engines: 1, room: 0.1, freeMB: 300, pressure: true, action: "logged" };+ const cap = { mb: 1000, mode: "log" as const, rung: "watchdog", stops: 0, flagged: 5, events: Array.from({ length: 5 }, () => event) };+ const base = { hour: timings.window(), day: timings.day(), live: timings.live(), limits: null, process: null };+ const shown = perfHealth({ ...base, bots: { at: 1, bots: 0, shown: [], shared: { procs: 0, threads: 0, rssMB: 0, cpuS: 0, cpuPct: 0, engines: 0, browsers: 0 }, cap } });+ expect(shown.bots?.cap?.events).toHaveLength(5);+ const many = { at: 1, bots: 100, shared: { procs: 1, threads: 1, rssMB: 1, cpuS: 1, cpuPct: 1, engines: 1, browsers: 1 }, cap,+ shown: Array.from({ length: 200 }, (_, index) => ({ id: `bot_${"x".repeat(56)}${index}`, procs: 999, threads: 9999, rssMB: 99999, peakMB: 99999, cpuS: 99999.9, cpuPct: 100, engines: 9, browsers: 1 })) };+ const trimmed = perfHealth({ ...base, bots: many });+ expect(JSON.stringify(trimmed).length).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);+ expect(trimmed.bots?.shown).toHaveLength(3);+ expect(trimmed.bots?.cap?.events).toHaveLength(1);+ });+});++describe("an opt-in cap (a number of MB set)", () => {+ it("stops nothing while the server has room to spare, however far over the cap a bot is", async () => {+ const h = dog(() => processes({ b: 3000 }), { pressure: () => ROOMY });+ for (let look = 0; look < 10; look++) { await h.watchdog.check(); h.advance(OVER_FOR_MS); }+ expect(h.signals).toEqual([]);+ expect(h.closed).toEqual([]);+ expect(h.watchdog.events().map((event) => [event.action, event.pressure])).toEqual([["held", false]]);+ // A room factor below 0.3 is pressure even before memory is short.+ const low = dog(() => processes({ b: 1600 }), { pressure: () => ({ room: 0.25, short: false, freeBytes: 4 * GB }) });+ await low.watchdog.check();+ low.advance(OVER_FOR_MS);+ expect((await low.watchdog.check()).map((event) => event.action)).toEqual(["engine"]);+ });++ it("gives a bot one engine's cap per engine it runs: two conversations are not one engine's budget", async () => {+ // Engines 300 and 310 at 700 MB each with a 100 MB browser: 1,500 MB against 2,000 MB.+ const two = dog(() => processes({ b: 700, b2: 700 }), { mode: "log", pressure: () => ROOMY });+ for (let look = 0; look < 5; look++) { expect(await two.watchdog.check()).toEqual([]); two.advance(OVER_FOR_MS); }+ // One engine of the same 1,500 MB: over.+ const one = dog(() => processes({ b: 1400 }), { mode: "log", pressure: () => ROOMY });+ await one.watchdog.check();+ one.advance(OVER_FOR_MS);+ expect((await one.watchdog.check()).map((event) => [event.botId, event.capMB, event.engines])).toEqual([["bot_b", 1000, 1]]);+ });++ it("stops in steps: what an exited engine left and the idle engines first, then (measured again) the largest busy engine, never another bot's or a shared one", async () => {+ // Bot B: busy engine 300 (1,600 MB), idle engine 310 (300 MB), an exited engine's leftover 321 (300 MB), browser 100 MB:+ // 2,300 MB against 2,000 MB. Bot A (1,200 MB) is over its own cap too but uses less. The shared engine is 5,000 MB.+ let sizes = { a: 1200, b: 1600, b2: 300, orphan: 300 };+ const h = dog(() => processes(sizes));+ expect(await h.watchdog.check()).toEqual([]);+ h.advance(10_000);+ // Memory short and over on a second look: the first step.+ expect((await h.watchdog.check()).map((event) => event.action)).toEqual(["idle"]);+ expect(h.signals).toEqual(["SIGTERM 310", "SIGTERM 311", "SIGTERM 321", "SIGKILL 310", "SIGKILL 311", "SIGKILL 321"]);+ expect(h.closed).toEqual([]);+ // Those gone, one engine of 1,600 MB and its browser: still over. The next step waits for a new measure.+ sizes = { a: 1200, b: 1600, b2: 0, orphan: 0 };+ h.signals.length = 0;+ expect(await h.watchdog.check()).toEqual([]);+ h.advance(5_000);+ expect((await h.watchdog.check()).map((event) => event.action)).toEqual(["engine"]);+ expect(h.signals).toEqual(["SIGTERM 300", "SIGTERM 301", "SIGKILL 300", "SIGKILL 301"]);+ expect(h.closed).toEqual([]);+ expect(h.watchdog.stops()).toBe(2);+ expect(h.logs.at(-1)).toMatch(/^memory: bot bot_b uses 1700 MB \(proportional\), over the 1000 MB .*: stopping its largest busy engine$/);+ });++ it("acts on the bot using the most only, and closes a browser by its session alone when that is the largest", async () => {+ // Both far over with memory short: due at once. Bot B (2,000 MB) over bot A (1,500 MB): bot B only; its browser is+ // larger than its busy engine.+ const h = dog(() => processes({ a: 1500, b: 600, browser: 1400 }));+ const [event, ...more] = await h.watchdog.check();+ expect(more).toEqual([]);+ expect(event).toMatchObject({ botId: "bot_b", action: "browser" });+ await h.watchdog.closed();+ expect(h.closed).toEqual(["bot-b"]);+ expect(h.signals).toEqual([]);+ });++ it("stops at once only far over with memory short, and with room factor alone waits the window", async () => {+ const far = dog(() => processes({ b: 1600 }), { busy: new Set(["tb"]) });+ expect((await far.watchdog.check()).map((event) => event.action)).toEqual(["engine"]);+ const near = dog(() => processes({ b: 1200 }), { pressure: () => ({ room: 0.2, short: false, freeBytes: 2 * GB }) });+ expect(await near.watchdog.check()).toEqual([]);+ near.advance(20_000);+ expect(await near.watchdog.check()).toEqual([]);+ near.advance(10_000);+ expect((await near.watchdog.check()).map((event) => event.action)).toEqual(["engine"]);+ });++ it("never stops an engine other conversations may join, even when it is the bot's largest", async () => {+ const owners = () => OWNERS.map((owner) => (owner.pid === 300 ? { ...owner, shareable: true } : owner));+ const h = dog(() => processes({ b: 1600, b2: 400 }), { owners, busy: new Set(["tb", "tc"]) });+ await h.watchdog.check();+ h.advance(OVER_FOR_MS);+ await h.watchdog.check();+ expect(h.signals).toEqual(["SIGTERM 310", "SIGTERM 311", "SIGKILL 310", "SIGKILL 311"]);+ });++ it("signals nothing whose start can't be read now, and kills only what is still the bot's after the grace", async () => {+ const unread = dog(() => processes({ b: 1600 }), { startOf: () => null });+ await unread.watchdog.check();+ expect(unread.signals).toEqual([]);+ const moved = dog(() => processes({ b: 1600 }), { startOf: (pid) => (pid === 301 ? "later" : `s${pid}`) });+ await moved.watchdog.check();+ expect(moved.signals).toEqual(["SIGTERM 300", "SIGKILL 300"]);+ // Read again after the grace: 301 is another process now (another start), so it gets no KILL.+ let rows = processes({ b: 1600 });+ const again = dog(() => rows);+ const checking = again.watchdog.check();+ rows = rows.map((row) => (row.pid === 301 ? { ...row, start: "other" } : row));+ await checking;+ expect(again.signals).toEqual(["SIGTERM 300", "SIGTERM 301", "SIGKILL 300"]);+ });++ it("counts shared pages once, and a bot whose shares can't be read only when it is far over", async () => {+ const shared = dog(() => processes({ a: 1600 }), { pss: (pid) => (pid === 200 ? 700 * MB : pid === 201 ? 200 * MB : null), busy: new Set(["ta"]) });+ for (let look = 0; look < 3; look++) { expect(await shared.watchdog.check()).toEqual([]); shared.advance(OVER_FOR_MS); }+ let sizes = { a: 1300 };+ const unread = dog(() => processes(sizes), { pss: () => null, busy: new Set(["ta"]) });+ for (let look = 0; look < 3; look++) { expect(await unread.watchdog.check()).toEqual([]); unread.advance(OVER_FOR_MS); }+ sizes = { a: 1600 };+ await unread.watchdog.check();+ unread.advance(10_000);+ expect((await unread.watchdog.check()).map((event) => [event.botId, event.measured])).toEqual([["bot_a", "estimated"]]);+ });++ it("reads each process's proportional size again only every few looks", async () => {+ const h = dog(() => processes({ b: 1600 }), { mode: "log", pressure: () => ROOMY });+ await h.watchdog.check();+ const first = h.pssReads();+ h.advance(5_000);+ await h.watchdog.check();+ h.advance(5_000);+ await h.watchdog.check();+ expect(h.pssReads()).toBe(first);+ h.advance(10_000);+ await h.watchdog.check();+ expect(h.pssReads()).toBe(first * 2);+ });++ it("does not look while no engine runs, and its timer's body never rejects", async () => {+ let lists = 0;+ const idle = new BotMemoryWatchdog({ cap: () => ({ mode: "enforce", bytes: MB }), list: () => { lists += 1; return []; }, pressure: () => SHORT,+ owners: () => [{ pid: 500, botIds: ["bot_b"], kind: "browser" }, { pid: 320, botIds: ["bot_b"], kind: "engine", exited: true }] });+ expect(await idle.check()).toEqual([]);+ expect(lists).toBe(0);+ const logs: string[] = [];+ const broken = new BotMemoryWatchdog({ cap: () => ({ mode: "enforce", bytes: MB }), list: () => { throw new Error("no /proc"); }, owners: () => OWNERS, pressure: () => SHORT, log: (line) => logs.push(line) });+ await expect(broken.tick()).resolves.toBeUndefined();+ const throwing = new BotMemoryWatchdog({ cap: () => { throw new Error("bad cap"); }, list: () => [], owners: () => OWNERS, pressure: () => SHORT, log: (line) => logs.push(line) });+ await expect(throwing.tick()).resolves.toBeUndefined();+ expect(logs).toEqual(["memory: the per-bot check failed: no /proc", "memory: the per-bot check failed: bad cap"]);+ });+});++describe("the line a stopped turn ends with", () => {+ it("is shown on the turn whose engine was stopped, not another conversation of the same bot", async () => {+ // Bot B: busy engine 300 (tb, 3,000 MB) and 310 (tc, 200 MB, busy too), its browser 100 MB: 3,300 MB against 2,000 MB,+ // far over with memory short. The largest busy engine is 300.+ const h = dog(() => processes({ b: 3000, b2: 200 }), { busy: new Set(["tb", "tc"]) });+ 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));+ for (const [threadId, botId] of [["tb", "bot_b"], ["tc", "bot_b"], ["ta", "bot_a"]]) await instance.adapter.sendTurn({ threadId, botId, text: "go" } as SendTurnInput);+ h.advance(1_000);+ expect((await h.watchdog.check()).map((event) => event.action)).toEqual(["engine"]);+ expect(h.signals).toEqual(["SIGTERM 300", "SIGTERM 301", "SIGKILL 300", "SIGKILL 301"]);+ 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: "tc", turnId: "t", type: "runtime.error", message: "its own failure" });+ emit({ threadId: "ta", turnId: "t", type: "runtime.error", message: "something else" });+ const line = "Researcher used more memory than this computer allows for one bot (3300 MB of 2000 MB) while memory was running short, 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 this computer more memory.";+ expect(shown()).toEqual([line, "turn.completed", "its own failure", "something else"]);+ expect(seen[0]).toMatchObject({ text: { key: "chat.notice.botMemoryCap", params: { bot: "Researcher", used: "3300", cap: "2000" } } });+ // A fault a retry cannot fix: no automatic retry or Chief retry starts the bot into the same cap again.+ expect(hostFaultOf(line)).toBe("bot_memory");+ expect(retryCannotFix("bot_memory")).toBe(true);+ expect(retriesTeammateThread(line)).toBe(false);+ expect(namesOwnCause(line)).toBe(true);+ expect(memoryStopped(line)).toBe(false);+ // The driver does not resend the stopped engine's turn; the other conversation's engine was not stopped.+ useBotMemoryWatchdog(h.watchdog);+ try {+ expect(stoppedForRoom("tb", 300)).toBe(true);+ expect(stoppedForRoom("tc", 310)).toBe(false);+ expect(stoppedForRoom("tc", 300)).toBe(false);+ } finally { useBotMemoryWatchdog(null); }+ 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"]);+ });+});diff --git a/server/bot-memory-cap.ts b/server/bot-memory-cap.tsindex 61d50f2f90..099e3fc86a 100644--- a/server/bot-memory-cap.ts+++ b/server/bot-memory-cap.ts@@ -1,19 +1,23 @@-// 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.+// How much of the server's memory one bot may use. By default this only watches and writes down: a bot over its cap is+// recorded ("would have stopped": its measured memory, the cap, its engines, the room left) in the health report's perf+// part and the server log, and nothing is signalled or closed. Only a number of MB set in OMB_BOT_MEMORY_MAX_MB makes it+// act, and then only when the server is short of memory, only on the bot using the most, and in steps: what the bot left+// running and its idle engines first, then (measured again, still over) its largest busy engine or browser, never all at+// once. A process several bots share, or one other conversations may join, is never stopped.+//+// 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. Every few+// seconds, while an engine runs, the watchdog 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) and checks a bot+// over its cap by proportional set size (shared pages counted once).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 { attributeRows, type BotTally, type FootprintOwner, type FootprintUnit } from "./perf/bot-footprint.ts";import type { ProcessRow } from "./perf/process-buckets.ts";import type { GateHost } from "./process-room.ts";@@ -28,11 +32,20 @@ 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;+/** A bot over its cap this long (or, with memory short, on two looks in a row) is due. */+export const OVER_FOR_MS = 30_000;+/** This far over (by proportional size) with memory short, and one look is enough. */+const FAR_OVER = 1.5;+/** Room for engines below this share (EngineMemory.roomFactor: 1 with room to spare, down to 0.1) is pressure. */+export const PRESSURE_ROOM = 0.3;+/** A process's proportional size is read again after this long: a look every few seconds reads few files. */+const PSS_FRESH_MS = 15_000;const STOP_GRACE_MS = 3_000;-/** A turn that fails this long after its bot was stopped for memory says so. */+/** A turn that fails this long after its engine was stopped for memory says so. */const EXPLAIN_FOR_MS = 60_000;+/** The health report carries this many recent events; the server keeps a few more. */+export const EVENTS_SHOWN = 5;+const EVENTS_KEPT = 20;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. */@@ -43,18 +56,24 @@ export interface CapInputs {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 {+/** "log": watch and write down only (the default); "enforce": act, set by a number in OMB_BOT_MEMORY_MAX_MB. */+export type CapMode = "log" | "enforce";+/** The memory one engine of a bot may use: a bot with several engines running (several conversations) may use that many. */+export interface CapSetting { mode: CapMode; bytes: number }++/** OMB_BOT_MEMORY_MAX_MB: a number of MB to enforce (any Linux host, desktop included: the watchdog reads /proc); "off" or 0 for no watchdog at all;+ * unset or "auto" to only write down where a bot goes over the default, which is computed 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 botMemoryCap(env: NodeJS.ProcessEnv, inputs: CapInputs, warn: (line: string) => void = () => undefined): CapSetting | 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 (raw && /^\d+$/.test(raw)) return { mode: "enforce", bytes: 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 (watch only) 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)));+ return { mode: "log", bytes: Math.round(Math.min(inputs.memoryBytes * CAP_SHARE, Math.max(BOT_CAP_FLOOR_BYTES, fair))) };}export type CapRung = "systemd-scope" | "cgroup" | "watchdog" | "none";@@ -64,7 +83,7 @@ const writable = (path: string) => { try { accessSync(path, constants.W_OK); ret/** 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[] } {+export function capLadder(cap: CapSetting | 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[] = [];@@ -74,7 +93,7 @@ export function capLadder(capBytes: number | null, deps: { platform?: NodeJS.Plaif (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 };+ return { rung: cap === null ? "none" : "watchdog", offered };}/** A process's proportional set size from /proc/<pid>/smaps_rollup; null where it can't be read. */@@ -83,133 +102,260 @@ export function pssBytes(pid: number, read: Read = readText): number | null {return found ? Number(found[1]) * 1024 : null;}-export interface CapStop { botId: string; at: number; usedBytes: number; capBytes: number; pids: number[] }+/** The server's room when the watchdog looks: engine-memory's room factor (1 with room to spare, down to 0.1), whether+ * admission would hold a new engine back (memory below its floor), and the memory free, where read. */+export interface CapPressure { room: number; short: boolean; freeBytes: number | null }++/** What the watchdog did, or would have done, about one bot: bot ids and numbers only. */+export interface CapEvent {+ at: number;+ botId: string;+ usedMB: number;+ /** "pss": every process's proportional size read; "estimated": some read as resident size, which errs high. */+ measured: "pss" | "estimated";+ /** The cap for this bot now: the cap for one engine times its engines running. */+ capMB: number;+ engines: number;+ room: number;+ freeMB: number | null;+ /** Whether the server was short of memory then: the opt-in cap acts only then. */+ pressure: boolean;+ /** logged: watch only (the default); held: an opt-in cap with room to spare; idle: stopped what it left running and its+ * idle engines; engine: stopped its largest busy engine; browser: closed its largest browser. */+ action: "logged" | "held" | "idle" | "engine" | "browser";+}++/** An engine stopped for its bot's memory: the conversations it ran, for the line their turn ends with. */+export interface CapStop { at: number; pid: number; threads: readonly string[]; botId: string; usedBytes: number; capBytes: number }++/** Conversations with a turn running now, as every engine's adapter sees them (withBotMemoryCap). */+const runningTurns = new Set<string>();export interface WatchdogOptions {- cap: () => number | null;+ cap: () => CapSetting | null;list: () => readonly ProcessRow[];owners: () => readonly FootprintOwner[];+ pressure: () => CapPressure;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>;+ /** Closes one browser session the way a memory stop closes one (its sign-ins saved). */+ closeBrowser?: (session: 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. */+ /** What each pid's start is now (Linux's start tick): only the process that was read is signalled. */startOf?: (pid: number) => string | null;+ /** Whether a conversation runs a turn now; every engine's adapter tells by default. */+ busy?: (threadId: string) => boolean;log?: (line: string) => void;now?: () => number;intervalMs?: number;graceMs?: number;}+const mb = (bytes: number) => Math.round(bytes / MB);+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>();+ /** By bot: since when it has been over its cap, how many looks in a row, and whether its first step was taken. */+ readonly #over = new Map<string, { since: number; looks: number; logged: boolean; stepped: boolean }>();+ readonly #pss = new Map<number, { start: string; bytes: number | null; at: number }>();+ /** Engines stopped, by pid: a pid the system later gives to another engine is not one of them for long. */+ readonly #stopped = new Map<number, CapStop>();+ readonly #events: CapEvent[] = [];#timer: ReturnType<typeof setInterval> | null = null;- #closing: Promise<unknown> = Promise.resolve();+ #acting: Promise<unknown> = Promise.resolve();#running = false;- #count = 0;+ #stops = 0;+ #flagged = 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 = setInterval(() => void this.tick(), 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 [];+ /** The timer's body: never rejects (an unhandled rejection every few seconds would restart the server). */+ async tick(): Promise<void> {+ try { await this.check(); } catch (error) { this.#log(`memory: the per-bot check failed: ${error instanceof Error ? error.message : String(error)}`); }+ }++ #log(line: string): void { try { (this.#options.log ?? ((text) => console.warn(text)))(line); } catch {} }++ /** One look at every bot; resolves with what it did or would have done. */+ async check(): Promise<CapEvent[]> {+ if (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.- // Where a process's share can't be read (another user's, a sandboxed one), its resident pages stand in; they err- // high, so a bot counted that way is stopped only when it stays far over.- let used = 0, estimated = false;- for (const pid of tally.pids) {- const share = this.#options.pss?.(pid) ?? null;- if (share === null) estimated = true;- used += share ?? rowRss(rows, pid);- }- if (used <= cap || (estimated && used < cap * FAR_OVER)) { this.#strikes.delete(id); continue; }- const strikes = (this.#strikes.get(id) ?? 0) + 1;- this.#strikes.set(id, strikes);- if (strikes >= STRIKES || (!estimated && used >= cap * FAR_OVER)) over.push({ id, tally, used });+ try { return await this.#look(); } finally { this.#running = false; }+ }++ async #look(): Promise<CapEvent[]> {+ const setting = this.#options.cap();+ if (setting === null) return [];+ const owners = this.#options.owners();+ // Nothing a bot runs without an engine is worth a look.+ if (!owners.some((owner) => owner.kind === "engine" && !owner.exited)) { this.#over.clear(); return []; }+ const now = (this.#options.now ?? Date.now)();+ const rows = this.#options.list();+ const byPid = new Map(rows.map((row) => [row.pid, row]));+ for (const pid of this.#pss.keys()) if (!byPid.has(pid)) this.#pss.delete(pid);+ const { bots } = attributeRows(rows, owners);+ for (const id of this.#over.keys()) if (!bots.has(id)) this.#over.delete(id);+ const due: Array<{ id: string; tally: BotTally; used: number; estimated: boolean; cap: number; sizes: Map<number, number> }> = [];+ let pressure: CapPressure | null = null;+ /** The bot over its cap using the most, due or not: the opt-in cap acts on no other. */+ let largest: { id: string; used: number } | null = null;+ for (const [id, tally] of bots) {+ const cap = setting.bytes * Math.max(1, tally.engines);+ if (tally.rssBytes <= cap) { this.#over.delete(id); continue; }+ // Resident pages count what several processes share once each; their proportional share counts it once. Where a+ // process's share can't be read (another user's, a sandboxed one), its resident pages stand in; they err high, so+ // a bot counted that way is due only when it is far over.+ let used = 0, estimated = false;+ const sizes = new Map<number, number>();+ for (const pid of tally.pids) {+ const share = this.#share(pid, byPid.get(pid), now);+ if (share === null) estimated = true;+ const size = share ?? byPid.get(pid)?.rssBytes ?? 0;+ sizes.set(pid, size);+ used += size;}- return await Promise.all(over.map(({ id, tally, used }) => this.#stopBot(id, tally, used, cap, starts)));- } finally { this.#running = false; }+ if (used <= cap || (estimated && used < cap * FAR_OVER)) { this.#over.delete(id); continue; }+ if (!largest || used > largest.used) largest = { id, used };+ const over = this.#over.get(id) ?? { since: now, looks: 0, logged: false, stepped: false };+ over.looks += 1;+ this.#over.set(id, over);+ pressure ??= this.#options.pressure();+ // Far over counts at once only before a first step: after one, the next waits for two new measures.+ const long = now - over.since >= OVER_FOR_MS, critical = pressure.short && (over.looks >= 2 || (!over.stepped && !estimated && used >= cap * FAR_OVER));+ if (long || critical) due.push({ id, tally, used, estimated, cap, sizes });+ }+ if (!due.length || pressure === null) return [];+ const pressed = pressure.short || pressure.room < PRESSURE_ROOM;+ const event = (bot: (typeof due)[number], action: CapEvent["action"]): CapEvent => ({+ at: now, botId: bot.id, usedMB: mb(bot.used), measured: bot.estimated ? "estimated" : "pss", capMB: mb(bot.cap), engines: bot.tally.engines,+ room: Math.round(pressure!.room * 100) / 100, freeMB: pressure!.freeBytes === null ? null : mb(pressure!.freeBytes), pressure: pressed, action,+ });+ due.sort((a, b) => b.used - a.used);+ if (setting.mode === "log" || !pressed) {+ // Each bot written down once while it stays over: a bot over for an hour is one event, not seven hundred.+ const noted: CapEvent[] = [];+ for (const bot of due) {+ const over = this.#over.get(bot.id)!;+ if (over.logged) continue;+ over.logged = true;+ noted.push(event(bot, setting.mode === "log" ? "logged" : "held"));+ this.#note(noted.at(-1)!, setting.mode === "log"+ ? "watch only, nothing stopped (set OMB_BOT_MEMORY_MAX_MB to a number of MB to enforce)"+ : "nothing stopped: the server has room to spare");+ }+ return noted;+ }+ // Only the bot using the most: one that is waiting for a new measure after a step keeps the others waiting too.+ const top = due[0]!;+ if (top.id !== largest?.id) return [];+ const over = this.#over.get(top.id)!;+ const units = [...top.tally.units.values()].filter((unit) => !unit.shareable);+ const busy = this.#options.busy ?? ((threadId: string) => runningTurns.has(threadId));+ const first = over.stepped ? [] : units.filter((unit) => unit.kind === "engine" && (unit.exited || !unit.threads.some(busy)));+ let step: { action: CapEvent["action"]; units: FootprintUnit[] };+ if (first.length) step = { action: "idle", units: first };+ else {+ const size = (unit: FootprintUnit) => unit.pids.reduce((sum, pid) => sum + (top.sizes.get(pid) ?? 0), 0);+ const largest = units.filter((unit) => !unit.exited).sort((a, b) => size(b) - size(a))[0];+ if (!largest) return [];+ step = { action: largest.kind === "browser" ? "browser" : "engine", units: [largest] };+ }+ // The next step waits for a new measure past the window (or memory still short on two looks).+ over.stepped = true;+ over.since = now;+ over.looks = 0;+ const done = event(top, step.action);+ this.#stops += 1;+ this.#note(done, step.action === "idle" ? `stopping what it left running and its idle engines (${step.units.length})`+ : step.action === "engine" ? "stopping its largest busy engine" : "closing its largest browser");+ for (const unit of step.units) {+ if (unit.kind === "engine" && !unit.exited) this.#stopped.set(unit.root, { at: now, pid: unit.root, threads: [...unit.threads], botId: top.id, usedBytes: top.used, capBytes: top.cap });+ }+ for (const [pid, stop] of this.#stopped) if (now - stop.at > EXPLAIN_FOR_MS) this.#stopped.delete(pid);+ const browsers = step.units.filter((unit) => unit.kind === "browser");+ const engines = step.units.filter((unit) => unit.kind === "engine");+ const starts = new Map(rows.map((row) => [row.pid, row.start]));+ // The browser closes on its own time (it waits for the stopped turn to let it go): the next look does not wait.+ const closing = browsers.map((unit) => (unit.session !== undefined && this.#options.closeBrowser ? this.#options.closeBrowser(unit.session).catch(() => undefined) : Promise.resolve()));+ await this.#signalUnits(top.id, engines, starts);+ this.#acting = Promise.all(closing);+ return [done];+ }++ #note(event: CapEvent, what: string): void {+ this.#events.push(event);+ if (this.#events.length > EVENTS_KEPT) this.#events.splice(0, this.#events.length - EVENTS_KEPT);+ if (event.action === "logged" || event.action === "held") this.#flagged += 1;+ this.#log(`memory: bot ${event.botId} uses ${event.usedMB} MB (${event.measured === "pss" ? "proportional" : "estimated from resident"}), over the ${event.capMB} MB `+ + `one bot may use with ${event.engines} engine${event.engines === 1 ? "" : "s"} running; room ${event.room}, ${event.freeMB === null ? "free memory unknown" : `${event.freeMB} MB free`}: ${what}`);+ }++ /** A pid's proportional size, read again only when stale or the pid is another process now. */+ #share(pid: number, row: ProcessRow | undefined, now: number): number | null {+ if (!this.#options.pss) return null;+ const known = this.#pss.get(pid);+ if (known && row && known.start === row.start && now - known.at < PSS_FRESH_MS) return known.bytes;+ const bytes = this.#options.pss(pid);+ if (row) this.#pss.set(pid, { start: row.start, bytes, at: now });+ return bytes;}- 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));+ /** TERM to each unit's processes still the ones read; after the grace, the list is read and attributed again and KILL+ * goes only to what is still this bot's, through the same record, with the same start. */+ async #signalUnits(botId: string, units: readonly FootprintUnit[], starts: ReadonlyMap<number, string>): Promise<void> {+ if (!units.length) return;+ const 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); };+ // A pid whose start can't be read now, or reads as another's, 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 {} };+ const roots = new Set(units.map((unit) => unit.root));+ send(units.flatMap((unit) => unit.pids), "SIGTERM");+ await new Promise((resolve) => { const timer = setTimeout(resolve, this.#options.graceMs ?? STOP_GRACE_MS); timer.unref?.(); });+ let still: number[] = [];try {- send(engine, "SIGTERM");- // The browser closes on its own time (it waits for the stopped turn to let it go): the next look at every other bot- // does not wait for it.- const closing = browser.size && this.#options.closeBrowsers ? this.#options.closeBrowsers(botId).catch(() => undefined) : Promise.resolve();- if (browser.size && !this.#options.closeBrowsers) send([...browser], "SIGTERM");- await new Promise((resolve) => { const timer = setTimeout(resolve, this.#options.graceMs ?? STOP_GRACE_MS); timer.unref?.(); });- send(engine, "SIGKILL");- if (browser.size && !this.#options.closeBrowsers) send([...browser], "SIGKILL");- this.#closing = closing.finally(() => this.#stopping.delete(botId));- } catch { this.#stopping.delete(botId); }- return stop;+ const again = this.#options.list();+ const tally = attributeRows(again, this.#options.owners()).bots.get(botId);+ still = [...tally?.units.values() ?? []].filter((unit) => roots.has(unit.root) && !unit.shareable).flatMap((unit) => unit.pids)+ .filter((pid) => again.find((row) => row.pid === pid)?.start === starts.get(pid));+ } catch {}+ send(still, "SIGKILL");}- /** 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;+ /** The stop of the engine that ran this conversation, while its turn should say so. */+ stopFor(threadId: string, at: number = Date.now()): CapStop | null {+ for (const stop of this.#stopped.values()) if (stop.threads.includes(threadId) && at - stop.at <= EXPLAIN_FOR_MS) return stop;+ return null;}- /** 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;+ /** Whether this conversation's engine process (`pid`, the one that exited) was stopped for its bot's memory: its driver+ * does not start it again at once. */+ stoppedEngine(threadId: string, pid: number | undefined, at: number = Date.now()): boolean {+ const stop = pid === undefined ? undefined : this.#stopped.get(pid);+ return stop !== undefined && stop.threads.includes(threadId) && at - stop.at <= EXPLAIN_FOR_MS;}- /** Resolves once the last stop's browser close has finished: for tests. */- closed(): Promise<unknown> { return this.#closing; }+ /** Resolves once the last step's browser close has finished: for tests. */+ closed(): Promise<unknown> { return this.#acting; }- /** Bots stopped since the server started. */- stops(): number { return this.#count; }+ /** Steps taken since the server started (the opt-in cap only). */+ stops(): number { return this.#stops; }+ /** Bots written down as over their cap with nothing stopped. */+ flagged(): number { return this.#flagged; }+ /** The most recent events, newest last. */+ events(limit = EVENTS_SHOWN): CapEvent[] { return this.#events.slice(-limit); }}-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)) });+/** The line a turn ends with when its engine was stopped for its bot's memory. */+export function capStopFailure(botName: string, stop: Pick<CapStop, "usedBytes" | "capBytes">): ReturnType<typeof noticeFailure> {+ return noticeFailure("chat.notice.botMemoryCap", { bot: botName, used: String(mb(stop.usedBytes)), cap: String(mb(stop.capBytes)) });}let watchdog: BotMemoryWatchdog | null = null;@@ -221,21 +367,22 @@ export function useBotMemoryWatchdog(dog: BotMemoryWatchdog | null, botName?: (bif (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;+/** Whether this conversation's engine (`pid`) was stopped for its bot's memory (session-idle.ts stoppedForRoom). */+export const stoppedForBotMemory = (threadId: string, pid?: number): boolean => watchdog?.stoppedEngine(threadId, 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.+ * Every engine's adapter: a turn whose engine the watchdog stopped for its bot's memory fails with that reason, never in+ * silence or as the engine's own failure; and the conversations running a turn, which the watchdog never takes for+ * idle. 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 turns = new Map<string, 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 at = turns.get(threadId), stop = at === undefined ? null : dog()?.stopFor(threadId, now()) ?? null;+ return at !== undefined && stop && stop.at >= at ? stop : null;};const present = (item: RuntimeEvent): RuntimeEvent[] => {if (item.type !== "runtime.error" && item.type !== "turn.completed") return [item];@@ -253,46 +400,56 @@ export function withBotMemoryCap(instance: ProviderInstance, dog: () => BotMemor};adapter.onEvent((item) => {if (item.type !== "turn.completed") return;+ runningTurns.delete(item.threadId);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() });+ turns.set(input.threadId, now());+ runningTurns.add(input.threadId);explained.delete(input.threadId);- return adapter.sendTurn(input);+ try { return await adapter.sendTurn(input); } catch (error) { runningTurns.delete(input.threadId); throw error; }},};return instance;}-export interface CapReport { mb: number | null; rung: CapRung; offered: CapRung[]; stops: number }-let report: () => CapReport = () => ({ mb: null, rung: "none", offered: [], stops: 0 });+export interface CapReport {+ mb: number | null; mode: CapMode | null; rung: CapRung; offered: CapRung[];+ /** Steps the opt-in cap took, and bots written down as over with nothing stopped, since the server started. */+ stops: number; flagged: number;+ events: CapEvent[];+}+let report: () => CapReport = () => ({ mb: null, mode: null, rung: "none", offered: [], stops: 0, flagged: 0, events: [] });/** 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;+ closeBrowser: (session: string) => Promise<void>; list: () => readonly ProcessRow[]; startOf: (pid: number) => string | null; pressure: () => CapPressure;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() }) },+ const cap = () => botMemoryCap(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 });+ const dog = ladder.rung === "watchdog" ? new BotMemoryWatchdog({ cap, list: deps.list, owners: deps.owners, pressure: deps.pressure, pss: (pid) => pssBytes(pid), closeBrowser: deps.closeBrowser, startOf: deps.startOf, log }) : null;+ report = () => {+ const now = dog ? cap() : null;+ return { mb: now ? mb(now.bytes) : null, mode: now?.mode ?? null, rung: dog ? ladder.rung : "none", offered: ladder.offered, stops: dog?.stops() ?? 0, flagged: dog?.flagged() ?? 0, events: dog?.events() ?? [] };+ };useBotMemoryWatchdog(dog, deps.botName);- if (dog) {+ if (dog && first) {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(", ")}` : ""}`);+ log(`memory: one bot may use up to ${mb(first.bytes)} MB per engine it runs (${first.mode === "enforce" ? `${BOT_MEMORY_ENV}; enforced when memory runs short` : "the default for this server's memory and turns; watch only, nothing is stopped"}); `+ + `this server checks every ${Math.round(WATCHDOG_MS / 1000)} s while an engine runs${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. */+/** The cap in force, how it is enforced, and what it did or would have done: for the health report. */export const botMemoryCapReport = (): CapReport => report();diff --git a/server/chat-notices.ts b/server/chat-notices.tsindex 31ca6ab728..3faa5f39ef 100644--- a/server/chat-notices.ts+++ b/server/chat-notices.ts@@ -151,7 +151,7 @@ export const CHAT_NOTICE = {"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 computer 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 this computer more memory.",+ "{bot} used more memory than this computer allows for one bot ({used} MB of {cap} MB) while memory was running short, 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 this computer 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.tsindex c5989d4a92..c20010aa78 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -1051,7 +1051,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>let session: AcpSession;if (pooled && !pooled.dead && !pooled.closing && pooled.contractKey === contractKey&& (!support.restartOnMcpChange || pooled.sessionKey === sessionKey)) {- if (pooled.idleTimer) clearTimeout(pooled.idleTimer);+ stopIdleClose(`${instanceId}\0${threadId}`, pooled.idleTimer); // busy again: no longer idlepooled.idleTimer = null;session = pooled;} else {diff --git a/server/drivers/acp/host.ts b/server/drivers/acp/host.tsindex f1d22377dd..730a67bdb7 100644--- a/server/drivers/acp/host.ts+++ b/server/drivers/acp/host.ts@@ -136,6 +136,7 @@ export class AcpHost {this.child = child;this.key = key;this.options = options;+ if (key !== null) engineOwners.shareable(child);let buf = "";// decode as UTF-8 across chunk boundaries — a raw `buf += chunk` splits// multibyte characters that straddle two reads and corrupts the textdiff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 32a92915cc..7f17daa423 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -1206,7 +1206,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {const live = sessions.get(threadId);if (!turn.sessionReset && live && !live.turn && !live.closing && live.child.exitCode === null && live.argsKey === argsKey && (!sessionId || sessionId === live.sessionId)) {- if (live.idleTimer) clearTimeout(live.idleTimer);+ stopIdleClose(`${instanceId}\0${threadId}`, live.idleTimer); // busy again: no longer idlelive.turn = { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, awaitingInit: true, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null };active.set(threadId, { stop: () => {if (live.turn) live.turn.stopRequested = true;@@ -1836,7 +1836,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {});settle(false, "exit_before_result");}- if (session.idleTimer) clearTimeout(session.idleTimer);+ stopIdleClose(`${instanceId}\0${threadId}`, session.idleTimer);session.broker?.close();session.elicit.close();session.context.close();diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.tsindex a2512e8ae9..f4014be703 100644--- a/server/drivers/session-idle.ts+++ b/server/drivers/session-idle.ts@@ -5,12 +5,13 @@// 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).+// shared a process several bots' conversations use (a shared ACP process): recycled 60 s after its last session+// (OMB_ACP_SHARED_RECYCLE_MS), a fixed time that does not shrink.+// Where turns wait for room (a Cloud home, a self-hosted Linux server), the per-chat and per-bot times shrink as memory or+// the pids limit fills (EngineMemory.roomFactor: the signals admission reads), down to a tenth and never below their+// floor, and per-chat engines already kept are looked at again every couple of seconds (sweepIdleEngines), not only when+// they 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";@@ -100,20 +101,24 @@ export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "}/** 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 }>();+const armed = new Map<string, { engine: WarmEngine; since: number; timer: ReturnType<typeof setTimeout> }>();/** 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 });+ armed.set(key, { engine, since: now, timer });keepWarm(key, engine);return timer;}+/** The engine is busy again or gone: its timer stops and it is no longer kept idle. A session ending with an old timer+ * (`timer` not the one armed under `key` now) leaves a later session's entry alone. */export function stopIdleClose(key: string, timer: ReturnType<typeof setTimeout> | null): void {if (timer) clearTimeout(timer);+ const entry = armed.get(key);+ if (timer && entry && entry.timer !== timer) return;warmEngines.delete(key);armed.delete(key);}@@ -126,7 +131,9 @@ export function sweepIdleEngines(memory: Pick<EngineMemory, "enabled" | "headrooif (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;+ // No longer idle (a turn took it again, or it ended): its driver arms it again when it next goes idle.+ if (!engine.idle()) { armed.delete(key); continue; }+ if (!engine.threadId || !engine.policy || (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);@@ -137,6 +144,9 @@ export function sweepIdleEngines(memory: Pick<EngineMemory, "enabled" | "headroo}engineMemory.useIdleSweep(() => void sweepIdleEngines());+/** How many per-chat engines are kept idle now: for tests. */+export const armedIdleCount = (): number => armed.size;+export function warmEngineKeys(): string[] {return [...warmEngines.keys()];}@@ -161,4 +171,4 @@ export function engineIdleMs(threadId: string, policy: SessionIdlePolicy,/** 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);+export const stoppedForRoom = (threadId: string, pid?: number): boolean => engineMemory.stoppedForRoom(threadId, pid) || stoppedForBotMemory(threadId, pid);diff --git a/server/engine-owners.ts b/server/engine-owners.tsindex 8cfa007c5e..39f2d0d69e 100644--- a/server/engine-owners.ts+++ b/server/engine-owners.ts@@ -13,11 +13,13 @@ export interface EngineOwner {start: string | null;threads: ReadonlyMap<string, string>;exited: boolean;+ /** Other conversations may join it (a shared ACP process). */+ shareable: boolean;}const MAX_ENTRIES = 4_096;-interface Entry { pid: number; start: string | null; threads: Map<string, string>; exited: boolean; seenSinceExit: number }+interface Entry { pid: number; start: string | null; threads: Map<string, string>; exited: boolean; seenSinceExit: number; shareable: boolean }export class EngineOwners {readonly #entries = new Map<number, Entry>();@@ -28,7 +30,7 @@ export class EngineOwners {const pid = child.pid;if (!pid) return;const turn = currentTurn();- const entry: Entry = { pid, start, threads: new Map(turn?.threadId ? [[turn.threadId, turn.botId ?? ""]] : []), exited: false, seenSinceExit: 0 };+ const entry: Entry = { pid, start, threads: new Map(turn?.threadId ? [[turn.threadId, turn.botId ?? ""]] : []), exited: false, seenSinceExit: 0, shareable: false };this.#entries.set(pid, entry);// Where no process list ever prunes it (no sampler runs), the oldest exited engines go first.if (this.#entries.size > MAX_ENTRIES) for (const [other, old] of this.#entries) { if (this.#entries.size <= MAX_ENTRIES) break; if (old.exited) this.#entries.delete(other); }@@ -43,12 +45,18 @@ export class EngineOwners {entry.threads.set(threadId, turn?.threadId === threadId ? turn.botId ?? "" : "");}+ /** Other conversations may join this engine process (a shared ACP process): the memory cap never stops it. */+ shareable(child: { pid?: number }): void {+ const entry = child.pid ? this.#entries.get(child.pid) : undefined;+ if (entry) entry.shareable = true;+ }+detach(child: { pid?: number }, threadId: string): void {if (child.pid) this.#entries.get(child.pid)?.threads.delete(threadId);}list(): EngineOwner[] {- return [...this.#entries.values()].map((entry) => ({ pid: entry.pid, start: entry.start, threads: entry.threads, exited: entry.exited }));+ return [...this.#entries.values()].map((entry) => ({ pid: entry.pid, start: entry.start, threads: entry.threads, exited: entry.exited, shareable: entry.shareable }));}/** After each process list: forgets an exited engine that no process, group or session in it still names, and one whosediff --git a/server/host/bot-footprint-owners.ts b/server/host/bot-footprint-owners.tsindex 0bdd808714..9ec0c76229 100644--- a/server/host/bot-footprint-owners.ts+++ b/server/host/bot-footprint-owners.ts@@ -11,7 +11,8 @@ export function footprintOwners(deps: { botOf: (threadId: string) => string | nuconst engines = deps.engines ?? allEngineOwners;return () => [...engines.list().map((engine): FootprintOwner => ({- pid: engine.pid, start: engine.start, kind: "engine", ...(engine.exited ? { exited: true } : {}),+ pid: engine.pid, start: engine.start, kind: "engine", ...(engine.exited ? { exited: true } : {}), ...(engine.shareable ? { shareable: true } : {}),+ threads: [...engine.threads.keys()],// The conversation's own bot, as the store says; a turn of another bot in it (a group's room) makes it shared.botIds: [...engine.threads].flatMap(([threadId, turnBot]) => {const owner = deps.botOf(threadId) ?? UNKNOWN;diff --git a/server/host/bot-memory-cap-host.ts b/server/host/bot-memory-cap-host.tsindex b1a0ec17f3..381cd5bbfe 100644--- a/server/host/bot-memory-cap-host.ts+++ b/server/host/bot-memory-cap-host.ts@@ -1,20 +1,33 @@-// Starts the per-bot memory cap (bot-memory-cap.ts) with this server's process list, bots and browsers.+// Starts the per-bot memory cap (bot-memory-cap.ts) with this server's process list, bots, browsers and room.import { readFileSync } from "node:fs";-import { startBotMemoryCap, type BotMemoryWatchdog } from "../bot-memory-cap.ts";-import { engineMemory } from "../engine-memory.ts";+import { startBotMemoryCap, type BotMemoryWatchdog, type CapPressure } from "../bot-memory-cap.ts";+import { engineMemory, readHostMemory, type EngineMemory, type HostMemory } 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 MB = 1_048_576;+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 {+/** The room the watchdog weighs: engine-memory's own signals where turns wait for room; elsewhere (an explicit cap on a+ * server without the gate) the same arithmetic from the memory read directly, so an opt-in cap still sees a shortage. */+export function capPressure(memory: Pick<EngineMemory, "enabled" | "roomFactor" | "shortOfRoom"> = engineMemory, read: () => HostMemory | null = () => readHostMemory()): CapPressure {+ const host = read();+ const free = host ? host.availableBytes + host.swapFreeBytes / 2 : null;+ if (memory.enabled) return { room: memory.roomFactor(), short: memory.shortOfRoom(), freeBytes: free };+ if (!host || free === null) return { room: 1, short: false, freeBytes: null };+ const floor = Math.max(320 * MB, host.totalBytes * 0.1);+ return { room: Math.min(1, Math.max(0.1, (free - floor) / (host.totalBytes / 2))), short: free < floor, freeBytes: free };+}++export function startBotMemoryCapHost(deps: { owners: () => readonly FootprintOwner[]; botName: (botId: string) => string | undefined; closeBrowser: (session: 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,+ closeBrowser: deps.closeBrowser, list: () => linuxProcessList().rows, startOf, pressure: () => capPressure(),});}diff --git a/server/host/browser.ts b/server/host/browser.tsindex 2502c9f25e..dc217e0579 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -484,7 +484,7 @@ export function createBrowserHost(deps: BrowserHostDeps) {const browserDaemons = createBrowserDaemons();/** Each running agent-browser daemon (its session's pid file) with the bots whose browser it is: one bot's own, or a* profile's several bots share. For the per-bot footprint (perf/bot-footprint.ts): one small file read a session. */- function browserOwners(): Array<{ pid: number; start?: string; botIds: string[]; kind: "browser" }> {+ function browserOwners(): Array<{ pid: number; start?: string; session: string; botIds: string[]; kind: "browser" }> {return [...usedBrowserSessions].flatMap(([session, spec]) => {// A browser attached to the person's own Chrome is theirs, not a bot's.if (chromeTarget(session, spec) || attachesToChrome(spec.env)) return [];@@ -494,18 +494,14 @@ export function createBrowserHost(deps: BrowserHostDeps) {const daemon = browserDaemons.owner(spec.command, session, pid);if (!daemon) return [];const botIds = store.bots.filter((bot) => browserSessionsOf(bot.id, bot.browserProfile).includes(session)).map((bot) => bot.id);- return [{ ...daemon, botIds, kind: "browser" as const }];+ return [{ ...daemon, session, 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) && !attachesToChrome(spec.env) && !shared(session) ? [closeForMemory(session, spec)] : [];- }));+ /** Closes one browser session the memory cap stopped (bot-memory-cap.ts), as one stopped for memory is: only that+ * session, so on a Team Cloud the same bot's browsers for other members stay open; never one on the person's own Chrome. */+ async function closeCapBrowser(session: string): Promise<void> {+ const spec = usedBrowserSessions.get(session);+ if (spec && !chromeTarget(session, spec) && !attachesToChrome(spec.env)) await 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 {@@ -643,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, closeBotBrowsers,+ eraseAudienceBrowsers, browserOwners, closeCapBrowser,};}diff --git a/server/idle-and-cap.test.ts b/server/idle-and-cap.test.tsindex c21c72570d..7b19bfa6a8 100644--- a/server/idle-and-cap.test.ts+++ b/server/idle-and-cap.test.ts@@ -1,19 +1,10 @@-// The one idle policy (drivers/session-idle.ts) and the per-bot memory cap (bot-memory-cap.ts).+// The one idle policy (drivers/session-idle.ts); the per-bot memory cap's own tests are in bot-memory-cap.test.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, memoryStopped, type HostMemory } from "./engine-memory.ts";-import { hostFaultOf, retryCannotFix } from "./host-fault.ts";-import { namesOwnCause } from "./process-shortage.ts";-import { retriesTeammateThread } from "./routine-recovery.ts";-import type { FootprintOwner } from "./perf/bot-footprint.ts";-import type { ProcessRow } from "./perf/process-buckets.ts";+import { armedIdleCount, armIdleClose, engineIdleMs, idleAfter, stopIdleClose, sweepIdleEngines, type WarmEngine } from "./drivers/session-idle.ts";+import { EngineMemory, type HostMemory } from "./engine-memory.ts";import { ProcessBudget } from "./process-room.ts";import { forgetPresence, sawThread } from "./thread-presence.ts";@@ -149,6 +140,27 @@ describe("one idle policy, shorter as the server runs short of room", () => {}});+ it("lets an engine go from the sweep's list once it is busy again or gone, and an old session's end leaves a newer one's entry", () => {+ const start = 1_800_000_000_000;+ const policy = { idleMs: 10 * 60_000, minimumMs: 10_000 };+ const before = armedIdleCount();+ const state = { busy: false };+ const engine: WarmEngine = { threadId: "g1", policy, idle: () => !state.busy, close: () => {} };+ const old = armIdleClose("g", 600_000, engine, start);+ // A new turn took the session (the driver stops the idle close), then it went idle again under a new timer.+ stopIdleClose("g", old);+ expect(armedIdleCount()).toBe(before);+ const fresh = armIdleClose("g", 600_000, engine, start);+ // The earlier session of this conversation ends now, with its old timer: the newer entry stays.+ stopIdleClose("g", old);+ expect(armedIdleCount()).toBe(before + 1);+ // An entry whose engine is busy again (its end came by a plain clearTimeout) is dropped at the next sweep.+ state.busy = true;+ clearTimeout(fresh);+ sweepIdleEngines({ enabled: true, headroom: () => 0.5, roomFactor: () => 0.5, shortOfRoom: () => false }, start + 60_000);+ expect(armedIdleCount()).toBe(before);+ });+it("runs the sweep on every tick of the gate", () => {const h = server();let swept = 0;@@ -202,172 +214,3 @@ describe("an idle engine goes before admission makes new work wait", () => {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" },- ];- /** By default every process's proportional size reads as its resident size. */- function dog(rows: () => ProcessRow[], pss: (pid: number) => number | null = (pid) => rows().find((row) => row.pid === pid)?.rssBytes ?? 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("stops a bot whose shares can't be read only when it stays far over, its resident pages erring high", async () => {- let sizes = { a: 1300 };- const h = dog(() => processes(sizes), () => null);- expect(await h.watchdog.check()).toEqual([]);- expect(await h.watchdog.check()).toEqual([]);- expect(await h.watchdog.check()).toEqual([]);- sizes = { a: 1600 };- expect(await h.watchdog.check()).toEqual([]);- expect((await h.watchdog.check()).map((stop) => stop.botId)).toEqual(["bot_a"]);- });-- it("leaves alone a pid the system gave to another process since it was read", async () => {- const h = dog(() => processes({ a: 1600 }), undefined, (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 computer 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 this computer 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 fault a retry cannot fix: no automatic retry or Chief retry starts the bot into the same cap again.- expect(hostFaultOf(line)).toBe("bot_memory");- expect(retryCannotFix("bot_memory")).toBe(true);- expect(retriesTeammateThread(line)).toBe(false);- expect(namesOwnCause(line)).toBe(true);- expect(memoryStopped(line)).toBe(false);- // 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.tsindex 6a65c46d3b..02ba051be7 100644--- a/server/index.ts+++ b/server/index.ts@@ -2377,7 +2377,7 @@ function cancelDirectTurnDispatch(botId: string, expectedThreadId?: string): Dirconst {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, closeBotBrowsers,+ browserReady, currentBrowserSpec, loginInput, browserSystemPrompt, closeBrowser, browserEngineSwitched, eraseDeletedBrowser, engineSummary, browserSessionsOf, signedInSitesTarget, uploadPaths, eraseAudienceBrowsers, browserOwners, closeCapBrowser,} = 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 } = createPersconst 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 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: (rows) => engineOwners.prune(rows), 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 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: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowser: closeCapBrowser }); 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.test.ts b/server/perf/bot-footprint.test.tsindex eacd4dedb1..6ce8ae1ffd 100644--- a/server/perf/bot-footprint.test.ts+++ b/server/perf/bot-footprint.test.ts@@ -138,7 +138,10 @@ describe("which bot an engine runs for", () => {const owners = new EngineOwners();const child = Object.assign(new EventEmitter(), { pid: 4242 });runInTurn({ botId: "bot_a", threadId: "thread_1" }, () => owners.track(child, "777"));- expect(owners.list()).toEqual([{ pid: 4242, start: "777", threads: new Map([["thread_1", "bot_a"]]), exited: false }]);+ expect(owners.list()).toEqual([{ pid: 4242, start: "777", threads: new Map([["thread_1", "bot_a"]]), exited: false, shareable: false }]);+ // A shared ACP process marks itself one other conversations may join.+ owners.shareable(child);+ expect(owners.list()[0]?.shareable).toBe(true);runInTurn({ botId: "bot_b", threadId: "thread_2" }, () => owners.attach(child, "thread_2"));owners.attach(child, "thread_3");expect([...owners.list()[0]!.threads]).toEqual([["thread_1", "bot_a"], ["thread_2", "bot_b"], ["thread_3", ""]]);@@ -163,7 +166,7 @@ describe("which bot an engine runs for", () => {const browsers: FootprintOwner[] = [{ pid: 11, botIds: ["bot_z"], kind: "browser" }];const botOf = (threadId: string) => (threadId === "thread_known" || threadId === "thread_k2" ? "bot_k" : null);const list = footprintOwners({ botOf, browsers: () => browsers, engines: owners });- expect(list()).toEqual([{ pid: 10, start: null, kind: "engine", botIds: ["bot_k"] }, browsers[0]]);+ expect(list()).toEqual([{ pid: 10, start: null, kind: "engine", botIds: ["bot_k"], threads: ["thread_known"] }, browsers[0]]);owners.attach(child, "thread_gone");expect(list()[0]?.botIds).toEqual(["bot_k", "?"]);const rows: ProcessRow[] = [{ pid: 10, ppid: 1, name: "opencode", cpuMs: 0, rssBytes: MB, start: "s" }];diff --git a/server/perf/bot-footprint.ts b/server/perf/bot-footprint.tsindex 774f861625..21df1f65db 100644--- a/server/perf/bot-footprint.ts+++ b/server/perf/bot-footprint.ts@@ -17,6 +17,24 @@ export interface FootprintOwner {kind: "engine" | "browser";/** It has exited: its pid may be another process's now, but its group and session still name what it left. */exited?: boolean;+ /** An engine's conversations now (for the memory cap: which are running a turn). */+ threads?: readonly string[];+ /** An engine process other conversations may join (a shared ACP process): the memory cap never stops one. */+ shareable?: boolean;+ /** A browser's session. */+ session?: string;+}++/** What one owner record brought a bot: the record's pid and its processes now. */+export interface FootprintUnit {+ root: number;+ kind: FootprintOwner["kind"];+ /** The root itself has exited: what is left ran on in its group or session. */+ exited: boolean;+ shareable: boolean;+ threads: string[];+ session?: string;+ pids: number[];}export interface BotTally {@@ -33,6 +51,8 @@ export interface BotTally {pids: number[];/** Those of `pids` that belong to it through a browser (its daemon and Chrome), not an engine. */browserPids: number[];+ /** Its processes by the record they count through, by that record's pid. */+ units: Map<number, FootprintUnit>;}export interface Attribution {@@ -41,7 +61,7 @@ export interface Attribution {shared: BotTally;}-const emptyTally = (): BotTally => ({ procs: 0, threads: 0, rssBytes: 0, cpuMs: 0, cpuDeltaMs: 0, engines: 0, browsers: 0, pids: [], browserPids: [] });+const emptyTally = (): BotTally => ({ procs: 0, threads: 0, rssBytes: 0, cpuMs: 0, cpuDeltaMs: 0, engines: 0, browsers: 0, pids: [], browserPids: [], units: new Map() });/** Whose each row is: a bot's id, SHARED, or undefined for none (the server, its own helpers, anything else). */export const SHARED = "\0shared";@@ -50,7 +70,8 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Footconst byPid = new Map(rows.map((row) => [row.pid, row]));// A leader the list shows with another start is another process now; one the list no longer shows (an engine that// exited) still names its group and session: the system gives no new process a number that still names one.- const roots = new Map<number, { label: string; kind: FootprintOwner["kind"] }>();+ type Root = { label: string; kind: FootprintOwner["kind"]; pid: number; exited: boolean; shareable: boolean; threads: string[]; session?: string };+ const roots = new Map<number, Root>();/** Leaders still running as themselves: only these name the process with their pid; the others name groups and sessions. */const live = new Set<number>();for (const owner of owners) {@@ -60,10 +81,11 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Footconst label = ids.length === 1 && ID.test(ids[0]!) ? ids[0]! : SHARED;const known = roots.get(owner.pid);// Two records of one pid disagreeing about its bot: shared, never either bot's.- roots.set(owner.pid, { label: known && known.label !== label ? SHARED : label, kind: owner.kind });+ roots.set(owner.pid, { label: known && known.label !== label ? SHARED : label, kind: owner.kind, pid: owner.pid, exited: (known?.exited ?? true) && owner.exited === true,+ shareable: known?.shareable === true || owner.shareable === true, threads: [...new Set([...known?.threads ?? [], ...owner.threads ?? []])], session: known?.session ?? owner.session });if (!owner.exited) live.add(owner.pid);}- type Label = { label: string; kind: FootprintOwner["kind"] } | null;+ type Label = Root | null;const labels = new Map<number, Label>();const labelOf = (row: ProcessRow, depth: number): Label => {const known = labels.get(row.pid);@@ -88,6 +110,9 @@ export function attributeRows(rows: readonly ProcessRow[], owners: readonly Footconst 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);+ const unit = tally.units.get(found.pid) ?? tally.units.set(found.pid, { root: found.pid, kind: found.kind, exited: found.exited, shareable: found.shareable, threads: found.threads,+ ...(found.session === undefined ? {} : { session: found.session }), pids: [] }).get(found.pid)!;+ unit.pids.push(row.pid);tally.procs += 1;tally.threads = tally.threads === null || row.threads === undefined ? null : tally.threads + row.threads;tally.rssBytes += row.rssBytes;@@ -116,6 +141,11 @@ export interface BotFootprintRow {browsers: number;}+export interface BotCapReport {+ mb: number | null; mode: "log" | "enforce" | null; rung: string; stops: number; flagged: number;+ events: ReadonlyArray<{ at: number; botId: string; usedMB: number; measured: string; capMB: number; engines: number; room: number; freeMB: number | null; pressure: boolean; action: string }>;+}+export interface BotFootprintReport {at: number | null;/** Bots with any process running at the last sample. */@@ -123,8 +153,9 @@ 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 };+ /** The memory one bot may use per engine it runs (bot-memory-cap.ts): MB or null for none; "log" (watch only, the+ * default) or "enforce" (a set number); how; steps taken and bots written down as over since start; the latest events. */+ cap?: BotCapReport;}const MB = 1_048_576;@@ -182,6 +213,14 @@ export function createBotFootprints(options: BotFootprintsOptions) {}export type BotFootprints = ReturnType<typeof createBotFootprints>;+function capLine(cap: BotCapReport): string {+ if (cap.mb === null) return " Memory one bot may use: no limit";+ const last = cap.events.at(-1);+ return ` Memory one bot may use: ${cap.mb} MB per engine (${cap.mode === "enforce" ? "enforced when memory runs short" : "watch only"}, ${cap.rung}); `+ + `steps taken since start: ${cap.stops}, over with nothing stopped: ${cap.flagged}`+ + (last ? `; latest: bot ${last.botId} ${last.usedMB} MB (${last.measured}) of ${last.capMB} MB, ${last.engines} engines, room ${last.room}, ${last.action}` : "");+}+/** The plain line for people: a @devs report and the desktop's diagnostics. */export function botFootprintLines(report: BotFootprintReport): string[] {if (report.at === null) return ["Per bot: not sampled yet"];@@ -191,7 +230,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}`}`] : []),+ ...(report.cap ? [capLine(report.cap)] : []),` 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.tsindex 0ec9792390..eb5cd4cfcd 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -6,7 +6,7 @@ import type { EngineLimitsReport } from "../../shared/limit-reset.ts";import type { RuntimeEvent } from "../contracts.ts";import type { StoreChange } from "../store.ts";import { createLoopStalls, requestArrivedBefore, type LoopStalls } from "./loop-stalls.ts";-import { createBotFootprints, type BotFootprintReport, type BotFootprints, type FootprintOwner } from "./bot-footprint.ts";+import { createBotFootprints, type BotCapReport, type BotFootprintReport, type BotFootprints, type FootprintOwner } from "./bot-footprint.ts";import { duration, limitHolds, perfHealth, perfLines, turnLine, type PerfHealth } from "./perf-report.ts";import { createProcessHealth, type ProcessHealthRecorder } from "./process-health.ts";import type { ProcessRow } from "./process-buckets.ts";@@ -43,7 +43,7 @@ export interface PerfHostDeps {/** After each sample, with its process list: records of exited engines it no longer needs can go. */pruneOwners?: (rows: readonly ProcessRow[]) => void;/** The memory one bot may use and how it is enforced (bot-memory-cap.ts). */- cap?: () => { mb: number | null; rung: string; stops: number };+ cap?: () => BotCapReport;}/** The health report shows this many bots, the ones using the most memory first; the admin's read shows every one. */diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.tsindex 09633f8dec..a011b900d3 100644--- a/server/perf/perf-report.ts+++ b/server/perf/perf-report.ts@@ -61,7 +61,7 @@ export function perfHealth(sources: PerfSources) {bots: sources.bots ?? null,};const size = () => JSON.stringify(body).length;- if (size() > PERF_HEALTH_MAX_BYTES && body.bots) body.bots = { ...body.bots, shown: body.bots.shown.slice(0, 3) };+ if (size() > PERF_HEALTH_MAX_BYTES && body.bots) body.bots = { ...body.bots, shown: body.bots.shown.slice(0, 3), ...(body.bots.cap ? { cap: { ...body.bots.cap, events: body.bots.cap.events.slice(-1) } } : {}) };if (size() > PERF_HEALTH_MAX_BYTES && body.process) body.process = { ...body.process, buckets: body.process.buckets.slice(0, 6) };if (size() > PERF_HEALTH_MAX_BYTES) body.h24.tools = body.h24.tools.slice(0, 4);if (size() > PERF_HEALTH_MAX_BYTES) body.live = body.live.slice(0, 2);diff --git a/src/locales/en.json b/src/locales/en.jsonindex 3f1fee9cfc..b5b45a3fed 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -10167,7 +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 computer 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 this computer more memory.",+ "chat.notice.botMemoryCap": "{bot} used more memory than this computer allows for one bot ({used} MB of {cap} MB) while memory was running short, 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 this computer 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.jsonindex 75bea4f200..d7d5007caa 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -10079,7 +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 computador 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 a este computador.",+ "chat.notice.botMemoryCap": "{bot} usou mais memória do que este computador permite para um bot ({used} MB de {cap} MB) enquanto a memória estava acabando, 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 a este computador.","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.",