Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Self-hosted servers wait for room under their container's process and memory limits (#6179)
Milind Soni6d9138b677d2
diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 44faa084e7..327778f98f 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -500,10 +500,84 @@ Leave room for the commands bots run: budget about 80 per working bot.| 20 | 4,096 | 18 GB || 34 | 4,096 | 28 GB |-The limit column includes two open browsers, which is as many as a server in-a container keeps open at once (`OMB_BROWSER_MAX_RUNNING` changes that). If-your platform's limit is fixed and lower than the row you need, have fewer-bots work at the same moment.+The limit column includes two open browsers. A server opens more when its+limits leave room for them (at most 40% of the process limit and of the memory+go to browsers; `OMB_BROWSER_MAX_RUNNING` sets the number instead), and each+new browser also waits for room for its processes, as a turn does. If+your platform's limit is fixed and lower than the row you need, the server+still works: fewer bots run at the same moment and the others wait.++**Turns wait for room instead of failing.** In a container that was given a+memory limit or a process limit, the server holds a turn back while its+engine would not fit, and starts it by itself when there is room:++- It reads the container's own limits (cgroup `memory.max` and `pids.max`,+ v1 or v2) and what is used now, never the host machine's totals.+- Before it makes a turn wait it closes an engine no turn is using. An idle+ engine otherwise stays loaded for ten minutes for the conversation in+ front of you and thirty seconds for work nobody is watching (a teammate's+ task, a routine), and no more stay idle than fit beside the ones working.+- A waiting turn says so in its chat ("Waiting for room on this server…"),+ and again every ten minutes. A routine's run waits the same way; a routine+ is never switched off for it.+- A bot's browser opens only where its processes fit under the process+ limit. Each open browser is counted at its full size for as long as it+ runs, so one that a bot opens halfway through its turn is never missed.+ With no room, the browser call waits up to 20 seconds, then tells the bot+ that the server is close to its limit and to try again later.+- If the system refuses to start a bot's engine anyway (`spawn EAGAIN`,+ `EMFILE`, `ENOMEM`), or the kernel stops an engine for memory, that is the+ server's shortage, not the AI's failure: nothing is sent to a backup AI+ and no Chief is asked about it. The chat shows one line, the turn starts+ again by itself once, half a minute later, behind the same wait, and only+ if that fails too are you told. A failure that names its own cause (a usage+ limit, a sign-in) is always shown as it is.+- A new engine that says nothing for 90 seconds is stopped the same way only+ while the server is short of room (its process limit nearly full, a start+ refused since the engine began, or memory short) and only once the+ engine and everything it started have stopped using the CPU. A slow first+ start, such as an engine that `npx` is still installing, is left to finish+ or to time out on its own.++`OMB_TURNS_MAX_RUNNING` sets how many turns run at once on the whole server:++| Value | What it does |+| --- | --- |+| unset | In a container with a memory or process limit: a number worked out from those limits (below). Anywhere else: no limit, as before. |+| `auto` | The worked-out number on any self-hosted server, with or without a container limit. |+| a number | That many turns at once. The live checks on memory and processes still apply. |+| `off` or `0` | No waiting at all. |++The worked-out number is the smaller of two: the memory limit less a tenth+(at least 320 MB), divided by 700 MB for an engine; and the process limit+less a tenth (at least 32) and 40 for the server, divided by 60. A 4 GB+container runs 5 turns at once, an 8 GB one 10; a process limit of 512 allows+7, 1,024 allows 14, 4,096 allows 60. The desktop app never uses this setting,+and a MausBot Cloud keeps its own rules.++On Kubernetes a pod's process limit (`podPidsLimit`) is set above the+container, where the server cannot read it. The server then learns it from+the first refused start and holds turns below that count for the next half+hour; set `OMB_TURNS_MAX_RUNNING` to a number to avoid that first refusal.++**Reading how close the server is.** At start the server logs one line with+what it found, for example `processes: process 1 is an init; limits:+processes and threads 512, memory 4096 MB, ulimit -u unlimited, /dev/shm 64+MB`. It logs one more line the first time it passes 80% of its process limit,+one the first time it passes 80% of its memory limit, and one the first time+more than 20 exited processes are waiting to be collected (which means the+container has no init). `GET+/api/diagnostics/performance` and the performance part of a problem report+carry a "Process room" block: what process 1 is, the limits, how many+processes, threads, zombies and open files there are now and at their most+since start (engines by kind, browser, tool servers, commands, other; sampled+each minute, and the kernel's own exact high-water marks where cgroup v2+keeps them), how+many turns run and wait and the longest wait, and counts since start of+turns that waited, starts the system refused by error code, engines that+never came up, and processes that had to be force-stopped or outlived their+turn. It holds numbers and fixed words only: no command line, path, bot name+or message.**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-box/env.test.ts b/server/bot-box/env.test.tsindex e842f82d74..e19ac6d987 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -53,7 +53,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_SMOKE_TEST", "OMB_SSE_HEARTBEAT_MS", "OMB_STATIC_DIR", "OMB_SYNC_ROOT", "OMB_TAILNET_ADDRESSES", "OMB_TAILNET_NAME", "OMB_TAILNET_SERVED", "OMB_TEAM_AWAY_WINDOW_MS","OMB_TEAM_PRESENCE_GRACE_MS", "OMB_TEST_INTERNAL_CAPABILITY_KEY", "OMB_TEST_ORG_LIBRARY_KEY","OMB_TEST_PLAN_USAGE_FILE", "OMB_TEST_TAILNET_STAND_IN", "OMB_THREAD_CACHE_MB", "OMB_TOOL_STALL_MS", "OMB_TREG_KEY", "OMB_TREG_URL", "OMB_TTS_DEFAULT_VOICE",- "OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURN_STALL_MS", "OMB_UNATTENDED_TURN_MAX_DENIALS", "OMB_UNATTENDED_TURN_MAX_MS", "OMB_UNATTENDED_TURN_MAX_REQUESTS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL",+ "OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURNS_MAX_RUNNING", "OMB_TURN_STALL_MS", "OMB_UNATTENDED_TURN_MAX_DENIALS", "OMB_UNATTENDED_TURN_MAX_MS", "OMB_UNATTENDED_TURN_MAX_REQUESTS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL","OMB_USAGE_CAP_DAILY_TOKENS", "OMB_USAGE_CAP_DAILY_USD", "OMB_USAGE_CAP_MONTHLY_TOKENS", "OMB_USAGE_CAP_MONTHLY_USD","OMB_USAGE_CAP_STOPS", "OMB_USER_DATA", "OMB_WARM_SUMMARY", "OMB_WARM_SUMMARY_TIME_SCALE", "OMB_WEBHOOK_PORT", "OMB_WEBHOOK_PUBLIC_URL", "OMB_WEBHOOK_SOCKET","OMB_WORKERS_AI_TOKEN", "OMB_XAI_TTS_API",diff --git a/server/bot-thread-limits.ts b/server/bot-thread-limits.tsindex 9359265cbb..2511c8193b 100644--- a/server/bot-thread-limits.ts+++ b/server/bot-thread-limits.ts@@ -1,6 +1,5 @@// How many threads one bot runs at once.-import { totalmem } from "node:os";-+import { boxMemory } from "./box-memory.ts";import { engineMemory } from "./engine-memory.ts";export const MAX_CONCURRENT_BOT_THREADS = 16;@@ -10,7 +9,8 @@ const DEFAULT_THREADS_FLOOR = 3, BYTES_PER_DEFAULT_THREAD = 2 * 1024 ** 3;export interface BotThreadsHost { memoryGate: boolean; totalBytes: number; oneThreadPerBot: boolean }type SavedThreads = { threads?: { maxConcurrentPerBot?: number } };-export const botThreadsHost = (oneThreadPerBot = false): BotThreadsHost => ({ memoryGate: engineMemory.enabled, totalBytes: totalmem(), oneThreadPerBot });+/** The memory this server may use: its container's limit where one is set, not the machine's. */+export const botThreadsHost = (oneThreadPerBot = false): BotThreadsHost => ({ memoryGate: engineMemory.enabled, totalBytes: boxMemory().bytes, oneThreadPerBot });export function defaultBotThreads(host: Pick<BotThreadsHost, "memoryGate" | "totalBytes"> = botThreadsHost()): number {if (host.memoryGate) return MAX_CONCURRENT_BOT_THREADS;diff --git a/server/browser-room.test.ts b/server/browser-room.test.tsindex 1d309b02c2..c86d76f88a 100644--- a/server/browser-room.test.ts+++ b/server/browser-room.test.ts@@ -122,6 +122,25 @@ describe("a browser over the limit", () => {value.left("viewed");expect(await value.enter("b", Date.now() + 1_000)).toBeNull();});++ it("asks the server's room for its processes once the count allows, and closes a spare browser before refusing", async () => {+ let free = 0;+ const admit = vi.fn(async () => (free > 0 ? (free--, null) : "No room for another browser."));+ const close = vi.fn(async () => { free++; return true; });+ const value = new BrowserRoom({ max: () => 3, spare: (session) => (session === "a" ? 1_000 : null), close, admit, waitMs: 300, pollMs: 20 });+ value.entered("a");+ value.entered("b");+ // the count allows a third, the server's room does not: a spare browser closed for it lets the new one in+ expect(await value.enter("c", Date.now() + 1_000)).toBeNull();+ expect(close.mock.calls).toEqual([["a"]]);+ expect(admit.mock.calls).toEqual([["c"], ["c"]]);+ expect(value.open).toBe(2);+ // an open browser is never asked about again, and with no spare browser left the refusal is the server's+ expect(await value.enter("c", Date.now() + 1_000)).toBeNull();+ expect(await value.enter("d", Date.now() + 1_000)).toBe("No room for another browser.");+ expect(admit).toHaveBeenCalledTimes(3);+ expect(value.open).toBe(2);+ });});describe("which browser a bot waiting for a slot may close", () => {diff --git a/server/browser-room.ts b/server/browser-room.tsindex ad218263a0..6284d4a6c9 100644--- a/server/browser-room.ts+++ b/server/browser-room.ts@@ -74,6 +74,9 @@ export interface BrowserRoomOptions {spare(session: string): number | null;/** Closes an unused browser; true once it is gone. */close(session: string): Promise<boolean>;+ /** Asked once the count allows a new browser: the server's own room for its processes (process-room.ts, a self-hosted+ * server's pids limit). Null once it fits; otherwise the refusal, after a spare browser is closed if one may go. */+ admit?(session: string): Promise<string | null>;waitMs?: number;pollMs?: number;}@@ -95,6 +98,13 @@ export class BrowserRoom {if (this.#open.has(session)) return null;const others = [...this.#open];if (others.length < Math.max(1, this.#options.max())) {+ const refused = await this.#options.admit?.(session) ?? null;+ if (refused !== null) {+ if (await this.#closeOneSpare(others)) continue;+ return refused;+ }+ // Another session may have taken the last place while the server's room was asked.+ if (!this.#open.has(session) && this.#open.size >= Math.max(1, this.#options.max())) continue;this.#open.add(session);return null;}diff --git a/server/browser/engines.test.ts b/server/browser/engines.test.tsindex f2f86e9513..68e7d85c07 100644--- a/server/browser/engines.test.ts+++ b/server/browser/engines.test.ts@@ -151,6 +151,22 @@ describe("the runtime router", () => {expect(old.agentRpc).toHaveBeenCalledTimes(2);});+ it("asks the server's room before an opt-in engine's tool call, and a call it has no room for never reaches it", async () => {+ let full: string | null = "No room for another browser.";+ const asked: string[] = [];+ const { old, chrome, runtime } = engines({ room: async (session) => { asked.push(session); return full; } });+ const refused = { isError: true, content: [{ type: "text", text: "No room for another browser." }] };+ await expect(runtime.agentRpc("s", CHROME, "tools/call", { name: "agent_browser_open" })).resolves.toEqual(refused);+ // agent-browser asks the same room through its own BrowserRoom, after its count of browsers+ await expect(runtime.agentRpc("s1", AGENT_BROWSER, "tools/call", { name: "agent_browser_open" })).resolves.toBe("agent-browser");+ await expect(runtime.agentRpc("s", CHROME, "tools/list", {}), "a listing opens no browser").resolves.toBe("chrome");+ expect(asked).toEqual(["s"]);+ expect([old.agentRpc.mock.calls.length, chrome.service.agentRpc.mock.calls.length]).toEqual([1, 1]);+ full = null;+ await expect(runtime.agentRpc("s", CHROME, "tools/call", { name: "agent_browser_open" })).resolves.toBe("chrome");+ expect(asked).toEqual(["s", "s"]);+ });+it("asks afterClaim once beforeDispatch has claimed, and its refusal reaches neither engine", async () => {const order: string[] = [];let refuse: string | null = null;diff --git a/server/browser/engines.ts b/server/browser/engines.tsindex 2c0c24fac2..dcd89f1640 100644--- a/server/browser/engines.ts+++ b/server/browser/engines.ts@@ -186,6 +186,10 @@ export class ChromeEngine {export interface RuntimeRouterOptions {/** What a tool call is told instead of reaching either engine, or null to run it. */refusal?(session: string, spec: BrowserSpawnSpec, params: unknown): string | null;+ /** Asked next, before an opt-in engine's tool call that may open the session's browser: what it is told while the server+ * has no room to run one (a self-hosted server's pids limit), or null once it has. agent-browser's calls ask the same+ * room through its BrowserRoom, after its count of browsers. */+ room?(session: string, spec: BrowserSpawnSpec, params: unknown): Promise<string | null>;/** Asked each time beforeDispatch ran, so after it claimed the session for this call's turn and before anything reaches* the engine: what a refusal that depends on who is calling tells the call, or null to run it. */afterClaim?(session: string, spec: BrowserSpawnSpec): string | null;@@ -203,6 +207,7 @@ export class RuntimeRouter {readonly #old: BrowserRuntime;readonly #chrome: ChromeEngine;readonly #refusal: RuntimeRouterOptions["refusal"];+ readonly #room: RuntimeRouterOptions["room"];readonly #afterClaim: RuntimeRouterOptions["afterClaim"];readonly #annotate: RuntimeRouterOptions["annotate"];readonly #afterCall: RuntimeRouterOptions["afterCall"];@@ -211,6 +216,7 @@ export class RuntimeRouter {this.#old = old;this.#chrome = chrome;this.#refusal = options.refusal;+ this.#room = options.room;this.#afterClaim = options.afterClaim;this.#annotate = options.annotate;this.#afterCall = options.afterCall;@@ -219,13 +225,15 @@ export class RuntimeRouter {async agentRpc(session: string, spec: BrowserSpawnSpec, method: "tools/list" | "tools/call", params: unknown, beforeDispatch?: () => void, ctx?: StepContext): Promise<unknown> {const refusal = method === "tools/call" ? this.#refusal?.(session, spec, params) : null;if (refusal) return { isError: true, content: [{ type: "text", text: refusal }] };+ const target = chromeTarget(session, spec);+ const full = method === "tools/call" && target ? await this.#room?.(session, spec, params) : null;+ if (full) return { isError: true, content: [{ type: "text", text: full }] };const afterClaim = method === "tools/call" ? this.#afterClaim : undefined;const dispatch = afterClaim ? () => {beforeDispatch?.();const text = afterClaim(session, spec);if (text) throw new ClaimRefused(text);} : beforeDispatch;- const target = chromeTarget(session, spec);let result: unknown;try {result = await (target ? this.#chrome.service.agentRpc(target, method, params, dispatch) : this.#old.agentRpc(session, spec, method, params, dispatch, ctx));diff --git a/server/chat-notices.ts b/server/chat-notices.tsindex 09f2bba3e5..14cce420b9 100644--- a/server/chat-notices.ts+++ b/server/chat-notices.ts@@ -152,6 +152,7 @@ export const CHAT_NOTICE = {"chat.notice.memoryReclaimedTask": "Ran out of room, so I stopped this task to keep everything else running.","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.",} as const;export type ChatNoticeKey = keyof typeof CHAT_NOTICE;diff --git a/server/drivers/acp/quiet-status.ts b/server/drivers/acp/quiet-status.tsindex 2d3488ebae..854c2a3552 100644--- a/server/drivers/acp/quiet-status.ts+++ b/server/drivers/acp/quiet-status.ts@@ -8,6 +8,8 @@ import { closeSync, existsSync, fstatSync, openSync, readdirSync, readFileSync,import { join } from "node:path";import { redactSecretsInText } from "../../redact.ts";+// The usage-limit wait (OMB_ACP_LIMIT_QUIET_MS) lives with the failure words, so reading a failure loads no ACP driver.+import { limitQuietMs, usageLimitWait } from "../engine-errors.ts";// Prompt silence guard (0 disables). Healthy agents go quiet for minutes: Qwen Code 0.24 sends// nothing while it compresses history, backs off a rate limit (60 s up to 5 min per wait) or runs@@ -313,16 +315,6 @@ export function sampleProcessTree(pid: number, since?: number): Promise<ProcessS* (OpenCode 1.18 sleeps for the provider's whole retry-after, uncapped, five times over). */export const LIMIT_WORDS = /\b429\b|rate.?limit|too many requests|usage limit|quota|GoUsageLimitError|FreeUsageLimitError|insufficient_quota|credits? (?:exhausted|used up)|out of credits/i;-/** How long an engine may stay quiet after a model request failed on a limit before the turn is ended as a usage limit,- * so the bot carries on with another AI: longer than any retry an engine makes without a provider's retry-after- * (OMB_ACP_LIMIT_QUIET_MS overrides). */-export const DEFAULT_LIMIT_QUIET_MS = 2 * 60_000;-export const limitQuietMs = (): number => knob("OMB_ACP_LIMIT_QUIET_MS", DEFAULT_LIMIT_QUIET_MS);--/** A 429 whose wait is longer than any engine retries on its own is a usage limit, not a short rate limit. */-export const usageLimitWait = (status: number | null | undefined, waitMs: number | null | undefined): boolean =>- status === 429 && (waitMs ?? 0) > limitQuietMs();-/** No open request, no CPU and nothing logged, this long: the engine is stuck, and the turn is stopped* (OMB_ACP_NO_SIGNS_STOP_MS overrides). */export const DEFAULT_NO_SIGNS_STOP_MS = 5 * 60_000;diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 0143af604a..dec27304fe 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -45,7 +45,7 @@ import { claudeApiError, claudeApiErrorMessage, claudeLimitError, claudeLimitFacimport { createOrgModelBlocks, modelSwapNotice, withOrgBlocks } from "./claude-model-access.ts";import { engineHomes } from "../engine-homes/engine-homes.ts";import { TEAM_TOOLS_FAILED, failedCustomMcp, teamToolsFailed } from "./team-tools.ts";-import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose } from "./session-idle.ts";+import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose, stoppedForRoom } from "./session-idle.ts";import { keyedStable, promptHalves, withRosterNote, withVolatileNote } from "./prompt-split.ts"; import { CLAUDE_OWN_MEMORY_OFF } from "./claude-own-memory.ts";import { parseVersionTriple, versionAtLeast } from "./acp/version-probe.ts";import {@@ -1733,7 +1733,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {const message = `claude exited ${code} before result${session.stderr ? `: ${session.stderr.trim().slice(-300)}` : ""}`;const verdict = classifyError({ exitCode: code, stderr: message });const endedBeforeTurn = session.turn.awaitingInit === true || (refusedAutocompact && !session.turn.sawStreamDelta && session.turn.answered !== true);- if (!retry.cancelled && mayResendTurn({ endedBeforeTurn, exitCode: code, transient: verdict.transient,+ if (!retry.cancelled && !stoppedForRoom(threadId, session.child.pid) && mayResendTurn({ endedBeforeTurn, exitCode: code, transient: verdict.transient,streamed: session.turn.sawStreamDelta, answered: session.turn.answered === true, attempt: retry.attempt })) {// `active` stays: an interrupt during the backoff reaches stop() and cancels the retry.const failedBroker = session.broker;diff --git a/server/drivers/codex-process.ts b/server/drivers/codex-process.tsindex a558cf0f7c..d186aae71f 100644--- a/server/drivers/codex-process.ts+++ b/server/drivers/codex-process.ts@@ -1,13 +1,14 @@import type { ChildProcess } from "node:child_process";import { existsSync } from "node:fs";-import { cpus } from "node:os";+import { availableParallelism } from "node:os";import { splitCliString } from "../env-path.ts";/** Every Codex app-server starts its MCP servers with its thread; many starting at once on a small host* push those calls past their timeouts. Launches past this many wait until one has its turn running. */export function codexLaunchLimit(): number {const configured = Number(process.env.OMB_CODEX_LAUNCH_SLOTS);- return Number.isInteger(configured) && configured > 0 ? configured : Math.max(2, cpus().length);+ // The CPUs this process may use (its container's or its affinity's), not every one the machine has.+ return Number.isInteger(configured) && configured > 0 ? configured : Math.max(2, availableParallelism());}let starting = 0;diff --git a/server/drivers/engine-errors.ts b/server/drivers/engine-errors.tsindex 896fd1ad1e..52d34b657f 100644--- a/server/drivers/engine-errors.ts+++ b/server/drivers/engine-errors.ts@@ -7,7 +7,19 @@ import { redactSecretsInText } from "../redact.ts";import { hostTimeZone } from "../turn-clock.ts";import { toolCountLimitFromError } from "../tool-count-limit.ts";import { MODEL_NO_ROUTE, USAGE_LIMIT } from "./retry.ts";-import { usageLimitWait } from "./acp/quiet-status.ts";++/** How long an engine may stay quiet after a model request failed on a limit before the turn is ended as a usage limit,+ * so the bot carries on with another AI: longer than any retry an engine makes without a provider's retry-after+ * (OMB_ACP_LIMIT_QUIET_MS overrides). */+export const DEFAULT_LIMIT_QUIET_MS = 2 * 60_000;+export const limitQuietMs = (): number => {+ const ms = Number(process.env.OMB_ACP_LIMIT_QUIET_MS);+ return Number.isFinite(ms) && ms > 0 ? ms : DEFAULT_LIMIT_QUIET_MS;+};++/** A 429 whose wait is longer than any engine retries on its own is a usage limit, not a short rate limit. */+export const usageLimitWait = (status: number | null | undefined, waitMs: number | null | undefined): boolean =>+ status === 429 && (waitMs ?? 0) > limitQuietMs();export type EngineFailureKind = "credits" | "usage_limit" | "rate_limit" | "overloaded" | "server" | "tool_schema" | "tool_count" | "model_no_route" | "refused";diff --git a/server/drivers/session-idle.test.ts b/server/drivers/session-idle.test.tsindex 84b5b302ac..3c0f0a6d92 100644--- a/server/drivers/session-idle.test.ts+++ b/server/drivers/session-idle.test.ts@@ -112,6 +112,19 @@ describe("idle engines on a small box", () => {expect(idleEnginesAllowed({ bytes: DESKTOP }, 0)).toBe(Infinity);});+ it("keeps no more idle engines than a self-hosted server's limits fit, on a box of any size, the longest idle closing first", () => {+ expect(idleEnginesAllowed({ bytes: DESKTOP }, 0, 2)).toBe(2);+ expect(idleEnginesAllowed(small, 0.4 * GB, 5)).toBe(1);+ const [a, b, d] = [engine(), engine(), engine()];+ const fits = () => 2;+ keepWarm("a", a.warm, { bytes: DESKTOP }, () => 8 * GB, fits);+ keepWarm("b", b.warm, { bytes: DESKTOP }, () => 8 * GB, fits);+ expect([a.state.closed, b.state.closed]).toEqual([0, 0]);+ keepWarm("d", d.warm, { bytes: DESKTOP }, () => 8 * GB, fits);+ expect([a.state.closed, b.state.closed, d.state.closed]).toEqual([1, 0, 0]);+ expect(warmEngineKeys()).toEqual(["b", "d"]);+ });+it("closes the engine idle longest when another goes idle and memory is tight, never a busy one", () => {const [a, b, c] = [engine(), engine(true), engine()];keepWarm("a", a.warm, small, () => 0.6 * GB);@@ -124,8 +137,8 @@ describe("idle engines on a small box", () => {it("keeps every idle engine on a large box, and forgets one once it closes or works again", () => {const [a, b] = [engine(), engine()];- keepWarm("a", a.warm, { bytes: DESKTOP }, () => 0);- keepWarm("b", b.warm, { bytes: DESKTOP }, () => 0);+ keepWarm("a", a.warm, { bytes: DESKTOP }, () => 0, () => Infinity);+ keepWarm("b", b.warm, { bytes: DESKTOP }, () => 0, () => Infinity);expect([a.state.closed, b.state.closed, warmEngineKeys()]).toEqual([0, 0, []]);keepWarm("a", a.warm, small, () => 0.6 * GB);stopIdleClose("a", null);diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.tsindex 6adfaa0fe9..d7170bd2af 100644--- a/server/drivers/session-idle.ts+++ b/server/drivers/session-idle.ts@@ -42,9 +42,11 @@ export function sessionIdlePolicy(return { idleMs: Math.max(minimumMs, configured), minimumMs };}-/** On a small box with less than half of it free, a second idle engine would leave no room for a turn's own engine. */-export function idleEnginesAllowed(box: Pick<BoxMemory, "bytes">, availableBytes: number): number {- return box.bytes <= SMALL_BOX_BYTES && availableBytes < box.bytes / 2 ? 1 : Infinity;+/** On a small box with less than half of it free, a second idle engine would leave no room for a turn's own engine. On a+ * self-hosted server whose memory or pids limit holds only so many engines (`fits`), no more stay idle than fit beside the+ * ones working: each holds its processes and threads against that limit while it waits. */+export function idleEnginesAllowed(box: Pick<BoxMemory, "bytes">, availableBytes: number, fits: number = Infinity): number {+ return Math.min(fits, box.bytes <= SMALL_BOX_BYTES && availableBytes < box.bytes / 2 ? 1 : Infinity);}export interface WarmEngine {@@ -58,12 +60,13 @@ const warmEngines = new Map<string, WarmEngine>();/** An engine went idle: when the box allows fewer idle engines than are up, the ones idle longest close now. */export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "bytes"> = boxMemory(),- available: () => number = availableMemory): void {- if (box.bytes > SMALL_BOX_BYTES) return;+ available: () => number = availableMemory, fits: () => number = () => engineMemory.idleEnginesAllowed()): void {+ const most = fits();+ if (box.bytes > SMALL_BOX_BYTES && most === Infinity) return;warmEngines.delete(key);warmEngines.set(key, engine);for (const [other, warm] of warmEngines) if (other !== key && !warm.idle()) warmEngines.delete(other);- const extra = warmEngines.size - idleEnginesAllowed(box, available());+ const extra = warmEngines.size - idleEnginesAllowed(box, available(), most);if (extra <= 0) return;for (const [other, warm] of [...warmEngines].slice(0, extra)) {warmEngines.delete(other);@@ -94,9 +97,9 @@ const WATCHED_MS = 30 * 60_000;export const UNWATCHED_IDLE_MS = 30_000;/**- * How long one thread's idle engine stays up after a turn. On a Cloud home: briefly for a thread no person has had in- * front of them lately, and for the one they have, the configured time scaled by the memory left (down to a tenth).- * Elsewhere the configured time.+ * How long one thread's idle engine stays up after a turn. Where turns wait for room (a Cloud home, a self-hosted Linux+ * server): briefly for a thread no person has had in front of them lately, and for the one they have, the configured time+ * scaled by the memory left (down to a tenth). Elsewhere the configured time.*/export function engineIdleMs(threadId: string, policy: SessionIdlePolicy, memory: Pick<EngineMemory, "enabled" | "headroom"> = engineMemory,now: number = Date.now()): number {@@ -104,3 +107,7 @@ export function engineIdleMs(threadId: string, policy: SessionIdlePolicy, memoryif (!seenWithin(threadId, WATCHED_MS, now)) return Math.max(policy.minimumMs, Math.min(policy.idleMs, UNWATCHED_IDLE_MS));return Math.max(policy.minimumMs, Math.round(policy.idleMs * memory.headroom()));}++/** Whether this thread's engine (`pid`, the process that exited) was just stopped to make room, or for want of it: a+ * driver does not start it again at once, into the same shortage. */+export const stoppedForRoom = (threadId: string, pid?: number): boolean => engineMemory.stoppedForRoom(threadId, pid);diff --git a/server/engine-memory.ts b/server/engine-memory.tsindex 792effcd0a..d961ba1575 100644--- a/server/engine-memory.ts+++ b/server/engine-memory.ts@@ -1,10 +1,18 @@-// On a Cloud home each engine process and the MCP servers it starts take hundreds of MB, and a Linux machine without swap-// that runs out keeps reclaiming, unresponsive, long before its OOM killer acts.+// Each engine process and the MCP servers it starts take hundreds of MB, and a Linux machine without swap that runs out+// keeps reclaiming, unresponsive, long before its OOM killer acts; in a container the kernel stops engines instead. So a+// turn that needs a new engine waits here for memory, and under a container's pids limit for room for its processes+// (process-room.ts), on a Cloud home and on a self-hosted Linux server alike.import { AsyncLocalStorage } from "node:async_hooks";import type { ChildProcess } from "node:child_process";import { readdirSync, readFileSync } from "node:fs";import { chatNotice, noticeFailure } from "./chat-notices.ts";-import { newEventId, newId, TurnNotStartedError, type ProviderAdapter, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener } from "./contracts.ts";+import { newEventId, newId, TurnAuthenticationRefusedError, TurnNotStartedError, TurnUsageLimitRefusedError, type ProviderAdapter, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener } from "./contracts.ts";+import { readCgroupMemory } from "./process-limits.ts";+import { namesOwnCause, shortageCode, type ShortageCode } from "./process-shortage.ts";+import {+ BROWSER_TASKS, ENGINE_TASKS, gateHost, linuxTreeUse, processBudget, SESSION_TASKS, turnsSetting, turnsUnder, type GateHost, type ProcessBudget, type TreeUse,+ type TurnsSetting,+} from "./process-room.ts";const MB = 1024 * 1024;const PAGE_BYTES = 4096;@@ -19,7 +27,14 @@ export const SESSION_BYTES = 200 * MB;* 2026-10-21. It runs outside the engine's process group, so an engine's measured size never includes it. */export const BROWSER_BYTES = 400 * MB;/** A new engine's share is held back this long while it starts and grows; it is measured once it has run this long. */-const RESERVE_MS = 90_000, SETTLED_MS = 30_000;+const RESERVE_MS = 90_000, SETTLED_MS = 30_000, TASKS_RESERVE_MS = 20_000, TASKS_SETTLED_MS = 5_000, SERVER_TURNS_FOR_MS = 5_000;+/** A new engine process that has sent nothing this long after its turn began, while the server is short of room, never+ * came up: under a full pids limit a process can start and then hang, its threads refused, without any error. With no+ * sign of a shortage, or while its processes still work (a cold `npx` install, a slow first start), each driver's own+ * start timeout decides instead. */+export const FIRST_FRAME_MS = 90_000;+/** A silent engine's tree is read this long apart: less CPU than IDLE_CPU_MS between two reads and no child running is idle. */+const FRAME_SAMPLE_MS = 5_000, FRAME_RECHECK_MS = 15_000, IDLE_CPU_MS = 50, FRAME_WATCH_MS = 10 * 60_000;const TICK_MS = 2_000, RELIEF_COOLDOWN_MS = 15_000, NOTICE_REPEAT_MS = 10 * 60_000, STOP_GRACE_MS = 5_000;/** How long a bot's turn lets a person's own work go first. Past this it takes its place by arrival, so it is never starved. */export const BOT_TURN_GIVES_WAY_MS = 5 * 60_000;@@ -38,8 +53,20 @@ export interface HostMemory { totalBytes: number; availableBytes: number; swapFrconst procText = (path: string) => readFileSync(path, "utf8");-/** /proc/meminfo, the kernel's OOM kill count and memory stall; null where there is no /proc (not Linux). */+/** /proc/meminfo, the kernel's OOM kill count and memory stall; null where there is no /proc (not Linux). /proc/meminfo is+ * the whole machine's even inside a container, so under a cgroup limit below the machine's memory the limit, what counts+ * against it and the cgroup's own OOM kills and stall are what is reported, and swap, which the limit may not allow, is not+ * counted on. */export function readHostMemory(read: (path: string) => string = procText): HostMemory | null {+ const host = readMachineMemory(read);+ if (!host) return null;+ const cgroup = readCgroupMemory((path) => { try { return read(path); } catch { return null; } });+ if (!cgroup || cgroup.limitBytes >= host.totalBytes) return host;+ return { totalBytes: cgroup.limitBytes, availableBytes: Math.max(0, Math.min(host.availableBytes, cgroup.limitBytes - cgroup.usedBytes)), swapFreeBytes: 0,+ oomKills: cgroup.oomKills ?? host.oomKills, fullStall10: cgroup.fullStall10 ?? host.fullStall10 };+}++function readMachineMemory(read: (path: string) => string): HostMemory | null {let meminfo: string;try { meminfo = read("/proc/meminfo"); } catch { return null; }const field = (name: string) => { const found = new RegExp(`^${name}:\\s+(\\d+) kB$`, "m").exec(meminfo); return found ? Number(found[1]) * 1024 : null; };@@ -94,9 +121,10 @@ export const memoryWaitText = (count: number) => `Waiting for memory: ${running(export const memoryStillWaitingText = (count: number) => `Still waiting for memory: ${running(count)}.`;/** How a wait reads to the person, in their language, and where else it shows. */export interface EngineWaits {- /** `limit`: the plan's most turns at once, when that is what this one waits for rather than memory. */- text(threadId: string, wait: { first: boolean; running: number; ahead: number; limit?: number }): string;- began(threadId: string, wait: { running: number; ahead: number; limit?: number }): void;+ /** `limit`: the most turns at once (a plan's, or a self-hosted server's), when that is what this one waits for rather+ * than room. `server`: a self-hosted server, whose wait is for memory or for room under its process limit. */+ text(threadId: string, wait: { first: boolean; running: number; ahead: number; limit?: number; server?: boolean }): string;+ began(threadId: string, wait: { running: number; ahead: number; limit?: number; server?: boolean }): void;/** Whether anything is waiting for memory changed. */changed(): void;}@@ -160,10 +188,18 @@ interface Waiter { wake: () => void; threadId: string; since: number }export interface EngineMemoryOptions {enabled: boolean;+ /** A self-hosted server also holds turns to a number of its own and to its container's pids limit; a Cloud home, the+ * default, keeps to memory and its plan. */+ host?: Exclude<GateHost, null>;+ /** OMB_TURNS_MAX_RUNNING on a self-hosted server. */+ turns?: TurnsSetting;+ processes?: ProcessBudget;read?: () => HostMemory | null;groups?: () => Map<number, number>;now?: () => number;signal?: (pid: number, signal: NodeJS.Signals) => void;+ /** An engine's process tree: whether it still works. Null where it can't be read, and then it is never stopped as silent. */+ tree?: (pid: number) => TreeUse | null;log?: (line: string) => void;tickMs?: number;}@@ -174,6 +210,7 @@ export class EngineMemory {private readonly groups: () => Map<number, number>;private readonly now: () => number;private readonly signal: (pid: number, signal: NodeJS.Signals) => void;+ private readonly tree: (pid: number) => TreeUse | null;private readonly log: (line: string) => void;private readonly tickMs: number;private readonly context = new AsyncLocalStorage<string>();@@ -184,6 +221,17 @@ export class EngineMemory {private readonly queue: Waiter[] = [];/** Threads whose engine was stopped for memory: how many tasks ran then, and whether their browser was running. */private readonly stops = new Map<string, { count: number; browser: boolean }>();+ /** Threads whose turn could not run its engine for want of room: the code its failure names, and whether the engine's own+ * spawn was refused (a later spawn in the same turn that works clears that) or the engine was stopped as silent. */+ private readonly starved = new Map<string, { code: ShortageCode; why: "refused" | "silent" }>();+ /** Threads whose engine this gate stopped, for room or for want of it, during their turn: that engine's pid. */+ private readonly roomStopped = new Map<string, number>();+ /** The last spawn the system refused for want of room, anywhere on the server. */+ private lastRefusal: { at: number; code: ShortageCode } | null = null;+ /** Threads whose turn is about to start an engine that keeps a session (expectFrame). */+ private readonly expecting = new Set<string>();+ private queuedEver = 0;+ private starvedEver = 0;/** Threads that ran while memory was short: the most tasks running then. */private readonly pressure = new Map<string, number>();private oomKills: number | null = null;@@ -198,13 +246,22 @@ export class EngineMemory {private ordered: { at: number; generation: number; list: Waiter[] } | null = null;private waits: EngineWaits | null = null;private cap: EngineCap | null = null;+ private readonly server: boolean;+ private readonly turns: TurnsSetting;+ private readonly processes: ProcessBudget | null;+ private serverTurns: { at: number; most: number | undefined } | null = null;constructor(options: EngineMemoryOptions) {this.enabled = options.enabled;+ this.server = options.host === "server";+ this.turns = options.turns ?? "auto";+ this.processes = this.server ? options.processes ?? processBudget : null;+ this.processes?.onRefused(() => this.wake());this.read = options.read ?? (() => readHostMemory());this.groups = options.groups ?? (() => processGroupBytes());this.now = options.now ?? Date.now;this.signal = options.signal ?? ((pid, signal) => process.kill(-pid, signal));+ this.tree = options.tree ?? ((pid) => linuxTreeUse(pid));this.log = options.log ?? ((line) => console.warn(`memory: ${line}`));this.tickMs = options.tickMs ?? TICK_MS;}@@ -218,16 +275,38 @@ export class EngineMemory {useCap(cap: EngineCap): void { this.cap = cap; }- /** Whether every turn here waits for a place under the plan's limit, not only one that starts an engine. */- limited(): boolean { return this.enabled && this.cap?.most() !== undefined; }+ /** A self-hosted server where turns wait for room (not a Cloud home, not the desktop app). */+ selfHosted(): boolean { return this.enabled && this.server; }++ /** Whether every turn here waits for a place under a limit on turns, not only one that starts an engine. */+ limited(): boolean { return this.enabled && this.most() !== undefined; }++ /** The most turns at once: the plan's, and on a self-hosted server the operator's number, or else what its memory and+ * its pids limit hold at an engine's usual size. */+ most(): number | undefined {+ const plan = this.cap?.most(), server = this.serverMost();+ return plan === undefined ? server : server === undefined ? plan : Math.min(plan, server);+ }++ private serverMost(): number | undefined {+ if (!this.server) return undefined;+ if (typeof this.turns === "number") return this.turns;+ const at = this.now();+ if (this.serverTurns && at - this.serverTurns.at < SERVER_TURNS_FOR_MS && at >= this.serverTurns.at) return this.serverTurns.most;+ const memory = this.read(), limit = this.processes?.limit() ?? null;+ const fits = [memory ? Math.max(1, Math.floor((memory.totalBytes - this.floor(memory)) / ENGINE_DEFAULT_BYTES)) : null, limit === null ? null : turnsUnder(limit)]+ .filter((count): count is number => count !== null);+ this.serverTurns = { at, most: fits.length ? Math.min(...fits) : undefined };+ return this.serverTurns.most;+ }/** The plan's limit when it is what this thread's turn must wait for now; undefined when there is a place. */private capped(threadId: string): number | undefined {- const most = this.cap?.most();- if (most === undefined || this.cap!.laneOwned?.(threadId)) return undefined;+ const most = this.most();+ if (most === undefined || this.cap?.laneOwned?.(threadId)) return undefined;let running = 0;for (const other of new Set([...this.active, ...this.reserved.keys()])) {- if (other === threadId || this.cap!.waitsOnOthers(other) || this.cap!.laneOwned?.(other)) continue;+ if (other === threadId || this.cap?.waitsOnOthers(other) || this.cap?.laneOwned?.(other)) continue;if (++running >= most) return most;}return undefined;@@ -238,11 +317,11 @@ export class EngineMemory {laneHasRoom(): boolean {if (!this.enabled) return true;if (this.queue.some((waiter) => this.personsOwn(waiter.threadId))) return false;- const most = this.cap?.most();+ const most = this.most();if (most === undefined) return true;let running = 0;for (const other of new Set([...this.active, ...this.reserved.keys()])) {- if (!this.cap!.waitsOnOthers(other) && ++running >= most) return false;+ if (!this.cap?.waitsOnOthers(other) && ++running >= most) return false;}return true;}@@ -262,10 +341,56 @@ export class EngineMemory {const pid = child.pid, engine: Engine = { child, threads: new Set([threadId]), startedAt: this.now(), stopping: false };this.engines.set(pid, engine);this.oomKills ??= this.read()?.oomKills ?? null;- child.once("exit", (_code, signal) => this.exited(pid, engine, signal));+ // A spawn that worked after one was refused in the same turn: the turn goes on, and its end is its own.+ if (this.starved.get(threadId)?.why === "refused") this.starved.delete(threadId);+ // An engine that keeps a session (Claude's stream, ACP, Codex's app-server) writes to its stdout first thing. Read from+ // the pipe's byte count: no listener is added to it.+ const out = this.expecting.delete(threadId) ? child.stdout as { bytesRead?: unknown } | null : null;+ const unwatch = out && typeof out.bytesRead === "number" ? this.watchFirstFrame(engine, out as { bytesRead: number }) : null;+ child.once("exit", (_code, signal) => { unwatch?.(); this.exited(pid, engine, signal); });this.arm();}+ /** From FIRST_FRAME_MS on, a new engine that has written nothing is stopped as one that never came up, only while the+ * server shows a shortage (pids at its limit at the start or now, a spawn refused since the start, memory short or+ * stalled) and only once its process tree has gone idle with no child running. Otherwise it is left to its driver. */+ private watchFirstFrame(engine: Engine, out: { bytesRead: number }): () => void {+ const pid = engine.child.pid!, crowdedAtStart = this.processes?.short(ENGINE_TASKS, 0) === true;+ let timer: ReturnType<typeof setTimeout> | null = null, last: TreeUse | null = null;+ const watch = (ms: number) => { timer = setTimeout(look, ms); timer.unref?.(); };+ const look = () => {+ timer = null;+ if (engine.stopping || out.bytesRead !== 0 || this.now() - engine.startedAt > FRAME_WATCH_MS) return;+ const code = this.shortage(engine.startedAt, crowdedAtStart), use = code === null ? null : this.tree(pid);+ if (code !== null && use && last && use.children === 0 && use.cpuMs - last.cpuMs < IDLE_CPU_MS) { void this.starveEngine(engine, code); return; }+ last = use;+ watch(use ? FRAME_SAMPLE_MS : FRAME_RECHECK_MS);+ };+ watch(FIRST_FRAME_MS - FRAME_SAMPLE_MS);+ return () => { if (timer) clearTimeout(timer); };+ }++ /** The shortage the server shows for an engine started at `since`, by the code its turn's failure would name; null for+ * none. */+ private shortage(since: number, crowdedAtStart: boolean): ShortageCode | null {+ if (this.lastRefusal && this.lastRefusal.at >= since) return this.lastRefusal.code;+ if (crowdedAtStart || this.processes?.short(0, 0)) return "EAGAIN";+ const memory = this.read();+ return memory && ((memory.fullStall10 ?? 0) >= STALL_PERCENT || this.free(memory) < this.floor(memory)) ? "ENOMEM" : null;+ }++ /** The next engine process this thread's turn starts keeps a session, and so speaks first: it gets FIRST_FRAME_MS to. */+ expectFrame(threadId: string): void { if (this.enabled) this.expecting.add(threadId); }++ /** A spawn the system refused. Every one is a sign of a shortage; an engine's own (`engine`) inside a thread's running+ * turn also fails that turn as one the server had no room for. */+ spawnRefused(code: string | undefined, engine = false): void {+ const threadId = this.context.getStore(), shortage = shortageCode({ code });+ if (!this.enabled || shortage === null) return;+ this.lastRefusal = { at: this.now(), code: shortage };+ if (engine && threadId !== undefined && this.active.has(threadId) && !this.starved.has(threadId)) this.starved.set(threadId, { code: shortage, why: "refused" });+ }+/** The engine processes tracked now, with the threads each runs: for the performance sampler's buckets. */enginePids(): Array<{ pid: number; threads: string[] }> { return [...this.engines].map(([pid, engine]) => ({ pid, threads: [...engine.threads] })); }@@ -278,7 +403,18 @@ export class EngineMemory {if (child.pid) this.engines.get(child.pid)?.threads.delete(threadId);}- turnStarted(threadId: string): void { if (this.enabled) this.active.add(threadId); }+ /** A turn starts with nothing from an earlier one: what stopped or starved that turn's engine is not this one's cause. */+ turnStarted(threadId: string): void {+ if (!this.enabled) return;+ this.active.add(threadId);+ this.forget(threadId);+ }++ private forget(threadId: string): void {+ this.stops.delete(threadId);+ this.starved.delete(threadId);+ this.roomStopped.delete(threadId);+ }/** This thread's engine process is still running (an engine keeps one between turns), so its turn starts no new one. */hasEngine(threadId: string): boolean {@@ -291,10 +427,46 @@ export class EngineMemory {this.active.delete(threadId);this.reserved.delete(threadId);this.pressure.delete(threadId);- this.stops.delete(threadId);+ this.forget(threadId);+ this.expecting.delete(threadId);this.wake();}+ /** A new engine never came up: its processes are stopped, and its threads' turns fail as ones the server had no room+ * for, which start again by themselves rather than as the AI's failure. */+ private async starveEngine(engine: Engine, code: ShortageCode): Promise<void> {+ if (engine.stopping || engine.child.exitCode !== null || engine.child.signalCode !== null) return;+ // Not a refused spawn: no limit is learned from it, and no count of refusals goes up.+ for (const threadId of this.working(engine)) if (!this.starved.has(threadId)) this.starved.set(threadId, { code, why: "silent" });+ this.noteRoomStopped(engine);+ this.starvedEver += 1;+ this.log(`an engine (pid ${engine.child.pid}) sent nothing for ${Math.round((this.now() - engine.startedAt) / 1000)} s after it started, idle, while the server was short of room (${code}); stopping it`);+ await this.stop(engine, "relief");+ }++ private noteRoomStopped(engine: Engine): void { for (const threadId of this.working(engine)) this.roomStopped.set(threadId, engine.child.pid!); }++ /** Whether this thread's engine was stopped to make room, or for want of it, in its turn: its turn is not sent again at+ * once. With `pid`, whether that engine process is the one stopped: any other exit is the engine's own. */+ stoppedForRoom(threadId: string, pid?: number): boolean {+ if (pid !== undefined) return this.roomStopped.get(threadId) === pid;+ return this.stops.has(threadId) || this.starved.has(threadId);+ }++ /** How many engines may stay loaded with no turn running, on a self-hosted server: what fits beside the ones working.+ * Infinity elsewhere. */+ idleEnginesAllowed(): number {+ const most = this.enabled ? this.serverMost() : undefined;+ return most === undefined ? Infinity : Math.max(1, most - this.busy());+ }++ /** Turns running and waiting now, and counts since the server started: numbers only. */+ counts(): { running: number; queued: number; longestWaitMs: number; most: number | null; queuedEver: number; starvedEver: number } {+ const at = this.now();+ return { running: this.active.size, queued: this.waitingSince.size, longestWaitMs: Math.max(0, ...[...this.waitingSince.values()].map((since) => at - since)),+ most: this.enabled ? this.most() ?? null : null, queuedEver: this.queuedEver, starvedEver: this.starvedEver };+ }+/** Tasks running on engines here now, or about to (admitted, not yet started); `also` counts one more thread. */busy(also?: string): number {const threads = this.busyThreads();@@ -342,9 +514,10 @@ export class EngineMemory {}if (announced === null || this.now() - announced >= NOTICE_REPEAT_MS) {const others = this.othersBusy(threadId), first = announced === null, ahead = this.order().indexOf(waiter);- const limit = this.capped(threadId), wait = { running: others, ahead, ...(limit === undefined ? {} : { limit }) };+ const limit = this.capped(threadId), wait = { running: others, ahead, ...(limit === undefined ? {} : { limit }), ...(this.server ? { server: true } : {}) };if (first) {this.waitingSince.set(waiter, this.now());+ this.queuedEver += 1;this.ledger.note(this.now(), "waits");this.waits?.began(threadId, wait);if (this.waitingSince.size === 1) this.waits?.changed();@@ -378,7 +551,11 @@ export class EngineMemory {return this.stopFailure(threadId)?.message ?? null;}- stopFailure(threadId: string, detail?: string): ReturnType<typeof noticeFailure> | null {+ /** `detail`: the failure that ends the turn, when one names its own cause (a usage limit, a sign-in) it is kept, whatever+ * shortage was seen in the turn. `interrupted`: the person stopped the turn, which no shortage explains. */+ stopFailure(threadId: string, detail?: string, interrupted = false): ReturnType<typeof noticeFailure> | null {+ const starved = this.starved.get(threadId);+ if (starved !== undefined && !interrupted && (detail === undefined || !namesOwnCause(detail))) return noticeFailure("chat.notice.outOfProcesses", { code: starved.code });const stop = this.stops.get(threadId);return stop === undefined ? null : noticeFailure(memoryStopKey(stop.browser, detail !== undefined), detail === undefined ? undefined : { detail });}@@ -412,6 +589,7 @@ export class EngineMemory {if (idle) { void this.stop(victim, "idle"); return; }const stopped = this.working(victim);this.noteStops(stopped, () => count);+ this.noteRoomStopped(victim);void this.stop(victim, "relief").then(() => this.closeBrowsers(stopped));}@@ -439,15 +617,21 @@ export class EngineMemory {private room(start: "process" | "session", threadId: string): "admit" | "wait" | Engine {const memory = this.read();- if (!memory) return "admit";+ if (!memory) return this.crowded(start, threadId, 0, false) ? this.idle() ?? (this.othersBusy(threadId) === 0 ? "admit" : "wait") : "admit";const groups = this.groups(), at = this.now();const live = [...this.engines.entries()].filter(([, engine]) => !engine.stopping);const measured = live.filter(([, engine]) => at - engine.startedAt >= SETTLED_MS).map(([pid]) => groups.get(pid)).filter((bytes) => bytes !== undefined);const process = Math.min(ENGINE_MAX_BYTES, Math.max(ENGINE_MIN_BYTES, measured.length ? measured.reduce((sum, bytes) => sum + bytes, 0) / measured.length : ENGINE_DEFAULT_BYTES));- let held = 0;+ let held = 0, heldTasks = 0, heldBrowser = false;const heldBrowsers = new Set<string>();for (const [threadId, admitted] of this.reserved) {if (at - admitted.at >= RESERVE_MS) { this.reserved.delete(threadId); continue; }+ // An engine's processes are all there within seconds of its start, long before its memory settles.+ const up = admitted.start === "process" && live.some(([, engine]) => engine.threads.has(threadId) && at - engine.startedAt >= TASKS_SETTLED_MS);+ if (at - admitted.at < TASKS_RESERVE_MS && !up) {+ heldTasks += admitted.start === "session" ? SESSION_TASKS : ENGINE_TASKS;+ heldBrowser ||= admitted.browser && this.browserStarts(threadId);+ }// A browser grows as it starts and loads its first pages: its share is held until it has run SETTLED_MS.if (admitted.browser) {if (!this.browserStarts(threadId)) admitted.browserSince ??= at;@@ -464,10 +648,20 @@ export class EngineMemory {}const newBrowser = this.browserStarts(threadId) && !heldBrowsers.has(this.browsers?.which?.(threadId) ?? threadId);const need = (start === "session" ? SESSION_BYTES : process) + (newBrowser ? BROWSER_BYTES : 0);- if (this.free(memory) - this.floor(memory) - held >= need) return "admit";+ if (this.free(memory) - this.floor(memory) - held >= need && !this.crowded(start, threadId, heldTasks, heldBrowser)) return "admit";return this.idle() ?? (this.othersBusy(threadId) === 0 ? "admit" : "wait");}+ /** Whether this start's processes would not fit under the server's pids limit. A browser starts on a bot's first browser+ * call, not with its engine, and itself waits for room before it opens (browser-room.ts): room for one more+ * is kept while any start pending may open one, rather than one for every such start, which would let one turn in at a+ * time. Browsers already running count in the limit's own count. */+ private crowded(start: "process" | "session", threadId: string, heldTasks: number, heldBrowser: boolean): boolean {+ if (!this.processes) return false;+ const browser = heldBrowser || this.browserStarts(threadId) ? BROWSER_TASKS : 0;+ return this.processes.short((start === "session" ? SESSION_TASKS : ENGINE_TASKS) + browser, heldTasks);+ }+private browserStarts(threadId: string): boolean { return this.browsers?.starts(threadId) === true; }private closeBrowsers(threadIds: string[]): void { for (const threadId of threadIds) this.browsers?.stopped(threadId); }@@ -475,7 +669,7 @@ export class EngineMemory {private async stop(engine: Engine, why: "idle" | "relief"): Promise<void> {const pid = engine.child.pid!, gone = () => engine.child.exitCode !== null || engine.child.signalCode !== null;engine.stopping = true;- this.log(`stopping ${why === "idle" ? "an idle engine" : "the newest engine"} (pid ${pid}) to free memory; ${tasks(this.busy())} running`);+ this.log(`stopping ${why === "idle" ? "an idle engine" : "an engine"} (pid ${pid}) to make room; ${tasks(this.busy())} running`);const exited = new Promise<void>((resolve) => { if (gone()) resolve(); else engine.child.once("exit", () => resolve()); });const grace = () => new Promise<void>((resolve) => { const timer = setTimeout(resolve, STOP_GRACE_MS); timer.unref?.(); });try { this.signal(pid, why === "idle" ? "SIGTERM" : "SIGKILL"); } catch {}@@ -490,6 +684,7 @@ export class EngineMemory {const working = this.working(engine);if (signal === "SIGKILL" && !engine.stopping && working.length && this.kernelKilled(this.read()?.oomKills ?? null)) {this.noteStops(working, (threadId) => this.busy(threadId));+ for (const threadId of working) this.roomStopped.set(threadId, pid);this.log(`the kernel stopped an engine (pid ${pid}) for memory`);this.closeBrowsers(working);}@@ -517,9 +712,11 @@ export class EngineMemory {private order(): Waiter[] {const at = this.now();if (this.ordered?.at === at && this.ordered.generation === this.generation) return this.ordered.list;- const first: Waiter[] = [], rest: Waiter[] = [];- for (const waiter of this.queue) (this.personsOwn(waiter.threadId) || at - waiter.since >= BOT_TURN_GIVES_WAY_MS ? first : rest).push(waiter);- this.ordered = { at, generation: this.generation, list: [...first, ...rest] };+ const holding: Waiter[] = [], first: Waiter[] = [], rest: Waiter[] = [];+ // A turn that already has its place under a limit on turns, and now waits for its engine's room, goes ahead of the+ // turns still waiting for a place: behind them it would hold its place for good, and they would wait on it.+ for (const waiter of this.queue) (this.active.has(waiter.threadId) ? holding : this.personsOwn(waiter.threadId) || at - waiter.since >= BOT_TURN_GIVES_WAY_MS ? first : rest).push(waiter);+ this.ordered = { at, generation: this.generation, list: [...holding, ...first, ...rest] };return this.ordered.list;}@@ -535,7 +732,12 @@ export class EngineMemory {}}-export const engineMemory = new EngineMemory({ enabled: (process.env.OMB_CLOUD_ROLE === "home" || process.env.OMB_CLOUD_ROLE === "team") && process.platform === "linux" });+const HOST = gateHost();+export const engineMemory = new EngineMemory({ enabled: HOST !== null, host: HOST ?? "cloud", turns: turnsSetting(process.env.OMB_TURNS_MAX_RUNNING) });++/** Engines that keep a session over stdout and answer first (stream-json's init, JSON-RPC's initialize); every driver+ * that admits its own engines (ACP) does too. */+const SESSION_KINDS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);/*** One engine's adapter on a Cloud home: a turn that needs a new engine process waits for memory first (saying so in the@@ -556,7 +758,8 @@ export function withEngineMemory(instance: ProviderInstance, memory: EngineMemorqueueMicrotask(() => { explained.delete(item.threadId); memory.turnEnded(item.threadId); });});const present = (item: RuntimeEvent): RuntimeEvent[] => {- const stopped = memory.stopFailure(item.threadId, item.type === "runtime.error" ? item.message.slice(0, 200) : undefined);+ const stopped = memory.stopFailure(item.threadId, item.type === "runtime.error" ? item.message.slice(0, 200) : undefined,+ item.type === "turn.completed" && item.stopReason === "interrupted");if (!stopped) return [item];if (item.type === "runtime.error") {explained.add(item.threadId);@@ -599,9 +802,14 @@ export function withEngineMemory(instance: ProviderInstance, memory: EngineMemorthrow error;}memory.turnStarted(threadId);+ if (SESSION_KINDS.has(instance.driverKind) || driverAdmits) memory.expectFrame(threadId);try {return await memory.within(threadId, () => adapter.sendTurn(driverAdmits ? { ...input, engineAdmission: admit } : input));} catch (error) {+ // A start the server had no room for names that, never the engine's own words: no backup AI is tried for it. A refusal+ // that names its own cause (a usage limit, a sign-in) stays what it is.+ if (error instanceof TurnNotStartedError && !(error instanceof TurnUsageLimitRefusedError || error instanceof TurnAuthenticationRefusedError)+ && memory.stoppedForRoom(threadId) && !namesOwnCause(error.message)) error.message = memory.stopFailure(threadId)?.message ?? error.message;memory.turnEnded(threadId);throw error;}diff --git a/server/host/browser.ts b/server/host/browser.tsindex ac2e4679fa..29a1cb5c9f 100644--- a/server/host/browser.ts+++ b/server/host/browser.ts@@ -46,6 +46,7 @@ import { passkeyAnnotation } from "../browser/passkey-notice.ts";import { LentChromeDoors, lentChromeGuidance, type ChromeLender } from "../browser/lent-chrome.ts";import type { ChromeRoute } from "../device-links.ts";import type { EngineBrowsers } from "../engine-memory.ts";+import { processBudget } from "../process-room.ts";import { augmentedPath } from "../env-path.ts";import { harnessMcpTokenEnv } from "../harness-mcp-token.ts";import type { FillLoginDeps } from "../login-fill.ts";@@ -78,7 +79,8 @@ export interface BrowserHostDeps {/** My Cloud's way to the person's own Chrome on the computer that lends it, and which computer that is. */lentChrome?: { route(): ChromeRoute | null; lender(): ChromeLender | null };/** The engine memory guard, told which browsers each thread's turn starts or holds. */- engineMemory?: { useBrowsers(browsers: EngineBrowsers): void };+ /** `selfHosted`: turns wait for room on this server, under its pids limit, and so do its bots' browsers. */+ engineMemory?: { useBrowsers(browsers: EngineBrowsers): void; selfHosted?(): boolean };/** Whose browser a conversation's turns use on a Team Cloud: the member's, the group chat's or the team's. Every* browser is the bot's own without it. */audienceOf?(threadId: string): Audience;@@ -109,11 +111,15 @@ export function createBrowserHost(deps: BrowserHostDeps) {const store: Pick<Store, "bots" | "bot" | "botByThread"> = { get bots() { return deps.store().bots; }, bot: (id: string) => deps.store().bot(id),botByThread: (threadId: string) => deps.store().botByThread(threadId) };+ // Where turns wait for room (a self-hosted server under its pids limit), a new browser also waits for room for its+ // processes. `runs` is read only when a browser call asks, after usedBrowserSessions exists.+ const processRoom = deps.engineMemory?.selfHosted?.() ? processBudget.browserRoom((session) => browserRunning(session, usedBrowserSessions.get(session))) : null;// Only a bot waiting for a slot closes a browser a running turn holds; the idle sweep below never does.const browserRoom = new BrowserRoom({max: deps.browsersAtOnce ?? (() => defaultBrowserRoomSize()),spare: (session) => spareForRoom(agentBrowserRuntime.spare(session), { holds: !turnResources.free(`browser:${session}`), idleMs: idleMs() }),close: (session) => agentBrowserRuntime.closeIfIdle(session, 1),+ ...(processRoom ? { admit: (session: string) => processRoom.enter(session) } : {}),});const agentBrowserRuntime = new BrowserRuntime({closeBrowser: (session, spec) => closeBrowserSession(spec.command, browserRuntimeEnv({ ...spec.env, AGENT_BROWSER_SESSION: session })),@@ -195,6 +201,10 @@ export function createBrowserHost(deps: BrowserHostDeps) {// person's own, outside the egress gate too; on My Cloud a call that can't reach it now says why instead.const browserRuntime = new RuntimeRouter(agentBrowserRuntime, chromeEngine, {refusal: (_session, spec, params) => (attachesToChrome(spec.env) ? null : browserEgress.callRefusal(params)),+ // The opt-in engine's browsers wait for the server's room here; agent-browser's wait in browserRoom above. The+ // person's own Chrome runs outside this server, and a close frees room.+ room: (session, spec, params) => (!processRoom || attachesToChrome(spec.env) || (params as { name?: unknown } | null)?.name === "agent_browser_close"+ ? Promise.resolve(null) : processRoom.enter(session)),// After beforeDispatch's claim the holder is this call's own turn, so the verdict is the caller's, not the last// holder's. Only a caller who may use the computer learns whether it lends Chrome or is online.afterClaim: (session, spec) => {diff --git a/server/host/chief-notices-retry.test.ts b/server/host/chief-notices-retry.test.tsindex 733e286a82..7aad56c459 100644--- a/server/host/chief-notices-retry.test.ts+++ b/server/host/chief-notices-retry.test.ts@@ -5,7 +5,7 @@ import "../server-line-packs.ts";import { engineFailureMessage } from "../drivers/engine-errors.ts";import { AUTO_RETRY_LEAD, RETRY_BLOCKED } from "../incidents.ts";import type { RoutineFailureFacts } from "../routine-recovery.ts";-import { createChiefNotices, MEMORY_RETRY_MS, MEMORY_RETRY_TEXT, type ChiefNoticeDeps } from "./chief-notices.ts";+import { createChiefNotices, MEMORY_RETRY_MS, MEMORY_RETRY_TEXT, ROOM_RETRY_TEXT, SERVER_MEMORY_RETRY_TEXT, type ChiefNoticeDeps } from "./chief-notices.ts";function fixture(over: Partial<ChiefNoticeDeps> = {}) {const bots = [@@ -211,6 +211,17 @@ describe("a run stopped to free memory", () => {expect(busy.continued).toEqual([]);});+ it("on a self-hosted server, starts a teammate's run again by itself too, saying it was this server, and asks no Chief", () => {+ const f = roomFixture({ selfHosted: () => true });+ f.store.appendMessage("ada-job", { role: "user", kind: "text", text: "Reconcile the September invoices." });+ f.notices.reportIncident({ kind: "failed", bot: f.ada as never, threadId: "ada-job", detail: STOPPED });+ expect(f.turnsOf("ada")).toEqual([]);+ f.settle();+ expect(f.continued).toEqual([{ botId: "ada", threadId: "ada-job", text: SERVER_MEMORY_RETRY_TEXT }]);+ expect(f.startTurn).not.toHaveBeenCalled();+ expect(f.turnsOf("chief")).toEqual([]);+ });+it("leaves a teammate's run to the Chief's own retry, and any other failure to the person", () => {const teammate = roomFixture();teammate.notices.reportIncident({ kind: "failed", bot: teammate.ada as never, threadId: "ada-job", detail: STOPPED });@@ -261,3 +272,62 @@ describe("a problem in a conversation that runs confined", () => {expect(f.turnsOf("chief")).toHaveLength(1);});});++describe("a run the server had no room to start", () => {+ const NO_ROOM = "There is no room to start another program (EAGAIN), so this task could not run. Nothing was sent to the AI. It starts again by itself when there is room.";++ function shortFixture(over: Partial<ChiefNoticeDeps> = {}) {+ const waiting: Array<{ run: () => void; ms: number }> = [];+ const continued: Array<{ botId: string; threadId: string; text: string }> = [];+ const told: unknown[] = [];+ const f = fixture({+ later: (run, ms) => { waiting.push({ run, ms }); },+ continueRequest: async (botId, threadId, text) => { continued.push({ botId, threadId, text }); },+ notify: (notification) => { told.push(notification); },+ ...over,+ });+ return { ...f, waiting, continued, told, settle: () => { for (const { run } of waiting.splice(0)) run(); } };+ }++ it("starts again by itself once, half a minute on, and no Chief's turn is started about it, though the teammate has one", () => {+ const f = shortFixture();+ f.store.appendMessage("ada-job", { role: "user", kind: "text", text: "Reconcile the September invoices." });+ f.notices.reportIncident({ kind: "failed", bot: f.ada as never, threadId: "ada-job", detail: NO_ROOM });+ expect(f.startTurn).not.toHaveBeenCalled();+ expect(f.told).toEqual([]);+ expect(f.waiting.map(({ ms }) => ms)).toEqual([MEMORY_RETRY_MS]);+ f.settle();+ expect(f.continued).toEqual([{ botId: "ada", threadId: "ada-job", text: ROOM_RETRY_TEXT }]);+ // That start finds no room either: the person hears, once, and still no Chief is asked and nothing starts again.+ f.notices.reportIncident({ kind: "failed", bot: f.ada as never, threadId: "ada-job", detail: NO_ROOM });+ f.settle();+ expect(f.continued).toHaveLength(1);+ expect(f.told).toHaveLength(1);+ expect(f.startTurn).not.toHaveBeenCalled();+ expect(f.turnsOf("chief")).toEqual([]);+ });++ it("does the same for a turn that could not start at all, and for Node's own words for the refusal", () => {+ const f = shortFixture();+ f.store.appendMessage("ada-job", { role: "user", kind: "text", text: "Reconcile the September invoices." });+ f.notices.reportIncident({ kind: "could-not-start", bot: f.ada as never, threadId: "ada-job", detail: "spawn failed: spawn /usr/local/bin/claude EAGAIN" });+ f.settle();+ expect(f.continued).toEqual([{ botId: "ada", threadId: "ada-job", text: ROOM_RETRY_TEXT }]);+ expect(f.startTurn).not.toHaveBeenCalled();+ });++ it("only tells the person where nothing can start it again, and leaves every other failure as it was", () => {+ const told: unknown[] = [];+ const bare = fixture({ notify: (notification) => { told.push(notification); } });+ bare.notices.reportIncident({ kind: "failed", bot: bare.ada as never, threadId: "ada-job", detail: NO_ROOM });+ expect(told).toHaveLength(1);+ expect(bare.startTurn).not.toHaveBeenCalled();+ // A crash still gets the teammate's one retry and then its Chief.+ const crash = shortFixture();+ crash.store.appendMessage("ada-job", { role: "user", kind: "text", text: "Reconcile the September invoices." });+ crash.notices.reportIncident({ kind: "failed", bot: crash.ada as never, threadId: "ada-job", detail: CRASH });+ expect(crash.turnsOf("ada")).toHaveLength(1);+ expect(crash.turnsOf("ada")[0]!.text.startsWith(AUTO_RETRY_LEAD)).toBe(true);+ expect(crash.continued).toEqual([]);+ });+});diff --git a/server/host/chief-notices.ts b/server/host/chief-notices.tsindex 6f09101a8a..98a178bd12 100644--- a/server/host/chief-notices.ts+++ b/server/host/chief-notices.ts@@ -1,6 +1,7 @@import { failedTurnTool } from "../../shared/failed-turn.ts";import { admit } from "../admission.ts";-import { memoryStopped } from "../engine-memory.ts";+import { engineMemory, memoryStopped } from "../engine-memory.ts";+import { outOfProcesses } from "../process-shortage.ts";import {AUTO_RETRY_LEAD, ChiefIncidentBudget, chiefForBot, INCIDENTS_THREAD_TITLE, OLD_INCIDENTS_THREAD_TITLE, IncidentLedger, incidentChip, incidentContext, incidentText, RETRY_BLOCKED, RETRY_LEAD,type Incident, type IncidentKind, type IncidentRetry,@@ -33,6 +34,9 @@ export interface ChiefNoticeDeps {/** Starts this thread's request again where it stopped: a continuation of the request the harness recorded, never a line* of the person's. Absent: a run stopped for memory with no Chief to retry it is only reported. */continueRequest?(botId: string, threadId: string, text: string): Promise<unknown>;+ /** A self-hosted server where turns wait for room: a run stopped for memory there is the server's shortage, as a start+ * it had no room for is, and no Chief is asked about it. */+ selfHosted?(): boolean;/** Runs a retry after a run stopped for memory, MEMORY_RETRY_MS later by default, so the machine settles first. */later?(run: () => void, ms: number): void;/** Security invariant: a read-and-draft run's prompt and reply carry mail and invite text, so its failures and@@ -64,6 +68,13 @@ export const FOLDED_LISTED = 5;export const MEMORY_RETRY_TEXT = "[OpenMausBot started this again by itself, once: the last run was stopped to free memory on this Cloud. "+ "Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]";+export const SERVER_MEMORY_RETRY_TEXT = "[OpenMausBot started this again by itself, once: the last run was stopped to free memory on this server. "+ + "Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]";++/** A run the server had no room to start is the server's shortage: it starts again by itself, and no AI is asked about it. */+export const ROOM_RETRY_TEXT = "[OpenMausBot started this again by itself, once: the last run could not start because this server had no room for another program. "+ + "Continue the request above from where it stopped and finish it. If the same problem comes back, say exactly what is blocking and stop.]";+export function createChiefNotices(deps: ChiefNoticeDeps) {const { store } = deps;const incidentLedger = new IncidentLedger();@@ -77,7 +88,7 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {/** A run stopped for memory that no Chief retries starts once more by itself; the person hears only if that one fails too,* or can't start. Never a run whose thread someone wrote in since, or that is running or queued again. */- function retryForRoom(bot: BotRecord, threadId: string, report: (retry?: IncidentRetry) => void): boolean {+ function retryForRoom(bot: BotRecord, threadId: string, report: (retry?: IncidentRetry) => void, text = MEMORY_RETRY_TEXT): boolean {const continueRequest = deps.continueRequest;if (!continueRequest) return false;const asked = store.activePath(threadId).findLast((line) => line.role === "user")?.id ?? "";@@ -89,7 +100,7 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {if (!store.bot(bot.id) || !store.taskByThread(bot.id, threadId)) return;if (store.activePath(threadId).some((line) => line.role === "user" && line.at > failedAt)) return;if (deps.threadBusy(bot.id, threadId) || deps.threadQueued?.(bot.id, threadId)) return;- continueRequest(bot.id, threadId, MEMORY_RETRY_TEXT)+ continueRequest(bot.id, threadId, text).catch((error) => report({ notRetried: `its retry could not start (${error instanceof Error ? error.message : String(error)})` }));}, MEMORY_RETRY_MS);return true;@@ -245,6 +256,14 @@ export function createChiefNotices(deps: ChiefNoticeDeps) {alreadyNotified: input.notified === true || input.kind === "could-not-start" || input.kind === "routine-failed",});const chiefRetries = Boolean(chief && !group && reachesChief(chief, bot, threadId));+ // Before any Chief hears: a Chief's turn about it would be a paid one, started on the same full server.+ const noRoom = outOfProcesses(input.detail), stoppedHere = !noRoom && memoryStopped(input.detail) && (deps.selfHosted ?? (() => engineMemory.selfHosted()))();+ if (noRoom || stoppedHere) {+ const person = (retry?: IncidentRetry): void => void deliver({ chief: null, title: INCIDENTS_THREAD_TITLE, bot, threadId, chip: incidentChip(incident, deps.threadLanguage?.(threadId)),+ text: incidentText(incident, count, retry), alreadyNotified: input.notified === true || input.kind === "could-not-start" || input.kind === "routine-failed" });+ if (group || input.kind === "routine-failed" || !retryForRoom(bot, threadId, person, noRoom ? ROOM_RETRY_TEXT : SERVER_MEMORY_RETRY_TEXT)) person();+ return;+ }if (input.kind === "failed" && !group && !chiefRetries && memoryStopped(input.detail) && retryForRoom(bot, threadId, report)) return;if (!chief || !chiefRetries) return report();const answered = store.activePath(threadId).findLast((line) => line.role === "user")?.text ?? "";diff --git a/server/host/wait-words.test.ts b/server/host/wait-words.test.tsindex 8f8392df54..b6a1ecfb68 100644--- a/server/host/wait-words.test.ts+++ b/server/host/wait-words.test.ts@@ -31,6 +31,19 @@ describe("how a wait for memory reads", () => {expect(held).toEqual([["t", "memory: 1 running, 3 ahead, on Starter"], ["u", "plan: 2 at once, 1 ahead"]]);});+ it("speaks of this server, not a Cloud or a plan, on a self-hosted one: room, or its number of tasks at once", () => {+ expect(words(false).waits.text("t", { first: true, running: 6, ahead: 2, server: true }))+ .toBe("Waiting for room on this server. Running now: 6. Ahead of this one: 2. It starts by itself when there's room.");+ expect(words(false).waits.text("t", { first: false, running: 6, ahead: 0, server: true })).toBe("Still waiting for room on this server. Running now: 6. Ahead of this one: 0.");+ expect(words(false).waits.text("t", { first: true, running: 7, ahead: 1, limit: 7, server: true }))+ .toBe("Waiting for a turn: this server runs 7 tasks at once. Ahead of this one: 1. It starts by itself when one finishes.");+ expect(words(false).waits.text("t", { first: false, running: 7, ahead: 0, limit: 7, server: true })).toBe("Still waiting: this server runs 7 tasks at once. Ahead of this one: 0.");+ const { waits, held } = words(false);+ waits.began("t", { running: 6, ahead: 2, server: true });+ waits.began("u", { running: 7, ahead: 1, limit: 7, server: true });+ expect(held).toEqual([["t", "room: 6 running, 2 ahead"], ["u", "server: 7 at once, 1 ahead"]]);+ });+it("names the plan's limit, not memory, when that is what the turn waits for", () => {expect(words(true).waits.text("t", { first: true, running: 2, ahead: 1, limit: 2 })).toBe("Waiting for a turn: Starter runs 2 tasks at once on this Cloud. Ahead of this one: 1. It starts by itself when one finishes, and a bigger plan runs more at once.");diff --git a/server/host/wait-words.ts b/server/host/wait-words.tsindex 77d68bfdca..94dd324b6d 100644--- a/server/host/wait-words.ts+++ b/server/host/wait-words.ts@@ -18,15 +18,16 @@ export interface WaitWordsDeps {export function createWaitWords(deps: WaitWordsDeps): EngineWaits & { queued(threadId: string, reason: SteerQueueReason | undefined): string | undefined } {return {- text(threadId, { first, running, ahead, limit }) {+ text(threadId, { first, running, ahead, limit, server }) {const language = deps.language(threadId);+ if (server) return limit !== undefined ? serverLine(language, first ? "server.room.turns" : "server.room.turnsStill", { limit, ahead }) : serverLine(language, first ? "server.room.wait" : "server.room.still", { running, ahead });if (limit !== undefined) return serverLine(language, first ? "server.planTurns.wait" : "server.planTurns.still", { limit, ahead });if (!first) return serverLine(language, "server.memory.still", { running, ahead });const wait = serverLine(language, "server.memory.wait", { running, ahead });return deps.starter() ? `${wait} ${serverLine(language, "server.memory.starter")}` : wait;},- began(threadId, { running, ahead, limit }) {- deps.held(threadId, limit !== undefined ? `plan: ${limit} at once, ${ahead} ahead` : `memory: ${running} running, ${ahead} ahead${deps.starter() ? ", on Starter" : ""}`);+ began(threadId, { running, ahead, limit, server }) {+ deps.held(threadId, limit !== undefined ? `${server ? "server" : "plan"}: ${limit} at once, ${ahead} ahead` : `${server ? "room" : "memory"}: ${running} running, ${ahead} ahead${deps.starter() ? ", on Starter" : ""}`);},changed: deps.changed,queued(threadId, reason) {diff --git a/server/index.ts b/server/index.tsindex 1d10d7eb2c..ab872b6083 100644--- a/server/index.ts+++ b/server/index.ts@@ -211,7 +211,7 @@ import {newId,} from "./contracts.ts";import { RETRY_MAX_ATTEMPTS } from "./drivers/retry.ts";-import { recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts";+import { recoveryCapabilityError, startupBackups } from "./automatic-recovery.ts"; import { outOfProcesses } from "./process-shortage.ts";import { createQuotaSwitchHost } from "./host/quota-switch.ts"; import { quotaSwitchEnabled } from "./quota-switch.ts"; import { createPeerLimitResend } from "./host/peer-limit-resend.ts";import { decodeGeneratedImage } from "./generated-image.ts";import { createMcpServersHost } from "./host/mcp-servers-host.ts"; import { createMcpKeys } from "./vault/mcp-keys.ts"; import { createLimitTakeover, signedOutStop } from "./host/limit-takeover.ts";@@ -8506,12 +8506,12 @@ async function beginTurn(} catch (cause) {let e = cause; perf.noteNotStarted(threadId, cause instanceof TurnNotStartedError ? cause.turnId : null, cause instanceof TurnUsageLimitRefusedError ? { limit: cause.scope, engine: registry.get(instanceId)?.driverKind ?? null, resetsAt: cause.resetsAt } : cause instanceof TurnAuthenticationRefusedError ? { signedOut: true } : {});// Only the driver can prove a task was never submitted; an error string is not that proof.- const mayRecover = e instanceof TurnNotStartedError &&- directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId);+ const claimed = e instanceof TurnNotStartedError && directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId);+ const mayRecover = claimed && !outOfProcesses((e as Error).message); // the server had no room: no backup AI is triedif (e instanceof TurnNotStartedError) {retireProviderTurn(e.turnId);if (e instanceof TurnUsageLimitRefusedError && !e.known) { if (e.scope === "engine") limitClock.noteLimit(instanceId, e.resetsAt); else limitTakeover.holdModel({ instanceId, model }, e.scope, e.resetsAt); } else if (e instanceof TurnAuthenticationRefusedError && !e.known) limitTakeover.noteSignedOut(instanceId);- if (!mayRecover) e = new DirectTurnSetupCancelled("turn stopped during provider setup");+ if (!claimed) e = new DirectTurnSetupCancelled("turn stopped during provider setup");}handoffs.abandon(threadId, dispatchClaimId);if (computerSelectionTurns.get(threadId)?.generation === dispatchClaimId) computerSelectionTurns.delete(threadId);diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.tsindex 6c6a0678d2..490ac139aa 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -7,6 +7,7 @@ import type { RuntimeEvent } from "../contracts.ts";import type { StoreChange } from "../store.ts";import { createLoopStalls, requestArrivedBefore, type LoopStalls } from "./loop-stalls.ts";import { duration, limitHolds, perfHealth, perfLines, turnLine, type PerfHealth } from "./perf-report.ts";+import { createProcessHealth, type ProcessHealthRecorder } from "./process-health.ts";import { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilization, OTHER_SAMPLE_MS, psProcessList, type ProcessSampler } from "./process-sampler.ts";import type { FailoverWhy } from "./turn-record.ts";import { createTurnTimings, type Refusal, type SlowNote, type TurnTimings } from "./turn-timings.ts";@@ -31,7 +32,9 @@ export interface PerfHostDeps {sampler?: ProcessSampler;/** Tests: the event-loop delay recorder. */stalls?: LoopStalls;- /** The engine processes the server tracks, with the threads each runs (engine-memory, on a Cloud home). */+ /** Tests: the process-room recorder. */+ processes?: ProcessHealthRecorder;+ /** The engine processes the server tracks, with the threads each runs (engine-memory, where turns wait for room). */engines?: () => ReadonlyArray<{ pid: number; threads: readonly string[] }>;}@@ -80,16 +83,20 @@ export function createPerfHost(deps: PerfHostDeps) {};const enginePids = () => new Map((deps.engines?.() ?? []).map(({ pid, threads }) => [pid, threads.map(timings.engineOf).find((kind) => kind !== null) ?? "unknown"] as const));const linux = process.platform === "linux", windows = process.platform === "win32";+ /** Its two warnings are said once each for the life of the server. */+ const processes = deps.processes ?? createProcessHealth({ warn: (kind, line) => say(kind, line) });const sampler = deps.sampler ?? createProcessSampler({list: linux ? () => linuxProcessList() : psProcessList, intervalMs: linux ? LINUX_SAMPLE_MS : OTHER_SAMPLE_MS,scope: deps.wholeMachine && linux ? "all" : "tree", utilization: nodeUtilization(), now, engines: enginePids,stalled: (ms) => say("loop", `event loop stalled: the ${linux ? 60 : 300}s sampler fired ${duration(ms)} late`), afterSample: watchHolds,+ seen: (rows, buckets) => processes.sample(rows, buckets),});if (deps.timer !== false && !windows) sampler.start();const stalls = deps.stalls ?? createLoopStalls();if (deps.timer !== false) stalls.start();+ if (deps.timer !== false && linux) guarded("limits", () => (deps.log ?? ((line: string) => console.warn(line)))(processes.startLine()), undefined);- const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null) });+ const sources = () => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: limits(), process: windows ? null : sampler.report(), stalls: guarded("stalls", () => stalls.report(), null), processes: processes.report() });return {timings,sampler,diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.tsindex 33a4879210..7c371f5fea 100644--- a/server/perf/perf-report.ts+++ b/server/perf/perf-report.ts@@ -6,6 +6,7 @@ import type { DayAggregate } from "./day-ledger.ts";import { SLOW_TURN_MS } from "./day-ledger.ts";import { PHASES, type Phase, type PhaseStats } from "./phases.ts";import type { StallsReport, StallStats, Tally } from "./loop-stalls.ts";+import { processHealthLines, trimmedProcessHealth, type ProcessHealth } from "./process-health.ts";import type { ProcessReport } from "./process-sampler.ts";import { RING_CAP, type LiveTurnView, type WindowStats } from "./turn-timings.ts";import type { TurnTiming } from "./turn-record.ts";@@ -27,6 +28,8 @@ export interface PerfSources {process: ProcessReport | null;/** The loop's delays measured all the time, and the blocking work the server times (loop-stalls.ts). */stalls?: StallsReport | null;+ /** How close the server is to its process and memory limits (process-health.ts); null where nothing records it. */+ processes?: ProcessHealth | null;}/** Engines refusing work, or within 10 points of their limit: driver kind, window, use and reset time only. */@@ -51,13 +54,16 @@ export function perfHealth(sources: PerfSources) {holds: limitHolds(sources.limits),process: sources.process,stalls: sources.stalls ?? null,+ processes: sources.processes ?? null,};const size = () => JSON.stringify(body).length;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);+ if (size() > PERF_HEALTH_MAX_BYTES && body.processes) body.processes = trimmedProcessHealth(body.processes);if (size() > PERF_HEALTH_MAX_BYTES) body.process = null;if (size() > PERF_HEALTH_MAX_BYTES) body.stalls = null;+ if (size() > PERF_HEALTH_MAX_BYTES) body.processes = null;return body;}export type PerfHealth = ReturnType<typeof perfHealth>;@@ -124,6 +130,7 @@ export function perfLines(sources: PerfSources, recent: readonly TurnTiming[], rlines.push(`Event loop: busy ${proc.loop.eluPct ?? "?"}% (max ${proc.loop.eluMaxPct ?? "?"}%), sampler timer late p95 ${duration(proc.loop.driftP95Ms)}, max ${duration(proc.loop.driftMaxMs)} (one reading per sample)`);} else lines.push("Processes: not sampled yet");if (sources.stalls) lines.push(...stallLines(sources.stalls));+ if (sources.processes) lines.push(...processHealthLines(sources.processes));lines.push(recentTitle);lines.push(...(recent.length ? recent.map((turn) => ` ${turnLine(turn)}`) : [" (none)"]));return lines;diff --git a/server/perf/process-buckets.ts b/server/perf/process-buckets.tsindex f2e9e52573..a457117d15 100644--- a/server/perf/process-buckets.ts+++ b/server/perf/process-buckets.ts@@ -14,6 +14,9 @@ export interface ProcessRow {rssBytes: number;/** Tells a pid apart from an earlier process that had it (its start time, as the source gives it). */start: string;+ /** Linux: the process's threads, and its state letter ("Z": exited, not yet collected). */+ threads?: number;+ state?: string;}/** Engine CLIs by executable name, as the drivers' kinds name them. */@@ -86,7 +89,9 @@ export function parseProcStat(pid: number, text: string): ProcessRow | null {const fields = text.slice(close + 2).split(" ");const ppid = Number(fields[1]), user = Number(fields[11]), system = Number(fields[12]), start = fields[19], rss = Number(fields[21]);if (!Number.isInteger(ppid) || !Number.isFinite(user) || !Number.isFinite(system) || !start) return null;- return { pid, ppid, name: text.slice(open + 1, close).toLowerCase(), cpuMs: ((user + system) * 1000) / CLOCK_TICKS, rssBytes: (Number.isFinite(rss) ? rss : 0) * PAGE_BYTES, start };+ const threads = Number(fields[17]);+ return { pid, ppid, name: text.slice(open + 1, close).toLowerCase(), cpuMs: ((user + system) * 1000) / CLOCK_TICKS, rssBytes: (Number.isFinite(rss) ? rss : 0) * PAGE_BYTES, start,+ ...(Number.isInteger(threads) && /^[A-Za-z]$/.test(fields[0] ?? "") ? { threads, state: fields[0]! } : {}) };}/** `/proc/self/stat`'s CPU time of children this process waited for, ms. */diff --git a/server/perf/process-health.test.ts b/server/perf/process-health.test.tsnew file mode 100644index 0000000000..8a8315c411--- /dev/null+++ b/server/perf/process-health.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it } from "vitest";+import type { ProcessLimits } from "../process-limits.ts";+import { classifyProcesses, type ProcessRow } from "./process-buckets.ts";+import { perfHealth, perfLines, PERF_HEALTH_MAX_BYTES, type PerfSources } from "./perf-report.ts";+import { createProcessHealth, processHealthLines, tally, trimmedProcessHealth, type ProcessHealth } from "./process-health.ts";+import { linuxProcessList, MAX_SAMPLED_PROCESSES } from "./process-sampler.ts";+import { createTurnTimings } from "./turn-timings.ts";++const MB = 1024 * 1024;+const SECRETS = [+ "sk-ant-api03-PRIVATEPRIVATEPRIVATE1234567890", "ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "hunter2-password", "[email protected]",+ "/Users/ada/Projects/acme-merger/plan.md", "acme-merger", "https://intranet.acme.test/q?token=abc", "intranet.acme.test",+ "Summarize the merger plan", "acme-internal", "Tallyspoon", "OMB_SECRET_VALUE_42", "lookup_customer", "Ada's Claude",+];+const leaks = (text: string) => SECRETS.filter((secret) => text.toLowerCase().includes(secret.toLowerCase()));++const SERVER = 14;+const row = (pid: number, ppid: number, name: string, threads = 7, state = "S"): ProcessRow => ({ pid, ppid, name, cpuMs: 1, rssBytes: MB, start: `s${pid}`, threads, state });+/** A container: tini, the launcher, the server; two engines with their tool servers and a command; a browser; orphans. */+const rows = (): ProcessRow[] => [+ row(1, 0, "tini", 1), row(7, 1, "node"), row(SERVER, 7, "node", 11),+ row(100, SERVER, "claude", 12), row(101, 100, "node"), row(102, 100, "node"), row(103, 100, "sh", 1), row(104, 103, "git", 1),+ row(200, SERVER, "node", 9), row(201, 200, "uvx", 3),+ row(300, SERVER, "agent-browser", 12), row(301, 300, "chromium", 35), row(302, 301, "chromium", 18),+ row(400, 1, "sleep", 1, "Z"), row(401, 1, "chromium", 1, "Z"),+];+const limits = (over: Partial<ProcessLimits> = {}): ProcessLimits => ({ pidsMax: 512, pidsCurrent: 126, nproc: "unlimited", shmBytes: 64 * MB, pid1: "init", reaper: "yes", ...over });+const quiet = { running: 0, queued: 0, longestWaitMs: 0, most: null, queuedEver: 0, starvedEver: 0 };+const none = { limit: null, spawnFailed: { EAGAIN: 0, EMFILE: 0, ENFILE: 0, ENOMEM: 0, ENOENT: 0, other: 0 }, forceKilled: 0, lateReaped: 0 };++describe("the process-room record", () => {+ it("counts processes by kind, threads, zombies and open files, and keeps the most of each since start", () => {+ const list = rows(), buckets = classifyProcesses(list, SERVER, true, new Map([[100, "claudeAgent"], [200, "codex"]]));+ const health = createProcessHealth({ platform: "linux", pid: SERVER, limits: () => limits(), memoryLimitBytes: () => 4096 * MB, memoryUsedBytes: () => null, peaks: () => ({ pids: 197, memoryBytes: 1530 * MB }), fds: () => 61,+ turns: () => ({ running: 2, queued: 3, longestWaitMs: 41_400, most: 7, queuedEver: 9, starvedEver: 1 }),+ counts: () => ({ limit: 512, spawnFailed: { EAGAIN: 4, EMFILE: 0, ENFILE: 0, ENOMEM: 1, ENOENT: 2, other: 0 }, forceKilled: 3, lateReaped: 5 }) });+ health.sample(list, buckets);+ // agent-browser's daemon is no browser by name: it counts with the commands the server started, and its Chrome as the browser.+ const now = { procs: 15, threads: 126, zombies: 2, fds: 61, pidsUsed: 126, engines: { claudeAgent: 1, codex: 1 }, browser: 2, mcp: 3, shell: 3, other: 4 };+ expect(health.report()).toEqual({+ pid1: "init", reaper: "yes", serverIsPid1: false,+ limits: { pids: 512, memMB: 4096, nproc: "unlimited", shmMB: 64, gate: 512 },+ now, peak: now, kernelPeak: { pids: 197, memMB: 1530 },+ turns: { running: 2, queued: 3, longestWaitS: 41, most: 7 },+ since: { queued: 9, starved: 1, spawnFailed: { EAGAIN: 4, EMFILE: 0, ENFILE: 0, ENOMEM: 1, ENOENT: 2, other: 0 }, forceKilled: 3, lateReaped: 5 },+ });+ // A quieter minute later: now falls, the most stays.+ health.sample(list.slice(0, 3), classifyProcesses(list.slice(0, 3), SERVER, true));+ expect(health.report().now).toMatchObject({ procs: 3, threads: 19, zombies: 0, browser: 0, engines: {} });+ expect(health.report().peak).toEqual(now);+ });++ it("is unknown, never zero, where the system has no such files: macOS's process list, Windows with none at all", () => {+ const mac = createProcessHealth({ platform: "darwin", turns: () => quiet, counts: () => none, memoryLimitBytes: () => { throw new Error("not read off Linux"); } });+ expect(mac.report()).toMatchObject({ pid1: "unknown", reaper: "unknown", limits: { pids: "unknown", memMB: "unknown", nproc: "unknown", shmMB: "unknown", gate: "none" }, now: "unknown", peak: "unknown", kernelPeak: { pids: "unknown", memMB: "unknown" } });+ // ps gives macOS no thread counts or states: the processes are counted, the rest stays unknown.+ const plain = [{ pid: 5, ppid: 1, name: "node", cpuMs: 1, rssBytes: MB, start: "ps:5" }, { pid: 6, ppid: 5, name: "claude", cpuMs: 1, rssBytes: MB, start: "ps:6" }];+ mac.sample(plain, classifyProcesses(plain, 5, true));+ expect(mac.report().now).toEqual({ procs: 2, threads: "unknown", zombies: "unknown", fds: "unknown", pidsUsed: "unknown", engines: { claudeAgent: 1 }, browser: 0, mcp: 0, shell: 0, other: 0 });+ const windows = createProcessHealth({ platform: "win32", turns: () => quiet, counts: () => none });+ expect(windows.report()).toMatchObject({ pid1: "unknown", limits: { pids: "unknown", memMB: "unknown" }, now: "unknown", peak: "unknown", turns: { running: 0, queued: 0, most: "none" } });+ expect(processHealthLines(windows.report()).join("\n")).toContain("Now: unknown (no process list on this system)");+ });++ it("says once when the server nears its limit, and once when zombies pile up, naming where to read on", () => {+ const said: Array<[string, string]> = [];+ const health = createProcessHealth({ platform: "linux", limits: () => limits({ pidsCurrent: 420, pid1: "node", reaper: "no" }), memoryLimitBytes: () => null, fds: () => 30,+ turns: () => quiet, counts: () => none, warn: (kind, line) => said.push([kind, line]) });+ const zombies = [row(1, 0, "node"), ...Array.from({ length: 25 }, (_, index) => row(500 + index, 1, "sleep", 1, "Z"))];+ for (let sample = 0; sample < 3; sample++) health.sample(zombies, classifyProcesses(zombies, 1, true));+ expect(said.map(([kind]) => kind)).toEqual(["processes:near", "processes:zombies"]);+ expect(said[0]![1]).toBe('this server runs 420 processes and threads of the 512 its container allows (25 of them zombies). Past the limit nothing new can start; turns wait for room before that. See docs/self-hosting.md, "Running on a container platform".');+ expect(said[1]![1]).toContain("25 exited processes are waiting to be collected and nothing collects them");+ expect(health.startLine()).toBe("processes: process 1 is this app, with no init; limits: processes and threads 512, memory none, ulimit -u unlimited, /dev/shm 64 MB");+ const calm = createProcessHealth({ platform: "linux", limits: () => limits({ pidsCurrent: 100 }), memoryLimitBytes: () => null, fds: () => 30, turns: () => quiet, counts: () => none,+ warn: () => { throw new Error("nothing to say"); } });+ calm.sample(rows(), classifyProcesses(rows(), SERVER, true));+ // Memory: once past 80% of the container's limit, and never where no limit is set.+ const memory: Array<[string, string]> = [];+ let used = 3_000 * 1024 * 1024;+ const tight = createProcessHealth({ platform: "linux", limits: () => limits({ pidsCurrent: 100 }), memoryLimitBytes: () => 4096 * 1024 * 1024, memoryUsedBytes: () => used,+ fds: () => 30, turns: () => quiet, counts: () => none, warn: (kind, line) => memory.push([kind, line]) });+ tight.sample(rows(), classifyProcesses(rows(), SERVER, true));+ expect(memory).toEqual([]);+ used = 3_500 * 1024 * 1024;+ for (let sample = 0; sample < 3; sample++) tight.sample(rows(), classifyProcesses(rows(), SERVER, true));+ expect(memory).toEqual([["processes:memory", 'this server uses 3500 MB of the 4096 MB its container allows. Past the limit the kernel stops an engine; turns wait for room before that. See docs/self-hosting.md, "Running on a container platform".']]);+ });++ it("carries numbers and fixed words only: no executable's name, path, argument, bot or engine name a person chose", () => {+ const named: ProcessRow[] = [+ row(SERVER, 1, "node"),+ row(100, SERVER, "/users/ada/projects/acme-merger/bin/sk-ant-api03-privateprivateprivate1234567890"),+ row(101, 100, "https://intranet.acme.test/q?token=abc"), row(102, 100, "tallyspoon"), row(103, SERVER, "lookup_customer"),+ row(104, 1, "summarize the merger plan", 1, "Z"), row(105, SERVER, "[email protected]"),+ ];+ // An engine kind that is no fixed word (a custom engine named by a person) reads as "unknown".+ const engines = new Map([[100, "Tallyspoon"], [103, "acme-internal"], [105, "hunter2-password"]]);+ const health = createProcessHealth({ platform: "linux", limits: () => limits(), memoryLimitBytes: () => 2048 * MB, memoryUsedBytes: () => null, peaks: () => ({ pids: 90, memoryBytes: null }), fds: () => 12, turns: () => quiet, counts: () => none });+ health.sample(named, classifyProcesses(named, SERVER, true, engines));+ const report = health.report();+ expect(report.now).toMatchObject({ engines: { unknown: 3 } });+ const sources: PerfSources = { hour: createTurnTimings({}).window(), day: createTurnTimings({}).day(), live: [], limits: null, process: null, processes: report };+ const texts = [JSON.stringify(report), JSON.stringify(perfHealth(sources)), perfLines(sources, [], "Latest turns:").join("\n"), processHealthLines(report).join("\n"), health.startLine()];+ for (const text of texts) expect(leaks(text)).toEqual([]);+ // Every string in the record is one of these words, or an engine kind from the server's own list.+ const strings: string[] = [];+ JSON.stringify(report, (_key, value) => { if (typeof value === "string") strings.push(value); if (value && typeof value === "object" && !Array.isArray(value)) strings.push(...Object.keys(value)); return value; });+ const fixed = new Set(["init", "node", "other", "unknown", "yes", "no", "max", "none", "unlimited", "pid1", "reaper", "serverIsPid1", "limits", "pids", "memMB", "nproc", "shmMB", "gate", "now", "peak", "kernelPeak",+ "procs", "threads", "zombies", "fds", "pidsUsed", "engines", "browser", "mcp", "shell", "turns", "running", "queued", "longestWaitS", "most", "since", "starved", "spawnFailed",+ "EAGAIN", "EMFILE", "ENFILE", "ENOMEM", "ENOENT", "forceKilled", "lateReaped"]);+ expect(strings.filter((word) => !fixed.has(word))).toEqual([]);+ });++ it("fits the health report's budget with every part at its fullest, giving up its own detail before the whole part", () => {+ const full = (count: number) => ({ procs: 99_999, threads: 999_999, zombies: 99_999, fds: 99_999, pidsUsed: 999_999, browser: 9_999, mcp: 9_999, shell: 9_999, other: 9_999,+ engines: Object.fromEntries(Array.from({ length: count }, (_, index) => [`someVeryLongEngineKindName${index}`, 9_999])) });+ const processes: ProcessHealth = { pid1: "unknown", reaper: "unknown", serverIsPid1: false, limits: { pids: 4_194_304, memMB: 1_048_576, nproc: 4_194_304, shmMB: 65_536, gate: 4_194_304 },+ now: full(8), peak: full(8), kernelPeak: { pids: 4_194_304, memMB: 1_048_576 }, turns: { running: 999, queued: 999, longestWaitS: 999_999, most: 999 },+ since: { queued: 999_999, starved: 999_999, spawnFailed: { EAGAIN: 999_999, EMFILE: 999_999, ENFILE: 999_999, ENOMEM: 999_999, ENOENT: 999_999, other: 999_999 }, forceKilled: 999_999, lateReaped: 999_999 } };+ const alone = JSON.stringify(processes).length;+ console.log(`process room, every part full: ${alone} bytes of the perf field's ${PERF_HEALTH_MAX_BYTES}`);+ expect(alone).toBeLessThan(1_400);+ expect(JSON.stringify(trimmedProcessHealth(processes)).length).toBeLessThan(alone / 2 + 200);+ expect(trimmedProcessHealth(processes)).toMatchObject({ peak: "unknown", since: processes.since, turns: processes.turns });+ expect(Object.keys((trimmedProcessHealth(processes).now as { engines: object }).engines)).toHaveLength(4);+ // The rest of the report at its fullest, as perf-privacy.test.ts builds it, leaves room for it.+ let clock = 1_800_000_000_000;+ const big = createTurnTimings({ now: () => clock });+ const kinds = ["mcp__browser__a", "mcp__computer__a", "Bash", "Read", "WebSearch", "WebFetch", "mcp__x__y", "remember", "routine", "publish_page", "show_widget", "delegate", "phone_tap", "TodoWrite", "generate_image", "mcp__data__q", "GMAIL_SEND_EMAIL", "anything"];+ for (let turn = 0; turn < 300; turn++) {+ const threadId = `thread_${turn}`;+ big.noteEvent({ eventId: "e", provider: "someVeryLongEngineKindName-abcdefghijk", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.started" });+ kinds.forEach((title, index) => big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "item.started", itemType: "tool", itemId: `i${index}`, title }));+ for (let retry = 0; retry < 4; retry++) big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.retrying", attempt: retry, delayMs: 1000, reason: `reason_${(turn * 4 + retry) % 20}` });+ big.noteEvent({ eventId: "e", provider: `engine${turn % 20}`, threadId, createdAt: "", turnId: `t${turn}`, type: "runtime.error", message: "m", limit: (["engine", "model", "credits"] as const)[turn % 3] });+ clock += 1_234_567;+ if (turn < 250) big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.completed", ok: turn % 2 === 0 });+ }+ clock = 1_800_000_000_000 + 250 * 1_234_567;+ const process = { at: clock, intervalS: 60, scope: "all" as const, samples: 60, browsers: 9, unseen60mS: 1234.5,+ buckets: Array.from({ length: 12 }, (_, index) => ({ bucket: `engine:someVeryLongEngineKindName${index}` as const, procs: 99, cpu5mS: 1234.5, cpu60mS: 12345.6, peakPct: 100, rssMB: 4096 })),+ loop: { eluPct: 100, eluMaxPct: 100, driftP95Ms: 123_456, driftMaxMs: 1_234_567 } };+ const body = perfHealth({ hour: big.window(), day: big.day(), live: big.live(), limits: null, process, processes });+ expect(JSON.stringify(body).length).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);+ expect(body.processes).not.toBeNull();+ expect(body.processes!.since).toEqual(processes.since);+ });++ it("reads at most a fixed number of processes for a sample", () => {+ const names = Array.from({ length: MAX_SAMPLED_PROCESSES + 500 }, (_, index) => String(index + 1));+ let reads = 0;+ const list = linuxProcessList((path) => { if (/^\/proc\/\d+\/stat$/.test(path)) { reads += 1; return `${path.split("/")[2]} (node) S 1 1 1 0 -1 0 0 0 0 0 1 1 0 0 20 0 7 0 5 0 10 0`; } return null; }, () => names);+ expect(list.rows).toHaveLength(MAX_SAMPLED_PROCESSES);+ expect(reads).toBe(MAX_SAMPLED_PROCESSES);+ });++ it("tallies a row outside every bucket as other, and nothing as the server's own", () => {+ const list = rows();+ expect(tally(list, new Map([[SERVER, "server"]]), 1, 2)).toMatchObject({ procs: 15, other: 14, browser: 0, mcp: 0, shell: 0, engines: {} });+ });+});diff --git a/server/perf/process-health.ts b/server/perf/process-health.tsnew file mode 100644index 0000000000..88fbe9e32a--- /dev/null+++ b/server/perf/process-health.ts@@ -0,0 +1,181 @@+// How close this server is to the limits on what it may run, for the next report of "out of processes": what process 1 is,+// the container's limits, how many processes, threads, zombies and open files there are now and at their most, and how+// often turns had to wait or a spawn was refused. Privacy invariant: numbers and the fixed words below only. Never a+// command line, an argument, a path, a name or anything a bot or a person wrote.+import { boxMemory } from "../box-memory.ts";+import { CHAT_RUNTIME_KINDS, ENGINE_PROCESS_KINDS, engineMemory } from "../engine-memory.ts";+import { openDescriptors, readCgroupMemory, readCgroupPeaks, readProcessLimits, type ProcessLimits, type Unknown } from "../process-limits.ts";+import { processBudget, type ProcessCounts } from "../process-room.ts";+import type { ProcessBucket, ProcessRow } from "./process-buckets.ts";++export const PROCESS_HEALTH_DOCS = 'docs/self-hosting.md, "Running on a container platform"';+/** Above this many zombies nothing is collecting them: a few come and go between a process's exit and its parent's wait. */+const ZOMBIES_WORTH_SAYING = 20;+const NEAR_LIMIT = 0.8;+const ENGINES_SHOWN = 8;+const MB = 1024 * 1024;++type Count = number | Unknown;+export interface ProcessTally {+ procs: number;+ /** Unknown where the process list carries no thread counts or states (macOS's `ps` columns). */+ threads: Count;+ zombies: Count;+ /** This server's own open file descriptors. */+ fds: Count;+ /** What the container's pids limit counts now: processes and threads. */+ pidsUsed: Count;+ /** Engine processes by engine kind, a fixed list's words. */+ engines: Record<string, number>;+ browser: number;+ mcp: number;+ shell: number;+ other: number;+}++export interface ProcessHealth {+ pid1: ProcessLimits["pid1"];+ reaper: ProcessLimits["reaper"];+ serverIsPid1: boolean;+ limits: { pids: number | "max" | Unknown; memMB: number | "none" | Unknown; nproc: number | "unlimited" | Unknown; shmMB: Count; gate: number | "none" };+ now: ProcessTally | Unknown;+ /** The most of each since start, from the sampler's lists (a minute apart on Linux). */+ peak: ProcessTally | Unknown;+ /** The kernel's own most since the container started: exact, where cgroup v2 keeps it. */+ kernelPeak: { pids: Count; memMB: Count };+ turns: { running: number; queued: number; longestWaitS: number; most: number | "none" };+ since: { queued: number; starved: number; spawnFailed: ProcessCounts["spawnFailed"]; forceKilled: number; lateReaped: number };+}++const KNOWN_ENGINES: ReadonlySet<string> = new Set([...ENGINE_PROCESS_KINDS, ...CHAT_RUNTIME_KINDS, "unknown"]);++/** One sample's rows as counts. A row outside every bucket (not started by this server, or adopted by an init) is "other". */+export function tally(rows: readonly ProcessRow[], buckets: ReadonlyMap<number, ProcessBucket>, fds: Count, pidsUsed: Count): ProcessTally {+ const out: ProcessTally = { procs: rows.length, threads: 0, zombies: 0, fds, pidsUsed, engines: {}, browser: 0, mcp: 0, shell: 0, other: 0 };+ let threads = 0, zombies = 0, detailed = rows.length > 0;+ for (const row of rows) {+ if (row.threads === undefined || row.state === undefined) detailed = false;+ threads += row.threads ?? 0;+ if (row.state === "Z") zombies += 1;+ const bucket = buckets.get(row.pid);+ if (bucket === "server") continue;+ if (bucket?.startsWith("engine:")) {+ const kind = bucket.slice("engine:".length), name = KNOWN_ENGINES.has(kind) ? kind : "unknown";+ if (Object.hasOwn(out.engines, name) || Object.keys(out.engines).length < ENGINES_SHOWN) out.engines[name] = (out.engines[name] ?? 0) + 1;+ } else if (bucket === "browser") out.browser += 1;+ else if (bucket === "mcp") out.mcp += 1;+ else if (bucket === "commands" || bucket === "build") out.shell += 1;+ else out.other += 1;+ }+ out.threads = detailed ? threads : "unknown";+ out.zombies = detailed ? zombies : "unknown";+ return out;+}++const higher = (a: Count, b: Count): Count => (a === "unknown" ? b : b === "unknown" ? a : Math.max(a, b));++function peakOf(peak: ProcessTally | null, now: ProcessTally): ProcessTally {+ if (!peak) return { ...now, engines: { ...now.engines } };+ const engines = { ...peak.engines };+ for (const [kind, count] of Object.entries(now.engines)) engines[kind] = Math.max(engines[kind] ?? 0, count);+ return { procs: Math.max(peak.procs, now.procs), threads: higher(peak.threads, now.threads), zombies: higher(peak.zombies, now.zombies), fds: higher(peak.fds, now.fds),+ pidsUsed: higher(peak.pidsUsed, now.pidsUsed), engines, browser: Math.max(peak.browser, now.browser), mcp: Math.max(peak.mcp, now.mcp),+ shell: Math.max(peak.shell, now.shell), other: Math.max(peak.other, now.other) };+}++export interface ProcessHealthDeps {+ limits?: () => ProcessLimits;+ memoryLimitBytes?: () => number | null;+ /** What counts against the container's memory limit now; null where none is set or readable. */+ memoryUsedBytes?: () => number | null;+ peaks?: () => { pids: number | null; memoryBytes: number | null };+ fds?: () => Count;+ turns?: () => { running: number; queued: number; longestWaitMs: number; most: number | null; queuedEver: number; starvedEver: number };+ counts?: () => ProcessCounts;+ platform?: NodeJS.Platform;+ pid?: number;+ /** One line at most per kind; the caller limits how often. */+ warn?: (kind: string, line: string) => void;+}++const words = (value: number | string, unit = "") => (typeof value === "number" ? `${value}${unit}` : value);++export function limitsLine(health: Pick<ProcessHealth, "pid1" | "reaper" | "limits">): string {+ const first = health.pid1 === "init" ? "an init" : health.pid1 === "node" ? (health.reaper === "yes" ? "this app, with an init beneath it" : "this app, with no init") : health.pid1 === "other" ? "another program" : "unknown";+ return `process 1 is ${first}; limits: processes and threads ${words(health.limits.pids)}, memory ${words(health.limits.memMB, " MB")}, ulimit -u ${words(health.limits.nproc)}, /dev/shm ${words(health.limits.shmMB, " MB")}`;+}++export function createProcessHealth(deps: ProcessHealthDeps = {}) {+ const platform = deps.platform ?? process.platform;+ const limits = deps.limits ?? (() => readProcessLimits({ platform }));+ const memoryLimit = deps.memoryLimitBytes ?? (() => boxMemory().cgroupLimit);+ const memoryUsed = deps.memoryUsedBytes ?? (() => (platform === "linux" ? readCgroupMemory()?.usedBytes ?? null : null));+ const peaks = deps.peaks ?? (() => (platform === "linux" ? readCgroupPeaks() : { pids: null, memoryBytes: null }));+ const fds = deps.fds ?? (() => (platform === "linux" ? openDescriptors() : "unknown"));+ const turns = deps.turns ?? (() => engineMemory.counts());+ const counts = deps.counts ?? (() => processBudget.counts());+ let now: ProcessTally | null = null, peak: ProcessTally | null = null;+ const told = new Set<string>();++ const report = (): ProcessHealth => {+ const read = limits(), turn = turns(), count = counts(), memory = platform === "linux" ? memoryLimit() : undefined, kernel = peaks();+ return {+ pid1: read.pid1, reaper: read.reaper, serverIsPid1: (deps.pid ?? process.pid) === 1,+ limits: { pids: read.pidsMax, memMB: memory === undefined ? "unknown" : memory === null ? "none" : Math.round(memory / MB), nproc: read.nproc,+ shmMB: read.shmBytes === "unknown" ? "unknown" : Math.round(read.shmBytes / MB), gate: count.limit ?? "none" },+ now: now ?? "unknown", peak: peak ?? "unknown",+ kernelPeak: { pids: kernel.pids ?? "unknown", memMB: kernel.memoryBytes === null ? "unknown" : Math.round(kernel.memoryBytes / MB) },+ turns: { running: turn.running, queued: turn.queued, longestWaitS: Math.round(turn.longestWaitMs / 1000), most: turn.most ?? "none" },+ since: { queued: turn.queuedEver, starved: turn.starvedEver, spawnFailed: count.spawnFailed, forceKilled: count.forceKilled, lateReaped: count.lateReaped },+ };+ };++ return {+ /** After each of the sampler's process lists: nothing here on a platform that has none. */+ sample(rows: readonly ProcessRow[], buckets: ReadonlyMap<number, ProcessBucket>): void {+ const read = limits();+ now = tally(rows, buckets, fds(), read.pidsCurrent);+ peak = peakOf(peak, now);+ const limit = counts().limit ?? (typeof read.pidsMax === "number" ? read.pidsMax : null);+ if (limit !== null && typeof now.pidsUsed === "number" && now.pidsUsed >= limit * NEAR_LIMIT && !told.has("near")) {+ told.add("near");+ deps.warn?.("processes:near", `this server runs ${now.pidsUsed} processes and threads of the ${limit} its container allows (${now.zombies === "unknown" ? "?" : now.zombies} of them zombies). Past the limit nothing new can start; turns wait for room before that. See ${PROCESS_HEALTH_DOCS}.`);+ }+ const memLimit = platform === "linux" ? memoryLimit() : null, used = memLimit === null ? null : memoryUsed();+ if (memLimit !== null && used !== null && used >= memLimit * NEAR_LIMIT && !told.has("memory")) {+ told.add("memory");+ deps.warn?.("processes:memory", `this server uses ${Math.round(used / MB)} MB of the ${Math.round(memLimit / MB)} MB its container allows. Past the limit the kernel stops an engine; turns wait for room before that. See ${PROCESS_HEALTH_DOCS}.`);+ }+ if (typeof now.zombies === "number" && now.zombies > ZOMBIES_WORTH_SAYING && !told.has("zombies")) {+ told.add("zombies");+ deps.warn?.("processes:zombies", `${now.zombies} exited processes are waiting to be collected and nothing collects them: this container has no init as process 1. They count against its process limit until it restarts. See ${PROCESS_HEALTH_DOCS}.`);+ }+ },+ report,+ startLine: () => `processes: ${limitsLine(report())}`,+ };+}+export type ProcessHealthRecorder = ReturnType<typeof createProcessHealth>;++const tallyLine = (count: ProcessTally) =>+ `${count.procs} processes, ${words(count.threads)} threads, ${words(count.zombies)} zombies, ${words(count.fds)} open files, ${words(count.pidsUsed)} against the limit; `+ + `engines ${Object.entries(count.engines).map(([kind, n]) => `${kind} ${n}`).join(", ") || "none"}, browser ${count.browser}, tool servers ${count.mcp}, commands ${count.shell}, other ${count.other}`;++/** The same for people: a @devs report and the diagnostics text. */+export function processHealthLines(health: ProcessHealth): string[] {+ const failed = Object.entries(health.since.spawnFailed).filter(([, n]) => n > 0).map(([code, n]) => `${code} ${n}`).join(", ") || "none";+ return [+ `Process room: ${limitsLine(health)}; new engines kept below ${words(health.limits.gate)} processes and threads`,+ ` Now: ${health.now === "unknown" ? "unknown (no process list on this system)" : tallyLine(health.now)}`,+ ` Most since start (sampled): ${health.peak === "unknown" ? "unknown" : tallyLine(health.peak)}`,+ ` Most since start (kernel): ${words(health.kernelPeak.pids)} processes and threads, ${words(health.kernelPeak.memMB, " MB")} memory`,+ ` Turns: ${health.turns.running} running, ${health.turns.queued} waiting for room (longest ${health.turns.longestWaitS}s), at most ${words(health.turns.most)} at once`,+ ` Since start: ${health.since.queued} waited for room; spawns refused: ${failed}; engines that never came up: ${health.since.starved}; force-stopped: ${health.since.forceKilled}; outlived their turn: ${health.since.lateReaped}`,+ ];+}++/** Without its most-since-start counts and with at most four engine kinds: what is dropped first when the report must shrink. */+export function trimmedProcessHealth(health: ProcessHealth): ProcessHealth {+ const fewer = (count: ProcessTally | Unknown) => (count === "unknown" ? count : { ...count, engines: Object.fromEntries(Object.entries(count.engines).slice(0, 4)) });+ return { ...health, now: fewer(health.now), peak: "unknown" };+}diff --git a/server/perf/process-sampler.test.ts b/server/perf/process-sampler.test.tsindex ca53764b28..0e36cb8e28 100644--- a/server/perf/process-sampler.test.ts+++ b/server/perf/process-sampler.test.ts@@ -41,7 +41,7 @@ describe("process buckets, from the executable's name and parent only", () => {});it("parses /proc stat lines (a comm with spaces and parentheses), ps lines and CPU counters", () => {- expect(parseProcStat(42, statLine(42, "Web Content (x)", 7, 150, 50))).toEqual({ pid: 42, ppid: 7, name: "web content (x)", cpuMs: 2_000, rssBytes: 256 * 4096, start: "5555" });+ expect(parseProcStat(42, statLine(42, "Web Content (x)", 7, 150, 50))).toEqual({ pid: 42, ppid: 7, name: "web content (x)", cpuMs: 2_000, rssBytes: 256 * 4096, start: "5555", threads: 1, state: "S" });expect(parseProcStat(1, "garbage")).toBeNull();expect(parseReapedChildrenMs(statLine(1, "node", 0, 0, 0, 1, 300, 200))).toBe(5_000);expect(parsePsTime("1:02.50")).toBe(62_500);diff --git a/server/perf/process-sampler.ts b/server/perf/process-sampler.tsindex 5a2a53867f..cf89773394 100644--- a/server/perf/process-sampler.ts+++ b/server/perf/process-sampler.ts@@ -42,12 +42,16 @@ export interface ProcessReport {const readText = (path: string): string | null => { try { return readFileSync(path, "utf8"); } catch { return null; } };-/** Every process /proc shows, read synchronously: one stat file each. */+/** A sample reads at most this many processes: a container holds a few thousand at its limit, a shared host may show more. */+export const MAX_SAMPLED_PROCESSES = 8_192;++/** Every process /proc shows, up to MAX_SAMPLED_PROCESSES, read synchronously: one stat file each. */export function linuxProcessList(read: (path: string) => string | null = readText, list: () => string[] = () => readdirSync("/proc")): ProcessList {const rows: ProcessRow[] = [];let names: string[] = [];try { names = list(); } catch {}for (const name of names) {+ if (rows.length >= MAX_SAMPLED_PROCESSES) break;if (!/^\d+$/.test(name)) continue;const text = read(`/proc/${name}/stat`);const row = text === null ? null : parseProcStat(Number(name), text);@@ -83,6 +87,8 @@ export interface ProcessSamplerOptions {engines?: () => ReadonlyMap<number, string>;/** After each timed sample: other once-a-sample checks ride the same timer. */afterSample?: () => void;+ /** Each sample's rows with their buckets, before the rows are dropped. */+ seen?: (rows: readonly ProcessRow[], buckets: ReadonlyMap<number, ProcessBucket>) => void;}export function nodeUtilization(): () => number | null {@@ -106,6 +112,7 @@ export function createProcessSampler(options: ProcessSamplerOptions) {const take = (list: ProcessList, driftMs: number) => {const at = monotonic();const buckets = classifyProcesses(list.rows, serverPid, options.scope === "tree", options.engines?.());+ try { options.seen?.(list.rows, buckets); } catch {}const cpu: Partial<Record<ProcessBucket, number>> = {}, procs: Partial<Record<ProcessBucket, number>> = {}, rss: Partial<Record<ProcessBucket, number>> = {};const rows = new Map<number, { start: string; cpuMs: number; bucket: ProcessBucket; ppid: number }>();let browsers = 0;diff --git a/server/process-limits.ts b/server/process-limits.tsnew file mode 100644index 0000000000..24a6d273a1--- /dev/null+++ b/server/process-limits.ts@@ -0,0 +1,141 @@+// What bounds how many processes this server may hold, read from Linux's own files. Everything is "unknown" where the+// file is not there (macOS, Windows, a sandbox that hides /sys): callers treat unknown as no information, never as zero.+import { readFileSync, readdirSync, statfsSync } from "node:fs";++export type Unknown = "unknown";++export interface ProcessLimits {+ /** The cgroup's pids.max: threads count against it as processes do. */+ pidsMax: number | "max" | Unknown;+ pidsCurrent: number | Unknown;+ /** RLIMIT_NPROC's soft value. */+ nproc: number | "unlimited" | Unknown;+ shmBytes: number | Unknown;+ /** Process 1: a program that collects orphans, Node (this server or its launcher), or something else. */+ pid1: "init" | "node" | "other" | Unknown;+ /** Whether something collects exited orphans: an init as process 1, or one this server runs under as a subreaper. */+ reaper: "yes" | "no" | Unknown;+}++type Read = (path: string) => string | null;+const readText: Read = (path) => { try { return readFileSync(path, "utf8"); } catch { return null; } };++const INITS: ReadonlySet<string> = new Set(["tini", "dumb-init", "docker-init", "init", "systemd", "s6-svscan", "runit", "catatonit", "pause"]);+const NODE = new Set(["node", "mainthread"]);++const count = (text: string | null): number | "max" | null => {+ const value = text?.trim();+ if (!value) return null;+ if (value === "max") return "max";+ return /^\d+$/.test(value) ? Number(value) : null;+};++/** This process's cgroup directory for pids: v2's unified tree, else v1's pids controller. In a container with its own+ * cgroup namespace the path is "/", so the files sit at the mount's root. */+function pidsFiles(read: Read): string[] {+ const own = read("/proc/self/cgroup") ?? "";+ const v2 = /^0::(\/.*)$/m.exec(own)?.[1], v1 = /^\d+:(?:[^:]*,)?pids(?:,[^:]*)?:(\/.*)$/m.exec(own)?.[1];+ const dirs = ["/sys/fs/cgroup", "/sys/fs/cgroup/pids"];+ if (v2 && v2 !== "/") dirs.unshift(`/sys/fs/cgroup${v2}`);+ if (v1 && v1 !== "/") dirs.unshift(`/sys/fs/cgroup/pids${v1}`);+ return dirs;+}++export interface CgroupMemory { limitBytes: number; usedBytes: number; oomKills: number | null; fullStall10: number | null }++/** This process's cgroup memory limit and what counts against it now (file pages the kernel can drop at once left out);+ * null where no limit is set or readable. v2's files, else v1's. */+export function readCgroupMemory(read: Read = readText): CgroupMemory | null {+ const own = read("/proc/self/cgroup") ?? "";+ const v2 = /^0::(\/.*)$/m.exec(own)?.[1], v1 = /^\d+:(?:[^:]*,)?memory(?:,[^:]*)?:(\/.*)$/m.exec(own)?.[1];+ const number = (text: string | null, pattern: RegExp) => { const found = text === null ? null : pattern.exec(text); return found ? Number(found[1]) : null; };+ for (const dir of [...(v2 && v2 !== "/" ? [`/sys/fs/cgroup${v2}`] : []), "/sys/fs/cgroup"]) {+ const limit = count(read(`${dir}/memory.max`)), used = count(read(`${dir}/memory.current`));+ if (typeof limit !== "number" || typeof used !== "number") continue;+ const droppable = number(read(`${dir}/memory.stat`), /^inactive_file (\d+)$/m) ?? 0;+ return { limitBytes: limit, usedBytes: Math.max(0, used - droppable), oomKills: number(read(`${dir}/memory.events`), /^oom_kill (\d+)$/m),+ fullStall10: number(read(`${dir}/memory.pressure`), /^full avg10=([\d.]+)/m) };+ }+ for (const dir of [...(v1 && v1 !== "/" ? [`/sys/fs/cgroup/memory${v1}`] : []), "/sys/fs/cgroup/memory"]) {+ const limit = count(read(`${dir}/memory.limit_in_bytes`)), used = count(read(`${dir}/memory.usage_in_bytes`));+ // v1 writes "no limit" as a number near 2^63.+ if (typeof limit !== "number" || typeof used !== "number" || limit >= 2 ** 60) continue;+ const droppable = number(read(`${dir}/memory.stat`), /^total_inactive_file (\d+)$/m) ?? 0;+ return { limitBytes: limit, usedBytes: Math.max(0, used - droppable), oomKills: number(read(`${dir}/memory.oom_control`), /^oom_kill (\d+)$/m), fullStall10: null };+ }+ return null;+}++/** Whether this process runs in a container that was given a limit: a pids or memory limit in the files at the cgroup+ * mount's root, which are the container's own there (its cgroup namespace, or v1's bind mount) and do not exist, or say+ * no limit, on a machine's real root cgroup. A limit set only on a parent the container cannot see (a Kubernetes pod's+ * pids limit) does not show. */+export function containerLimited(read: Read = readText): boolean {+ if (typeof count(read("/sys/fs/cgroup/pids.max")) === "number" || typeof count(read("/sys/fs/cgroup/memory.max")) === "number") return true;+ if (typeof count(read("/sys/fs/cgroup/pids/pids.max")) === "number") return true;+ const v1 = count(read("/sys/fs/cgroup/memory/memory.limit_in_bytes"));+ return typeof v1 === "number" && v1 < 2 ** 60;+}++/** The cgroup's limit and how much of it is used now. A limit set on a parent cgroup the container cannot see (a+ * Kubernetes pod's) reads as "max" here. */+export function readPids(read: Read = readText): { max: number | "max" | null; current: number | null } {+ for (const dir of pidsFiles(read)) {+ const current = count(read(`${dir}/pids.current`));+ if (typeof current !== "number") continue;+ return { max: count(read(`${dir}/pids.max`)), current };+ }+ return { max: null, current: null };+}++/** The kernel's own high-water marks for this cgroup since it was made (cgroup v2: pids.peak, memory.peak); null where+ * the kernel keeps none. */+export function readCgroupPeaks(read: Read = readText): { pids: number | null; memoryBytes: number | null } {+ const peak = (file: string) => {+ for (const dir of pidsFiles(read)) { const value = count(read(`${dir}/${file}`)); if (typeof value === "number") return value; }+ return null;+ };+ return { pids: peak("pids.peak"), memoryBytes: peak("memory.peak") };+}++function nproc(read: Read): ProcessLimits["nproc"] {+ const soft = /^Max processes\s+(\S+)/m.exec(read("/proc/self/limits") ?? "")?.[1];+ if (soft === undefined) return "unknown";+ return soft === "unlimited" ? "unlimited" : /^\d+$/.test(soft) ? Number(soft) : "unknown";+}++const comm = (read: Read, pid: number | string) => read(`/proc/${pid}/comm`)?.trim().toLowerCase() ?? null;++function parentOf(read: Read, pid: number): number | null {+ const stat = read(`/proc/${pid}/stat`);+ if (!stat) return null;+ const parent = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);+ return Number.isInteger(parent) ? parent : null;+}++export interface LimitsOptions { platform?: NodeJS.Platform; read?: Read; pid?: number; shm?: () => number | null }++const shmBytes = (): number | null => {+ try { const stats = statfsSync("/dev/shm"); return Number(stats.blocks) * Number(stats.bsize); } catch { return null; }+};++export function readProcessLimits(options: LimitsOptions = {}): ProcessLimits {+ const unknown: ProcessLimits = { pidsMax: "unknown", pidsCurrent: "unknown", nproc: "unknown", shmBytes: "unknown", pid1: "unknown", reaper: "unknown" };+ if ((options.platform ?? process.platform) !== "linux") return unknown;+ const read = options.read ?? readText, pid = options.pid ?? process.pid;+ const pids = readPids(read), first = comm(read, 1);+ const pid1: ProcessLimits["pid1"] = first === null ? "unknown" : INITS.has(first) ? "init" : NODE.has(first) ? "node" : "other";+ let reaper: ProcessLimits["reaper"] = pid1 === "init" ? "yes" : pid1 === "node" ? "no" : "unknown";+ // Process 1 is not an init: the launcher may still have put one, as a subreaper, between itself and this server.+ for (let at: number | null = pid, depth = 0; reaper !== "yes" && at !== null && at > 1 && depth < 8; at = parentOf(read, at), depth += 1) {+ const name = comm(read, at);+ if (name !== null && (name === "tini" || name === "dumb-init" || name === "catatonit")) reaper = "yes";+ }+ const shm = (options.shm ?? shmBytes)();+ return { pidsMax: pids.max ?? "unknown", pidsCurrent: pids.current ?? "unknown", nproc: nproc(read), shmBytes: shm ?? "unknown", pid1, reaper };+}++/** Open file descriptors of this process; "unknown" where /proc is not there. */+export function openDescriptors(list: (path: string) => string[] = readdirSync): number | Unknown {+ try { return list("/proc/self/fd").length; } catch { return "unknown"; }+}diff --git a/server/process-room.test.ts b/server/process-room.test.tsnew file mode 100644index 0000000000..543499e10c--- /dev/null+++ b/server/process-room.test.ts@@ -0,0 +1,823 @@+import type { ChildProcess } from "node:child_process";+import { EventEmitter } from "node:events";+import { afterEach, describe, expect, it, vi } from "vitest";+import { TurnNotStartedError, type ProviderInstance, type RuntimeEvent, type RuntimeEventListener, type SendTurnInput } from "./contracts.ts";+import { engineFailureKind } from "./drivers/engine-errors.ts";+import { classifyError } from "./drivers/retry.ts";+import { EngineMemory, FIRST_FRAME_MS, readHostMemory, withEngineMemory, type HostMemory } from "./engine-memory.ts";+import { containerLimited, readCgroupMemory, readPids, readProcessLimits } from "./process-limits.ts";+import { BROWSER_NO_ROOM, BROWSER_TASKS, ENGINE_TASKS, gateHost, linuxTreeUse, margin, ProcessBudget, turnsSetting, turnsUnder, type TreeUse } from "./process-room.ts";+import { outOfProcesses, shortageCode } from "./process-shortage.ts";+import { describeSpawnFailure, linuxGroupOnlyExited } from "./procs.ts";+import { classifyRoutineFailure, recoverRun, ROUTINE_BUSY_WAIT_MS } from "./routine-recovery.ts";+import type { RoutineRun } from "./routines.ts";++const MB = 1024 * 1024, GB = 1024 * MB;+const files = (map: Record<string, string>) => (path: string) => map[path] ?? null;++describe("the container's limits, from Linux's own files", () => {+ it("reads the pids limit and the count against it: cgroup v2, a cgroup that is not the mount's root, and v1", () => {+ expect(readPids(files({ "/sys/fs/cgroup/pids.max": "512\n", "/sys/fs/cgroup/pids.current": "31\n" }))).toEqual({ max: 512, current: 31 });+ expect(readPids(files({ "/sys/fs/cgroup/pids.max": "max\n", "/sys/fs/cgroup/pids.current": "31\n" }))).toEqual({ max: "max", current: 31 });+ expect(readPids(files({ "/proc/self/cgroup": "0::/system.slice/omb.service\n", "/sys/fs/cgroup/system.slice/omb.service/pids.max": "4096\n",+ "/sys/fs/cgroup/system.slice/omb.service/pids.current": "40\n", "/sys/fs/cgroup/pids.current": "9000\n" }))).toEqual({ max: 4096, current: 40 });+ expect(readPids(files({ "/proc/self/cgroup": "5:cpu,cpuacct:/\n3:pids:/\n", "/sys/fs/cgroup/pids/pids.max": "1024\n", "/sys/fs/cgroup/pids/pids.current": "77\n" }))).toEqual({ max: 1024, current: 77 });+ expect(readPids(() => null)).toEqual({ max: null, current: null });+ });++ it("reads the memory limit and what counts against it, leaving out file pages the kernel can drop", () => {+ const v2 = files({ "/sys/fs/cgroup/memory.max": "2147483648\n", "/sys/fs/cgroup/memory.current": "1500000000\n", "/sys/fs/cgroup/memory.stat": "anon 900000000\ninactive_file 400000000\n",+ "/sys/fs/cgroup/memory.events": "low 0\noom 3\noom_kill 2\n", "/sys/fs/cgroup/memory.pressure": "some avg10=1.00 avg60=0 avg300=0 total=1\nfull avg10=0.50 avg60=0 avg300=0 total=1\n" });+ expect(readCgroupMemory(v2)).toEqual({ limitBytes: 2 * GB, usedBytes: 1_100_000_000, oomKills: 2, fullStall10: 0.5 });+ expect(readCgroupMemory(files({ "/sys/fs/cgroup/memory.max": "max\n", "/sys/fs/cgroup/memory.current": "5\n" }))).toBeNull();+ const v1 = files({ "/sys/fs/cgroup/memory/memory.limit_in_bytes": "1073741824\n", "/sys/fs/cgroup/memory/memory.usage_in_bytes": "600000000\n",+ "/sys/fs/cgroup/memory/memory.stat": "total_inactive_file 100000000\n", "/sys/fs/cgroup/memory/memory.oom_control": "oom_kill_disable 0\nunder_oom 0\noom_kill 1\n" });+ expect(readCgroupMemory(v1)).toEqual({ limitBytes: GB, usedBytes: 500_000_000, oomKills: 1, fullStall10: null });+ expect(readCgroupMemory(files({ "/sys/fs/cgroup/memory/memory.limit_in_bytes": "9223372036854771712\n", "/sys/fs/cgroup/memory/memory.usage_in_bytes": "1\n" }))).toBeNull();+ });++ it("gives the gate the container's memory, not the machine's: a 2 GB container on a 64 GB host has 2 GB", () => {+ const host = { "/proc/meminfo": "MemTotal: 67108864 kB\nMemAvailable: 60000000 kB\nSwapFree: 8388608 kB\n", "/proc/vmstat": "oom_kill 40\n" };+ const container = { ...host, "/sys/fs/cgroup/memory.max": String(2 * GB), "/sys/fs/cgroup/memory.current": String(1536 * MB), "/sys/fs/cgroup/memory.stat": "inactive_file 0\n", "/sys/fs/cgroup/memory.events": "oom_kill 1\n" };+ const read = (map: Record<string, string>) => (path: string) => { if (path in map) return map[path]!; throw new Error("ENOENT"); };+ expect(readHostMemory(read(container))).toEqual({ totalBytes: 2 * GB, availableBytes: 512 * MB, swapFreeBytes: 0, oomKills: 1, fullStall10: null });+ // No limit below the machine's memory: the machine's numbers, as before.+ expect(readHostMemory(read(host))).toMatchObject({ totalBytes: 67108864 * 1024, swapFreeBytes: 8388608 * 1024, oomKills: 40 });+ expect(readHostMemory(read({ ...host, "/sys/fs/cgroup/memory.max": "max\n", "/sys/fs/cgroup/memory.current": "1\n" }))).toMatchObject({ totalBytes: 67108864 * 1024 });+ });++ it("says what process 1 is and whether anything collects orphans, and is all unknown where Linux's files are not there", () => {+ const base = { "/sys/fs/cgroup/pids.max": "512\n", "/sys/fs/cgroup/pids.current": "30\n", "/proc/self/limits": "Limit Soft Limit Hard Limit Units\nMax processes unlimited unlimited processes \n" };+ const stat = (pid: number, parent: number) => `${pid} (node) S ${parent} ${pid} ${pid} 0 -1`;+ expect(readProcessLimits({ platform: "linux", pid: 14, shm: () => 64 * MB, read: files({ ...base, "/proc/1/comm": "tini\n" }) }))+ .toEqual({ pidsMax: 512, pidsCurrent: 30, nproc: "unlimited", shmBytes: 64 * MB, pid1: "init", reaper: "yes" });+ expect(readProcessLimits({ platform: "linux", pid: 14, shm: () => null, read: files({ ...base, "/proc/1/comm": "MainThread\n", "/proc/14/comm": "node\n", "/proc/14/stat": stat(14, 1) }) }))+ .toMatchObject({ pid1: "node", reaper: "no", shmBytes: "unknown" });+ // The launcher as process 1 with the image's tini beneath it.+ expect(readProcessLimits({ platform: "linux", pid: 14, shm: () => null, read: files({ ...base, "/proc/1/comm": "node\n", "/proc/14/comm": "node\n", "/proc/14/stat": stat(14, 13), "/proc/13/comm": "tini\n", "/proc/13/stat": stat(13, 1) }) }))+ .toMatchObject({ pid1: "node", reaper: "yes" });+ expect(readProcessLimits({ platform: "linux", pid: 14, shm: () => null, read: files({ "/proc/1/comm": "start.sh\n", "/proc/self/limits": "Max processes 4096 4096 processes \n" }) }))+ .toEqual({ pidsMax: "unknown", pidsCurrent: "unknown", nproc: 4096, shmBytes: "unknown", pid1: "other", reaper: "unknown" });+ for (const platform of ["darwin", "win32"] as const) {+ expect(readProcessLimits({ platform, read: () => { throw new Error("nothing is read"); }, shm: () => { throw new Error("nothing is read"); } }))+ .toEqual({ pidsMax: "unknown", pidsCurrent: "unknown", nproc: "unknown", shmBytes: "unknown", pid1: "unknown", reaper: "unknown" });+ }+ });+});++describe("where turns wait for room, and the one setting", () => {+ it("reads OMB_TURNS_MAX_RUNNING as a number, off, or the container's own limits", () => {+ expect(turnsSetting("12")).toBe(12);+ expect(turnsSetting(" off ")).toBe("off");+ expect(turnsSetting("0")).toBe("off");+ for (const value of [undefined, "", "auto", "-3", "2.5", "many"]) expect(turnsSetting(value)).toBe("auto");+ });++ it("is on for a Cloud home and for a self-hosted Linux server in a container with a limit, never for the desktop app, and elsewhere only when asked for", () => {+ const limited = () => true, open = () => false;+ expect(gateHost({}, "linux", limited)).toBe("server");+ expect(gateHost({}, "linux", open)).toBeNull();+ expect(gateHost({ OMB_TURNS_MAX_RUNNING: "auto" }, "linux", open)).toBe("server");+ expect(gateHost({ OMB_TURNS_MAX_RUNNING: "8" }, "linux", open)).toBe("server");+ expect(gateHost({ OMB_CLOUD_ROLE: "home" }, "linux", open)).toBe("cloud");+ expect(gateHost({ OMB_CLOUD_ROLE: "team", OMB_TURNS_MAX_RUNNING: "off" }, "linux", open)).toBe("cloud");+ expect(gateHost({ OMB_DESKTOP_PARENT: "1" }, "linux", limited)).toBeNull();+ expect(gateHost({ OMB_DESKTOP_PARENT: "1", OMB_TURNS_MAX_RUNNING: "4" }, "linux", limited)).toBeNull();+ expect(gateHost({ OMB_TURNS_MAX_RUNNING: "off" }, "linux", limited)).toBeNull();+ for (const platform of ["darwin", "win32"] as const) {+ expect(gateHost({}, platform, () => { throw new Error("nothing is read off Linux"); })).toBeNull();+ expect(gateHost({ OMB_TURNS_MAX_RUNNING: "6" }, platform, open)).toBe("server");+ }+ });++ it("knows a container that was given a limit by the files at its cgroup root, and a machine's own root by their absence", () => {+ expect(containerLimited(files({ "/sys/fs/cgroup/pids.max": "512\n", "/sys/fs/cgroup/memory.max": "max\n" }))).toBe(true);+ expect(containerLimited(files({ "/sys/fs/cgroup/pids.max": "max\n", "/sys/fs/cgroup/memory.max": "4294967296\n" }))).toBe(true);+ expect(containerLimited(files({ "/sys/fs/cgroup/pids/pids.max": "1024\n" }))).toBe(true);+ expect(containerLimited(files({ "/sys/fs/cgroup/memory/memory.limit_in_bytes": "2147483648\n" }))).toBe(true);+ expect(containerLimited(files({ "/sys/fs/cgroup/pids.max": "max\n", "/sys/fs/cgroup/memory.max": "max\n" }))).toBe(false);+ expect(containerLimited(files({ "/sys/fs/cgroup/memory/memory.limit_in_bytes": "9223372036854771712\n" }))).toBe(false);+ // A server under systemd on a plain machine: its limits sit in its own cgroup's directory, not at the root.+ expect(containerLimited(files({ "/proc/self/cgroup": "0::/system.slice/omb.service\n", "/sys/fs/cgroup/system.slice/omb.service/pids.max": "4915\n" }))).toBe(false);+ expect(containerLimited(() => null)).toBe(false);+ });++ it("fits engines under a pids limit with a tenth of it, and at least 32, kept back", () => {+ expect([margin(100), margin(512), margin(4096)]).toEqual([32, 51, 410]);+ expect([turnsUnder(128), turnsUnder(512), turnsUnder(1024), turnsUnder(2048), turnsUnder(4096)]).toEqual([1, 7, 14, 30, 60]);+ });+});++describe("the pids budget", () => {+ const budget = (state: { max: number | "max" | null; current: number | null }) => {+ let clock = 1_000_000;+ const logs: string[] = [];+ const made = new ProcessBudget({ read: () => state, now: () => clock, log: (line) => logs.push(line) });+ return { made, logs, advance: (ms: number) => { clock += ms; } };+ };++ it("has room while the count, what is promised to engines still starting and one more engine stay under the limit less its margin", () => {+ const state = { max: 512 as number | "max" | null, current: 300 as number | null };+ const { made, advance } = budget(state);+ expect(made.short(ENGINE_TASKS, 0)).toBe(false);+ expect(made.short(ENGINE_TASKS, 60)).toBe(false);+ expect(made.short(ENGINE_TASKS, 120)).toBe(true);+ state.current = 402; advance(1_000);+ expect(made.short(ENGINE_TASKS, 0)).toBe(true);+ expect(made.limit()).toBe(512);+ });++ it("holds nothing back where no limit is set or readable: not Linux, a hidden /sys, pids.max of max", () => {+ for (const state of [{ max: null, current: null }, { max: "max" as const, current: 9_000 }, { max: 512, current: null }]) {+ const { made } = budget(state);+ expect(made.short(ENGINE_TASKS, 10_000)).toBe(false);+ }+ expect(budget({ max: null, current: null }).made.limit()).toBeNull();+ });++ it("learns the limit from the first refused spawn where none is readable (one set on a pod, above the container)", () => {+ const state = { max: "max" as number | "max" | null, current: 1_020 as number | null };+ const { made, logs, advance } = budget(state);+ let woken = 0;+ made.onRefused(() => { woken += 1; });+ made.spawnFailed("EAGAIN");+ expect(made.limit()).toBe(1_020);+ expect(woken).toBe(1);+ expect(logs).toEqual(["a spawn was refused (EAGAIN) with 1020 processes and threads running; new work now waits below that count"]);+ advance(60_000);+ state.current = 500;+ expect(made.short(ENGINE_TASKS, 0)).toBe(false);+ state.current = 900; advance(1_000);+ expect(made.short(ENGINE_TASKS, 0)).toBe(true);+ made.spawnFailed("EAGAIN");+ expect(logs).toHaveLength(1);+ // A limit the container shows is the one in force, whatever a refusal looked like.+ const shown = budget({ max: 4096, current: 300 });+ shown.made.spawnFailed("EAGAIN");+ expect(shown.made.limit()).toBe(4096);+ });++ it("starts nothing for half a minute after a spawn refused for open files or memory, and counts every refusal by its code", () => {+ const { made, advance } = budget({ max: 4096, current: 100 });+ made.spawnFailed("EMFILE");+ expect(made.short(ENGINE_TASKS, 0)).toBe(true);+ advance(31_000);+ expect(made.short(ENGINE_TASKS, 0)).toBe(false);+ made.spawnFailed("ENOENT"); made.spawnFailed(undefined); made.spawnFailed("EACCES"); made.spawnFailed("ENOMEM");+ made.noteForceKilled(); made.noteLateReaped(); made.noteLateReaped();+ expect(made.short(ENGINE_TASKS, 0)).toBe(true);+ expect(made.counts()).toEqual({ limit: 4096, spawnFailed: { EAGAIN: 0, EMFILE: 1, ENFILE: 0, ENOMEM: 1, ENOENT: 1, other: 2 }, forceKilled: 1, lateReaped: 2 });+ });+});++describe("a spawn the system refused is the server's shortage, not the AI's failure", () => {+ const refused = (code: string) => Object.assign(new Error(`spawn /usr/local/bin/claude ${code}`), { code });++ it("says so in one plain line that names no program, for the codes that mean no room", () => {+ for (const code of ["EAGAIN", "EMFILE", "ENFILE", "ENOMEM"]) {+ const failure = describeSpawnFailure(refused(code), "claude", "/data/work");+ expect(failure).toEqual({ message: `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.`,+ setup: false, text: { key: "chat.notice.outOfProcesses", params: { code } } });+ expect(failure.message).not.toContain("claude");+ expect(outOfProcesses(failure.message)).toBe(true);+ expect(shortageCode(refused(code))).toBe(code);+ }+ expect(describeSpawnFailure(refused("ENOENT"), "claude").setup).toBe(true);+ expect(shortageCode(refused("ENOENT"))).toBeNull();+ expect(shortageCode(new Error("EAGAIN in words only"))).toBeNull();+ });++ it("knows Node's own words for it too, and nothing else", () => {+ expect(outOfProcesses("spawn failed: spawn /app/engine EAGAIN")).toBe(true);+ expect(outOfProcesses("spawn git EMFILE")).toBe(true);+ expect(outOfProcesses("Error: spawn ENOMEM")).toBe(true);+ for (const other of ["claude exited 1 before result", "getaddrinfo EAI_AGAIN api.example.test", "Resource temporarily unavailable", "spawn claude ENOENT", ""]) expect(outOfProcesses(other)).toBe(false);+ });++ it("reads only the head of a failure: an engine that crashed with a file watcher's EMFILE in its stderr ran, and may go to a backup", () => {+ for (const crash of [+ "claude exited 1 before result: Error: EMFILE: too many open files, watch '/data/work'\n at FSWatcher.<computed>",+ "claude exited 1 before result: [warn] watcher\nError: spawn npx EAGAIN",+ "The AI stopped before it answered.\nThere is no room to start another program (EAGAIN), so this task could not run.",+ ]) expect(outOfProcesses(crash)).toBe(false);+ });++ it("is never read as a usage limit, a rate limit or a transient AI error, so nothing is retried on a model or handed to a backup", () => {+ const text = describeSpawnFailure(refused("EAGAIN"), "claude").message;+ expect(classifyError({ text })).toEqual({ transient: false, reason: "unknown" });+ expect(classifyError({ text: "spawn failed: spawn /app/engine EAGAIN" })).toEqual({ transient: false, reason: "unknown" });+ expect(engineFailureKind(text)).toBeFalsy();+ });++ it("makes a routine's run wait and start again, as for a busy bot, instead of failing or using up its one retry", () => {+ expect(classifyRoutineFailure(describeSpawnFailure(refused("EAGAIN"), "claude").message)).toEqual({ kind: "busy" });+ expect(classifyRoutineFailure("spawn failed: spawn /app/engine ENOMEM", { cause: "refused" })).toEqual({ kind: "busy" });+ expect(classifyRoutineFailure("claude exited 1 before result")).toEqual({ kind: "retry", cause: "failed" });+ });+});++describe("a process group that holds only exited processes", () => {+ const stat = (pid: number, state: string, group: number) => `${pid} (sleep one) ${state} 1 ${group} ${group} 0 -1`;+ const table = (rows: Record<number, string>) => [() => [...Object.keys(rows), "self", "cpuinfo"], (pid: number) => { if (rows[pid] === undefined) throw new Error("gone"); return rows[pid]!; }] as const;++ it("counts as gone: nothing collects a zombie where Node is a container's process 1, and kill(-group, 0) succeeds for it for good", () => {+ expect(linuxGroupOnlyExited(500, ...table({ 501: stat(501, "Z", 500), 502: stat(502, "Z", 500), 9: stat(9, "S", 9) }))).toBe(true);+ expect(linuxGroupOnlyExited(500, ...table({ 501: stat(501, "Z", 500), 502: stat(502, "X", 500) }))).toBe(true);+ });++ it("is still there while any member runs, and is not called gone when no member is found or /proc can't be read", () => {+ expect(linuxGroupOnlyExited(500, ...table({ 501: stat(501, "Z", 500), 502: stat(502, "S", 500) }))).toBe(false);+ expect(linuxGroupOnlyExited(500, ...table({ 9: stat(9, "Z", 9) }))).toBe(false);+ expect(linuxGroupOnlyExited(500, () => { throw new Error("EACCES"); })).toBe(false);+ });+});++class FakeChild extends EventEmitter {+ exitCode: number | null = null;+ signalCode: NodeJS.Signals | null = null;+ readonly pid: number;+ /** A pipe's count of what the process wrote; null: a process with no stdout of its own to watch. */+ readonly stdout: { bytesRead: number } | null;+ constructor(pid: number, piped = true) { super(); this.pid = pid; this.stdout = piped ? { bytesRead: 0 } : null; }+ exit(signal: NodeJS.Signals | null = null) {+ if (signal) this.signalCode = signal; else this.exitCode = 0;+ this.emit("exit", this.exitCode, signal);+ }+}++/** A self-hosted server in a container: `pids` is its pids.max, each engine holds 44 against it, and memory is plentiful+ * unless the test says otherwise. */+function server(options: { pids?: number | "max" | null; turns?: number | "auto"; total?: number; available?: number; perEngine?: number; host?: "server" | "cloud";+ tree?: (pid: number) => TreeUse | null } = {}) {+ let clock = 1_800_000_000_000, nextPid = 1000;+ const children = new Map<number, FakeChild>();+ const signals: string[] = [];+ const perEngine = options.perEngine ?? 300 * MB;+ const state = { base: 26, total: options.total ?? 64 * GB, available: options.available ?? 60 * GB };+ const pids = options.pids === undefined ? 512 : options.pids;+ const budget = new ProcessBudget({ read: () => ({ max: pids, current: pids === null ? null : state.base + children.size * 44 }), now: () => clock, log: () => {} });+ /** Each engine's tree: idle with no child unless the test says otherwise. */+ const trees = new Map<number, TreeUse>();+ const memory = new EngineMemory({+ enabled: true, host: options.host ?? "server", turns: options.turns ?? "auto", processes: budget, tickMs: 5,+ tree: options.tree ?? ((pid) => (children.has(pid) ? trees.get(pid) ?? { cpuMs: 0, children: 0 } : null)),+ read: (): HostMemory => ({ totalBytes: state.total, availableBytes: Math.max(0, state.available - children.size * perEngine), swapFreeBytes: 0, oomKills: 0, fullStall10: 0 }),+ groups: () => new Map([...children.keys()].map((pid) => [pid, perEngine])),+ now: () => clock, log: () => {},+ signal: (pid, signal) => {+ signals.push(`${signal} -${pid}`);+ const child = children.get(pid);+ if (child && child.exitCode === null && child.signalCode === null) queueMicrotask(() => child.exit(signal));+ },+ });+ const spawn = (threadId: string, piped = true) => memory.within(threadId, () => {+ const child = new FakeChild(nextPid++, piped);+ children.set(child.pid, child);+ child.once("exit", () => children.delete(child.pid));+ memory.track(child as unknown as ChildProcess);+ return child;+ });+ /** One turn admitted and its engine started, as the adapter does. */+ const start = async (threadId: string) => {+ const turn = await memory.admit(threadId, new AbortController().signal, () => {}, "turn");+ const engine = memory.hasEngine(threadId) || await memory.admit(threadId, new AbortController().signal, () => {}, "process");+ memory.turnStarted(threadId);+ if (!memory.hasEngine(threadId)) spawn(threadId);+ return turn && engine;+ };+ return { memory, budget, children, signals, state, trees, spawn, start, advance: (ms: number) => { clock += ms; } };+}++const settle = () => new Promise((resolve) => setTimeout(resolve, 25));++describe("a self-hosted server's turns at once", () => {+ it("defaults to what its pids limit and its memory hold at an engine's usual size, whichever is fewer", () => {+ expect(server({ pids: 512 }).memory.most()).toBe(7);+ expect(server({ pids: 4096 }).memory.most()).toBe(60);+ // A 4 GB container: 410 MB kept back, 700 MB an engine.+ expect(server({ pids: 4096, total: 4 * GB, available: 3 * GB }).memory.most()).toBe(5);+ expect(server({ pids: "max", total: 2 * GB, available: 1 * GB }).memory.most()).toBe(2);+ expect(server({ pids: 512, turns: 3 }).memory.most()).toBe(3);+ expect(server({ pids: 512, turns: 40 }).memory.most()).toBe(40);+ });++ it("sets no number on a Cloud home, whose plan and memory decide as before, and reads no pids limit there", async () => {+ const cloud = server({ pids: 128, host: "cloud" });+ expect(cloud.memory.most()).toBeUndefined();+ expect(cloud.memory.limited()).toBe(false);+ for (const thread of ["a", "b", "c", "d", "e", "f"]) {+ expect(await cloud.memory.admit(thread, new AbortController().signal, () => { throw new Error("no wait on a Cloud for pids"); })).toBe(true);+ cloud.memory.turnStarted(thread); cloud.spawn(thread);+ }+ expect(cloud.memory.idleEnginesAllowed()).toBe(Infinity);+ });++ it("queues the turn past the number, saying it waits on this server, and starts it when one ends", async () => {+ const s = server({ pids: 4096, turns: 2 });+ expect(await s.start("a")).toBe(true);+ expect(await s.start("b")).toBe(true);+ const said: Array<{ limit?: number; server?: boolean; ahead: number }> = [];+ s.memory.useWaits({ text: (_thread, wait) => { said.push({ limit: wait.limit, server: wait.server, ahead: wait.ahead }); return "waiting"; }, began: () => {}, changed: () => {} });+ const third = s.memory.admit("c", new AbortController().signal, () => {}, "turn");+ await settle();+ expect(said).toEqual([{ limit: 2, server: true, ahead: 0 }]);+ expect(s.memory.counts()).toMatchObject({ running: 2, queued: 1, most: 2, queuedEver: 1 });+ s.memory.turnEnded("a");+ expect(await third).toBe(true);+ expect(s.memory.counts()).toMatchObject({ queued: 0, queuedEver: 1 });+ });+});++describe("a burst of turns under a limit on turns", () => {+ it("starts the ones that got a place, though the rest queued before their engines were let in, and then the rest in turn", async () => {+ const s = server({ pids: 4096, turns: 2 });+ const order: string[] = [];+ // Every turn asks for its place first; only then do the two that got one ask for room for their engines.+ const places = ["a", "b", "c", "d", "e"].map((thread) => s.memory.admit(thread, new AbortController().signal, () => {}, "turn").then(() => thread));+ await settle();+ expect(s.memory.counts()).toMatchObject({ running: 2, queued: 3 });+ for (const thread of ["a", "b"]) {+ expect(await s.memory.admit(thread, new AbortController().signal, () => { throw new Error(`${thread} holds a place and has room: no wait`); }, "process")).toBe(true);+ s.memory.turnStarted(thread); s.spawn(thread); order.push(thread);+ }+ s.memory.turnEnded("a");+ expect(await Promise.race(places.slice(2))).toBe("c");+ expect(await s.memory.admit("c", new AbortController().signal, () => {}, "process")).toBe(true);+ s.memory.turnStarted("c"); s.spawn("c"); order.push("c");+ for (const thread of ["b", "c"]) s.memory.turnEnded(thread);+ await settle();+ for (const thread of ["d", "e"]) { expect(await s.memory.admit(thread, new AbortController().signal, () => {}, "process")).toBe(true); s.memory.turnStarted(thread); s.spawn(thread); order.push(thread); }+ expect(order).toEqual(["a", "b", "c", "d", "e"]);+ for (const thread of ["d", "e"]) s.memory.turnEnded(thread);+ await Promise.all(places);+ });+});++describe("room under the pids limit", () => {+ it("lets engines start while their processes fit, then stops one nobody is using, oldest first, to fit the next", async () => {+ // 512 allowed, 51 kept back, 26 the server's: engines of 44 fit while 26 + 44n + what is promised + 60 stays within 461.+ const s = server({ pids: 512, turns: 40 });+ for (const thread of ["a", "b", "c", "d", "e", "f", "g", "h", "i"]) {+ expect(await s.start(thread)).toBe(true);+ s.advance(21_000);+ }+ expect(s.signals).toEqual([]);+ expect(s.children.size).toBe(9);+ // 26 + 9 × 44 = 422; a tenth engine's 60 would pass 461. "a" and "b" are done and their engines idle.+ s.memory.turnEnded("a"); s.memory.turnEnded("b");+ expect(await s.start("j")).toBe(true);+ expect(s.signals).toEqual(["SIGTERM -1000"]);+ expect(s.memory.hasEngine("a")).toBe(false);+ expect(s.memory.hasEngine("b")).toBe(true);+ });++ it("makes the turn wait, saying so, when every engine is working, and starts it when one ends", async () => {+ const s = server({ pids: 512, turns: 40 });+ for (const thread of ["a", "b", "c", "d", "e", "f", "g", "h", "i"]) { await s.start(thread); s.advance(21_000); }+ const notices: string[] = [];+ const ninth = s.memory.admit("j", new AbortController().signal, (text) => notices.push(text), "process");+ await settle();+ expect(notices).toHaveLength(1);+ expect(s.signals).toEqual([]);+ s.memory.turnEnded("c");+ expect(await ninth).toBe(true);+ expect(s.signals).toEqual(["SIGTERM -1002"]);+ });++ it("counts engines let in but not yet running, so a burst does not all start at once", async () => {+ const s = server({ pids: 512, turns: 40 });+ const admitted: string[] = [];+ const turns = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"].map(async (thread) => {+ if (await s.memory.admit(thread, new AbortController().signal, () => {}, "process")) admitted.push(thread);+ });+ await settle();+ // Nothing has started, so the count still reads 26: seven promised engines of 60 fit under 461, an eighth does not.+ expect(admitted).toEqual(["a", "b", "c", "d", "e", "f", "g"]);+ for (const thread of admitted) s.memory.turnEnded(thread);+ await Promise.all(turns);+ });++ it("keeps room for one more browser while starts are pending, not one for each bot that may browse", async () => {+ const s = server({ pids: 512, turns: 40 });+ s.memory.useBrowsers({ starts: () => true, running: () => false, stopped: () => {} });+ const admitted: string[] = [];+ const turns = ["a", "b", "c", "d", "e", "f"].map(async (thread) => {+ if (await s.memory.admit(thread, new AbortController().signal, () => {}, "process")) admitted.push(thread);+ });+ await settle();+ // 26 now, 60 for each engine promised and 170 for one browser: four fit under 461 (one each would have let in one).+ expect(admitted).toEqual(["a", "b", "c", "d"]);+ for (const thread of ["a", "b", "c", "d", "e", "f"]) s.memory.turnEnded(thread);+ await Promise.all(turns);+ });++ it("never holds back the only task, and holds nothing where no pids limit can be read", async () => {+ const full = server({ pids: 64, turns: 40 });+ expect(await full.start("a")).toBe(true);+ const open = server({ pids: null, turns: 40 });+ for (const thread of ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]) expect(await open.start(thread)).toBe(true);+ expect(open.signals).toEqual([]);+ });++ it("holds new engines back after the kernel refused a spawn, at the count it refused at", async () => {+ const s = server({ pids: "max", turns: 40 });+ for (const thread of ["a", "b", "c", "d", "e"]) { await s.start(thread); s.advance(21_000); }+ // 26 + 5 × 44 = 246 when the sixth engine's spawn is refused: the limit sits above the container, unreadable.+ s.budget.spawnFailed("EAGAIN");+ expect(s.budget.limit()).toBe(246);+ s.advance(31_000);+ const notices: string[] = [];+ const sixth = s.memory.admit("f", new AbortController().signal, (text) => notices.push(text), "process");+ await settle();+ expect(notices).toHaveLength(1);+ // It was full with five: 32 are kept back, so a new engine's 60 fit once three have gone.+ s.memory.turnEnded("a"); s.memory.turnEnded("b");+ await settle();+ expect(s.signals).toEqual(["SIGTERM -1000", "SIGTERM -1001"]);+ s.memory.turnEnded("c");+ expect(await sixth).toBe(true);+ expect(s.signals).toEqual(["SIGTERM -1000", "SIGTERM -1001", "SIGTERM -1002"]);+ // Half an hour with no further refusal and the learned limit is forgotten.+ s.advance(31 * 60_000);+ expect(s.budget.limit()).toBeNull();+ });++ it("keeps no more engines idle than fit beside the ones working", async () => {+ const s = server({ pids: 512 });+ expect(s.memory.idleEnginesAllowed()).toBe(7);+ for (const thread of ["a", "b", "c"]) { await s.start(thread); s.advance(6_000); }+ expect(s.memory.idleEnginesAllowed()).toBe(4);+ for (const thread of ["d", "e", "f", "g"]) { await s.start(thread); s.advance(6_000); }+ expect(s.memory.idleEnginesAllowed()).toBe(1);+ });+});++describe("a new engine that never comes up", () => {+ afterEach(() => { vi.useRealTimers(); });++ function fakeInstance(driverKind = "claudeAgent", capabilities: Record<string, unknown> = {}) {+ const listeners = new Set<RuntimeEventListener>();+ const sent: string[] = [];+ const interrupted: string[] = [];+ const instance = {+ instanceId: "one", driverKind, displayName: "Engine", enabled: true, continuationIdentity: { driverKind, continuationKey: "k" },+ snapshot: { getSnapshot: () => ({}), refresh: async () => ({}) }, models: [],+ adapter: {+ provider: driverKind, capabilities: { sessionModelSwitch: "unsupported", ...capabilities },+ onEvent: (listener: RuntimeEventListener) => { listeners.add(listener); return () => listeners.delete(listener); },+ sendTurn: async (input: SendTurnInput) => { sent.push(input.threadId); return { turnId: `turn-${input.threadId}` }; },+ interruptTurn: async (threadId: string) => { interrupted.push(threadId); },+ stopAll: async () => {},+ },+ } as unknown as ProviderInstance;+ const emit = (event: Record<string, unknown>) => { for (const listener of listeners) listener({ eventId: "e", provider: driverKind, createdAt: "", ...event } as RuntimeEvent); };+ return { instance, sent, interrupted, emit };+ }++ /** An adapter whose sendTurn starts its engine, as spawnCli does inside the driver's own sendTurn. */+ function spawning(s: ReturnType<typeof server>, driverKind = "claudeAgent") {+ const fake = fakeInstance(driverKind);+ const send = fake.instance.adapter.sendTurn;+ (fake.instance.adapter as { sendTurn: typeof send }).sendTurn = async (input) => { if (!s.memory.hasEngine(input.threadId)) s.spawn(input.threadId); return send(input); };+ const decorated = withEngineMemory(fake.instance, s.memory);+ const seen: RuntimeEvent[] = [];+ decorated.adapter.onEvent((event) => seen.push(event));+ return { ...fake, decorated, seen, failure: () => (seen.find((event) => event.type === "runtime.error") as (RuntimeEvent & { message: string }) | undefined)?.message };+ }++ const NO_ROOM = "There is no room to start another program (EAGAIN), so this task could not run. Nothing was sent to the AI. It starts again by itself when there is room.";++ it("is stopped after a minute and a half with nothing on its stdout while the pids limit is full, and its turn fails as one the server had no room for", async () => {+ vi.useFakeTimers();+ const s = server({ pids: 512 });+ const turn = spawning(s);+ await turn.decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ // Other work fills the container: 474 of 512, past the 51 kept back.+ s.state.base = 430;+ // The driver's own "turn started" is not the engine speaking.+ turn.emit({ type: "turn.started", threadId: "t1", turnId: "turn-t1" });+ await vi.advanceTimersByTimeAsync(FIRST_FRAME_MS - 1_000);+ expect(s.signals).toEqual([]);+ await vi.advanceTimersByTimeAsync(2_000);+ expect(s.signals).toEqual(["SIGKILL -1000"]);+ expect(s.memory.stoppedForRoom("t1")).toBe(true);+ expect(s.memory.counts().starvedEver).toBe(1);+ // Not a refused spawn: nothing is counted as one, and no limit is learned from it.+ expect(s.budget.counts().spawnFailed.EAGAIN).toBe(0);+ // The driver reports its engine's exit in its own words; the person reads the server's one line instead.+ turn.emit({ type: "runtime.error", threadId: "t1", turnId: "turn-t1", message: "claude exited null before result" });+ turn.emit({ type: "turn.completed", threadId: "t1", turnId: "turn-t1", ok: false, stopReason: "exit_before_result", cost: null });+ expect(turn.failure()).toBe(NO_ROOM);+ expect(outOfProcesses(turn.failure()!)).toBe(true);+ expect(turn.interrupted).toEqual([]);+ await vi.advanceTimersByTimeAsync(10);+ expect(s.memory.stoppedForRoom("t1")).toBe(false);+ });++ it("holds an engine that admits itself (ACP) to the same deadline when a spawn was refused meanwhile, and a start it gives up on names the server's shortage", async () => {+ vi.useFakeTimers();+ const s = server({ pids: 4096 });+ const fake = fakeInstance("geminiAgent", { engineAdmission: true });+ let fail: ((error: Error) => void) | null = null;+ (fake.instance.adapter as { sendTurn: (input: SendTurnInput) => Promise<{ turnId: string }> }).sendTurn = async (input) => {+ await input.engineAdmission?.("process");+ s.spawn(input.threadId);+ // An ACP turn that may go to a backup answers only once the engine's handshake settles.+ return new Promise((_resolve, reject) => { fail = reject; });+ };+ const decorated = withEngineMemory(fake.instance, s.memory);+ decorated.adapter.onEvent(() => {});+ const turn = decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ const caught = turn.catch((error: unknown) => error);+ await vi.advanceTimersByTimeAsync(1_000);+ // The server's own spawn of something else is refused while the engine starts.+ s.memory.spawnRefused("EAGAIN");+ await vi.advanceTimersByTimeAsync(FIRST_FRAME_MS);+ expect(s.signals).toEqual(["SIGKILL -1000"]);+ fail!(new TurnNotStartedError("turn-t1", "Gemini exited before it answered initialize"));+ const error = await caught;+ expect(error).toBeInstanceOf(TurnNotStartedError);+ expect((error as Error).message).toBe(NO_ROOM);+ expect(outOfProcesses((error as Error).message)).toBe(true);+ });++ it("names memory when memory is what is short", async () => {+ vi.useFakeTimers();+ const s = server({ pids: "max", total: 4 * GB, available: 3 * GB });+ const turn = spawning(s);+ await turn.decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ s.state.available = 500 * MB;+ await vi.advanceTimersByTimeAsync(FIRST_FRAME_MS + 1_000);+ expect(s.signals).toEqual(["SIGKILL -1000"]);+ turn.emit({ type: "turn.completed", threadId: "t1", turnId: "turn-t1", ok: false, stopReason: "exit_before_result", cost: null });+ expect(turn.failure()).toBe(NO_ROOM.replace("EAGAIN", "ENOMEM"));+ expect(outOfProcesses(turn.failure()!)).toBe(true);+ expect(s.budget.limit()).toBeNull();+ });++ it("is left alone with no sign of a shortage, however long it is silent (a cold npx start, a slow first start): its driver's own timeout decides", async () => {+ vi.useFakeTimers();+ // A container with only a memory limit (pids.max reads "max"), plenty of it free, three engines already running.+ const s = server({ pids: "max", total: 8 * GB, available: 7 * GB });+ const before = s.memory.most();+ for (const thread of ["a", "b", "c"]) { await s.start(thread); s.children.get([...s.children.keys()].at(-1)!)!.stdout!.bytesRead = 100; }+ s.memory.expectFrame("d");+ await s.start("d");+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(s.signals).toEqual([]);+ expect(s.memory.stoppedForRoom("d")).toBe(false);+ expect(s.budget.limit()).toBeNull();+ expect(s.memory.most()).toBe(before);+ expect(s.memory.counts().starvedEver).toBe(0);+ });++ it("is left alone on a Cloud home where nothing is short, an ACP engine that takes minutes to answer initialize among them", async () => {+ vi.useFakeTimers();+ const s = server({ host: "cloud" });+ const fake = fakeInstance("customAcp", { engineAdmission: true });+ (fake.instance.adapter as { sendTurn: (input: SendTurnInput) => Promise<unknown> }).sendTurn = async (input) => {+ await input.engineAdmission?.("process"); s.spawn(input.threadId); return new Promise(() => {});+ };+ const decorated = withEngineMemory(fake.instance, s.memory);+ decorated.adapter.onEvent(() => {});+ void decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ await vi.advanceTimersByTimeAsync(4 * 60_000);+ expect(s.signals).toEqual([]);+ expect(s.memory.stoppedForRoom("t1")).toBe(false);+ });++ it("is left alone under a real shortage while its processes still work or a child runs (npx installing), and stopped once they are idle", async () => {+ vi.useFakeTimers();+ const s = server({ pids: 512 });+ const turn = spawning(s);+ await turn.decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ s.state.base = 430;+ // Busy: a second of CPU every few seconds.+ let cpuMs = 0;+ const busy = setInterval(() => { cpuMs += 1_000; s.trees.set(1000, { cpuMs, children: 0 }); }, 2_000);+ await vi.advanceTimersByTimeAsync(3 * 60_000);+ expect(s.signals).toEqual([]);+ clearInterval(busy);+ // Idle itself, but its npx child still runs.+ s.trees.set(1000, { cpuMs, children: 2 });+ await vi.advanceTimersByTimeAsync(60_000);+ expect(s.signals).toEqual([]);+ s.trees.set(1000, { cpuMs, children: 0 });+ await vi.advanceTimersByTimeAsync(40_000);+ expect(s.signals).toEqual(["SIGKILL -1000"]);+ });++ it("is never stopped as silent where its processes can't be read", async () => {+ vi.useFakeTimers();+ const s = server({ pids: 512, tree: () => null });+ const turn = spawning(s);+ await turn.decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ s.state.base = 430;+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(s.signals).toEqual([]);+ });++ it("is left alone once it has written anything, when its thread's engine was already running, for a process with no stdout, and for an engine that keeps no session", async () => {+ vi.useFakeTimers();+ const s = server({ pids: 4096 });+ const fake = fakeInstance();+ const send = fake.instance.adapter.sendTurn;+ (fake.instance.adapter as { sendTurn: typeof send }).sendTurn = async (input) => {+ if (!s.memory.hasEngine(input.threadId)) s.spawn(input.threadId).stdout!.bytesRead = 312;+ return send(input);+ };+ const decorated = withEngineMemory(fake.instance, s.memory);+ decorated.adapter.onEvent(() => {});+ await decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ // A shortage all along: none of these is stopped for it.+ s.memory.spawnRefused("EMFILE");+ await vi.advanceTimersByTimeAsync(FIRST_FRAME_MS * 3);+ fake.emit({ type: "turn.completed", threadId: "t1", turnId: "turn-t1", ok: true, stopReason: "end_turn", cost: null });+ await vi.advanceTimersByTimeAsync(10);+ // The same thread again: its engine is still up, and a slow model is not a missing engine.+ await decorated.adapter.sendTurn({ threadId: "t1", text: "again" } as SendTurnInput);+ s.memory.spawnRefused("EMFILE");+ await vi.advanceTimersByTimeAsync(FIRST_FRAME_MS * 3);+ // A process with no stdout to watch, and one started for a turn on an engine that may say nothing until its answer.+ s.memory.expectFrame("t3");+ s.spawn("t3", false);+ const quiet = fakeInstance("piAgent");+ const send2 = quiet.instance.adapter.sendTurn;+ (quiet.instance.adapter as { sendTurn: typeof send2 }).sendTurn = async (input) => { s.spawn(input.threadId); return send2(input); };+ const pi = withEngineMemory(quiet.instance, s.memory);+ pi.adapter.onEvent(() => {});+ await pi.adapter.sendTurn({ threadId: "t4", text: "hi" } as SendTurnInput);+ // Nor another process the same turn starts after its engine.+ await decorated.adapter.sendTurn({ threadId: "t5", text: "hi" } as SendTurnInput);+ s.spawn("t5");+ s.memory.spawnRefused("EMFILE");+ await vi.advanceTimersByTimeAsync(FIRST_FRAME_MS * 3);+ expect(s.signals).toEqual([]);+ expect(s.memory.counts().starvedEver).toBe(0);+ });++ it("tells a driver its exited engine was stopped for room only for the process this gate stopped, so any other exit may be sent again", async () => {+ vi.useFakeTimers();+ const s = server({ pids: 512 });+ const turn = spawning(s);+ await turn.decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ s.state.base = 430;+ await vi.advanceTimersByTimeAsync(FIRST_FRAME_MS + 1_000);+ expect(s.memory.stoppedForRoom("t1", 1000)).toBe(true);+ expect(s.memory.stoppedForRoom("t1", 1001)).toBe(false);+ // A memory stop of an earlier turn is not this one's.+ s.memory.turnStarted("t1");+ expect(s.memory.stoppedForRoom("t1", 1000)).toBe(false);+ expect(s.memory.stoppedForRoom("t1")).toBe(false);+ });+});++describe("a spawn refused during a turn", () => {+ const NO_ROOM = "There is no room to start another program (EAGAIN), so this task could not run. Nothing was sent to the AI. It starts again by itself when there is room.";++ it("fails the turn whose own engine's spawn the system refused as the server's shortage, and only that thread's", () => {+ const s = server({ pids: 4096 });+ s.memory.turnStarted("t1"); s.memory.turnStarted("t2"); s.memory.turnStarted("t3");+ s.memory.within("t1", () => s.memory.spawnRefused("EAGAIN", true));+ s.memory.within("t2", () => s.memory.spawnRefused("ENOENT", true));+ // A refusal of some other spawn in a turn (a probe, a helper) is a sign of a shortage, never that turn's failure.+ s.memory.within("t3", () => s.memory.spawnRefused("EAGAIN"));+ s.memory.spawnRefused("EMFILE", true);+ expect([s.memory.stoppedForRoom("t1"), s.memory.stoppedForRoom("t2"), s.memory.stoppedForRoom("t3")]).toEqual([true, false, false]);+ expect(s.memory.stopFailure("t1")?.message).toBe(NO_ROOM);+ s.memory.turnEnded("t1");+ expect(s.memory.stoppedForRoom("t1")).toBe(false);+ });++ it("is forgotten once a later spawn in the same turn works: the turn goes on, and its end is its own", () => {+ const s = server({ pids: 4096 });+ s.memory.turnStarted("t1");+ s.memory.within("t1", () => s.memory.spawnRefused("EAGAIN", true));+ s.spawn("t1");+ expect(s.memory.stoppedForRoom("t1")).toBe(false);+ expect(s.memory.stopFailure("t1", "claude exited 1 before result: Error: boom")).toBeNull();+ });++ it("outside a running turn is never carried into the thread's next one", () => {+ const s = server({ pids: 4096 });+ s.memory.turnStarted("t1");+ s.memory.turnEnded("t1");+ // A spawn from a timer the last turn armed.+ s.memory.within("t1", () => s.memory.spawnRefused("EAGAIN", true));+ s.memory.turnStarted("t1");+ expect(s.memory.stoppedForRoom("t1")).toBe(false);+ expect(s.memory.stopFailure("t1")).toBeNull();+ });++ it("never relabels a failure that names its own cause: a usage limit stays a usage limit, and a routine does not wait on it as busy", () => {+ const s = server({ pids: 4096 });+ s.memory.turnStarted("t1");+ s.memory.within("t1", () => s.memory.spawnRefused("EAGAIN", true));+ const limit = "You've hit your usage limit · resets 5pm";+ expect(s.memory.stopFailure("t1", limit)).toBeNull();+ expect(classifyRoutineFailure(limit)).not.toEqual({ kind: "busy" });+ // A failure in the engine's words of nothing in particular is still the shortage's.+ expect(s.memory.stopFailure("t1", "claude exited null before result")?.message).toBe(NO_ROOM);+ });++ it("keeps a usage-limit refusal of the turn's start what it is", async () => {+ const s = server({ pids: 4096 });+ const instance = {+ instanceId: "one", driverKind: "claudeAgent", displayName: "Engine", enabled: true, continuationIdentity: { driverKind: "claudeAgent", continuationKey: "k" },+ snapshot: { getSnapshot: () => ({}), refresh: async () => ({}) }, models: [],+ adapter: {+ provider: "claudeAgent", capabilities: { sessionModelSwitch: "unsupported" }, onEvent: () => () => {},+ sendTurn: async () => { s.memory.spawnRefused("EAGAIN", true); throw new TurnNotStartedError("turn-t1", "You've hit your usage limit · resets 5pm"); },+ interruptTurn: async () => {}, stopAll: async () => {},+ },+ } as unknown as ProviderInstance;+ const error = await withEngineMemory(instance, s.memory).adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput).catch((caught: unknown) => caught);+ expect((error as Error).message).toBe("You've hit your usage limit · resets 5pm");+ });++ it("does not explain a turn the person stopped, nor one after a refusal from before it began", async () => {+ const s = server({ pids: 4096 });+ const listeners = new Set<RuntimeEventListener>();+ const instance = {+ instanceId: "one", driverKind: "claudeAgent", displayName: "Engine", enabled: true, continuationIdentity: { driverKind: "claudeAgent", continuationKey: "k" },+ snapshot: { getSnapshot: () => ({}), refresh: async () => ({}) }, models: [],+ adapter: {+ provider: "claudeAgent", capabilities: { sessionModelSwitch: "unsupported" },+ onEvent: (listener: RuntimeEventListener) => { listeners.add(listener); return () => listeners.delete(listener); },+ sendTurn: async (input: SendTurnInput) => ({ turnId: `turn-${input.threadId}` }),+ interruptTurn: async () => {}, stopAll: async () => {},+ },+ } as unknown as ProviderInstance;+ const decorated = withEngineMemory(instance, s.memory);+ const seen: RuntimeEvent[] = [];+ decorated.adapter.onEvent((event) => seen.push(event));+ const stop = (threadId: string) => { for (const listener of listeners) listener({ eventId: "e", provider: "claudeAgent", createdAt: "", type: "turn.completed", threadId, turnId: `turn-${threadId}`, ok: false, stopReason: "interrupted", cost: null } as RuntimeEvent); };+ s.memory.within("t1", () => s.memory.spawnRefused("EAGAIN", true));+ await decorated.adapter.sendTurn({ threadId: "t1", text: "hi" } as SendTurnInput);+ stop("t1");+ // Refused in the turn, then the person stopped it.+ await decorated.adapter.sendTurn({ threadId: "t2", text: "hi" } as SendTurnInput);+ s.memory.within("t2", () => s.memory.spawnRefused("EAGAIN", true));+ stop("t2");+ expect(seen.filter((event) => event.type === "runtime.error")).toEqual([]);+ });++ it("holds a routine run of checked items that waits for room to the same hour as any other run", () => {+ const now = 1_800_000_000_000;+ const run = () => ({ id: "r1", routineId: "x", target: "bot", botId: "b", status: "running", checkKey: "k", deferredAt: now - ROUTINE_BUSY_WAIT_MS }) as unknown as RoutineRun;+ expect(recoverRun(run(), NO_ROOM, {}, now, [])).toMatchObject({ queued: false });+ // Its bot busy with the person: it waits as long as that takes, as before.+ expect(recoverRun(run(), "busy", { cause: "busy" }, now, [])).toEqual({ queued: true });+ });+});++describe("browsers under the pids limit", () => {+ afterEach(() => { vi.useRealTimers(); });++ function room(current: { value: number }, measured: { value: number | null }, running: Set<string>) {+ const budget = new ProcessBudget({ read: () => ({ max: 1024, current: current.value }), browserTasks: () => measured.value, log: () => {}, pollMs: 100 });+ return { budget, room: budget.browserRoom((session) => running.has(session)) };+ }++ it("opens one only where its processes fit, waits a while for room, then says why it cannot", async () => {+ vi.useFakeTimers();+ // 1,024 allowed, 102 kept back: 922 to work in.+ const current = { value: 700 }, measured = { value: 0 }, running = new Set<string>();+ const { room: browsers } = room(current, measured, running);+ expect(await browsers.enter("bot-a")).toBeNull();+ // bot-a's browser counts at its full size though the count does not show it yet: 700 + 170 + 170 > 922.+ const second = browsers.enter("bot-b");+ await vi.advanceTimersByTimeAsync(21_000);+ expect(await second).toBe(BROWSER_NO_ROOM);+ // Once it runs and the count shows it, it is counted once.+ running.add("bot-a");+ current.value = 700 + BROWSER_TASKS; measured.value = BROWSER_TASKS;+ expect(await browsers.enter("bot-a")).toBeNull();+ current.value = 400 + BROWSER_TASKS;+ expect(await browsers.enter("bot-b")).toBeNull();+ });++ it("holds each running browser's room against new engines for as long as it runs, and frees it when it closes", async () => {+ vi.useFakeTimers();+ const current = { value: 500 }, measured = { value: 40 }, running = new Set<string>(["bot-a"]);+ const { budget, room: browsers } = room(current, measured, running);+ expect(await browsers.enter("bot-a")).toBeNull();+ // 500 now, of which the browser shows 40 while it starts: 130 more are held for it, and an engine's 60 still fit (690 of 922).+ expect(budget.short(ENGINE_TASKS, 0)).toBe(false);+ current.value = 750;+ expect(budget.short(ENGINE_TASKS, 0)).toBe(true);+ // Long after it started, still running at 40 threads: still held at its full size.+ vi.advanceTimersByTime(10 * 60_000);+ expect(budget.short(ENGINE_TASKS, 0)).toBe(true);+ running.delete("bot-a"); measured.value = 0; current.value = 710;+ vi.advanceTimersByTime(2_000);+ expect(budget.short(ENGINE_TASKS, 0)).toBe(false);+ });++ it("reads each browser and engine tree from /proc's own rows", () => {+ const row = (pid: number, ppid: number, name: string, cpuMs: number, state = "S", threads = 1) => ({ pid, ppid, name, cpuMs, rssBytes: 0, start: "1", threads, state });+ const rows = [row(10, 1, "claude", 500), row(11, 10, "npm exec", 2_000), row(12, 11, "node", 300), row(13, 10, "sh", 0, "Z"), row(20, 1, "node", 9_000)];+ expect(linuxTreeUse(10, () => rows, () => 100)).toEqual({ cpuMs: 2_900, children: 2 });+ expect(linuxTreeUse(99, () => rows, () => 0)).toBeNull();+ });+});diff --git a/server/process-room.ts b/server/process-room.tsnew file mode 100644index 0000000000..7398adf051--- /dev/null+++ b/server/process-room.ts@@ -0,0 +1,213 @@+// A server in a container may hold only so many processes and threads (its cgroup's pids.max); past that every spawn+// fails with EAGAIN. The gate that holds turns for memory (engine-memory.ts) asks here whether one more engine fits.+import { readFileSync } from "node:fs";+import { nameBucket, parseReapedChildrenMs, type ProcessRow } from "./perf/process-buckets.ts";+import { linuxProcessList } from "./perf/process-sampler.ts";+import { containerLimited, readPids } from "./process-limits.ts";+import type { ShortageCode } from "./process-shortage.ts";++/** What one working bot holds against pids.max: its engine and the five tool servers a default bot's engine starts ran as+ * 6 processes with 44 threads (a scripted engine on Node 24, 2026-11-16); a real engine CLI and the commands it runs add+ * to that. */+export const ENGINE_TASKS = 60;+/** One more session in an engine process that is already running: its tool servers. */+export const SESSION_TASKS = 40;+/** One bot's browser: 13 processes with 163 threads (agent-browser 0.37.0 and Chromium 156 on one page, 2026-11-16). */+export const BROWSER_TASKS = 170;+/** The server, its launcher and init, and what the server runs for itself (git, probes). */+const SERVER_TASKS = 40;+/** After a refused spawn that names no pids limit (open files, memory), nothing new starts for this long. */+const SHORTAGE_HOLD_MS = 30_000;+/** A limit learned from a refused spawn is kept this long after the last refusal: the refusal may have been another+ * limit's (ulimit -u, shared with every process of the same user), or the container's may have been raised. */+const LEARNED_FOR_MS = 30 * 60_000;+/** A browser let in counts at its full size while it starts, whatever its process says; after that while it runs. */+const BROWSER_START_MS = 60_000;+/** How long a browser call waits for room before it is told why it cannot open one: well inside the call's own budget. */+const BROWSER_WAIT_MS = 20_000;+export const BROWSER_NO_ROOM = "This server is close to its limit on running programs, so another browser cannot open now. " ++ "Try the browser again in a few minutes, or carry on without it.";++/** Kept below the limit for what nobody counts ahead: a command's own children, a probe, a thread pool growing. */+export const margin = (limit: number) => Math.max(32, Math.round(limit * 0.1));+/** How many engines fit under a pids limit. */+export const turnsUnder = (limit: number) => Math.max(1, Math.floor((limit - margin(limit) - SERVER_TASKS) / ENGINE_TASKS));++export type SpawnFailureCode = ShortageCode | "ENOENT" | "other";+export interface ProcessCounts {+ /** The pids limit the gate works to: the cgroup's, or the count at which a spawn was first refused. Null: none known. */+ limit: number | null;+ spawnFailed: Record<SpawnFailureCode, number>;+ forceKilled: number;+ lateReaped: number;+}++export interface ProcessBudgetOptions {+ read?: () => { max: number | "max" | null; current: number | null };+ /** The threads every browser process runs now, counted against the limit already; null where they can't be read. */+ browserTasks?: () => number | null;+ now?: () => number;+ log?: (line: string) => void;+ pollMs?: number;+}++export class ProcessBudget {+ private readonly read: () => { max: number | "max" | null; current: number | null };+ private readonly now: () => number;+ private readonly log: (line: string) => void;+ /** The count at which the kernel first refused a spawn: the limit, where none can be read (one set on a parent cgroup). */+ private learned: { limit: number; at: number } | null = null;+ private holdUntil = -Infinity;+ private readonly spawnFailures: Record<SpawnFailureCode, number> = { EAGAIN: 0, EMFILE: 0, ENFILE: 0, ENOMEM: 0, ENOENT: 0, other: 0 };+ private forceKilled = 0;+ private lateReaped = 0;+ private refused: (() => void) | null = null;+ private readonly browserTasks: () => number | null;+ private readonly pollMs: number;+ /** Browsers let in (browserRoom), by session, and when. */+ private readonly browsers = new Map<string, number>();+ private browserRuns: ((session: string) => boolean) | null = null;+ private seenBrowsers: { at: number; tasks: number | null } | null = null;++ constructor(options: ProcessBudgetOptions = {}) {+ this.read = options.read ?? (() => readPids());+ this.browserTasks = options.browserTasks ?? (() => browserTasksNow());+ this.now = options.now ?? Date.now;+ this.log = options.log ?? ((line) => console.warn(`processes: ${line}`));+ this.pollMs = options.pollMs ?? 1_000;+ }++ /** Called when the system refuses a spawn for want of room: whoever holds turns back looks again. */+ onRefused(refused: () => void): void { this.refused = refused; }++ /** Two small files, read each time: a count a moment old would hold a turn back after the room it waited for came. */+ private state(): { max: number | "max" | null; current: number | null } { return this.read(); }++ /** The limit in force; null where none is set, readable or learned. */+ limit(): number | null {+ const { max } = this.state();+ if (typeof max === "number") return max;+ if (this.learned && this.now() - this.learned.at >= LEARNED_FOR_MS) this.learned = null;+ return this.learned?.limit ?? null;+ }++ /** Whether `tasks` more, on top of `held` already promised to engines still starting and the browsers running, would+ * not fit. */+ short(tasks: number, held: number): boolean {+ if (this.now() < this.holdUntil) return true;+ const limit = this.limit(), { current } = this.state();+ return limit !== null && current !== null && current + held + this.browsersHeld() + tasks > limit - margin(limit);+ }++ /** What the browsers let in still hold against the limit beyond what the count shows of them: each counts at its full+ * size for as long as it runs, so one opened after its turn was let in (on a bot's first browser call) is never missed,+ * and one still starting or loading a page has its room kept. */+ private browsersHeld(): number {+ const at = this.now();+ for (const [session, since] of this.browsers) if (at - since >= BROWSER_START_MS && this.browserRuns?.(session) === false) this.browsers.delete(session);+ if (!this.browsers.size) return 0;+ if (!this.seenBrowsers || at - this.seenBrowsers.at >= 1_000 || at < this.seenBrowsers.at) this.seenBrowsers = { at, tasks: this.browserTasks() };+ return Math.max(0, this.browsers.size * BROWSER_TASKS - (this.seenBrowsers.tasks ?? 0));+ }++ /** The gate a bot's browser passes before it opens: `runs` says whether a session's browser is running now. */+ browserRoom(runs: (session: string) => boolean): { enter(session: string): Promise<string | null> } {+ this.browserRuns = runs;+ return { enter: (session) => this.enterBrowser(session, this.now() + BROWSER_WAIT_MS) };+ }++ /** Null once this session's browser may run: it already does, or its processes fit. Otherwise it waits for room until+ * `until`, then answers why it cannot open. */+ private async enterBrowser(session: string, until: number): Promise<string | null> {+ for (;;) {+ const since = this.browsers.get(session);+ if (since !== undefined && (this.now() - since < BROWSER_START_MS || this.browserRuns?.(session) !== false)) return null;+ this.browsers.delete(session);+ if (this.browserRuns?.(session) || !this.short(BROWSER_TASKS, 0)) { this.browsers.set(session, this.now()); return null; }+ if (this.now() >= until) return BROWSER_NO_ROOM;+ await new Promise((resolve) => { const timer = setTimeout(resolve, Math.max(1, Math.min(this.pollMs, until - this.now()))); timer.unref?.(); });+ }+ }++ /** Every spawn the operating system refused, by its code. A pids refusal also teaches the limit where none is readable. */+ spawnFailed(code: string | undefined): void {+ const known: SpawnFailureCode = code !== undefined && Object.hasOwn(this.spawnFailures, code) ? (code as SpawnFailureCode) : "other";+ this.spawnFailures[known] += 1;+ if (known === "ENOENT" || known === "other") return;+ this.holdUntil = this.now() + SHORTAGE_HOLD_MS;+ if (known === "EAGAIN") {+ const { max, current } = this.state();+ if (current !== null && typeof max !== "number") {+ const first = this.learned === null;+ this.learned = { limit: Math.min(this.learned?.limit ?? Infinity, Math.max(64, current)), at: this.now() };+ if (first) this.log(`a spawn was refused (EAGAIN) with ${current} processes and threads running; new work now waits below that count`);+ }+ }+ this.refused?.();+ }++ noteForceKilled(): void { this.forceKilled += 1; }+ noteLateReaped(): void { this.lateReaped += 1; }++ counts(): ProcessCounts {+ return { limit: this.limit(), spawnFailed: { ...this.spawnFailures }, forceKilled: this.forceKilled, lateReaped: this.lateReaped };+ }+}++export const processBudget = new ProcessBudget();++/** The threads of every browser process (Chromium, Firefox, agent-browser) /proc shows; null where none can be read. */+export function browserTasksNow(rows: readonly ProcessRow[] = linuxProcessList().rows): number | null {+ if (!rows.length) return null;+ return rows.reduce((sum, row) => sum + (nameBucket(row.name) === "browser" || row.name === "agent-browser" ? row.threads ?? 1 : 0), 0);+}++/** What one engine's process tree is doing: CPU used so far (its own, its descendants', and its exited children's) and how+ * many descendants still run. */+export interface TreeUse { cpuMs: number; children: number }++/** The tree under `pid` by parent, from /proc; null where it can't be read (not Linux) or the process is gone. */+export function linuxTreeUse(pid: number, rows: () => readonly ProcessRow[] = () => linuxProcessList().rows,+ reapedMs: (pid: number) => number | null = (of) => { try { return parseReapedChildrenMs(readFileSync(`/proc/${of}/stat`, "utf8")); } catch { return null; } }): TreeUse | null {+ const below = new Map<number, ProcessRow[]>();+ let root: ProcessRow | undefined;+ for (const row of rows()) {+ if (row.pid === pid) root = row;+ else below.set(row.ppid, [...below.get(row.ppid) ?? [], row]);+ }+ if (!root) return null;+ let cpuMs = root.cpuMs + (reapedMs(pid) ?? 0), children = 0;+ const seen = new Set([pid]), queue = [...below.get(pid) ?? []];+ for (let row = queue.pop(); row; row = queue.pop()) {+ if (seen.has(row.pid)) continue;+ seen.add(row.pid);+ cpuMs += row.cpuMs;+ if (row.state !== "Z" && row.state !== "X") children += 1;+ queue.push(...below.get(row.pid) ?? []);+ }+ return { cpuMs, children };+}++export type TurnsSetting = number | "auto" | "off";++/** OMB_TURNS_MAX_RUNNING: a whole number of turns at once; "off" or 0 for no gate at all; "auto", unset or anything else+ * for a number worked out from the server's memory and pids limit. */+export function turnsSetting(value: string | undefined): TurnsSetting {+ const text = value?.trim().toLowerCase();+ if (text === "off" || text === "0") return "off";+ return text && /^\d+$/.test(text) ? Number(text) : "auto";+}++export type GateHost = "cloud" | "server" | null;++/** Where turns wait for room. A Cloud home, as before. A self-hosted Linux server in a container that was given a memory+ * or pids limit, which is where a turn too many ends in a killed engine or a refused spawn. Any self-hosted server whose+ * operator set OMB_TURNS_MAX_RUNNING to a number or "auto". Never the desktop app's own server. */+export function gateHost(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform, limited: () => boolean = containerLimited): GateHost {+ if ((env.OMB_CLOUD_ROLE === "home" || env.OMB_CLOUD_ROLE === "team") && platform === "linux") return "cloud";+ if (env.OMB_DESKTOP_PARENT === "1") return null;+ const setting = turnsSetting(env.OMB_TURNS_MAX_RUNNING);+ if (setting === "off") return null;+ if (typeof setting === "number" || env.OMB_TURNS_MAX_RUNNING?.trim().toLowerCase() === "auto") return "server";+ return platform === "linux" && limited() ? "server" : null;+}diff --git a/server/process-shortage.ts b/server/process-shortage.tsnew file mode 100644index 0000000000..020e45b9be--- /dev/null+++ b/server/process-shortage.ts@@ -0,0 +1,34 @@+// A spawn the operating system refused for want of room (a container's pids limit, open files, memory) is this server's+// shortage, never the AI's failure: nothing was sent to a model, so nothing is retried on one or handed to a backup.+import { engineFailureKind } from "./drivers/engine-errors.ts";+import { classifyError } from "./drivers/retry.ts";+import { hostFaultOf } from "./host-fault.ts";++/** spawn(2)/fork(2) failures that mean "no room now": EAGAIN (the pids limit or RLIMIT_NPROC), EMFILE and ENFILE (open+ * files), ENOMEM. */+const SHORTAGE_CODES: ReadonlySet<string> = new Set(["EAGAIN", "EMFILE", "ENFILE", "ENOMEM"]);+export type ShortageCode = "EAGAIN" | "EMFILE" | "ENFILE" | "ENOMEM";++export function shortageCode(error: unknown): ShortageCode | null {+ const code = (error as { code?: unknown } | null)?.code;+ return typeof code === "string" && SHORTAGE_CODES.has(code) ? (code as ShortageCode) : null;+}++/** chat.notice.outOfProcesses's own words, and Node's error for a spawn it was refused, as a failure's first line. */+const NO_ROOM_NOTICE = /^There is no room to start another program \((?:EAGAIN|EMFILE|ENFILE|ENOMEM)\)/;+const SPAWN_REFUSED = /^(?:Error: )?(?:spawn failed: )?(?:posix_)?spawn(?:Sync)?\b[^\n]*\b(?:EAGAIN|EMFILE|ENFILE|ENOMEM)\b/;++/** Whether a failed turn's cause is the server's own refused spawn: the server's notice for it or Node's spawn error at the+ * head of the failure. Never an engine that exited on its own, whatever its stderr tail says (a file watcher's "EMFILE: too+ * many open files, watch"): that engine ran, and its turn may still go to a backup AI. */+export const outOfProcesses = (cause: string): boolean => NO_ROOM_NOTICE.test(cause) || SPAWN_REFUSED.test(cause);++const OWN_CAUSES: ReadonlySet<string> = new Set(["auth", "quota", "unknown_model", "provider_safety"]);++/** Whether a failure names its own cause (a usage limit, a sign-in, the provider's refusal, a tool server, a full disk): it+ * is never relabelled as the server's shortage, though one was seen during the same turn. */+export function namesOwnCause(failure: string): boolean {+ if (engineFailureKind(failure) !== null || OWN_CAUSES.has(classifyError({ text: failure }).reason)) return true;+ const fault = hostFaultOf(failure);+ return fault === "signed_out" || fault === "tool_server" || fault === "disk_full";+}diff --git a/server/procs-spawn-refused.test.ts b/server/procs-spawn-refused.test.tsnew file mode 100644index 0000000000..4cb8eae831--- /dev/null+++ b/server/procs-spawn-refused.test.ts@@ -0,0 +1,40 @@+import { afterEach, describe, expect, it, vi } from "vitest";++const refusal = vi.hoisted(() => ({ code: null as string | null }));+vi.mock("node:child_process", async (actual) => {+ const real = await actual<typeof import("node:child_process")>();+ return {+ ...real,+ spawn: (...args: Parameters<typeof real.spawn>) => {+ // Node throws some refusals (ENOMEM) from spawn itself rather than reporting them on the child.+ if (refusal.code) throw Object.assign(new Error(`spawn ${refusal.code}`), { code: refusal.code, errno: -12, syscall: "spawn" });+ return real.spawn(...args);+ },+ };+});++const { engineMemory } = await import("./engine-memory.ts");+const { processBudget } = await import("./process-room.ts");+const { spawnCli } = await import("./procs.ts");++describe("a spawn Node refuses by throwing", () => {+ afterEach(() => { refusal.code = null; vi.restoreAllMocks(); });++ it("is counted as a refused spawn, by its code, and told to the turn's gate as its engine's, then thrown on", () => {+ const told = vi.spyOn(engineMemory, "spawnRefused");+ const before = processBudget.counts().spawnFailed.ENOMEM;+ refusal.code = "ENOMEM";+ expect(() => spawnCli(process.execPath, ["-e", ""], { stdio: ["pipe", "pipe", "pipe"] }, "bot")).toThrow(/ENOMEM/);+ expect(processBudget.counts().spawnFailed.ENOMEM).toBe(before + 1);+ expect(told).toHaveBeenCalledWith("ENOMEM", true);+ expect(() => spawnCli(process.execPath, ["-e", ""], { stdio: ["pipe", "pipe", "pipe"] })).toThrow(/ENOMEM/);+ expect(told).toHaveBeenLastCalledWith("ENOMEM", false);+ });++ it("counts nothing for a throw that is no shortage", () => {+ const before = processBudget.counts().spawnFailed;+ refusal.code = "ERR_INVALID_ARG_VALUE";+ expect(() => spawnCli(process.execPath, ["-e", ""], { stdio: ["pipe", "pipe", "pipe"] })).toThrow();+ expect(processBudget.counts().spawnFailed).toEqual(before);+ });+});diff --git a/server/procs.ts b/server/procs.tsindex e0e1be7d0d..45dab9c20b 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -21,6 +21,9 @@ import { engineHomes } from "./engine-homes/engine-homes.ts";import type { HomedSpawn } from "./engine-homes/layout.ts";import { resolveCliSpawn, type ResolvedSpawn } from "./env-path.ts";import { spawnBotWork } from "./oom-score.ts";+import { noticeFailure } from "./chat-notices.ts";+import { processBudget } from "./process-room.ts";+import { shortageCode } from "./process-shortage.ts";export function resolveCli(cli: string, args: string[] = [], env?: NodeJS.ProcessEnv): ResolvedSpawn {return resolveCliSpawn(cli, args, env);@@ -169,6 +172,24 @@ function linuxDescendantsStopped(child: ChildProcess): boolean {return true;}+/** Whether every process still in this group has exited and only waits to be collected. Where nothing collects orphans+ * (Node as a container's process 1) such members stay for good, and kill(-pgid, 0) goes on succeeding for them. False+ * when a member runs, when none is found, or when /proc can't say. */+export function linuxGroupOnlyExited(group: number, list: () => string[] = () => readdirSync("/proc"), stat: (pid: number) => string = (pid) => readFileSync(`/proc/${pid}/stat`, "utf8")): boolean {+ let entries: string[];+ try { entries = list(); } catch { return false; }+ let members = 0;+ for (const entry of entries) {+ if (!/^\d+$/.test(entry)) continue;+ let fields: string[];+ try { const text = stat(Number(entry)); fields = text.slice(text.lastIndexOf(")") + 2).split(" "); } catch { continue; }+ if (Number(fields[2]) !== group) continue;+ if (fields[0] !== "Z" && fields[0] !== "X") return false;+ members += 1;+ }+ return members > 0;+}+function linuxRootIdentityMatches(child: ChildProcess): boolean | undefined {const start = child.pid && linuxTrees.get(child)?.get(child.pid);if (!child.pid || process.platform !== "linux" || !cliGroups.has(child)) return true;@@ -297,12 +318,19 @@ export function spawnCli(...(process.platform === "win32" ? { windowsHide: true } : { detached: true }),}) as ChildProcessByStdio<Writable, Readable, Readable>;let child: ChildProcessByStdio<Writable, Readable, Readable>;+ const refused = (code: string | undefined) => { processBudget.spawnFailed(code); engineMemory.spawnRefused(code, owner === "bot"); };try {child = owner === "bot" || botWork ? spawnBotWork(start) : start();+ } catch (error) {+ // Node throws some refusals (ENOMEM) at once rather than reporting them on the child.+ if (shortageCode(error)) refused((error as NodeJS.ErrnoException).code);+ throw error;} finally {for (const fd of boxed?.extraFds ?? []) try { closeSync(fd); } catch {}}rememberLiveSpawn(child, [resolved.command, ...resolved.args]);+ // Node reports most refused spawns (EAGAIN, EMFILE, ENOENT) on the child, a tick later, with no pid.+ child.once("error", (error: NodeJS.ErrnoException) => { if (!child.pid) refused(error.code); });// The broker token minted for this process dies with it.if (boxed?.token) child.once("exit", boxed.release);if (process.platform !== "win32") cliGroups.add(child);@@ -433,9 +461,11 @@ export function cliVersionReader(cli: string): (err: Error | null, stdout: strin}/** Node reports a missing cwd as the CLI's own ENOENT, so pass `cwd` to tell a moved folder from a missing CLI. */-type SpawnFailure = { message: string; setup: boolean };+type SpawnFailure = { message: string; setup: boolean; text?: ReturnType<typeof noticeFailure>["text"] };export function describeSpawnFailure(err: NodeJS.ErrnoException, cli: string, cwd?: string): SpawnFailure {+ const shortage = shortageCode(err);+ if (shortage) return { ...noticeFailure("chat.notice.outOfProcesses", { code: shortage }), setup: false };if (err.code === "ENOENT") {if (cwd && !existsSync(cwd))return { message: `This chat's working folder no longer exists: ${cwd}. Choose another folder in the bot's settings, or create it again.`, setup: false };@@ -477,7 +507,7 @@ async function stopCliTree(child: ChildProcess, pid: number, timeoutMs: number):if (linuxRootIdentityMatches(child) === undefined) return false;try {process.kill(-pid, 0);- return false;+ return process.platform === "linux" && linuxGroupOnlyExited(pid);} catch (error) {// EPERM and other failures do not prove that the group is gone.return (error as NodeJS.ErrnoException).code === "ESRCH";@@ -509,8 +539,10 @@ async function stopCliTree(child: ChildProcess, pid: number, timeoutMs: number):return true;};if (settled()) return true;+ if (exited()) processBudget.noteLateReaped();signal("SIGTERM");if (await wait(timeoutMs)) return true;+ processBudget.noteForceKilled();signal("SIGKILL");return wait(1_000);}diff --git a/server/routine-recovery.ts b/server/routine-recovery.tsindex 334aa1691b..9fc1c55c0e 100644--- a/server/routine-recovery.ts+++ b/server/routine-recovery.ts@@ -10,6 +10,7 @@ import { isCountedSkip, type RoutineRetryCause } from "../shared/routines.ts";import { engineFailureKind } from "./drivers/engine-errors.ts";import { classifyError } from "./drivers/retry.ts";import { hostFaultOf, retryCannotFix } from "./host-fault.ts";+import { outOfProcesses } from "./process-shortage.ts";import { nextOccurrence } from "./routine-schedules.ts";import type { Routine, RoutineRun } from "./routines.ts";import { codedLine, fittedLine, type RoutineLine, type RoutineLineKey } from "./routine-lines.ts";@@ -93,7 +94,8 @@ const FIRST_START: Record<RoutineRetryCause, string> = {* stop someone pressed or typed, a refusal, a spent cap, and a fault a second start would meet again (no process could* start, a full disk, a tool server that is down). Routine runs and teammate threads both judge by this. */export function classifyRoutineFailure(failure: string, facts: RoutineFailureFacts = {}): RoutineFailureClass {- if (facts.cause === "busy") return { kind: "busy" };+ // The server had no room to start the run's engine: the run waits and starts again, as for a busy bot.+ if (facts.cause === "busy" || outOfProcesses(failure)) return { kind: "busy" };if (facts.cause === "stalled" || facts.cause === "cap") return { kind: "final" };if (facts.stopReason && NOT_RETRIED_STOPS.has(facts.stopReason)) return { kind: "final" };if (classifyContinuable(facts.stopReason, failure) === "cap") return { kind: "final" };@@ -217,8 +219,9 @@ export function recoverRun(run: RoutineRun, failure: string, facts: RoutineFailu};if (verdict.kind === "busy") {run.deferredAt ??= now;- // A run of checked items waits as long as it takes: its bot is busy with the person, which is not a failure.- if (now - run.deferredAt >= ROUTINE_BUSY_WAIT_MS && run.checkKey === undefined) return failed(codedLine("error", "routines.server.stillBusy", { minutes: ROUTINE_BUSY_WAIT_MS / 60_000, failure }));+ // A run of checked items waits as long as its bot is busy with the person, which is not a failure; a server with no room+ // to start it is held to the same hour as any other run.+ if (now - run.deferredAt >= ROUTINE_BUSY_WAIT_MS && (run.checkKey === undefined || outOfProcesses(failure))) return failed(codedLine("error", "routines.server.stillBusy", { minutes: ROUTINE_BUSY_WAIT_MS / 60_000, failure }));run.status = "queued";run.retryAt = now + ROUTINE_BUSY_RECHECK_MS;attend(run, codedLine("attention", "routines.server.waitingToStart", { failure }));diff --git a/src/locales/de.json b/src/locales/de.jsonindex c8c0a00ffe..b10eccf852 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -217,6 +217,11 @@"server.memory.starter": "Starter hat Platz für etwa eine Aufgabe gleichzeitig. Ein größerer Plan führt mehr gleichzeitig aus.","server.planTurns.wait": "Wartet auf einen Platz: Starter führt auf dieser Cloud {limit} Aufgaben gleichzeitig aus. Davor in der Reihe: {ahead}. Es startet von selbst, sobald eine fertig ist, und ein größerer Plan führt mehr gleichzeitig aus.","server.planTurns.still": "Wartet noch: Starter führt {limit} Aufgaben gleichzeitig aus. Davor in der Reihe: {ahead}.",+ "server.room.wait": "Wartet auf Platz auf diesem Server. Läuft gerade: {running}. Davor in der Reihe: {ahead}. Startet von selbst, sobald Platz ist.",+ "server.room.still": "Wartet weiter auf Platz auf diesem Server. Läuft gerade: {running}. Davor in der Reihe: {ahead}.",+ "server.room.turns": "Wartet auf einen Platz: Dieser Server führt {limit} Aufgaben gleichzeitig aus. Davor in der Reihe: {ahead}. Es startet von selbst, sobald eine fertig ist.",+ "server.room.turnsStill": "Wartet noch: Dieser Server führt {limit} Aufgaben gleichzeitig aus. Davor in der Reihe: {ahead}.",+ "chat.notice.outOfProcesses": "Es ist kein Platz, um ein weiteres Programm zu starten ({code}), deshalb konnte diese Aufgabe nicht laufen. An die KI wurde nichts gesendet. Sie startet von selbst neu, sobald Platz ist.","server.botPaused": "Pausiert: Starter hält {limit} Bots wach. Führe ein Upgrade durch, um ihn zu wecken, oder tausche, welche Bots wach sind.","server.botHeld": "{bot} ist pausiert und nimmt keine neue Arbeit an. Setze ihn über sein Menü in der Seitenleiste fort.","server.botHeldDepartment": "{bot} ist mit der Abteilung {department} pausiert und nimmt keine neue Arbeit an. Setze die Abteilung über ihr Menü in der Seitenleiste fort.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex f6f3906526..74e9e18f52 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -353,6 +353,10 @@"server.memory.starter": "Starter has room for about one task at a time. A bigger plan runs more at once.","server.planTurns.wait": "Waiting for a turn: Starter runs {limit} tasks at once on this Cloud. Ahead of this one: {ahead}. It starts by itself when one finishes, and a bigger plan runs more at once.","server.planTurns.still": "Still waiting: Starter runs {limit} tasks at once. Ahead of this one: {ahead}.",+ "server.room.wait": "Waiting for room on this server. Running now: {running}. Ahead of this one: {ahead}. It starts by itself when there's room.",+ "server.room.still": "Still waiting for room on this server. Running now: {running}. Ahead of this one: {ahead}.",+ "server.room.turns": "Waiting for a turn: this server runs {limit} tasks at once. Ahead of this one: {ahead}. It starts by itself when one finishes.",+ "server.room.turnsStill": "Still waiting: this server runs {limit} tasks at once. Ahead of this one: {ahead}.","server.botPaused": "Paused: Starter keeps {limit} bots awake. Upgrade to wake it, or swap which bots are awake.","server.botHeld": "{bot} is paused, so it takes no new work. Resume it from its menu in the sidebar.","server.botHeldDepartment": "{bot} is paused with the {department} department, so it takes no new work. Resume the department from its menu in the sidebar.",@@ -10302,6 +10306,7 @@"chat.notice.memoryReclaimedTask": "Ran out of room, so I stopped this task to keep everything else running.","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.","server.personFirst.stoppedSeconds": "Stopped a step that had run for {seconds} s, to answer you first","server.personFirst.stoppedMinutes": "Stopped a step that had run for {minutes} min, to answer you first","server.runOwner.onlyAskerStops": "Only {name} or an admin can stop this.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 9f0d3da90e..0d96832a35 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -336,6 +336,10 @@"server.memory.starter": "O Starter tem capacidade para cerca de uma tarefa por vez. Um plano maior roda mais tarefas ao mesmo tempo.","server.planTurns.wait": "Aguardando a vez: o Starter roda {limit} tarefas ao mesmo tempo nesta Cloud. À frente desta: {ahead}. Ela começa sozinha quando uma terminar, e um plano maior roda mais ao mesmo tempo.","server.planTurns.still": "Ainda aguardando: o Starter roda {limit} tarefas ao mesmo tempo. À frente desta: {ahead}.",+ "server.room.wait": "Aguardando espaço neste servidor. Tarefas em execução: {running}. À frente desta: {ahead}. Ela começa sozinha quando houver espaço.",+ "server.room.still": "Ainda aguardando espaço neste servidor. Tarefas em execução: {running}. À frente desta: {ahead}.",+ "server.room.turns": "Aguardando a vez: este servidor roda {limit} tarefas ao mesmo tempo. À frente desta: {ahead}. Ela começa sozinha quando uma terminar.",+ "server.room.turnsStill": "Ainda aguardando: este servidor roda {limit} tarefas ao mesmo tempo. À frente desta: {ahead}.","server.botPaused": "Pausado: o Starter mantém {limit} bots ativos. Faça upgrade para ativá-lo ou troque quais bots ficam ativos.","server.botHeld": "{bot} está pausado e não recebe trabalho novo. Retome-o pelo menu dele na barra lateral.","server.botHeldDepartment": "{bot} está pausado junto com o departamento {department} e não recebe trabalho novo. Retome o departamento pelo menu dele na barra lateral.",@@ -10214,6 +10218,7 @@"chat.notice.memoryReclaimedTask": "Faltou memória, então interrompi esta tarefa para manter o restante funcionando.","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.","server.personFirst.stoppedSeconds": "Interrompi um passo que já durava {seconds} s para responder a você primeiro","server.runOwner.onlyAskerStops": "Só {name} ou um administrador pode interromper isto.","server.runOwner.notYourQueued": "Só quem enviou esta mensagem pode removê-la.",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex b85301a3b8..571aeb5961 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -3336,6 +3336,11 @@"computer.problem.localHyprlandPlugin": "1311e4bdddbde6a209aa2fd0aa99af48183eb734d1a3eee207fbc4ff650c5855","server.planTurns.wait": "4dbae7d3d46768148b7a5b4aabef68fef270cdbbd76cf03d22f8a5be747faef0","server.planTurns.still": "51775f0db963d196a61bc2e5ccf974e2349b05b9577304f16eea007555bc0904",+ "server.room.wait": "221a8b208fb0d422501142a2ddd78e86b60a22730fba6423293438d770645555",+ "server.room.still": "2ab8db3821e55f07ade15cecd95f296010c4b39f5c8828a34b3dfff525171b7b",+ "server.room.turns": "22d3991e5e5089d0ec7c8997863b7172c73e1bc0bbaf9dc96febeaae98e02d0b",+ "server.room.turnsStill": "02e83aa50e246a76d138335f0ba4d12c15efc909de572cb1a27be7ccaee2307f",+ "chat.notice.outOfProcesses": "7dd799040935793afd9a12757698c404c5b9d9a83d9a749dda145d05607a5a85","server.botPaused": "44a1a67145a3178073e8dd5ecbc95a7bba0e9bdb2a4daca56b58c81c0a5a9105","botLimit.tasks.title": "406225acaae475dfba01e5670171a780563961c82f6cb05f9c74eed8d564c373","botLimit.tasks.body": "8858c581592229bb8a2c27d0c646c80294e5832f15be671067eda856926b55b1",@@ -35430,6 +35435,7 @@"chat.notice.memoryReclaimedTask": "dba7fcaec67b6efec3b4a221c8e1b2db7d3036d17c3aced17417ff186e774354","chat.notice.memoryReclaimedBrowserDetail": "29c781b36ba9bc63c701f8ac7c9488b0b116430c3e400ceaa51694c41e3d9050","chat.notice.memoryReclaimedTaskDetail": "8692d2880c5425cd005f7002561ae2d7850e41209d0dcf40b1e098a9ea1725f8",+ "chat.notice.outOfProcesses": "7dd799040935793afd9a12757698c404c5b9d9a83d9a749dda145d05607a5a85","server.personFirst.stoppedSeconds": "9ccef9cb0269e710e1fb314a11834a4033b48d66cb54ca6b38e8c7a2fdcb9a8a","server.personFirst.stoppedMinutes": "b36afce574a81b8dfc9a4141f280973c6ca5fa7ef4ae008045494b31622ce387","server.routines.held.planCancelled": "8a6b13354ba469ae192bc6f6e65a0e40689ade9798eafb23136f6dfdb8a2db48",@@ -35854,6 +35860,10 @@"computer.problem.localHyprlandPlugin": "1311e4bdddbde6a209aa2fd0aa99af48183eb734d1a3eee207fbc4ff650c5855","server.planTurns.wait": "4dbae7d3d46768148b7a5b4aabef68fef270cdbbd76cf03d22f8a5be747faef0","server.planTurns.still": "51775f0db963d196a61bc2e5ccf974e2349b05b9577304f16eea007555bc0904",+ "server.room.wait": "221a8b208fb0d422501142a2ddd78e86b60a22730fba6423293438d770645555",+ "server.room.still": "2ab8db3821e55f07ade15cecd95f296010c4b39f5c8828a34b3dfff525171b7b",+ "server.room.turns": "22d3991e5e5089d0ec7c8997863b7172c73e1bc0bbaf9dc96febeaae98e02d0b",+ "server.room.turnsStill": "02e83aa50e246a76d138335f0ba4d12c15efc909de572cb1a27be7ccaee2307f","server.botPaused": "44a1a67145a3178073e8dd5ecbc95a7bba0e9bdb2a4daca56b58c81c0a5a9105","botLimit.tasks.title": "406225acaae475dfba01e5670171a780563961c82f6cb05f9c74eed8d564c373","botLimit.tasks.body": "8858c581592229bb8a2c27d0c646c80294e5832f15be671067eda856926b55b1",