Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Server: cap idle warm engines, keep sleep out of stall counts, guard the data folder everywhere (#6773)
Milind Soni0792adcc7171
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex 87a7033b12..aa14c4399e 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -39,7 +39,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_FIRST_REPLY_NOTICE_MS", "OMB_FISH_AUDIO_API", "OMB_FISH_AUDIO_API_KEY", "OMB_FISH_LIVE_AGENT_ID", "OMB_FISH_LIVE_URL", "OMB_FLEET_SOCKET", "OMB_GATE_","OMB_GEMINI_API_KEY", "OMB_GEMINI_IMAGE_KEY", "OMB_GEMINI_LIVE_MODEL", "OMB_GEMINI_LIVE_URL", "OMB_GEMINI_TTS_API", "OMB_GOAL_WAIT_MAX_MS","OMB_GREENFERENCE_API_KEY", "OMB_GROQ_API_KEY", "OMB_HANDOFF_MAX_FAILURES", "OMB_HANDOFF_MAX_TURNS", "OMB_HELPER_INSTANCE", "OMB_HELPER_MODEL", "OMB_HOOKS", "OMB_HOOK_",- "OMB_HOSTED_", "OMB_HOSTED_MODELS", "OMB_HOSTED_MODEL_TOKEN", "OMB_HOSTED_MODEL_URL", "OMB_INSTALLATION_CREDENTIAL",+ "OMB_HOSTED_", "OMB_HOSTED_MODELS", "OMB_HOSTED_MODEL_TOKEN", "OMB_HOSTED_MODEL_URL", "OMB_IDLE_ENGINES_MAX", "OMB_INSTALLATION_CREDENTIAL","OMB_JEV_API_KEY", "OMB_LAN", "OMB_LICENSE_KEY", "OMB_LINUX_GPU", "OMB_LIVE_PROVIDER", "OMB_LOCAL_VM_UPDATE_WAIT_MS","OMB_LOOPBACK_TRUST", "OMB_LOOP_GUARD", "OMB_LOOP_GUARD_STOP_AT", "OMB_LOOP_GUARD_UNATTENDED_STOP_AT", "OMB_META_API_KEY", "OMB_MODELGO_API_KEY", "OMB_NETLIFY_API_URL", "OMB_OPENAI_API_KEY","OMB_OPENAI_IMAGE_KEY", "OMB_OPENAI_LIVE_KEY", "OMB_OPENAI_LIVE_URL", "OMB_OPENROUTER_API_KEY",diff --git a/server/cli.ts b/server/cli.tsindex 0d1f69f32c..bf1ee73cca 100644--- a/server/cli.ts+++ b/server/cli.ts@@ -41,7 +41,7 @@ import { defaultSetupIo, SetupCancelled, type SetupIo } from "./cli-prompts.ts";import { routeCli, usage } from "./cli-usage.ts"; import { savedSessionHeaders } from "./headless/saved-servers.ts";import { normalizePhoneOrigin, phonePairingInstructions, runPhoneSetup } from "./cli-phone-setup.ts";import { browserSignInLines, desktopOwnedRefusal, formatSessions, pairingBlock, RELAY_NOT_WITH_TUNNEL, relayPairingBlock, showRelayPairing } from "./cli-pairing.ts";-import { cliCommand, cliPrefix } from "./cli-invocation.ts";+import { cliCommand, cliPrefix } from "./cli-invocation.ts"; import { defaultDataDir, type DataHomes } from "./data-dir.ts";import { checkReach, envPublicUrl, lanProblem, localLinkBase, noRouteLines, publicUrlProblem, reachLines, waitForReach, type Route } from "./cli-reach.ts";import { lanUrl } from "./lan-address.ts";import { isLoopbackHost } from "../electron/server-address.mjs";@@ -124,7 +124,7 @@ export interface CliOptions {const COMMANDS = ["setup", "start", "serve", "pair", "sessions", "devices", "status", "login", "logout", "access", "service", "browser", "fleet", "help", "--help", "-h", "--version", "-v", "version"];-export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): CliOptions | { error: string } {+export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env, homes: DataHomes = {}): CliOptions | { error: string } {const implicitStart = !argv.length || (argv[0]!.startsWith("--") && argv[0] !== "--help" && argv[0] !== "--version");const [command = "start", ...rest] = implicitStart ? ["start", ...argv] : argv;if (!COMMANDS.includes(command)) {@@ -133,7 +133,7 @@ export function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env):const options: CliOptions = {command: command === "--help" || command === "-h" ? "help" : command === "--version" || command === "-v" ? "version" : command === "devices" ? "sessions" : (command as CliOptions["command"]),port: Number(env.OMB_PORT || 8799),- dataDir: env.OMB_DATA_DIR || join(homedir(), ".openmausbot"),+ dataDir: rest.includes("--data-dir") ? "" : defaultDataDir(env, homes.under, homes.realHome),tailscale: false,tunnel: false,client: false,diff --git a/server/config-cli.ts b/server/config-cli.tsindex a7ed1c6cfa..2b094092dc 100644--- a/server/config-cli.ts+++ b/server/config-cli.ts@@ -1,7 +1,7 @@-import { homedir } from "node:os";-import { join, resolve } from "node:path";+import { resolve } from "node:path";import { listConfigBackups, restoreConfigBackup } from "./config-backup.ts";+import { defaultDataDir, type DataHomes } from "./data-dir.ts";import { parseStoredConfig } from "./config.ts";import { parseJson } from "./schema.ts";@@ -47,12 +47,12 @@ function settingsProblem(text: string): string | null {}}-export function parseConfigArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): ConfigCliArgs | ConfigCliError {+export function parseConfigArgs(argv: string[], env: NodeJS.ProcessEnv = process.env, homes: DataHomes = {}): ConfigCliArgs | ConfigCliError {const json = argv.includes("--json");const help = argv.includes("--help") || argv.includes("-h");const dryRun = argv.includes("--dry-run");const fail = (error: string): ConfigCliError => ({ error, json });- let dataDir = env.OMB_DATA_DIR || join(homedir(), ".openmausbot");+ let dataDir = argv.includes("--data-dir") ? "" : defaultDataDir(env, homes.under, homes.realHome);let name: string | undefined;const words = argv.filter((arg) => arg !== "--json" && arg !== "--help" && arg !== "-h" && arg !== "--dry-run");const command = words[0];diff --git a/server/data-dir-entry-points.test.ts b/server/data-dir-entry-points.test.tsnew file mode 100644index 0000000000..e0ed0f5dd2--- /dev/null+++ b/server/data-dir-entry-points.test.ts@@ -0,0 +1,50 @@+import { join, resolve } from "node:path";+import { describe, expect, it } from "vitest";++import { parseArgs } from "./cli.ts";+import { parseConfigArgs } from "./config-cli.ts";+import type { DataHomes } from "./data-dir.ts";+import { parseSentinelArgs } from "./sentinel/cli.ts";+import { serverCommand } from "./server-launcher.ts";+import { handoffDir } from "./turn-continuation.ts";++const REAL = join("/fake-account", "person");+const ELSEWHERE = join("/fake-temp", "omb-test-home-1");+const PROFILE = join(REAL, ".openmausbot-profiles", "work");+const homes = (under: string): DataHomes => ({ under: () => under, realHome: () => REAL });+type Env = Record<string, string | undefined>;++const dataDirOf = (result: { dataDir: string } | { error: string }): string => {+ if ("error" in result) throw new Error(result.error);+ return result.dataDir;+};++const ENTRY_POINTS: Array<[string, (env: Env, home: string) => string, ((env: Env, home: string, given: string) => string) | null]> = [+ ["openmausbot", (env, home) => dataDirOf(parseArgs(["status"], env, homes(home))), (env, home, given) => dataDirOf(parseArgs(["status", "--data-dir", given], env, homes(home)))],+ ["openmausbot config", (env, home) => dataDirOf(parseConfigArgs(["backups"], env, homes(home))), (env, home, given) => dataDirOf(parseConfigArgs(["backups", "--data-dir", given], env, homes(home)))],+ ["openmausbot sentinel", (env, home) => dataDirOf(parseSentinelArgs(["--out", ELSEWHERE], env, homes(home))),+ (env, home, given) => dataDirOf(parseSentinelArgs(["--out", ELSEWHERE, "--data-dir", given], env, homes(home)))],+ ["the container launcher", (env, home) => dirOfCache(serverCommand("/app", env, { exists: () => true, box: { bytes: 4 * 1024 ** 3, cgroupLimit: null }, homes: homes(home) }).env), null],+ ["turn handoffs", (env, home) => resolve(handoffDir(env, homes(home)), ".."), null],+];+const dirOfCache = (env: Env) => resolve(env.OMB_SERVER_COMPILE_CACHE!, "..", "..");++describe.each(ENTRY_POINTS)("%s's data folder", (_name, resolvedAs, flagged) => {+ const resolved = (env: Env, home: string) => resolve(resolvedAs(env, home));+ it("is .openmausbot under the home in a normal run, and OMB_DATA_DIR (a desktop profile's folder) as given", () => {+ expect(resolved({}, REAL)).toBe(resolve(REAL, ".openmausbot"));+ expect(resolved({ NODE_ENV: "production" }, REAL)).toBe(resolve(REAL, ".openmausbot"));+ expect(resolved({ OMB_DATA_DIR: PROFILE }, REAL)).toBe(resolve(PROFILE));+ });++ it.each([{ VITEST: "true" }, { NODE_ENV: "test" }, { OMB_BENCH: "1" }])("refuses the real home's folder in a test or benchmark run: %o", (env) => {+ expect(() => resolved(env, REAL)).toThrow(/OMB_DATA_DIR is not set.*refusing to use the real data folder/);+ expect(resolved({ ...env, OMB_DATA_DIR: PROFILE }, REAL)).toBe(resolve(PROFILE));+ expect(resolved(env, ELSEWHERE)).toBe(resolve(ELSEWHERE, ".openmausbot"));+ });++ it.skipIf(!flagged)("takes --data-dir in a test run without looking at the home", () => {+ const given = join(ELSEWHERE, "data");+ expect(flagged!({ NODE_ENV: "test" }, REAL, given)).toBe(resolve(given));+ });+});diff --git a/server/data-dir.ts b/server/data-dir.tsindex ead4257ac4..6335e9c9ab 100644--- a/server/data-dir.ts+++ b/server/data-dir.ts@@ -15,6 +15,9 @@ export function dataHome(): string {type Env = Record<string, string | undefined>;+/** Where defaultDataDir looks: the home the folder goes under and the account's own home. Tests give both. */+export interface DataHomes { under?: () => string; realHome?: () => string | null }+/** What marks this process as a test or a benchmark, if anything does. */export function testRunSignal(env: Env): string | null {if (env.VITEST !== undefined) return "VITEST";diff --git a/server/drivers/idle-engine-cap.test.ts b/server/drivers/idle-engine-cap.test.tsnew file mode 100644index 0000000000..e623e256ad--- /dev/null+++ b/server/drivers/idle-engine-cap.test.ts@@ -0,0 +1,106 @@+// A box with room to spare and a cap of two idle engines: Claude's per-thread processes and Codex's kept app-servers count+// together, the least recently used close first, and a thread with a turn running is never closed.+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { randomUUID } from "node:crypto";+import { once } from "node:events";+import { chmodSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import { ensureDirs, NATIVE_DIR } from "../config.ts";+import type { ProviderInstance } from "../contracts.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { recordEvents, type EventRecorder } from "../testing/events.ts";+import { ClaudeDriver } from "./claude.ts";+import { CodexConnection, codexWarmSessions } from "./codex-warm.ts";+import { warmEngineKeys } from "./session-idle.ts";++const GB = 1024 ** 3;+vi.mock("../box-memory.ts", async (original) => ({+ ...await original<typeof import("../box-memory.ts")>(),+ boxMemory: () => ({ bytes: 16 * GB, cgroupLimit: null }),+ availableMemory: () => 12 * GB,+}));++const here = dirname(fileURLToPath(import.meta.url));+const FAKE_CLAUDE = join(here, "..", "testing", "fake-claude-cli.ts");++let scratch: string, instance: ProviderInstance, recorder: EventRecorder;+const children: ChildProcessWithoutNullStreams[] = [];++beforeEach(() => {+ ensureDirs();+ chmodSync(FAKE_CLAUDE, 0o755);+ scratch = mkdtempSync(join(tmpdir(), "omb-idle-cap-"));+ vi.stubEnv("OMB_IDLE_ENGINES_MAX", "2");+});+afterEach(async () => {+ vi.unstubAllEnvs();+ recorder.stop();+ await instance.dispose();+ for (const child of children.splice(0)) {+ if (child.exitCode !== null || child.signalCode !== null) continue;+ const exited = once(child, "exit");+ child.kill("SIGKILL");+ await exited;+ }+ await removeTempDir(scratch);+});++const closedIdle = (threadId: string) => {+ try { return readFileSync(join(NATIVE_DIR, `${threadId}.ndjson`), "utf8").includes('"close":"idle"'); } catch { return false; }+};+const completed = (turnId: string) => recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+const turn = async (threadId: string) => completed((await instance.adapter.sendTurn({ threadId, text: "go" })).turnId);+const startClaude = async () => {+ instance = await ClaudeDriver.create({ instanceId: `cap-claude-${randomUUID()}`, displayName: "Claude", environment: {}, enabled: true, config: { cli: FAKE_CLAUDE, permissionMode: "acceptEdits" } });+ recorder = recordEvents(instance.adapter);+};+const codexProcess = () => {+ const child = spawn(process.execPath, ["-e", "process.stdin.pipe(process.stdout); setInterval(() => {}, 1000);"], { stdio: ["pipe", "pipe", "pipe"] });+ children.push(child);+ return new CodexConnection(child);+};++it("keeps the two most recently used of five idle engines across Claude and Codex, the three oldest closing", async () => {+ await startClaude();+ const claudeThreads = [randomUUID(), randomUUID(), randomUUID()];+ for (const threadId of claudeThreads) await turn(threadId);+ await expect.poll(() => claudeThreads.map(closedIdle), { timeout: 10_000 }).toEqual([true, false, false]);++ const codex = codexWarmSessions<null>(`cap-codex-${randomUUID()}`);+ const codexThreads = [randomUUID(), randomUUID()];+ const kept = codexThreads.map((threadId) => {+ const session = { connection: codexProcess(), contract: "{}", nativeThreadId: `native-${threadId}`, configDigest: "config", cwd: "/work", carried: null };+ expect(codex.keep(threadId, session)).toBe(true);+ return session;+ });+ await expect.poll(() => claudeThreads.map(closedIdle), { timeout: 10_000 }).toEqual([true, true, true]);+ expect(codexThreads.map((threadId) => codex.has(threadId))).toEqual([true, true]);+ expect(kept.map((session) => session.connection.alive)).toEqual([true, true]);+ expect(warmEngineKeys()).toHaveLength(2);+ await codex.closeAll("test over");+}, 30_000);++it("never closes a thread whose turn is running, and counts it once its turn ends", async () => {+ const release = join(scratch, "release");+ vi.stubEnv("FAKE_CLAUDE_MODE", "hang");+ vi.stubEnv("FAKE_CLAUDE_RELEASE", release);+ await startClaude();+ const busy = randomUUID();+ const { turnId: busyTurn } = await instance.adapter.sendTurn({ threadId: busy, text: "go" });+ await recorder.until((event) => event.type === "session.started" && event.threadId === busy);+ vi.stubEnv("FAKE_CLAUDE_MODE", "happy");++ const others = [randomUUID(), randomUUID(), randomUUID()];+ for (const threadId of others) await turn(threadId);+ await expect.poll(() => others.map(closedIdle), { timeout: 10_000 }).toEqual([true, false, false]);+ expect(closedIdle(busy)).toBe(false);++ writeFileSync(release, "");+ await completed(busyTurn);+ await expect.poll(() => closedIdle(others[1]!), { timeout: 10_000 }).toBe(true);+ expect([closedIdle(busy), closedIdle(others[2]!)]).toEqual([false, false]);+}, 30_000);diff --git a/server/drivers/session-idle.test.ts b/server/drivers/session-idle.test.tsindex 88aa340731..7a9db462d8 100644--- a/server/drivers/session-idle.test.ts+++ b/server/drivers/session-idle.test.ts@@ -2,7 +2,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { forgetPresence, personAsks, sawThread, seenWithin } from "../thread-presence.ts";import {- armedIdleCount, armIdleClose, engineIdleMs, idleEnginesAllowed, keepWarm, PRESTART_IDLE_MS, PRESTART_MOST, prestartAllowed, sessionIdlePolicy, SMALL_BOX_BYTES, SMALL_BOX_IDLE_MS, stopIdleClose, sweepIdleEngines,+ armedIdleCount, armIdleClose, engineIdleMs, idleEngineCap, idleEnginesAllowed, keepWarm, PRESTART_IDLE_MS, PRESTART_MOST, prestartAllowed, sessionIdlePolicy, SMALL_BOX_BYTES,+ SMALL_BOX_IDLE_ENGINES, SMALL_BOX_IDLE_MS, stopIdleClose, sweepIdleEngines,UNWATCHED_IDLE_MS, warmEngineKeys, type WarmEngine,} from "./session-idle.ts";@@ -136,11 +137,11 @@ describe("idle engines on a small box", () => {expect(warmEngineKeys()).toEqual(["c"]);});- it("keeps every idle engine on a large box, and forgets one once it closes or works again", () => {+ it("keeps every idle engine on a large box up to the cap, and forgets one once it closes or works again", () => {const [a, b] = [engine(), engine()];- 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, { bytes: DESKTOP }, () => 0, () => Infinity, () => 8);+ keepWarm("b", b.warm, { bytes: DESKTOP }, () => 0, () => Infinity, () => 8);+ expect([a.state.closed, b.state.closed, warmEngineKeys()]).toEqual([0, 0, ["a", "b"]]);keepWarm("a", a.warm, small, () => 0.6 * GB);stopIdleClose("a", null);keepWarm("b", b.warm, small, () => 0.1 * GB);@@ -211,6 +212,91 @@ describe("idle engines on a small box", () => {});});+describe("the cap on idle engines", () => {+ const engine = (threadId: string, busy = false) => {+ const state = { busy, closed: 0 };+ return { state, warm: { threadId, idle: () => !state.busy, close: () => { state.closed += 1; } } as WarmEngine };+ };+ const capped = (most: number) => (key: string, warm: WarmEngine) => keepWarm(key, warm, { bytes: DESKTOP }, () => 8 * GB, () => Infinity, () => most);+ afterEach(() => {+ for (const key of warmEngineKeys()) stopIdleClose(key, null);+ forgetPresence();+ });++ it("is one idle engine per 2 GB between four and eight, two on a small box, or OMB_IDLE_ENGINES_MAX", () => {+ expect(idleEngineCap({}, 4 * GB)).toBe(4);+ expect(idleEngineCap({}, 8 * GB)).toBe(4);+ expect(idleEngineCap({}, 12 * GB)).toBe(6);+ expect(idleEngineCap({}, DESKTOP)).toBe(8);+ expect(idleEngineCap({}, 64 * GB)).toBe(8);+ expect(idleEngineCap({}, SMALL_BOX_BYTES)).toBe(SMALL_BOX_IDLE_ENGINES);+ expect(idleEngineCap({ OMB_IDLE_ENGINES_MAX: "12" }, DESKTOP)).toBe(12);+ expect(idleEngineCap({ OMB_IDLE_ENGINES_MAX: "1" }, GB)).toBe(1);+ for (const unusable of ["0", "-2", "2.5", "many", ""]) expect(idleEngineCap({ OMB_IDLE_ENGINES_MAX: unusable }, DESKTOP)).toBe(8);+ });++ it("closes the least recently used idle engines past the cap, on a box with room to spare", () => {+ const engines = ["a", "b", "c", "d", "e", "f"].map((id) => [id, engine(id)] as const);+ for (const [id, { warm }] of engines) capped(3)(id, warm);+ expect(engines.map(([, { state }]) => state.closed)).toEqual([1, 1, 1, 0, 0, 0]);+ expect(warmEngineKeys()).toEqual(["d", "e", "f"]);+ });++ it("never closes or counts an engine with a turn running", () => {+ const [busy, b, c, d] = [engine("busy"), engine("b"), engine("c"), engine("d")];+ capped(2)("busy", busy.warm);+ busy.state.busy = true;+ capped(2)("b", b.warm);+ capped(2)("c", c.warm);+ expect([busy.state.closed, b.state.closed, c.state.closed]).toEqual([0, 0, 0]);+ capped(2)("d", d.warm);+ expect([busy.state.closed, b.state.closed, c.state.closed, d.state.closed]).toEqual([0, 1, 0, 0]);+ });++ it("counts an engine as used again when it goes idle after a turn or a person opens its conversation", () => {+ const [a, b, c, d, e] = [engine("a"), engine("b"), engine("c"), engine("d"), engine("e")];+ for (const id of ["a", "b", "c", "d", "e"]) sawThread(id);+ capped(3)("a", a.warm);+ capped(3)("b", b.warm);+ capped(3)("c", c.warm);+ sawThread("a");+ capped(3)("d", d.warm);+ expect([a.state.closed, b.state.closed]).toEqual([0, 1]);+ capped(3)("c", c.warm);+ capped(3)("e", e.warm);+ expect([a.state.closed, c.state.closed, d.state.closed]).toEqual([1, 0, 0]);+ expect(warmEngineKeys()).toEqual(["d", "c", "e"]);+ });++ it("closes an engine no person has had in front of them before one they have", () => {+ const [mine, routine, next] = [engine("mine"), engine("routine"), engine("next")];+ sawThread("mine");+ capped(2)("mine", mine.warm);+ capped(2)("routine", routine.warm);+ capped(2)("next", next.warm);+ expect([mine.state.closed, routine.state.closed, next.state.closed]).toEqual([0, 1, 0]);+ });++ it("never closes the engine that is going idle, even one no person has in front of them", () => {+ const [mine, theirs, routine] = [engine("mine"), engine("theirs"), engine("routine")];+ sawThread("mine");+ sawThread("theirs");+ capped(2)("mine", mine.warm);+ capped(2)("theirs", theirs.warm);+ capped(2)("routine", routine.warm);+ expect([mine.state.closed, theirs.state.closed, routine.state.closed]).toEqual([1, 0, 0]);+ expect(warmEngineKeys()).toEqual(["theirs", "routine"]);+ });++ it("keeps an engine started ahead of a first message as the most recent, and never closes a held one", () => {+ const [used, held, spare] = [engine("used"), engine("held"), engine("spare")];+ capped(1)("held", { ...held.warm, held: () => true });+ capped(1)("used", used.warm);+ capped(1)("spare", { ...spare.warm, spare: () => true });+ expect([used.state.closed, held.state.closed, spare.state.closed]).toEqual([1, 0, 0]);+ });+});+describe("engines started before a first message", () => {const engine = (spare: boolean) => {const state = { closed: 0 };diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.tsindex e62ed2788a..2bc80b4f49 100644--- a/server/drivers/session-idle.ts+++ b/server/drivers/session-idle.ts@@ -12,10 +12,12 @@// floor, and per-chat engines already kept are looked at again every couple of seconds (sweepIdleEngines), not only when// they went idle. Short of room, a keep-warm hold yields too. Before admission makes a new engine wait it stops the// engine idle longest (engine-memory.ts), and a browser with no room to open asks for the same first (host/browser.ts).+// On every host, no more per-chat engines stay idle at once than idleEngineCap allows: past it, the least recently used+// closes as another goes idle, and its conversation's next turn resumes its session by id.import { availableMemory, boxMemory, type BoxMemory } from "../box-memory.ts";import { stoppedForBotMemory } from "../bot-memory-cap.ts";import { engineMemory, type EngineMemory } from "../engine-memory.ts";-import { seenWithin } from "../thread-presence.ts";+import { onThreadSeen, seenWithin } from "../thread-presence.ts";export type IdleScope = "per-chat" | "per-bot" | "shared";@@ -83,21 +85,46 @@ export interface WarmEngine {spare?: () => boolean;}-/** Idle engines of every driver, the longest idle first. */+const GB = 1024 ** 3;+export const SMALL_BOX_IDLE_ENGINES = 2;+const IDLE_ENGINES_FEWEST = 4, IDLE_ENGINES_MOST = 8;++/** How many engines may stay idle at once across every driver and conversation, whatever the idle times allow:+ * OMB_IDLE_ENGINES_MAX (1 or more), else one per 2 GB of the box between four and eight, and two on a box of 1.5 GB or+ * less. Each holds 250 to 450 MB with its MCP servers. */+export function idleEngineCap(env: Record<string, string | undefined> = process.env, boxBytes: number = boxMemory().bytes): number {+ const configured = Number(env.OMB_IDLE_ENGINES_MAX);+ if (env.OMB_IDLE_ENGINES_MAX && Number.isInteger(configured) && configured >= 1) return configured;+ if (boxBytes <= SMALL_BOX_BYTES) return SMALL_BOX_IDLE_ENGINES;+ return Math.min(IDLE_ENGINES_MOST, Math.max(IDLE_ENGINES_FEWEST, Math.floor(boxBytes / (2 * GB))));+}++/** Idle engines of every driver, the least recently used first: an engine moves to the end when it goes idle and when a+ * person opens or reads its conversation. */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. */+/** An engine went idle: when the box allows fewer idle engines than are up, the ones idle longest close now (an engine+ * started ahead of a first message before them); past the cap on idle engines, the least recently used close now (one+ * whose conversation no person has had in front of them before them). Never one with a turn running, nor one held. */export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "bytes"> = boxMemory(),- available: () => number = availableMemory, fits: () => number = () => engineMemory.idleEnginesAllowed()): void {- const most = fits();- if (box.bytes > SMALL_BOX_BYTES && most === Infinity) return;+ available: () => number = availableMemory, fits: () => number = () => engineMemory.idleEnginesAllowed(),+ cap: () => number = () => idleEngineCap(process.env, box.bytes)): void {warmEngines.delete(key);warmEngines.set(key, engine);for (const [other, warm] of warmEngines) if (other !== key && (!warm.idle() || warm.held?.())) warmEngines.delete(other);- const extra = warmEngines.size - idleEnginesAllowed(box, available(), most);- if (extra <= 0) return;- for (const [other, warm] of sparesFirst([...warmEngines]).slice(0, extra)) {- warmEngines.delete(other);+ const most = fits();+ const roomAllows = box.bytes > SMALL_BOX_BYTES && most === Infinity ? Infinity : idleEnginesAllowed(box, available(), most);+ const idleBefore = () => [...warmEngines].filter(([other]) => other !== key);+ closeKept(sparesFirst(idleBefore()).slice(0, Math.max(0, warmEngines.size - roomAllows)));+ closeKept(unwatchedFirst(idleBefore()).slice(0, Math.max(0, warmEngines.size - Math.max(1, cap()))));+}++function closeKept(engines: Array<[string, WarmEngine]>): void {+ for (const [key, warm] of engines) {+ warmEngines.delete(key);+ const entry = armed.get(key);+ if (entry) clearTimeout(entry.timer);+ armed.delete(key);warm.close();}}@@ -105,6 +132,20 @@ export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "const sparesFirst = (engines: Array<[string, WarmEngine]>): Array<[string, WarmEngine]> =>[...engines.filter(([, warm]) => warm.spare?.()), ...engines.filter(([, warm]) => !warm.spare?.())];+const watched = (warm: WarmEngine): boolean => warm.threadId !== undefined && seenWithin(warm.threadId, WATCHED_MS);+const unwatchedFirst = (engines: Array<[string, WarmEngine]>): Array<[string, WarmEngine]> =>+ [...engines.filter(([, warm]) => !watched(warm)), ...engines.filter(([, warm]) => watched(warm))];++/** A person opened or read a conversation: its idle engines become the most recently used. */+function touchWarm(threadId: string): void {+ const touched = [...warmEngines].filter(([, warm]) => warm.threadId === threadId);+ for (const [key, warm] of touched) {+ warmEngines.delete(key);+ warmEngines.set(key, warm);+ }+}+onThreadSeen(touchWarm);+/** Every per-chat engine idle now, with when it went idle: what the sweep looks at again. */const armed = new Map<string, { engine: WarmEngine; since: number; timer: ReturnType<typeof setTimeout> }>();diff --git a/server/headless/host-doctor.test.ts b/server/headless/host-doctor.test.tsindex d0cd4c9a63..705eefaae9 100644--- a/server/headless/host-doctor.test.ts+++ b/server/headless/host-doctor.test.ts@@ -1,3 +1,4 @@+import { join, posix } from "node:path";import { describe, expect, it } from "vitest";import type { VerbContext } from "./context.ts";@@ -166,6 +167,12 @@ describe("doctor --host", () => {const flagged = await hostDoctor(ctx({ host: true, "data-dir": "/srv/mausbot", port: "9000", domain: "Maus.Example.com" }), probe({freeBytes: (path) => { seen.push(path); return 412 * GB; }, files: { "/proc/net/tcp": tcp(443, 9000) } }));expect(seen).toEqual(["/srv/from-env", "/srv/mausbot"]);+ const homes = { under: () => "/fake-account/person", realHome: () => "/fake-account/person" };+ await hostDoctor(ctx({ host: true }), watching, homes);+ expect(seen.at(-1)).toBe(posix.resolve(join("/fake-account/person", ".openmausbot")));+ await expect(hostDoctor(ctx({ host: true }, { NODE_ENV: "test" }), watching, homes)).rejects.toThrow(/refusing to use the real data folder/);+ await hostDoctor(ctx({ host: true, "data-dir": "/srv/given" }, { NODE_ENV: "test" }), watching, homes);+ expect(seen.at(-1)).toBe("/srv/given");expect((flagged.result as { checks: HostCheck[] }).checks.filter((check) => check.status === "FAIL").map((check) => check.message)).toEqual(["Port 9000 is taken by another program", "Port 443 is taken, and --domain maus.example.com needs 80 and 443"]);await expect(hostDoctor(ctx({ host: true, port: "99999" }), probe())).rejects.toMatchObject({ exitCode: 2 });diff --git a/server/headless/host-doctor.ts b/server/headless/host-doctor.tsindex 6bc6f6d533..82e1cec496 100644--- a/server/headless/host-doctor.ts+++ b/server/headless/host-doctor.ts@@ -3,9 +3,10 @@// a server that runs the MausBot connector it also asks that for its own checks, which start one throwaway box probe.import { execFile } from "node:child_process";import { existsSync, readdirSync, readFileSync, statfsSync } from "node:fs";-import { arch, cpus, homedir, release, totalmem } from "node:os";-import { dirname, join, posix, resolve } from "node:path";+import { arch, cpus, release, totalmem } from "node:os";+import { dirname, posix, resolve } from "node:path";+import { defaultDataDir, type DataHomes } from "../data-dir.ts";import { PRODUCTION_CLOUD_ORIGIN } from "../devs-report-send.ts";import { EXIT, flag, usageError } from "./args.ts";import type { VerbContext, VerbOutcome } from "./context.ts";@@ -311,12 +312,12 @@ export function systemProbe(): HostProbe {};}-export async function hostDoctor(ctx: VerbContext, probe: HostProbe = systemProbe()): Promise<VerbOutcome> {+export async function hostDoctor(ctx: VerbContext, probe: HostProbe = systemProbe(), homes: DataHomes = {}): Promise<VerbOutcome> {const rawPort = flag(ctx.flags, "port") ?? ctx.env.OMB_PORT ?? "8799";const port = Number(rawPort);if (!Number.isInteger(port) || port < 1 || port > 65_535) throw usageError("--port must be 1-65535");// A Linux machine's path, also when the checks are tested on Windows.- const dataDir = posix.resolve(flag(ctx.flags, "data-dir") ?? (ctx.env.OMB_DATA_DIR || join(homedir(), ".openmausbot")));+ const dataDir = posix.resolve(flag(ctx.flags, "data-dir") ?? defaultDataDir(ctx.env, homes.under, homes.realHome));const domain = flag(ctx.flags, "domain")?.trim().toLowerCase();return hostReport(await checkHost(probe, { dataDir, port, ...(domain ? { domain } : {}) }));}diff --git a/server/perf/loop-pause.ts b/server/perf/loop-pause.tsnew file mode 100644index 0000000000..3f5f420ef4--- /dev/null+++ b/server/perf/loop-pause.ts@@ -0,0 +1,15 @@+// A gap the event loop only waited through was not the server's: the computer slept or the process was paused.+import { performance } from "node:perf_hooks";++export const LATE_TIMER_MS = 2_000;++/** A timer `lateMs` overdue was held up by the loop only if the loop worked through that lateness. `waitedMs` is how+ * long the loop sat waiting since the timer was set `intervalMs` ago; null where that is not known. */+export function pausedNotStalled(intervalMs: number, lateMs: number, waitedMs: number | null): boolean {+ if (waitedMs === null || lateMs < LATE_TIMER_MS) return false;+ const workedMs = Math.max(0, intervalMs + lateMs - waitedMs);+ return workedMs < lateMs / 2;+}++/** Node's count of the time the event loop spent waiting so far, ms. */+export const loopIdleMs = (): number => performance.eventLoopUtilization().idle;diff --git a/server/perf/loop-stalls.test.ts b/server/perf/loop-stalls.test.tsindex 8a6a757647..248b89b95d 100644--- a/server/perf/loop-stalls.test.ts+++ b/server/perf/loop-stalls.test.ts@@ -1,15 +1,16 @@import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import type { IntervalHistogram } from "node:perf_hooks";import { setTimeout as delay } from "node:timers/promises";import { describe, expect, it } from "vitest";import { writeFileAtomic } from "../atomic.ts";-import { createLoopStalls, markRequestArrival, requestArrivedBefore, stallStats, timeBlocking } from "./loop-stalls.ts";+import { createLoopStalls, markRequestArrival, requestArrivedBefore, STALL_RESOLUTION_MS, stallStats, timeBlocking } from "./loop-stalls.ts";import { PERF_HEALTH_MAX_BYTES, perfHealth, stallLines } from "./perf-report.ts";const tally = { n: 0, ms: 0, maxMs: 0 };-const minute = (count: number, points: Array<[number, number]>) => ({ count, points, maxMs: points.at(-1)![1], saves: tally, runtimeReads: tally });+const minute = (count: number, points: Array<[number, number]>) => ({ count, points, maxMs: points.at(-1)![1], saves: tally, runtimeReads: tally, pauses: tally });describe("loop stall percentiles", () => {it("weighs each minute by its samples, so one bad minute shows in the hour's tail and not its middle", () => {@@ -56,6 +57,51 @@ describe("the loop stall recorder", () => {}});+ it("counts a gap the loop only waited through as a sleep or a pause, and one it worked through as a stall", () => {+ const delays: number[] = [];+ const histogram = {+ get count() { return delays.length; },+ get max() { return delays.length ? (Math.max(...delays) + STALL_RESOLUTION_MS) * 1e6 : 0; },+ get percentiles() { return new Map(delays.length ? [[0, 20.1e6], [99, 20.1e6], [100, (Math.max(...delays) + STALL_RESOLUTION_MS) * 1e6]] : []); },+ reset() { delays.length = 0; }, enable: () => true, disable: () => true,+ } as unknown as IntervalHistogram;+ let mono = 0, waited: number | null = 0;+ const resumed: number[] = [];+ const stalls = createLoopStalls({ histogram, monotonic: () => mono, idle: () => waited, resumed: (ms) => resumed.push(ms) });+ const minute = (gapMs: number, workedMs: number, rollAfter = true) => {+ delays.push(0.1, 0.1, gapMs);+ mono += 60_000 + gapMs;+ if (waited !== null) waited += 60_000 + gapMs - workedMs;+ if (rollAfter) stalls.roll();+ };++ const hour = 3_600_000;+ minute(hour, 100);+ expect(resumed).toEqual([hour]);+ expect(stalls.report()).toMatchObject({ m1: null, h1: null, pauses: { h1: { n: 1, ms: hour, maxMs: hour } } });++ minute(5_000, 5_100);+ expect(resumed).toEqual([hour]);+ expect(stalls.report()).toMatchObject({ m1: { max: 5_000 }, h1: { max: 5_000 }, pauses: { m1: { n: 0 }, h1: { n: 1 } } });++ minute(10 * 60_000, 50, false);+ expect(stalls.report()).toMatchObject({ h1: { max: 5_000 }, pauses: { h1: { n: 2, maxMs: hour } } });+ stalls.roll();+ expect(resumed).toEqual([hour, 10 * 60_000]);+ expect(stallLines(stalls.report())[3]).toMatch(/^ {2}Sleeps or pauses, left out of the stalls: last minute 0 .*; last hour 2 /);++ mono += 10_000;+ stalls.roll();+ minute(10_000, 0);+ expect(resumed).toHaveLength(2);+ expect(stalls.report().m1).toMatchObject({ max: 10_000 });++ waited = null;+ minute(hour, 100);+ expect(resumed).toHaveLength(2);+ expect(stalls.report().h1).toMatchObject({ max: hour });+ });+it("starts a message's wait when its request arrived, only for that request and only if recent", async () => {expect(requestArrivedBefore(Date.now())).toBeUndefined();await (async () => {diff --git a/server/perf/loop-stalls.ts b/server/perf/loop-stalls.tsindex f3801b6c36..aaab757f44 100644--- a/server/perf/loop-stalls.ts+++ b/server/perf/loop-stalls.ts@@ -1,9 +1,12 @@// How long the event loop could not answer, measured all the time (perf_hooks.monitorEventLoopDelay), and the blocking// work the server times itself: whole-file saves and runtime-store reads. The process sampler's own "timer late" reads-// one timer once a minute, so it missed 2–3 s stalls a probe saw; this does not. Numbers only, no names or content.+// one timer once a minute, so it missed 2–3 s stalls a probe saw; this does not. Numbers only, no names or content. A+// minute whose longest delay the loop only waited through (loop-pause.ts) holds a sleep or a pause, counted apart.import { AsyncLocalStorage } from "node:async_hooks";import { monitorEventLoopDelay, performance, type IntervalHistogram } from "node:perf_hooks";+import { loopIdleMs, pausedNotStalled } from "./loop-pause.ts";+export type BlockingKind = "saves" | "runtimeReads";export interface Tally { n: number; ms: number; maxMs: number }const zero = (): Tally => ({ n: 0, ms: 0, maxMs: 0 });@@ -38,7 +41,7 @@ export function requestArrivedBefore(at: number, withinMs = 60_000): number | un}/** A distribution as monitorEventLoopDelay gives it: [percentile, delay ms] in rising order, and how many samples. */-interface Minute { count: number; points: Array<[number, number]>; maxMs: number; saves: Tally; runtimeReads: Tally }+interface Minute { count: number; points: Array<[number, number]>; maxMs: number; saves: Tally; runtimeReads: Tally; pauses: Tally }export interface StallStats { p50: number; p95: number; p99: number; max: number; over100ms: number; over1s: number }export interface StallsReport {@@ -48,14 +51,19 @@ export interface StallsReport {/** Whole-file saves and runtime-store reads: how many, their total and longest ms. */saves: { m1: Tally; h1: Tally };runtimeReads: { m1: Tally; h1: Tally };+ /** Minutes the computer slept or the server was paused in, kept out of the delays: how many, the gaps' total and longest ms. */+ pauses: { m1: Tally; h1: Tally };}/** The histogram holds the time between its timer's firings: the delay is what exceeds the timer's own interval. */const lateMs = (ns: number, resolutionMs: number) => Math.max(0, Math.round(ns / 1e5) / 10 - resolutionMs);-function minuteOf(histogram: Pick<IntervalHistogram, "count" | "max" | "percentiles">, tallies: Record<BlockingKind, Tally>, resolutionMs: number): Minute {+/** A minute with `pausedMs` set held a sleep or a pause: its delays are left out, since one sample cannot be taken out. */+function minuteOf(histogram: Pick<IntervalHistogram, "count" | "max" | "percentiles">, tallies: Record<BlockingKind, Tally>, resolutionMs: number, pausedMs: number | null): Minute {+ const tallied = { saves: { ...tallies.saves }, runtimeReads: { ...tallies.runtimeReads } };+ if (pausedMs !== null) return { count: 0, points: [], maxMs: 0, ...tallied, pauses: { n: 1, ms: pausedMs, maxMs: pausedMs } };const points = [...histogram.percentiles].map(([percentile, ns]) => [percentile, lateMs(ns, resolutionMs)] as [number, number]).sort((a, b) => a[0] - b[0]);- return { count: histogram.count, points, maxMs: histogram.count ? lateMs(histogram.max, resolutionMs) : 0, saves: { ...tallies.saves }, runtimeReads: { ...tallies.runtimeReads } };+ return { count: histogram.count, points, maxMs: histogram.count ? lateMs(histogram.max, resolutionMs) : 0, ...tallied, pauses: zero() };}/** The share of a minute's samples at or under `value`. */@@ -94,22 +102,50 @@ export const STALL_RESOLUTION_MS = 20;export const MINUTE_MS = 60_000;const MINUTES_KEPT = 60;-export function createLoopStalls(options: { histogram?: IntervalHistogram; minuteMs?: number; resolutionMs?: number } = {}) {+export interface LoopStallsOptions {+ histogram?: IntervalHistogram;+ minuteMs?: number;+ resolutionMs?: number;+ monotonic?: () => number;+ /** The event loop's time spent waiting so far, ms; null where not available. Node's own counter unless `monotonic` is given. */+ idle?: () => number | null;+ /** A minute's longest delay, ms, was a sleep or a pause the loop only waited through: left out of the delays. */+ resumed?: (gapMs: number) => void;+}++export function createLoopStalls(options: LoopStallsOptions = {}) {const resolutionMs = options.resolutionMs ?? STALL_RESOLUTION_MS;const histogram = options.histogram ?? monitorEventLoopDelay({ resolution: resolutionMs });const minuteMs = options.minuteMs ?? MINUTE_MS;+ const monotonic = options.monotonic ?? (() => performance.now());+ const idle = options.idle ?? (options.monotonic ? () => null : loopIdleMs);const minutes: Minute[] = [];let timer: ReturnType<typeof setInterval> | undefined;+ let since = monotonic(), idleSince = idle(), lastSince = since, lastIdleSince = idleSince;+ /** The minute under way's longest delay when the loop worked less than half of it over this minute and the one before:+ * the delay is recorded on a timer of its own, so a stall the last minute worked through can land in this one. */+ const pausedMs = (): number | null => {+ if (!histogram.count) return null;+ const gap = lateMs(histogram.max, resolutionMs), idleNow = idle();+ return pausedNotStalled(monotonic() - lastSince - gap, gap, idleNow === null || lastIdleSince === null ? null : idleNow - lastIdleSince) ? gap : null;+ };const roll = () => {- minutes.push(minuteOf(histogram, current, resolutionMs));+ const paused = pausedMs();+ minutes.push(minuteOf(histogram, current, resolutionMs, paused));if (minutes.length > MINUTES_KEPT) minutes.shift();histogram.reset();current = { saves: zero(), runtimeReads: zero() };+ [lastSince, lastIdleSince] = [since, idleSince];+ since = monotonic();+ idleSince = idle();+ if (paused !== null) options.resumed?.(Math.round(paused));};return {start() {if (timer) return;histogram.enable();+ since = lastSince = monotonic();+ idleSince = lastIdleSince = idle();timer = setInterval(roll, minuteMs);timer.unref?.();},@@ -122,7 +158,7 @@ export function createLoopStalls(options: { histogram?: IntervalHistogram; minutroll,/** The last full minute (or the one under way, before the first ends) and the last hour including the minute under way. */report(): StallsReport {- const live = minuteOf(histogram, current, resolutionMs);+ const live = minuteOf(histogram, current, resolutionMs, pausedMs());const last = minutes.at(-1);const m1 = last && last.count ? last : live;const hour = [...minutes.slice(-(MINUTES_KEPT - 1)), live];@@ -130,6 +166,7 @@ export function createLoopStalls(options: { histogram?: IntervalHistogram; minutm1: stallStats([m1]), h1: stallStats(hour),saves: { m1: rounded(m1.saves), h1: rounded(sum(hour.map((minute) => minute.saves))) },runtimeReads: { m1: rounded(m1.runtimeReads), h1: rounded(sum(hour.map((minute) => minute.runtimeReads))) },+ pauses: { m1: rounded(m1.pauses), h1: rounded(sum(hour.map((minute) => minute.pauses))) },};},};diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.tsindex 1611170b5e..c61e3ae2d2 100644--- a/server/perf/perf-host.ts+++ b/server/perf/perf-host.ts@@ -111,7 +111,7 @@ export function createPerfHost(deps: PerfHostDeps) {seen: (rows, buckets) => { processes.sample(rows, buckets); guarded("bots", () => footprints.sample(rows), null); },});if (deps.timer !== false && !windows) sampler.start();- const stalls = deps.stalls ?? createLoopStalls();+ const stalls = deps.stalls ?? createLoopStalls({ resumed: (ms) => say("sleep", `the computer slept or the server was paused: the event loop waited through a ${duration(ms)} gap, not counted as a stall`) });if (deps.timer !== false) stalls.start();if (deps.timer !== false && linux) guarded("limits", () => (deps.log ?? ((line: string) => console.warn(line)))(processes.startLine()), undefined);diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.tsindex 534bdc409c..4889febfc1 100644--- a/server/perf/perf-report.ts+++ b/server/perf/perf-report.ts@@ -90,6 +90,7 @@ export const stallLines = (stalls: StallsReport): string[] => [`Event loop stalls, measured all the time: last minute ${stallLine(stalls.m1)}; last hour ${stallLine(stalls.h1)}`,` Whole-file saves: last minute ${tallyLine(stalls.saves.m1)}; last hour ${tallyLine(stalls.saves.h1)}`,` Runtime store reads: last minute ${tallyLine(stalls.runtimeReads.m1)}; last hour ${tallyLine(stalls.runtimeReads.h1)}`,+ ` Sleeps or pauses, left out of the stalls: last minute ${tallyLine(stalls.pauses.m1)}; last hour ${tallyLine(stalls.pauses.h1)}`,];/** 850ms, 14s, 6m12s, 1h03m. */diff --git a/server/perf/process-sampler.ts b/server/perf/process-sampler.tsindex 3749e2011d..5b5c7ced28 100644--- a/server/perf/process-sampler.ts+++ b/server/perf/process-sampler.ts@@ -8,6 +8,7 @@ import { execFile } from "node:child_process";import { readdirSync, readFileSync } from "node:fs";import { performance } from "node:perf_hooks";+import { LATE_TIMER_MS, loopIdleMs, pausedNotStalled } from "./loop-pause.ts";import { exactQuantile } from "./phases.ts";import {classifyProcesses, parseCgroupCpuMs, parseProcStat, parsePsLine, parseReapedChildrenMs, type ProcessBucket, type ProcessRow,@@ -17,15 +18,7 @@ export const LINUX_SAMPLE_MS = 60_000;export const OTHER_SAMPLE_MS = 5 * 60_000;const HOUR = 3_600_000, FIVE_MINUTES = 5 * 60_000;const BUCKETS_SHOWN = 12;-export const LATE_TIMER_MS = 2_000;--/** A timer `lateMs` overdue was held up by the loop only if the loop worked through that lateness. `waitedMs` is how- * long the loop sat waiting since the timer was set `intervalMs` ago; null where that is not known. */-export function pausedNotStalled(intervalMs: number, lateMs: number, waitedMs: number | null): boolean {- if (waitedMs === null || lateMs < LATE_TIMER_MS) return false;- const workedMs = Math.max(0, intervalMs + lateMs - waitedMs);- return workedMs < lateMs / 2;-}+export { LATE_TIMER_MS, pausedNotStalled };export interface ProcessList {rows: ProcessRow[];@@ -119,7 +112,7 @@ export function nodeUtilization(): () => number | null {export function createProcessSampler(options: ProcessSamplerOptions) {const now = options.now ?? Date.now, monotonic = options.monotonic ?? (() => performance.now());const serverPid = options.serverPid ?? process.pid;- const idle = options.idle ?? (options.monotonic ? () => null : () => performance.eventLoopUtilization().idle);+ const idle = options.idle ?? (options.monotonic ? () => null : loopIdleMs);const samples: Sample[] = [];let previous: { at: number; rows: Map<number, { start: string; cpuMs: number; bucket: ProcessBucket; ppid: number }>; reapedMs: number | null; totalMs: number | null } | null = null;let latest: { at: number; procs: Partial<Record<ProcessBucket, number>>; rss: Partial<Record<ProcessBucket, number>>; browsers: number } | null = null;diff --git a/server/sentinel/cli.ts b/server/sentinel/cli.tsindex 5bac26cf19..060f21a482 100644--- a/server/sentinel/cli.ts+++ b/server/sentinel/cli.ts@@ -2,6 +2,7 @@ import { existsSync, readFileSync, statSync } from "node:fs";import { homedir } from "node:os";import { join, resolve } from "node:path";+import { defaultDataDir, type DataHomes } from "../data-dir.ts";import { checkSentinelInstall, type SentinelInstallCheck } from "../service-unit.ts";import { defaultSentinelOut, outRefusal } from "./paths.ts";import { runScan, type ScanSummary } from "./scan.ts";@@ -36,9 +37,9 @@ copy tool output or message text.--check-install check that the installed schedule (service install --sentinel)still points at a node and a script that exist`;-export function parseSentinelArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): SentinelArgs | { error: string; json: boolean } {+export function parseSentinelArgs(argv: string[], env: NodeJS.ProcessEnv = process.env, homes: DataHomes = {}): SentinelArgs | { error: string; json: boolean } {const json = argv.includes("--json");- let dataDir = env.OMB_DATA_DIR || join(homedir(), ".openmausbot");+ let dataDir = argv.includes("--data-dir") ? "" : defaultDataDir(env, homes.under, homes.realHome);let out: string | undefined;const args: Omit<SentinelArgs, "dataDir" | "out"> = { json };for (let i = 0; i < argv.length; i += 1) {diff --git a/server/server-launcher.ts b/server/server-launcher.tsindex 9386683c03..253b31c0b6 100644--- a/server/server-launcher.ts+++ b/server/server-launcher.ts@@ -1,20 +1,20 @@// Container entry: restarts the server in place on RESTART_EXIT_CODE, so a restart the server asks for keeps the container.import { spawn, type ChildProcess } from "node:child_process";import { existsSync, realpathSync } from "node:fs";-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 { defaultDataDir, type DataHomes } from "./data-dir.ts";import { clearRecordsFromEarlierRunOfThisContainer } from "./data-dir-lease.ts";import { restartLine, restartPolicy } from "./restart.ts";/** The server's heap sized to the container's memory limit, run through the bootstrap that keeps Node's compile cache on* the data volume, so a restarted container reuses the compiled bundle. */-export function serverCommand(here: string, env: NodeJS.ProcessEnv, options: { exists?: (path: string) => boolean; box?: BoxMemory } = {}) {+export function serverCommand(here: string, env: NodeJS.ProcessEnv, options: { exists?: (path: string) => boolean; box?: BoxMemory; homes?: DataHomes } = {}) {const bootstrap = join(here, "desktop-entry.mjs");const cached = (options.exists ?? existsSync)(bootstrap);- const dataDir = env.OMB_DATA_DIR || join(homedir(), ".openmausbot");+ const dataDir = defaultDataDir(env, options.homes?.under, options.homes?.realHome);return {args: [...heapSizeArgs((options.box ?? boxMemory()).cgroupLimit, env.NODE_OPTIONS), cached ? bootstrap : join(here, "index.js")],env: cached ? { ...env, OMB_SERVER_COMPILE_CACHE: join(dataDir, "cache", "node-compile") } : env,@@ -61,7 +61,7 @@ if (isEntry()) {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");+ const dataDir = defaultDataDir(process.env);try {// A container starts with nothing of its own running: a lease its earlier run left is a dead server's.for (const { path, pid } of clearRecordsFromEarlierRunOfThisContainer(dataDir)) console.log(`Removed ${path}, left by this container's server (process ${pid}) when it stopped without closing.`);diff --git a/server/turn-continuation.ts b/server/turn-continuation.tsindex c642b4c4d0..27f43859b7 100644--- a/server/turn-continuation.ts+++ b/server/turn-continuation.ts@@ -1,9 +1,10 @@import { mkdirSync, writeFileSync } from "node:fs";-import { homedir } from "node:os";import { join, resolve } from "node:path";-export function handoffDir(): string {- return resolve(process.env.OMB_DATA_DIR || join(homedir(), ".openmausbot"), "handoffs");+import { defaultDataDir, type DataHomes } from "./data-dir.ts";++export function handoffDir(env: Record<string, string | undefined> = process.env, homes: DataHomes = {}): string {+ return resolve(defaultDataDir(env, homes.under, homes.realHome), "handoffs");}export interface HandoffInput {