Skip to content

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

fix(docker): the server image brings its own init, and Chrome copes with a small /dev/shm (#6160)

Milind Sonia144ecb826a7
diff --git a/Dockerfile b/Dockerfile
index 028d0bc881..b6c5486b67 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -20,10 +20,15 @@
# ...) and OpenMausBot's own state (~/.openmausbot) persist across container
# restarts.
#
-# A plain `docker run` of either image wants `--init --shm-size=512m`, as the
-# compose files set: the bots' browsers leave exited processes for an init to
-# collect, and Chrome needs shared memory (docs/browser-packaging.md, "Process
-# hygiene"). On Fly Machines (the Cloud home) Fly's own init is PID 1.
+# The bots' browsers, engines and shells leave exited processes for an init to
+# collect (docs/browser-packaging.md, "Process hygiene"). The server image
+# brings its own, tini, as its entrypoint: a container platform runs an image
+# with no `--init`, and Node as PID 1 waits only for its own children, so the
+# rest stay as zombies until the container's pids limit refuses every spawn.
+# The compose files' `init: true` on top of it is harmless. The Cloud home
+# has no entrypoint: Fly's own init is PID 1 there, and a plain `docker run`
+# of that image wants `--init`. Chrome keeps its shared memory out of a small
+# /dev/shm by itself (server/browser/chrome/shm.ts).
FROM caddy:2.10.2 AS edge
# Official Caddy carries a privileged-port file capability. The Cloud home's
@@ -74,9 +79,10 @@ RUN arch=x64 && if [ "$TARGETARCH" = arm64 ]; then arch=arm64; fi \
FROM node:24-bookworm-slim AS runtime
# Install Chrome's Bookworm libraries directly: agent-browser --with-deps
# invokes sudo even as root, and this image deliberately does not ship sudo.
-# git + curl: agent CLIs shell out to git; curl backs the healthcheck
+# git + curl: agent CLIs shell out to git; curl backs the healthcheck. tini is
+# the server image's init, and what its launcher falls back to as PID 1.
RUN apt-get update \
- && apt-get install -y --no-install-recommends ca-certificates curl git \
+ && apt-get install -y --no-install-recommends ca-certificates curl git tini \
libxcb-shm0 libx11-xcb1 libx11-6 libxcb1 libxext6 libxrandr2 \
libxcomposite1 libxcursor1 libxdamage1 libxfixes3 libxi6 libgtk-3-0 \
libpangocairo-1.0-0 libpango-1.0-0 libatk1.0-0 libcairo-gobject2 \
@@ -254,4 +260,7 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
# The launcher runs dist-server/index.js and starts it again when it asks to
# (a copied workspace committing, server/restart.ts), so the container, and a
# Caddy sharing its network, stays up through that restart.
+# -s: under `docker run --init` or compose's `init: true` tini is not PID 1,
+# and collects the server's orphans as a subreaper instead of warning.
+ENTRYPOINT ["/usr/bin/tini", "-s", "--"]
CMD ["node", "dist-server/server-launcher.js"]
diff --git a/docs/browser-packaging.md b/docs/browser-packaging.md
index abdbe880e2..e6b6645b09 100644
--- a/docs/browser-packaging.md
+++ b/docs/browser-packaging.md
@@ -235,18 +235,25 @@ same rules hold on the desktop, a server and Cloud:
environments, so there a Chrome whose daemon was killed is not found.
**Containers.** Chrome's helper processes need something to collect them
-once their parent exits, and Chrome needs shared memory. Both Docker compose
-files and the Podman one set `init: true` and `shm_size: 512m`, as
-OpenMausBot's desktop containers do (`--shm-size 512m`); a plain
-`docker run` wants `--init --shm-size=512m`. agent-browser 0.37.0 itself
-adds `--no-sandbox` and `--disable-dev-shm-usage` when it sees
-`/.dockerenv` or `/run/.containerenv`, runs as root or under CI, or finds
-docker, kubepods or lxc in `/proc/1/cgroup`. A runtime that shows none of
-these (a Kubernetes pod on cgroup v2, for one) needs `/dev/shm` room of its
-own (on Kubernetes, an `emptyDir` with `medium: Memory`). The image does
-not set `AGENT_BROWSER_ARGS`: OpenMausBot hands its browsers a curated
-environment that would not carry it. On Fly Machines (the Cloud home) Fly's
-own init runs as PID 1.
+once their parent exits, and Chrome needs shared memory. The server image
+brings both: tini is its entrypoint, so exited processes are collected on a
+host that passes no `--init` (a container platform), and a Chrome started
+where `/dev/shm` is under 512 MB, or missing, gets
+`--disable-dev-shm-usage`, which keeps its shared memory in `/tmp`. Both
+Docker compose files and the Podman one still set `init: true` and
+`shm_size: 512m`, as OpenMausBot's desktop containers do
+(`--shm-size 512m`); an init on top of the image's own is harmless. A
+server whose entrypoint was replaced, so that it is process 1 itself, says
+so in one line at start and starts itself again under the image's tini,
+which then stays process 1 for the life of the container.
+agent-browser 0.37.0 itself adds `--no-sandbox` and
+`--disable-dev-shm-usage` when it sees `/.dockerenv` or
+`/run/.containerenv`, runs as root or under CI, or finds docker, kubepods
+or lxc in `/proc/1/cgroup`; a runtime that shows none of these (a
+Kubernetes pod on cgroup v2, for one) is covered by the `/dev/shm` check.
+The Cloud home image has no entrypoint of its own: on Fly Machines Fly's
+init runs as PID 1, and a plain `docker run` of that image wants `--init`.
+See [Running on a container platform](self-hosting.md#running-on-a-container-platform-railway-render-kubernetes-cloud-run).
## Video recording
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index cefe068b24..08407b6bb8 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -430,6 +430,86 @@ across code changes. To pick up the current ones, rebuild with a new tag:
docker compose build --build-arg CHROME_CACHE_TAG=$(date +%F) omb && docker compose up -d
```
+## Running on a container platform (Railway, Render, Kubernetes, Cloud Run)
+
+These platforms run the image's own command, with no `--init`, and usually
+with a 64 MB `/dev/shm` and a limit on how many processes the container may
+hold. The server image (`ghcr.io/milind-soni/openmausbot`) is built for that:
+
+- **It brings its own init.** tini is the image's entrypoint and collects
+ the processes that bots' engines, browsers and shell commands leave behind.
+ Without one they stay in the process table as zombies until the container's
+ limit is reached, and then nothing new can start: bots fail with
+ `spawn EAGAIN`. Keep the image's entrypoint when you set a start command.
+ If your platform replaces it, the server says so in one line at start and
+ starts itself again under the image's tini, which then stays process 1; an
+ init of the platform's own on top (`docker run --init`, Compose's
+ `init: true`) does no harm. A command you give the container runs as
+ written, so start it with `openmausbot …` or `node …`
+ (`docker run --rm ghcr.io/milind-soni/openmausbot openmausbot --version`):
+ a bare `--version` or `dist-server/openmausbot.js`, which older images
+ passed on to Node, no longer starts.
+- **Chrome does not need a larger `/dev/shm`.** Where `/dev/shm` is under
+ 512 MB the bots' browser keeps its shared memory in `/tmp`, so there is
+ nothing to set. `/tmp` is slower, and where it is itself in memory (Cloud
+ Run) it counts against the container's memory limit; a 512 MB `/dev/shm`,
+ where your platform lets you set one, avoids both.
+- **Mount a volume at `/data`.** Engine sign-ins and all of OpenMausBot's
+ state live there.
+- **Give the platform a way in.** The server listens on `127.0.0.1` inside
+ the container, which a proxy outside the container cannot reach. Any one
+ of these works:
+ - `OMB_LAN=1`: the server listens on every IPv4 address, on `OMB_PORT`
+ (8799 unless you set it; point the platform there). It still drops any
+ connection whose either end is not a private address (10/8, 172.16/12,
+ 192.168/16, 100.64/10, link-local), so it answers a proxy that reaches
+ the container over a private network, such as an ingress controller
+ inside a Kubernetes cluster, and refuses one that arrives from a public
+ address: check which your platform's does. Every request through it is
+ a remote one and has to pair.
+ - A proxy next to the server (a sidecar in the same Kubernetes pod or
+ Cloud Run service): share an in-memory volume between the two, set
+ `OMB_TUNNEL_SOCKET` to a socket in it, and point the proxy at that
+ socket, as [the Compose setup](#docker-with-https-on-your-own-domain)'s
+ Caddy does. A sidecar can reach `127.0.0.1:8799` too, but then it must
+ add `X-Forwarded-For` to every request (Caddy does): a loopback request
+ with no forwarding header and a loopback `Host` is taken to be the
+ server's owner.
+ - A tunnel that dials out, so nothing has to reach the container:
+ `openmausbot serve --tunnel` as the start command ([`--tunnel`](#ways-in-in-detail)).
+
+**How many processes and how much memory.** A container's process limit
+(`pids.max`; Docker's `--pids-limit`, Kubernetes' `podPidsLimit`) counts
+threads, not only processes, and every bot that is working holds an engine
+and the small helper programs that give it its tools:
+
+| What | Processes | Counted against the limit | Memory |
+| --- | --- | --- | --- |
+| The server itself | 3 | about 20 | about 1 GB |
+| Each bot that is working | 6 or more | about 45, more while it runs commands | about 700 MB |
+| Each open browser | about 13 | about 165 | about 400 MB |
+
+An engine stays loaded for ten minutes after its bot's last turn, so count
+the bots that work within the same ten minutes, not only in the same second.
+Leave room for the commands bots run: budget about 80 per working bot.
+
+| Bots working at once | Process limit to ask for | Memory |
+| --- | --- | --- |
+| 5 | 1,024 | 6 GB |
+| 10 | 2,048 | 10 GB |
+| 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.
+
+**Bots' cloud computers do not count.** A bot's cloud computer runs at the
+provider that hosts it, not in this container, so its desktop and browser
+use none of the container's processes or memory. Only the built-in browser
+described above runs here.
+
## From source
Requirements: Node 24+, pnpm, and at least one agent CLI installed and
diff --git a/scripts/docker-image.test.ts b/scripts/docker-image.test.ts
index b2182ad9e6..6f1fff0e23 100644
--- a/scripts/docker-image.test.ts
+++ b/scripts/docker-image.test.ts
@@ -153,12 +153,17 @@ describe("container images", () => {
expect(last(server, "USER")).toBe("maus");
expect(last(server, "VOLUME")).toBe('["/data"]');
expect(last(server, "CMD")).toBe('["node", "dist-server/server-launcher.js"]');
+ // A container platform runs the image with no --init: the image is its own.
+ expect(last(server, "ENTRYPOINT")).toBe('["/usr/bin/tini", "-s", "--"]');
+ expect(chain("runtime").find(step => step.op === "RUN" && step.args.includes("apt-get install"))!.args).toMatch(/ tini /);
expect(last(server, "HEALTHCHECK")).toContain("http://127.0.0.1:8799/api/health");
const home = chain("cloud-home");
expect(last(home, "USER")).toBe("root");
expect(last(home, "VOLUME")).toBe('["/data"]');
expect(last(home, "EXPOSE")).toBe("8080");
expect(last(home, "CMD")).toBe('["node", "/app/dist-server/cloud-home-start.js"]');
+ // Fly's init is PID 1 on a Cloud home, and its supervisor starts as root.
+ expect(last(home, "ENTRYPOINT")).toBeUndefined();
expect(last(home, "HEALTHCHECK")).toContain("http://127.0.0.1:8080/api/health");
expect(last(chain("runtime"), "ENV")).toMatch(/^AGENT_BROWSER_EXECUTABLE_PATH=\/opt\/openmausbot-browser\/chrome .*NODE_ENV=production$/);
});
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index d81fc571c3..08bd70b58c 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_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_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL",
+ "OMB_TTS_KEY", "OMB_TUNNEL_ORIGIN_PORT", "OMB_TUNNEL_SOCKET", "OMB_TURN_STALL_MS", "OMB_UNDER_IMAGE_INIT", "OMB_UPDATE_CHANNEL", "OMB_UPDATE_INSTALL",
"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/browser-engine.ts b/server/browser-engine.ts
index a1cd9379ea..59f717228f 100644
--- a/server/browser-engine.ts
+++ b/server/browser-engine.ts
@@ -13,6 +13,7 @@ import { BROWSER_VIEWPORT, viewportArgs, type PageSize } from "./browser-page-si
import { browserRuntimeEnv, ownsBrowserViewport } from "./browser-runtime.ts";
import { spawnBotWork } from "./oom-score.ts";
import { SIGN_IN_PROMPT } from "./system-prompt.ts";
+import { devShmIsSmall } from "./browser/chrome/shm.ts";
import { gateChromeSettings } from "./browser/egress/gate.ts";
import {
AGENT_BROWSER_VERSION,
@@ -581,6 +582,8 @@ export function agentBrowserIntegration(input: {
/** The Chrome OMB prepared for the engine to start (server/browser/chrome/launcher.ts); unused when attaching. */
launcher?: Record<string, string>;
dataDir?: string;
+ /** /dev/shm is too small for Chrome's shared memory; read from the host when absent. */
+ smallShm?: boolean;
}): { command: string; args: string[]; env: Record<string, string> } {
const sourceEnv = input.env ?? process.env;
const env: Record<string, string> = {
@@ -624,6 +627,8 @@ export function agentBrowserIntegration(input: {
const launch = { ...env, ...input.launcher };
// A kept profile's disk cache would otherwise grow to Chrome's default of several hundred megabytes per profile.
if (env.AGENT_BROWSER_PROFILE) launch.AGENT_BROWSER_ARGS = [launch.AGENT_BROWSER_ARGS, PROFILE_CACHE_ARG].filter(Boolean).join("\n");
+ // agent-browser 0.37 adds this itself only where it recognises Docker, and a container platform leaves no such mark.
+ if (input.smallShm ?? devShmIsSmall(input.platform ?? process.platform)) launch.AGENT_BROWSER_ARGS = [launch.AGENT_BROWSER_ARGS, "--disable-dev-shm-usage"].filter(Boolean).join("\n");
Object.assign(env, input.launcher, agentBrowserEgressEnv(launch, input.egressPort ?? 0, input.platform ?? process.platform));
}
return { command: input.binaryPath, args: ["mcp", "--tools", "core", "--no-webmcp"], env };
diff --git a/server/browser/chrome/flags.ts b/server/browser/chrome/flags.ts
index 4481f3c92e..e8448d196b 100644
--- a/server/browser/chrome/flags.ts
+++ b/server/browser/chrome/flags.ts
@@ -65,6 +65,8 @@ export interface ChromeFlagsInput {
viewport?: { width: number; height: number } | null;
/** False only when an operator explicitly turned Chrome's sandbox off. */
sandbox?: boolean;
+ /** /dev/shm is too small for Chrome's shared memory (shm.ts). */
+ smallShm?: boolean;
/** Null when session restore reopens the profile's tabs. */
startUrl?: string | null;
/** A window only: where it opens, e.g. parked off-screen. */
@@ -114,7 +116,7 @@ export function chromeArgs(input: ChromeFlagsInput): string[] {
// headless never shows: about 50 MB per browser.
if (headless) args.push("--mute-audio", "--disable-features=WebUIOmniboxPopup,WebUIOmniboxAimPopup,WebUIReloadButton");
if (input.host !== "desktop") args.push("--disk-cache-size=52428800");
- if (input.host === "container") args.push("--disable-dev-shm-usage");
+ if (input.host === "container" || input.smallShm) args.push("--disable-dev-shm-usage");
if (input.sandbox === false) args.push("--no-sandbox");
if (input.startUrl !== null) args.push(input.startUrl ?? "about:blank");
return args;
diff --git a/server/browser/chrome/launch.ts b/server/browser/chrome/launch.ts
index 544063c549..dee704506d 100644
--- a/server/browser/chrome/launch.ts
+++ b/server/browser/chrome/launch.ts
@@ -6,6 +6,7 @@ import { pipeTransport, type CdpTransport } from "../cdp/transport.ts";
import { chromeArgs, chromeEnv, type ChromeEnvInput, type ChromeFlagsInput } from "./flags.ts";
import { diagnoseLaunchFailure, type BrowserHostError } from "./host-setup.ts";
import type { ProcessRegistry } from "./processes.ts";
+import { devShmIsSmall } from "./shm.ts";
export interface LaunchOptions extends ChromeFlagsInput, Omit<ChromeEnvInput, "host"> {
/** A resolved Chrome or Chrome for Testing executable. */
@@ -98,7 +99,7 @@ function handshake(transport: CdpTransport, exited: Promise<ChromeExit>, timeout
/** Starts Chrome on --remote-debugging-pipe (fd 3 to Chrome, fd 4 back) and waits until it answers. */
export async function launchChrome(options: LaunchOptions): Promise<ChromeProcess> {
- const argv = chromeArgs(options);
+ const argv = chromeArgs({ ...options, smallShm: options.smallShm ?? devShmIsSmall() });
const env = chromeEnv(options.env ?? process.env, {
host: options.host,
timezone: options.timezone ?? null,
diff --git a/server/browser/chrome/shm.test.ts b/server/browser/chrome/shm.test.ts
new file mode 100644
index 0000000000..b4e978ee16
--- /dev/null
+++ b/server/browser/chrome/shm.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { chromeArgs } from "./flags.ts";
+import { devShmIsSmall } from "./shm.ts";
+
+const MB = 1024 * 1024;
+const shm = (bytes: number) => () => ({ blocks: bytes / 4096, bsize: 4096 });
+
+describe("a small /dev/shm", () => {
+ it("is one under the 512 MB the compose files give, or one that is missing; only Linux has it", () => {
+ expect(devShmIsSmall("linux", shm(64 * MB))).toBe(true);
+ expect(devShmIsSmall("linux", shm(511 * MB))).toBe(true);
+ expect(devShmIsSmall("linux", shm(512 * MB))).toBe(false);
+ expect(devShmIsSmall("linux", () => ({ blocks: 2_000_000n, bsize: 4096n }))).toBe(false);
+ expect(devShmIsSmall("linux", () => { throw Object.assign(new Error("no such file"), { code: "ENOENT" }); })).toBe(true);
+ for (const platform of ["darwin", "win32"] as const) {
+ expect(devShmIsSmall(platform, () => { throw new Error("never read"); })).toBe(false);
+ }
+ });
+
+ it("keeps Chrome's shared memory out of it on any host, not only where Docker left its mark", () => {
+ const args = (host: "server" | "desktop", smallShm: boolean) => chromeArgs({ userDataDir: "/p", mode: "headless", host, platform: "linux", smallShm });
+ expect(args("server", true)).toContain("--disable-dev-shm-usage");
+ expect(args("desktop", true)).toContain("--disable-dev-shm-usage");
+ expect(args("server", false)).not.toContain("--disable-dev-shm-usage");
+ expect(chromeArgs({ userDataDir: "/p", mode: "headless", host: "container", platform: "linux", smallShm: false })).toContain("--disable-dev-shm-usage");
+ });
+});
diff --git a/server/browser/chrome/shm.ts b/server/browser/chrome/shm.ts
new file mode 100644
index 0000000000..5d2c41bb7c
--- /dev/null
+++ b/server/browser/chrome/shm.ts
@@ -0,0 +1,18 @@
+import { statfsSync } from "node:fs";
+
+/** What the compose files give /dev/shm. Docker's default, and most container platforms', is 64 MB, which a Chrome page
+ * with large images or a video fills; Chrome then crashes the tab (crbug.com/736452). */
+const ROOMY_BYTES = 512 * 1024 * 1024;
+
+type Statfs = (path: string) => { blocks: number | bigint; bsize: number | bigint };
+
+/** True where Chrome should keep its shared memory out of /dev/shm (--disable-dev-shm-usage puts it in /tmp). */
+export function devShmIsSmall(platform: NodeJS.Platform = process.platform, statfs: Statfs = statfsSync): boolean {
+ if (platform !== "linux") return false;
+ try {
+ const stats = statfs("/dev/shm");
+ return Number(stats.blocks) * Number(stats.bsize) < ROOMY_BYTES;
+ } catch {
+ return true;
+ }
+}
diff --git a/server/container-init.test.ts b/server/container-init.test.ts
new file mode 100644
index 0000000000..c311f7d907
--- /dev/null
+++ b/server/container-init.test.ts
@@ -0,0 +1,72 @@
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it, vi } from "vitest";
+import { canRun, containerInit, execUnderInit, IMAGE_INIT, UNDER_IMAGE_INIT } from "./container-init.ts";
+
+const asOne = { pid: 1, platform: "linux" as const, execPath: "/usr/local/bin/node", execArgv: ["--max-old-space-size=3072"], argv: ["/usr/local/bin/node", "/app/dist-server/server-launcher.js", "--flag"] };
+
+describe("the server as a container's process 1", () => {
+ it("changes nothing behind an init, and nothing outside Linux", () => {
+ expect(containerInit({ pid: 7, platform: "linux", runnable: () => true, env: {} })).toEqual({ exec: null, line: null });
+ for (const platform of ["darwin", "win32"] as const) expect(containerInit({ ...asOne, platform, runnable: () => true, env: {} })).toEqual({ exec: null, line: null });
+ });
+
+ it("starts the launcher again under the image's tini, with its own flags, arguments and environment, and says so in one line", () => {
+ const init = containerInit({ ...asOne, runnable: (path) => path === IMAGE_INIT, env: { NODE_OPTIONS: "--enable-source-maps", OMB_DATA_DIR: "/data" } });
+ expect(init.exec).toEqual({
+ file: "/usr/bin/tini",
+ args: ["/usr/bin/tini", "--", "/usr/local/bin/node", "--max-old-space-size=3072", "/app/dist-server/server-launcher.js", "--flag"],
+ env: { NODE_OPTIONS: "--enable-source-maps", OMB_DATA_DIR: "/data", [UNDER_IMAGE_INIT]: "1" },
+ });
+ expect(init.line).toContain("process 1");
+ expect(init.line).toContain("docs/self-hosting.md");
+ expect(init.line).not.toContain("\n");
+ });
+
+ it("never starts itself again once it already has", () => {
+ const init = containerInit({ ...asOne, runnable: () => true, env: { [UNDER_IMAGE_INIT]: "1" } });
+ expect(init.exec).toBeNull();
+ expect(init.line).toContain("spawn EAGAIN");
+ expect(init.line).not.toContain("\n");
+ });
+
+ it("without tini only says what will happen and how to fix it", () => {
+ const init = containerInit({ ...asOne, runnable: () => false, env: {} });
+ expect(init.exec).toBeNull();
+ expect(init.line).toContain("spawn EAGAIN");
+ expect(init.line).toContain("--init");
+ expect(init.line).not.toContain("\n");
+ });
+
+ it("does not hand execve a tini it cannot run: Node 24 aborts the process when execve fails", () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-init-"));
+ try {
+ const plain = join(dir, "tini"), program = join(dir, "program");
+ writeFileSync(plain, "", { mode: 0o644 });
+ writeFileSync(program, "#!/bin/sh\n", { mode: 0o755 });
+ // Windows has no execute bit (X_OK checks only that the file exists), so a 0644 file counts there; the server
+ // only ever execs tini on Linux, where the bit is what Node 24's execve would trip on.
+ const refused = process.platform === "win32" ? [dir, "/dev/null", join(dir, "missing")] : [plain, dir, "/dev/null", join(dir, "missing")];
+ for (const file of refused) expect(canRun(file), file).toBe(false);
+ expect(canRun(program)).toBe(true);
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+ });
+
+ it("carries on without an init, in one line, when the exec is refused or this Node has none", () => {
+ const exec = { file: IMAGE_INIT, args: [IMAGE_INIT, "--", "node"], env: {} };
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ const refused = vi.fn(() => { throw Object.assign(new Error("EACCES: permission denied, execve '/usr/bin/tini'"), { code: "EACCES" }); });
+ execUnderInit(exec, refused as never);
+ expect(refused).toHaveBeenCalledWith(IMAGE_INIT, exec.args, exec.env);
+ execUnderInit(exec, null);
+ expect(warn).toHaveBeenCalledTimes(2);
+ for (const [line] of warn.mock.calls) {
+ expect(line).toContain("spawn EAGAIN");
+ expect(line).not.toContain("\n");
+ }
+ expect(warn.mock.calls[0]![0]).toContain("EACCES");
+ } finally { warn.mockRestore(); }
+ });
+});
diff --git a/server/container-init.ts b/server/container-init.ts
new file mode 100644
index 0000000000..95a45a6562
--- /dev/null
+++ b/server/container-init.ts
@@ -0,0 +1,58 @@
+import { accessSync, constants, statSync } from "node:fs";
+
+/** Debian's tini package, which the server image installs and names as its entrypoint. */
+export const IMAGE_INIT = "/usr/bin/tini";
+/** Set on the launcher run again under tini, so a launcher that is still process 1 there never runs itself again. */
+export const UNDER_IMAGE_INIT = "OMB_UNDER_IMAGE_INIT";
+const DOCS = 'docs/self-hosting.md, "Running on a container platform"';
+const NO_INIT = `nothing collects the processes bots leave behind, so they pile up until the container's process limit and bots fail to start ("spawn EAGAIN"). Start the container with an init (docker run --init, or tini as its entrypoint): ${DOCS}.`;
+
+export interface ContainerInit {
+ /** Replace this process with the image's tini running this same launcher (execve's file, argv and environment), so
+ * tini is process 1 for the life of the container; null when something else already collects exited processes. */
+ exec: { file: string; args: string[]; env: NodeJS.ProcessEnv } | null;
+ /** Said once at start, when this process found itself the container's process 1. */
+ line: string | null;
+}
+
+/** Linux hands a process whose parent exited to process 1 (or the nearest subreaper), which must wait() for it or it
+ * stays in the process table as a zombie and counts against the container's pids limit. Node waits only for the
+ * children it started itself, so as process 1 it hands that place to tini and runs as tini's child: tini then collects
+ * every orphan, across server restarts, and passes `docker stop` on. */
+export function containerInit(options: {
+ pid?: number; platform?: NodeJS.Platform; runnable?: (path: string) => boolean;
+ env?: NodeJS.ProcessEnv; execPath?: string; execArgv?: string[]; argv?: string[];
+} = {}): ContainerInit {
+ if ((options.platform ?? process.platform) !== "linux" || (options.pid ?? process.pid) !== 1) return { exec: null, line: null };
+ const env = options.env ?? process.env;
+ if (env[UNDER_IMAGE_INIT] === "1") return { exec: null, line: `OpenMausBot is still process 1 after starting under ${IMAGE_INIT}: ${NO_INIT}` };
+ if (!(options.runnable ?? canRun)(IMAGE_INIT)) return { exec: null, line: `OpenMausBot is process 1 in this container and has no init it can run (${IMAGE_INIT} is missing or not executable): ${NO_INIT}` };
+ const execPath = options.execPath ?? process.execPath, argv = options.argv ?? process.argv;
+ return {
+ exec: { file: IMAGE_INIT, args: [IMAGE_INIT, "--", execPath, ...(options.execArgv ?? process.execArgv), ...argv.slice(1)], env: { ...env, [UNDER_IMAGE_INIT]: "1" } },
+ line: `OpenMausBot is process 1 in this container: the image's entrypoint was replaced. It starts again under ${IMAGE_INIT}, so the processes bots leave behind are still collected (${DOCS}).`,
+ };
+}
+
+/** A regular file this user may execute (not on a noexec mount). Checked before execve because Node 24 aborts the
+ * whole process when execve fails, rather than throwing. */
+export function canRun(file: string): boolean {
+ try {
+ if (!statSync(file).isFile()) return false;
+ accessSync(file, constants.X_OK);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Runs `exec` and does not return; when it cannot (this Node has no execve, or the kernel refuses where Node throws),
+ * says why and carries on without an init. */
+export function execUnderInit(exec: NonNullable<ContainerInit["exec"]>, execve: ((file: string, args: string[], env: NodeJS.ProcessEnv) => never) | null = process.execve?.bind(process) ?? null): void {
+ try {
+ if (!execve) throw new Error("this Node cannot replace its own process");
+ execve(exec.file, exec.args, exec.env);
+ } catch (error) {
+ console.warn(`OpenMausBot could not start under ${exec.file} (${error instanceof Error ? error.message : String(error)}): ${NO_INIT}`);
+ }
+}
diff --git a/server/server-launcher.ts b/server/server-launcher.ts
index 69b0ba94e1..2e8eeeb75e 100644
--- a/server/server-launcher.ts
+++ b/server/server-launcher.ts
@@ -5,6 +5,7 @@ import { homedir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { boxMemory, heapSizeArgs, type BoxMemory } from "./box-memory.ts";
+import { containerInit, execUnderInit, UNDER_IMAGE_INIT } from "./container-init.ts";
import { clearRecordsFromEarlierRunOfThisContainer } from "./data-dir-lease.ts";
import { restartPolicy } from "./restart.ts";
@@ -52,6 +53,11 @@ function isEntry(): boolean {
}
if (isEntry()) {
+ // First, before anything this run would do twice: as process 1, hand that place to the image's tini.
+ const init = containerInit();
+ if (init.line) console.warn(init.line);
+ if (init.exec) execUnderInit(init.exec);
+ delete process.env[UNDER_IMAGE_INIT];
const dataDir = process.env.OMB_DATA_DIR || join(homedir(), ".openmausbot");
try {
// A container starts with nothing of its own running: a lease its earlier run left is a dead server's.