Skip to content

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

perf: the server fits a small box (#4177)

Milind Soni4ef947695267
diff --git a/scripts/bench-desktop.ts b/scripts/bench-desktop.ts
index 90aacc2d14..f3101bd0fa 100644
--- a/scripts/bench-desktop.ts
+++ b/scripts/bench-desktop.ts
@@ -74,7 +74,7 @@ const STREAM_ENV = {
FAKE_CLAUDE_TOOL_CALLS: JSON.stringify(TOOL_CALLS),
};
-interface Tally { cpu: { user: number; system: number }; memory: { rss: number; heapUsed: number }; fired: Record<string, number>; intervals: Record<string, number>; writes: Record<string, { bytes: number; calls: number }>; fsyncs: number; renames: number; spawns: number }
+interface Tally { cpu: { user: number; system: number }; memory: { rss: number; heapUsed: number }; fired: Record<string, number>; intervals: Record<string, number>; writes: Record<string, { bytes: number; calls: number }>; fsyncs: number; renames: number; spawns: number; spawned?: Record<string, number> }
interface Fixture {
url: string; dataDir: string; pid: number; readyMs: number; logPath: string;
api(method: string, path: string, body?: unknown): Promise<{ status: number; ms: number; bytes: number; body: any }>;
@@ -321,7 +321,7 @@ async function bundleServer(): Promise<string> {
const { serverLocalePlugin } = await import("./server-locale-plugin.mjs");
const outdir = join(work, "dist-server");
await build({
- entryPoints: [join(ROOT, "server", "index.ts")], bundle: true, platform: "node", target: "node20", format: "esm", outdir, logLevel: "warning",
+ entryPoints: [join(ROOT, "server", "index.ts")], bundle: true, platform: "node", target: "node20", format: "esm", outdir, logLevel: "warning", minifyWhitespace: true, minifySyntax: true, lineLimit: 500,
plugins: [{ name: "yaml-esm", setup(builder) { builder.onResolve({ filter: /^yaml$/ }, () => ({ path: join(ROOT, "node_modules", "yaml", "browser", "index.js") })); } }, serverLocalePlugin],
banner: { js: 'import { createRequire as __ombCreateRequire } from "node:module";\nconst require = __ombCreateRequire(import.meta.url);' },
});
@@ -549,19 +549,28 @@ async function main() {
const cache = join(work, "compile-cache");
const packaged: number[] = [];
const memory: Record<string, number> = {};
+ const heap: Record<string, number> = {};
+ const spawned: Record<string, Record<string, number>> = {};
+ // The first start sets up a new data folder; the next two start again on it, as a restart or a Cloud's wake does.
+ const dataDir = newDataDir();
for (let i = 0; i < 3; i++) {
- const fixture = await startFixture({ bundle: { entry, cache } });
+ const fixture = await startFixture({ bundle: { entry, cache }, dataDir });
packaged.push(Math.round(fixture.readyMs));
await sleep(i === 0 ? 11_000 : 3_000);
+ if (i === 0) spawned.firstStartAt11s = (await fixture.tally()).spawned ?? {};
if (i === 2) {
- memory.at3s = await rssMb(fixture);
+ const at3s = await fixture.tally();
+ [memory.at3s, heap.at3s, spawned.laterStartAt3s] = [round(at3s.memory.rss / 1048576), round(at3s.memory.heapUsed / 1048576), at3s.spawned ?? {}];
await sleep(27_000);
- memory.at30s = await rssMb(fixture);
+ const at30s = await fixture.tally();
+ [memory.at30s, heap.at30s, spawned.laterStartAt30s] = [round(at30s.memory.rss / 1048576), round(at30s.memory.heapUsed / 1048576), at30s.spawned ?? {}];
}
- await fixture.close();
+ await fixture.close(i < 2);
}
server.bundleReadyMs = { cold: packaged[0], warm: packaged.slice(1) };
server.bundleRssMb = memory;
+ server.bundleHeapMb = heap;
+ server.bundleSpawned = spawned;
server.bundleKb = kb(statSync(join(dirname(entry), "index.js")).size);
} catch (error) {
server.bundleError = error instanceof Error ? error.message : String(error);
diff --git a/scripts/bundle-server.mjs b/scripts/bundle-server.mjs
index 854a12446e..34fd3a58e1 100644
--- a/scripts/bundle-server.mjs
+++ b/scripts/bundle-server.mjs
@@ -71,6 +71,10 @@ await build({
format: "esm",
outbase: server,
outdir: join(root, "dist-server"),
+ // Function names stay in stack traces. Node prints a whole source line with an uncaught error, so no line may be long.
+ minifyWhitespace: true,
+ minifySyntax: true,
+ lineLimit: 500,
// Written after tsc, replacing its output for these entry points.
allowOverwrite: true,
logLevel: "info",
@@ -136,7 +140,7 @@ if (existsSync(join(root, "enterprise", "server", "index.ts"))) {
copyFileSync(join(root, "enterprise", "LICENSE"), join(root, "dist-server", "enterprise", "LICENSE"));
}
-// The packaged desktop forks this bootstrap to turn on Node's compile cache.
+// The packaged desktop and the container launcher run this bootstrap to turn on Node's compile cache.
// Copied, not bundled: esbuild would inline index.js into it.
copyFileSync(join(root, "scripts", "desktop-server-entry.mjs"), join(root, "dist-server", "desktop-entry.mjs"));
diff --git a/scripts/desktop-server-entry.mjs b/scripts/desktop-server-entry.mjs
index 663e6dcf0a..9e768034bb 100644
--- a/scripts/desktop-server-entry.mjs
+++ b/scripts/desktop-server-entry.mjs
@@ -1,4 +1,4 @@
-// The packaged desktop forks this instead of index.js: it turns on Node's
+// The packaged desktop and the container launcher run this instead of index.js: it turns on Node's
// on-disk compile cache for this process, so a relaunch reuses the compiled
// bundle, then runs the server unchanged. Copied, not bundled: bundling would
// inline index.js.
diff --git a/scripts/smoke-packaged-server.mjs b/scripts/smoke-packaged-server.mjs
index 309fd06f85..a4cf94e6dd 100644
--- a/scripts/smoke-packaged-server.mjs
+++ b/scripts/smoke-packaged-server.mjs
@@ -282,7 +282,8 @@ if (listening) {
}
// The container image runs the server through server-launcher.js: it must start
-// index.js as its own child, and SIGTERM must end both with a clean exit.
+// the server as its own child, through the bootstrap that keeps Node's compile
+// cache on the data volume, and SIGTERM must end both with a clean exit.
let launcherReport = null;
if (listening && process.platform !== "win32") {
const launcherHome = mkdtempSync(join(tmpdir(), "omb-smoke-launcher-"));
@@ -306,13 +307,20 @@ if (listening && process.platform !== "win32") {
} catch { /* not up yet */ }
if (serverPid === null) await new Promise((resolve) => setTimeout(resolve, 300));
}
+ // The bootstrap writes the cache about 10 s after the server starts.
+ const launcherCache = join(launcherHome, ".openmausbot", "cache", "node-compile");
+ let cached = false;
+ for (const written = Date.now() + 30_000; serverPid !== null && !cached && Date.now() < written && launcher.exitCode === null;) {
+ try { cached = readdirSync(launcherCache).some((name) => /^v\d+\.\d+\.\d+-/.test(name)); } catch { /* not yet */ }
+ if (!cached) await new Promise((resolve) => setTimeout(resolve, 300));
+ }
launcher.kill("SIGTERM");
let timer;
const exit = await Promise.race([exited, new Promise((resolve) => { timer = setTimeout(() => resolve({ timeout: true }), 20_000); })]);
clearTimeout(timer);
let stillServing = false;
try { await fetch(`http://127.0.0.1:${launcherPort}/api/health`, { signal: AbortSignal.timeout(2_000) }); stillServing = true; } catch { /* stopped */ }
- launcherReport = { serverPid, launcherPid: launcher.pid, exit, stillServing, output: launcherOutput.slice(-2_000) };
+ launcherReport = { serverPid, launcherPid: launcher.pid, cached, exit, stillServing, output: launcherOutput.slice(-2_000) };
} catch (error) {
launcherReport = { error: String(error), output: launcherOutput.slice(-2_000) };
} finally {
@@ -377,8 +385,8 @@ if (listening) {
cleanup();
if (launcherReport && (launcherReport.error || !launcherReport.serverPid || launcherReport.serverPid === launcherReport.launcherPid ||
- launcherReport.exit?.code !== 0 || launcherReport.stillServing)) {
- console.error("the packaged container launcher did not run the server as its child and stop it cleanly:");
+ !launcherReport.cached || launcherReport.exit?.code !== 0 || launcherReport.stillServing)) {
+ console.error("the packaged container launcher did not run the server as its child on its compile cache and stop it cleanly:");
console.error(JSON.stringify(launcherReport, null, 2));
process.exit(1);
}
diff --git a/scripts/testing/bench-server-tally.mjs b/scripts/testing/bench-server-tally.mjs
index ac55d73332..318aaa51e6 100644
--- a/scripts/testing/bench-server-tally.mjs
+++ b/scripts/testing/bench-server-tally.mjs
@@ -75,6 +75,19 @@ for (const method of ["write", "writeFile", "appendFile"]) {
const original = FileHandle[method];
FileHandle[method] = function (data, ...rest) { const path = handlePaths.get(this); if (path) tallyWrite(path, data); return original.call(this, data, ...rest); };
}
+// Processes that started (a CLI that is not installed has no pid), by program and first argument. exec goes through
+// execFile, so it is not counted twice.
+const spawned = new Map();
+const countSpawn = (file, args, started) => {
+ if (!started?.pid) return;
+ const first = Array.isArray(args) ? args.find((arg) => typeof arg === "string") : undefined;
+ const key = `${basename(String(file)).split(" ")[0]}${first ? ` ${basename(first).slice(0, 40)}` : ""}`;
+ spawned.set(key, (spawned.get(key) ?? 0) + 1);
+};
+for (const method of ["spawn", "spawnSync", "execFile", "fork"]) {
+ const original = childProcess[method];
+ childProcess[method] = function (file, args, ...rest) { const started = original.call(this, file, args, ...rest); countSpawn(file, args, started); return started; };
+}
for (const name of ["spawn", "spawnSync", "execFile", "execFileSync", "exec", "execSync", "fork"]) {
const original = childProcess[name];
childProcess[name] = function (...args) { spawns += 1; return original.apply(this, args); };
@@ -92,6 +105,7 @@ if (out) {
writes: Object.fromEntries(writes),
fsyncs,
renames,
+ spawned: Object.fromEntries(spawned),
spawns,
}));
});
diff --git a/scripts/testing/lazy-server-modules.test.ts b/scripts/testing/lazy-server-modules.test.ts
new file mode 100644
index 0000000000..86a0e1f3a8
--- /dev/null
+++ b/scripts/testing/lazy-server-modules.test.ts
@@ -0,0 +1,13 @@
+// One static import anywhere makes esbuild run the module when the bundle loads, so each of these stays a first-use import.
+import { execFileSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { expect, it } from "vitest";
+
+const ROOT = new URL("../../", import.meta.url);
+const FIRST_USE_ONLY = /^\s*import\s+(?!type\b)[^;]*?from\s+["'](tar|undici|@hpke\/core)["']/m;
+
+it("the server loads tar, undici and the phone-secret cipher at first use", () => {
+ const files = execFileSync("git", ["ls-files", "server", "shared"], { cwd: ROOT, encoding: "utf8" }).split("\n")
+ .filter((file) => file.endsWith(".ts") && !file.includes(".test.") && !file.includes("/testing/"));
+ expect(files.filter((file) => FIRST_USE_ONLY.test(readFileSync(new URL(file, ROOT), "utf8")))).toEqual([]);
+});
diff --git a/server/bot-box/broker-probe.ts b/server/bot-box/broker-probe.ts
index 6b662eead3..3f4f8be325 100644
--- a/server/bot-box/broker-probe.ts
+++ b/server/bot-box/broker-probe.ts
@@ -3,7 +3,7 @@
// and the broker adds the headers and forwards. So the test asks the broker too, through its socket, with a grant made
// the same way and revoked as soon as the test ends. Where turns aren't boxed, bots and the test both go direct.
import { randomUUID } from "node:crypto";
-import { Agent, fetch as fetchVia } from "undici";
+import type { Agent } from "undici";
import type { BoxBroker } from "./box.ts";
import { brokerUrl } from "./broker.ts";
@@ -27,8 +27,10 @@ export function brokeredServer(path: BrokerPath, name: string, server: { url: st
const threadId = `mcp-test-${randomUUID()}`;
const grant = mcpGrantName(name);
const { token } = path.broker.mintForThread({ threadId, grants: { [grant]: { upstream: server.url, headers: { ...server.headers } } }, ttlMs: PROBE_GRANT_TTL_MS });
- const agent = new Agent({ connect: { socketPath: path.socketPath } });
+ let agent: Agent | undefined;
const brokered: typeof fetch = async (input, init) => {
+ const { Agent: UndiciAgent, fetch: fetchVia } = await import("undici");
+ agent ??= new UndiciAgent({ connect: { socketPath: path.socketPath } });
const response = await fetchVia(String(input instanceof Request ? input.url : input), { ...init, dispatcher: agent } as Parameters<typeof fetchVia>[1]) as unknown as Response;
if (response.status !== 502 || !(response.headers.get("content-type") ?? "").startsWith("application/json")) return response;
const text = await response.text().catch(() => "");
@@ -40,7 +42,7 @@ export function brokeredServer(path: BrokerPath, name: string, server: { url: st
fetch: brokered,
done: async () => {
path.broker.revokeThread(threadId);
- await agent.close().catch(() => {});
+ await agent?.close().catch(() => {});
},
};
}
diff --git a/server/box-memory.test.ts b/server/box-memory.test.ts
new file mode 100644
index 0000000000..fc19b16e4c
--- /dev/null
+++ b/server/box-memory.test.ts
@@ -0,0 +1,45 @@
+import { homedir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { boxMemoryFrom, heapSizeArgs } from "./box-memory.ts";
+import { serverCommand } from "./server-launcher.ts";
+
+const GB = 1024 ** 3;
+
+describe("the box's memory", () => {
+ it("is the cgroup's limit only when one is set below the machine's memory", () => {
+ expect(boxMemoryFrom(0, 16 * GB)).toEqual({ bytes: 16 * GB, cgroupLimit: null });
+ expect(boxMemoryFrom(2 ** 64 - 1, 8 * GB)).toEqual({ bytes: 8 * GB, cgroupLimit: null });
+ expect(boxMemoryFrom(GB, 8 * GB)).toEqual({ bytes: GB, cgroupLimit: GB });
+ });
+
+ it("sizes the heap to 60% of a cgroup limit, unless NODE_OPTIONS already does", () => {
+ expect(heapSizeArgs(GB, undefined)).toEqual(["--max-old-space-size=614"]);
+ expect(heapSizeArgs(128 * 1024 ** 2, "")).toEqual(["--max-old-space-size=128"]);
+ expect(heapSizeArgs(64 * GB, "--enable-source-maps")).toEqual(["--max-old-space-size=4096"]);
+ expect(heapSizeArgs(null, undefined)).toEqual([]);
+ expect(heapSizeArgs(GB, "--max_old_space_size=300")).toEqual([]);
+ expect(heapSizeArgs(GB, "--max-old-space-size=300")).toEqual([]);
+ });
+});
+
+describe("the container's server command", () => {
+ const here = join("/app", "dist-server");
+ const small = { bytes: GB, cgroupLimit: GB };
+
+ it("runs the server through the compile-cache bootstrap, its cache on the data volume, its heap sized to the limit", () => {
+ const command = serverCommand(here, { OMB_DATA_DIR: join("/srv", "omb"), OMB_PORT: "8799" }, { exists: () => true, box: small });
+ expect(command).toEqual({
+ args: ["--max-old-space-size=614", join(here, "desktop-entry.mjs")],
+ env: { OMB_DATA_DIR: join("/srv", "omb"), OMB_PORT: "8799", OMB_SERVER_COMPILE_CACHE: join("/srv", "omb", "cache", "node-compile") },
+ });
+ expect(serverCommand(here, {}, { exists: () => true, box: small }).env.OMB_SERVER_COMPILE_CACHE)
+ .toBe(join(homedir(), ".openmausbot", "cache", "node-compile"));
+ });
+
+ it("runs index.js itself without the bootstrap, and leaves the heap alone without a limit or when NODE_OPTIONS sizes it", () => {
+ expect(serverCommand(here, {}, { exists: () => false, box: { bytes: 16 * GB, cgroupLimit: null } })).toEqual({ args: [join(here, "index.js")], env: {} });
+ expect(serverCommand(here, { NODE_OPTIONS: "--max-old-space-size=900" }, { exists: () => true, box: small }).args).toEqual([join(here, "desktop-entry.mjs")]);
+ });
+});
diff --git a/server/box-memory.ts b/server/box-memory.ts
new file mode 100644
index 0000000000..eaa013b535
--- /dev/null
+++ b/server/box-memory.ts
@@ -0,0 +1,39 @@
+import { freemem, totalmem } from "node:os";
+
+const MB = 1024 * 1024;
+
+export interface BoxMemory {
+ /** What this server may use: its cgroup's limit when one is set below the machine's memory, else the machine's. */
+ bytes: number;
+ /** Set only when a cgroup (a container's --memory, a systemd MemoryMax) caps this server below the machine's memory. */
+ cgroupLimit: number | null;
+}
+
+/** libuv reads cgroup v2 `memory.max` or v1 `memory.limit_in_bytes` along /proc/self/cgroup and reports the tightest;
+ * with no limit it answers 0, or UINT64_MAX for a cgroup whose limit is "max". */
+export function boxMemoryFrom(constrained: number, total: number): BoxMemory {
+ const cgroupLimit = constrained > 0 && constrained < total ? constrained : null;
+ return { bytes: cgroupLimit ?? total, cgroupLimit };
+}
+
+let box: BoxMemory | undefined;
+export function boxMemory(): BoxMemory {
+ box ??= boxMemoryFrom(process.constrainedMemory?.() ?? 0, totalmem());
+ return box;
+}
+
+/** Free memory within the cgroup limit where there is one. */
+export function availableMemory(): number {
+ return process.availableMemory?.() ?? freemem();
+}
+
+const HEAP_SHARE = 0.6;
+const HEAP_MIN_MB = 128, HEAP_MAX_MB = 4096;
+
+/** Node sizes its old space to a quarter of a cgroup limit; a server on a small box runs out of heap long before the box
+ * runs out of memory. No flag without a cgroup limit, or when NODE_OPTIONS already sizes the heap. */
+export function heapSizeArgs(cgroupLimit: number | null, nodeOptions: string | undefined): string[] {
+ if (cgroupLimit === null || /--max[-_]old[-_]space[-_]size/.test(nodeOptions ?? "")) return [];
+ const mb = Math.min(HEAP_MAX_MB, Math.max(HEAP_MIN_MB, Math.floor((cgroupLimit * HEAP_SHARE) / MB)));
+ return [`--max-old-space-size=${mb}`];
+}
diff --git a/server/browser-evidence.ts b/server/browser-evidence.ts
index 0d6c7b78f0..a781fd5879 100644
--- a/server/browser-evidence.ts
+++ b/server/browser-evidence.ts
@@ -7,7 +7,6 @@ import { open, readFile, stat, statfs as statfsAsync } from "node:fs/promises";
import { isAbsolute, join, relative } from "node:path";
import type { Writable } from "node:stream";
-import { Header } from "tar";
import { writeFileAtomic } from "./atomic.ts";
@@ -286,6 +285,7 @@ export class BrowserEvidence {
out.once("drain", settle);
out.once("close", closed);
});
+ const { Header } = await import("tar");
const entry = async (path: string, body: Buffer | { file: string; size: number }, mtime: Date) => {
const bytes = Buffer.isBuffer(body) ? body.length : body.size;
const block = Buffer.alloc(512);
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index d85e107599..6c79fa257d 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -10,6 +10,7 @@ import {
CLOUD_SECRETS_FD_ENV, cloudHomeConfiguration, cloudHomeHost, cloudHomeSecrets, prepareCloudHomeVolume,
withoutCloudSecrets, withoutIgnoredCloudKeys, type CloudHomeConfig,
} from "./cloud-home.ts";
+import { boxMemory, heapSizeArgs } from "./box-memory.ts";
import { clearRecordsFromOtherMachines } from "./data-dir-lease.ts";
import { OOM_SCORE, protectSupervisor, spawnWithOomScore } from "./oom-score.ts";
import { restartPolicy } from "./restart.ts";
@@ -242,7 +243,7 @@ export function startCloudHome(env: NodeJS.ProcessEnv = process.env) {
};
const policy = restartPolicy();
const runServer = () => {
- watch(spawnWithOomScore(OOM_SCORE.server, () => spawnWithSecrets(process.execPath, [join(here, "index.js")], server, secrets, ids)), (code) => {
+ watch(spawnWithOomScore(OOM_SCORE.server, () => spawnWithSecrets(process.execPath, [...heapSizeArgs(boxMemory().cgroupLimit, server.NODE_OPTIONS), join(here, "index.js")], server, secrets, ids)), (code) => {
if (!policy.again(code, stopping)) return false;
runServer();
return true;
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index ae65062bb9..01e581695a 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -10,7 +10,7 @@ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:pat
import { createHash } from "node:crypto";
import { PROVIDER_CREDENTIAL_ENV, stripControlPlaneEnv, WORKSPACE_CREDENTIAL_ENV } from "../../config.ts";
-import { openStartupModelCatalog, readStartupModelCache, writeStartupModelCache } from "../../startup-model-catalog.ts";
+import { openStartupModelCatalog, readStartupModelCache, unconfirmedModelCatalog, writeStartupModelCache } from "../../startup-model-catalog.ts";
import { decodeInjectId } from "../local-inject.ts";
import { DeviceAuthController, type DeviceSignIn } from "../device-auth.ts";
import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";
@@ -60,7 +60,7 @@ import { acpToolEndEvents } from "./tool-items.ts";
import { AcpHost } from "./host.ts";
import { endTurn, trackRunningTool, type AcpAskFinish, type AcpSession, type AcpTurn } from "./turn-state.ts";
import { recoveryPromptFor } from "../../resume-recovery.ts";
-import { engineIdleMs, sessionIdlePolicy } from "../session-idle.ts";
+import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose } from "../session-idle.ts";
import { classifyError } from "../retry.ts";
import { engineFailureKind, engineFailureMessage, stopCause } from "../engine-errors.ts";
import { narrowsNativeTools, parseToolScope } from "../../../shared/tool-scope.ts";
@@ -348,8 +348,8 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
if (resolved.options.length) {
models = resolved;
accountModels = new Set(resolved.options.map((option) => option.id));
- }
- } catch {}
+ } else unconfirmedModelCatalog(models);
+ } catch { unconfirmedModelCatalog(models); }
try { writeStartupModelCache(instanceId, models); } catch {}
};
let startupModelRefresh: Promise<void> | null = null;
@@ -398,7 +398,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const session = sessions.get(threadId);
if (!session || session.closing) return;
session.closing = true;
- if (session.idleTimer) clearTimeout(session.idleTimer);
+ stopIdleClose(`${instanceId}\0${threadId}`, session.idleTimer);
appendNative(threadId, { dir: "out", source: SOURCE, msg: { close: why } });
sessions.delete(threadId);
const { host, sessionId } = session;
@@ -465,8 +465,8 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const session = sessions.get(threadId);
if (!session) return;
if (session.idleTimer) clearTimeout(session.idleTimer);
- session.idleTimer = setTimeout(() => closeSession(threadId, "idle"), engineIdleMs(threadId, sessionIdle));
- session.idleTimer.unref?.();
+ session.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, engineIdleMs(threadId, sessionIdle), { close: () => closeSession(threadId, "idle"),
+ idle: () => sessions.get(threadId) === session && !session.closing && !session.current });
};
// Session allows the driver keeps when the agent offered no `allow_always`: exact operations per
// thread, for the native session's life. A generic title with no input is never remembered.
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 4823d840d1..4443c71ccd 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -7,7 +7,7 @@ import { homedir, tmpdir } from "node:os";
import { join, dirname, isAbsolute, normalize } from "node:path";
import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";
-import { openStartupModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
+import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
import { writeFileAtomic, writeFileAtomicIfChanged } from "../atomic.ts";
import { augmentedPath } from "../env-path.ts";
import { brokerSocketPath, cliVersionReader, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";
@@ -43,7 +43,7 @@ import { claudeApiErrorMessage, claudeLimitFacts, claudeLimitRefusal, claudeUsag
import { 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 { engineIdleMs, sessionIdlePolicy } from "./session-idle.ts";
+import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose } from "./session-idle.ts";
import { promptHalves, withVolatileNote } from "./prompt-split.ts";
import { parseVersionTriple, versionAtLeast } from "./acp/version-probe.ts";
import {
@@ -822,9 +822,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (config.managed) return;
try {
const resolved = await mergeLocalInject(readClaudeModelCatalog(catalogEnv), catalogEnv);
- if (resolved.options.length) models = resolved;
+ if (resolved.options.length) models = resolved; else unconfirmedModelCatalog(models);
await orgBlocks.refresh(true);
- } catch {}
+ } catch { unconfirmedModelCatalog(models); }
try { writeStartupModelCache(instanceId, models); } catch {}
};
const startupModelRefresh = config.managed ? null : (await openStartupModelCatalog({
@@ -933,7 +933,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (!s || s.closing) return;
s.closing = true;
forks.closed(threadId, why, s.sessionId);
- if (s.idleTimer) clearTimeout(s.idleTimer);
+ stopIdleClose(`${instanceId}\0${threadId}`, s.idleTimer);
// Close the broker before a replacement binds the same socket; a late close must not unlink it.
const broker = s.broker;
s.broker = undefined;
@@ -953,8 +953,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (!s) return;
if (s.idleTimer) clearTimeout(s.idleTimer);
const held = (warmHolds.get(threadId) ?? 0) - Date.now();
- s.idleTimer = setTimeout(() => closeSession(threadId, "idle"), Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)));
- s.idleTimer.unref?.();
+ s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, "idle"),
+ idle: () => sessions.get(threadId) === s && !s.closing && !s.turn && !active.has(threadId) && (warmHolds.get(threadId) ?? 0) <= Date.now() });
};
// Keep-warm pings and warm summaries fork a thread's session with its live launch contract (claude-warm-summary.ts).
const forks = claudeForks({ cli: config.cli, contracts: warmContracts, holds: warmHolds, armIdle, supports: (flag) => cliVersion === null || claudeCliSupports(cliVersion, flag),
diff --git a/server/drivers/codex-catalog.ts b/server/drivers/codex-catalog.ts
index 2263456154..46986fb8bc 100644
--- a/server/drivers/codex-catalog.ts
+++ b/server/drivers/codex-catalog.ts
@@ -8,6 +8,7 @@ import type { ModelCatalog } from "../contracts.ts";
import { qualifiedModelLabel } from "../contracts.ts";
import { killCliTree, spawnCli } from "../procs.ts";
import { codexHome } from "./codex-identity.ts";
+import { unconfirmedModelCatalog } from "../startup-model-catalog.ts";
import { mergeLocalInject } from "./local-inject.ts";
export const STATIC_CODEX_MODELS: ModelCatalog = {
@@ -353,7 +354,17 @@ export async function readCodexModelCatalog(
fetchImpl: typeof fetch = fetch,
cli?: string,
): Promise<ModelCatalog> {
- const official = (cli ? await readCodexAppServerModelCatalog(cli, env) : null) ?? STATIC_CODEX_MODELS;
+ const official = cli ? await readCodexAppServerModelCatalog(cli, env) : null;
+ const catalog = await catalogAround(official ?? STATIC_CODEX_MODELS, env, fetchImpl);
+ if (cli && !official) unconfirmedModelCatalog(catalog);
+ return catalog;
+}
+
+async function catalogAround(
+ official: ModelCatalog,
+ env: Record<string, string | undefined>,
+ fetchImpl: typeof fetch,
+): Promise<ModelCatalog> {
// A relative CODEX_HOME or user home must not load a catalog from another directory.
const home = codexHome(env);
if (!home) return mergeLocalInject(official, env, fetchImpl);
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index 0f2857a7ec..475853cc21 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -11,7 +11,7 @@ import { homedir } from "node:os";
import { codexConfigMcp, codexConfigRunsServer, mountedMcpServerName } from "./codex-mcp-names.ts";
import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";
-import { laterStartup, openStartupModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
+import { laterStartup, openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
import { hostedWorkspaceConfigured } from "../enterprise.ts";
import { cloudHomeConfigured } from "../cloud-home.ts";
import { serverVersion } from "../environment.ts";
@@ -511,13 +511,13 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (generation === planGeneration && !planSigningOut && !disposed && (!kept || catalog.options.length)) models = catalog;
}
} catch (error) {
- if (!kept) throw error;
+ if (!kept) throw error; unconfirmedModelCatalog(kept);
}
} else {
try {
const resolved = await readCodexModelCatalog(catalogEnv, fetch, config.cli);
- if (resolved.options.length) models = resolved;
- } catch {}
+ if (resolved.options.length) models = resolved; else unconfirmedModelCatalog(models);
+ } catch { unconfirmedModelCatalog(models); }
}
try { writeStartupModelCache(instanceId, models); } catch {}
};
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index fe0f864457..939a6624be 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -27,7 +27,7 @@ import { requestTooLargeMessage } from "../../shared/request-too-large.ts";
import { toolSchemaProfileFor } from "../tool-schema-profile.ts";
import { classifyContinuable, writeTurnHandoff } from "../turn-continuation.ts";
import { KEY_REJECTED_REASON, keyRejected, noteKeyAccepted, noteKeyRejected, rejectsKey } from "../key-rejections.ts";
-import { Agent, fetch as fetchWithoutLimits } from "undici";
+import type { Agent } from "undici";
export interface OpenAIChatMessage {
role: "system" | "user" | "assistant" | "tool";
@@ -106,8 +106,9 @@ interface NativeLog {
const FETCH_LIMIT_MS = 300_000;
const LIVENESS_MISSES = 3;
let unlimitedAgent: Agent | undefined;
-function fetchPastLimit(url: string, init: RequestInit): Promise<Response> {
- unlimitedAgent ??= new Agent({ headersTimeout: 0, bodyTimeout: 0 });
+async function fetchPastLimit(url: string, init: RequestInit): Promise<Response> {
+ const { Agent: UndiciAgent, fetch: fetchWithoutLimits } = await import("undici");
+ unlimitedAgent ??= new UndiciAgent({ headersTimeout: 0, bodyTimeout: 0 });
return fetchWithoutLimits(url, { ...init, dispatcher: unlimitedAgent } as Parameters<typeof fetchWithoutLimits>[1]) as unknown as Promise<Response>;
}
diff --git a/server/drivers/pi.ts b/server/drivers/pi.ts
index b807a685f1..3606df43c3 100644
--- a/server/drivers/pi.ts
+++ b/server/drivers/pi.ts
@@ -6,7 +6,7 @@ import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { PROVIDER_CREDENTIAL_ENV, stripWorkspaceCredentialEnv } from "../config.ts";
-import { openStartupModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
+import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
import { augmentedPath } from "../env-path.ts";
import { describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";
import {
@@ -397,10 +397,10 @@ export const PiDriver: ProviderDriver<PiConfig> = {
const catalogEnv = piEnvironment({ ...process.env, ...input.environment });
let models = EMPTY;
const readModels = async () => {
- let base = models;
+ let base = models, listed = false;
try {
const resolved = await fetchPiModels(config.cli, catalogEnv);
- if (resolved.options.length) base = resolved;
+ if (resolved.options.length) [base, listed] = [resolved, true];
} catch {}
try {
const next = await applyPiLocalCatalog(base, catalogEnv);
@@ -408,7 +408,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
} catch {
if (base.options.length) models = base;
}
- try { writeStartupModelCache(instanceId, models); } catch {}
+ try { if (!listed) unconfirmedModelCatalog(models); writeStartupModelCache(instanceId, models); } catch {}
};
const refreshModels = async () => {
await updatePiModelCatalog(config.cli, catalogEnv);
diff --git a/server/drivers/session-idle.test.ts b/server/drivers/session-idle.test.ts
index 581b79f56b..84b5b302ac 100644
--- a/server/drivers/session-idle.test.ts
+++ b/server/drivers/session-idle.test.ts
@@ -1,12 +1,25 @@
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { forgetPresence, personAsks, sawThread, seenWithin } from "../thread-presence.ts";
-import { engineIdleMs, sessionIdlePolicy, UNWATCHED_IDLE_MS } from "./session-idle.ts";
+import {
+ armIdleClose, engineIdleMs, idleEnginesAllowed, keepWarm, sessionIdlePolicy, SMALL_BOX_IDLE_MS, stopIdleClose, UNWATCHED_IDLE_MS, warmEngineKeys,
+} from "./session-idle.ts";
+
+const GB = 1024 ** 3;
+const DESKTOP = 16 * GB;
describe("sessionIdlePolicy", () => {
it("defaults to ten minutes with a ten-second floor", () => {
- expect(sessionIdlePolicy("CLAUDE", {})).toEqual({ idleMs: 10 * 60_000, minimumMs: 10_000 });
- expect(sessionIdlePolicy("ACP", {})).toEqual({ idleMs: 10 * 60_000, minimumMs: 10_000 });
+ expect(sessionIdlePolicy("CLAUDE", {}, DESKTOP)).toEqual({ idleMs: 10 * 60_000, minimumMs: 10_000 });
+ expect(sessionIdlePolicy("ACP", {}, DESKTOP)).toEqual({ idleMs: 10 * 60_000, minimumMs: 10_000 });
+ });
+
+ it("keeps an idle engine two and a half minutes on a box of 1.5 GB or less, unless configured", () => {
+ expect(sessionIdlePolicy("CLAUDE", {}, 1.5 * GB).idleMs).toBe(SMALL_BOX_IDLE_MS);
+ expect(sessionIdlePolicy("ACP", {}, 512 * 1024 ** 2).idleMs).toBe(SMALL_BOX_IDLE_MS);
+ expect(sessionIdlePolicy("ACP", {}, 2 * GB).idleMs).toBe(10 * 60_000);
+ expect(sessionIdlePolicy("CLAUDE", { OMB_SESSION_IDLE_MS: "600000" }, GB).idleMs).toBe(600_000);
+ expect(sessionIdlePolicy("ACP", { OMB_ACP_SESSION_IDLE_MIN_MS: "200000" }, GB)).toEqual({ idleMs: 200_000, minimumMs: 200_000 });
});
it("honors each harness's own legacy names", () => {
@@ -36,8 +49,8 @@ describe("sessionIdlePolicy", () => {
it("rejects unusable delays before the floor instead of coercing them to a 1 ms timer", () => {
for (const raw of ["not-a-number", "0", "-5", "", "Infinity", "1e309", "2147483648"]) {
- expect(sessionIdlePolicy("CLAUDE", { OMB_CLAUDE_SESSION_IDLE_MS: raw }).idleMs).toBe(10 * 60_000);
- expect(sessionIdlePolicy("ACP", { OMB_SESSION_IDLE_MS: raw }).idleMs).toBe(10 * 60_000);
+ expect(sessionIdlePolicy("CLAUDE", { OMB_CLAUDE_SESSION_IDLE_MS: raw }, DESKTOP).idleMs).toBe(10 * 60_000);
+ expect(sessionIdlePolicy("ACP", { OMB_SESSION_IDLE_MS: raw }, DESKTOP).idleMs).toBe(10 * 60_000);
}
expect(sessionIdlePolicy("CLAUDE", { OMB_CLAUDE_SESSION_IDLE_MS: "2147483647" }).idleMs).toBe(2_147_483_647);
expect(sessionIdlePolicy("ACP", { OMB_ACP_SESSION_IDLE_MIN_MS: "Infinity" }).minimumMs).toBe(10_000);
@@ -84,3 +97,54 @@ describe("an idle engine's keep-alive", () => {
expect(seenWithin("t2000", 60_000, now)).toBe(true);
});
});
+
+describe("idle engines on a small box", () => {
+ const small = { bytes: GB };
+ const engine = (busy = false) => {
+ const state = { busy, closed: 0 };
+ return { state, warm: { idle: () => !state.busy, close: () => { state.closed += 1; } } };
+ };
+ afterEach(() => { for (const key of warmEngineKeys()) stopIdleClose(key, null); });
+
+ it("allows one idle engine once less than half of a small box is free, and any number otherwise", () => {
+ expect(idleEnginesAllowed(small, 0.4 * GB)).toBe(1);
+ expect(idleEnginesAllowed(small, 0.6 * GB)).toBe(Infinity);
+ expect(idleEnginesAllowed({ bytes: DESKTOP }, 0)).toBe(Infinity);
+ });
+
+ 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);
+ keepWarm("b", b.warm, small, () => 0.6 * GB);
+ expect(a.state.closed).toBe(0);
+ keepWarm("c", c.warm, small, () => 0.3 * GB);
+ expect([a.state.closed, b.state.closed, c.state.closed]).toEqual([1, 0, 0]);
+ expect(warmEngineKeys()).toEqual(["c"]);
+ });
+
+ 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);
+ expect([a.state.closed, b.state.closed, warmEngineKeys()]).toEqual([0, 0, []]);
+ keepWarm("a", a.warm, small, () => 0.6 * GB);
+ stopIdleClose("a", null);
+ keepWarm("b", b.warm, small, () => 0.1 * GB);
+ expect(a.state.closed).toBe(0);
+ });
+
+ it("closes on its timer like any idle engine", () => {
+ vi.useFakeTimers();
+ try {
+ const a = engine();
+ const timer = armIdleClose("a", 150_000, a.warm);
+ vi.advanceTimersByTime(149_999);
+ expect(a.state.closed).toBe(0);
+ vi.advanceTimersByTime(1);
+ expect(a.state.closed).toBe(1);
+ stopIdleClose("a", timer);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.ts
index 4627840e66..6adfaa0fe9 100644
--- a/server/drivers/session-idle.ts
+++ b/server/drivers/session-idle.ts
@@ -1,3 +1,4 @@
+import { availableMemory, boxMemory, type BoxMemory } from "../box-memory.ts";
import { engineMemory, type EngineMemory } from "../engine-memory.ts";
import { seenWithin } from "../thread-presence.ts";
@@ -7,6 +8,10 @@ export interface SessionIdlePolicy {
}
const DEFAULT_IDLE_MS = 10 * 60_000;
+/** One warm engine and its MCP servers take 250 to 450 MB: on a box this small an idle one is soon given back, and the
+ * next turn resumes its session by id. */
+export const SMALL_BOX_BYTES = 1.5 * 1024 ** 3;
+export const SMALL_BOX_IDLE_MS = 150_000;
const MINIMUM_IDLE_MS = 10_000;
/** setTimeout treats anything above 2^31-1 ms as 1 ms. */
const MAX_TIMER_MS = 2_147_483_647;
@@ -17,10 +22,12 @@ function usableMilliseconds(raw: string | undefined): number | null {
}
/** Per-harness names (OMB_CLAUDE_SESSION_IDLE_*, OMB_ACP_SESSION_IDLE_*) win over OMB_SESSION_IDLE_MS /
- * OMB_SESSION_IDLE_MIN_MS; the floor is the greater of ten seconds and any configured minimum. */
+ * OMB_SESSION_IDLE_MIN_MS, which win over the box's default; the floor is the greater of ten seconds and any configured
+ * minimum. */
export function sessionIdlePolicy(
driverPrefix: string,
env: Record<string, string | undefined> = process.env,
+ boxBytes: number = boxMemory().bytes,
): SessionIdlePolicy {
const minimumMs = Math.max(
MINIMUM_IDLE_MS,
@@ -31,10 +38,56 @@ export function sessionIdlePolicy(
const configured =
usableMilliseconds(
env[`OMB_${driverPrefix}_SESSION_IDLE_MS`] ?? env.OMB_SESSION_IDLE_MS,
- ) ?? DEFAULT_IDLE_MS;
+ ) ?? (boxBytes <= SMALL_BOX_BYTES ? SMALL_BOX_IDLE_MS : DEFAULT_IDLE_MS);
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;
+}
+
+export interface WarmEngine {
+ /** Still idle and free to close: no turn running, no hold keeping it up. */
+ idle: () => boolean;
+ close: () => void;
+}
+
+/** Idle engines of every driver, the longest idle first. */
+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;
+ 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());
+ if (extra <= 0) return;
+ for (const [other, warm] of [...warmEngines].slice(0, extra)) {
+ warmEngines.delete(other);
+ warm.close();
+ }
+}
+
+/** Closes an idle engine after `ms`, or sooner on a small box once another engine goes idle after it. */
+export function armIdleClose(key: string, ms: number, engine: WarmEngine): ReturnType<typeof setTimeout> {
+ const timer = setTimeout(engine.close, ms);
+ timer.unref?.();
+ keepWarm(key, engine);
+ return timer;
+}
+
+export function stopIdleClose(key: string, timer: ReturnType<typeof setTimeout> | null): void {
+ if (timer) clearTimeout(timer);
+ warmEngines.delete(key);
+}
+
+export function warmEngineKeys(): string[] {
+ return [...warmEngines.keys()];
+}
+
/** A person wrote in, opened or read the thread this recently: it is the conversation in front of them. */
const WATCHED_MS = 30 * 60_000;
/** A thread nobody has in front of them (a teammate's delegated work, a routine) keeps its engine this long. */
diff --git a/server/drivers/small-box-idle.test.ts b/server/drivers/small-box-idle.test.ts
new file mode 100644
index 0000000000..7cadc3b9de
--- /dev/null
+++ b/server/drivers/small-box-idle.test.ts
@@ -0,0 +1,78 @@
+// Two conversations on a small box with little memory free: the one idle longest gives back its engine as soon as the
+// other goes idle, and its next turn resumes by session id.
+import { randomUUID } from "node:crypto";
+import { chmodSync, mkdtempSync, readFileSync } 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 { GrokAgentDriver } from "./acp/grok.ts";
+import { ClaudeDriver } from "./claude.ts";
+
+const GB = 1024 ** 3;
+vi.mock("../box-memory.ts", async (original) => ({
+ ...await original<typeof import("../box-memory.ts")>(),
+ boxMemory: () => ({ bytes: GB, cgroupLimit: null }),
+ availableMemory: () => 0.2 * GB,
+}));
+
+const here = dirname(fileURLToPath(import.meta.url));
+const FAKE_CLAUDE = join(here, "..", "testing", "fake-claude-cli.ts");
+const FAKE_ACP = join(here, "..", "testing", "fake-acp-cli.ts");
+
+let scratch: string, instance: ProviderInstance, recorder: EventRecorder;
+
+beforeEach(() => {
+ ensureDirs();
+ chmodSync(FAKE_CLAUDE, 0o755);
+ chmodSync(FAKE_ACP, 0o755);
+ scratch = mkdtempSync(join(tmpdir(), "omb-small-box-"));
+});
+afterEach(async () => {
+ delete process.env.FAKE_CLAUDE_DUMP;
+ recorder.stop();
+ await instance.dispose();
+ await removeTempDir(scratch);
+});
+
+const threads = () => [randomUUID(), randomUUID()];
+const closedIdle = (threadId: string) => {
+ try { return readFileSync(join(NATIVE_DIR, `${threadId}.ndjson`), "utf8").includes('"close":"idle"'); } catch { return false; }
+};
+const turn = async (threadId: string, resumeCursor?: string) => {
+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "go", ...(resumeCursor ? { resumeCursor } : {}) });
+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+};
+
+it("closes Claude's longest-idle engine when a second goes idle, and resumes it on the next turn", async () => {
+ instance = await ClaudeDriver.create({ instanceId: "small-claude", displayName: "Claude", environment: {}, enabled: true, config: { cli: FAKE_CLAUDE, permissionMode: "acceptEdits" } });
+ recorder = recordEvents(instance.adapter);
+ const [first, second] = threads();
+ await turn(first!);
+ expect(closedIdle(first!)).toBe(false);
+ await turn(second!);
+ await expect.poll(() => closedIdle(first!), { timeout: 10_000 }).toBe(true);
+ expect(closedIdle(second!)).toBe(false);
+
+ const started = recorder.events.find((event) => event.type === "session.started" && event.threadId === first) as { sessionId: string };
+ process.env.FAKE_CLAUDE_DUMP = join(scratch, "resumed.json");
+ await turn(first!, started.sessionId);
+ expect(JSON.parse(readFileSync(join(scratch, "resumed.json"), "utf8")).argv).toContain("--resume");
+ await expect.poll(() => closedIdle(second!), { timeout: 10_000 }).toBe(true);
+}, 30_000);
+
+it("closes an ACP engine's longest-idle session when a second goes idle", async () => {
+ instance = await GrokAgentDriver.create({ instanceId: "small-acp", displayName: "Grok", environment: {}, enabled: true, config: { cli: FAKE_ACP, fullAuto: true } });
+ recorder = recordEvents(instance.adapter);
+ const [first, second] = threads();
+ await turn(first!);
+ expect(closedIdle(first!)).toBe(false);
+ await turn(second!);
+ await expect.poll(() => closedIdle(first!), { timeout: 10_000 }).toBe(true);
+ expect(closedIdle(second!)).toBe(false);
+}, 30_000);
diff --git a/server/engine-standalone.ts b/server/engine-standalone.ts
index 82f4335889..f3004032e7 100644
--- a/server/engine-standalone.ts
+++ b/server/engine-standalone.ts
@@ -16,7 +16,6 @@ import {
import { chmod, copyFile, link, lstat, mkdir, open, readdir, rename, rm, stat, unlink, writeFile, type FileHandle } from "node:fs/promises";
import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";
import { stripVTControlCharacters } from "node:util";
-import * as tar from "tar";
import { writeFileAtomic } from "./atomic.ts";
import { cliProbeEnvironment } from "./cli-probe.ts";
@@ -436,6 +435,7 @@ async function download(release: StandaloneRelease, asset: StandaloneAsset, dest
/** Plain files and folders only, each inside the staging folder; `./` prefixes are allowed. */
async function extractTarGz(archivePath: string, staging: string): Promise<boolean> {
let unsafe = false;
+ const tar = await import("tar");
await tar.x({
file: archivePath,
cwd: staging,
diff --git a/server/environment.ts b/server/environment.ts
index 8ebb1a98f9..8fc89cc37c 100644
--- a/server/environment.ts
+++ b/server/environment.ts
@@ -119,6 +119,13 @@ export function loadEnvironmentId(dataDir: string): string {
}
}
+let stamp: string | undefined;
+/** This server's release and, on a Cloud, its image: what it runs changes with either, the engines' CLIs included. */
+export function buildStamp(): string {
+ stamp ??= [serverVersion(), process.env.OMB_CLOUD_IMAGE?.trim()].filter(Boolean).join(" ");
+ return stamp;
+}
+
/** The desktop's own version, else the bundle's package.json (scripts/bundle-server.mjs), else the checkout's. */
export function serverVersion(root = SERVER_ROOT): string {
const fromEnv = process.env.OMB_APP_VERSION?.trim();
diff --git a/server/harness/engine-status-file.test.ts b/server/harness/engine-status-file.test.ts
index 26616f462c..64c58dd6f8 100644
--- a/server/harness/engine-status-file.test.ts
+++ b/server/harness/engine-status-file.test.ts
@@ -22,7 +22,7 @@ it("writes what the save delay still holds when the process exits cleanly, once"
flushEngineStatusFiles();
expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ v: 1, engines: [row] });
const read = status.read(() => ({ driverKind: "antigravityAgent", cli: "agy" }));
- expect(read.get("work")).toEqual({ state: "available", authenticated: true });
+ expect(read.get("work")).toEqual({ snapshot: { state: "available", authenticated: true }, checkedAt: null, settings: null });
flushEngineStatusFiles();
expect(process.listeners("exit").filter((listener) => listener === flushEngineStatusFiles)).toHaveLength(1);
});
@@ -39,6 +39,6 @@ it("keeps the marks the welcome and the AI tests read: a ChatGPT plan and OpenCo
]);
flushEngineStatusFiles();
const read = status.read((instanceId) => instanceId === "opencode" ? { driverKind: "opencodeGo", cli: "opencode" } : { driverKind: "codex", cli: "codex" });
- expect(read.get("opencode")).toEqual(free);
- expect(read.get("codex")).toEqual(plan);
+ expect(read.get("opencode")?.snapshot).toEqual(free);
+ expect(read.get("codex")?.snapshot).toEqual(plan);
});
diff --git a/server/harness/engine-status-file.ts b/server/harness/engine-status-file.ts
index e59ff1f69e..f4993814a9 100644
--- a/server/harness/engine-status-file.ts
+++ b/server/harness/engine-status-file.ts
@@ -9,6 +9,15 @@ export interface EngineStatusRow {
driverKind: string;
cli: string | null;
snapshot: ProviderSnapshot;
+ /** When a probe last gave this status, and a digest of the engine's settings it was probed with. */
+ checkedAt?: number;
+ settings?: string;
+}
+
+export interface SavedEngineStatus {
+ snapshot: ProviderSnapshot;
+ checkedAt: number | null;
+ settings: string | null;
}
type Target = (instanceId: InstanceId) => { driverKind: string; cli: string | null } | null;
@@ -89,8 +98,8 @@ export function engineStatusFile(file: string) {
};
return {
/** The statuses the last run recorded, for the engines still configured with the same driver and CLI. */
- read(target: Target): Map<InstanceId, ProviderSnapshot> {
- const seeds = new Map<InstanceId, ProviderSnapshot>();
+ read(target: Target): Map<InstanceId, SavedEngineStatus> {
+ const seeds = new Map<InstanceId, SavedEngineStatus>();
let rows: unknown;
try {
rows = (JSON.parse(readFileSync(file, "utf8")) as { engines?: unknown }).engines;
@@ -102,7 +111,10 @@ export function engineStatusFile(file: string) {
if (!row || !text(row.instanceId)) continue;
const now = target(row.instanceId);
const snapshot = snapshotFrom(row.snapshot);
- if (snapshot && now && now.driverKind === row.driverKind && now.cli === (row.cli ?? null)) seeds.set(row.instanceId, snapshot);
+ if (snapshot && now && now.driverKind === row.driverKind && now.cli === (row.cli ?? null)) {
+ seeds.set(row.instanceId, { snapshot, checkedAt: typeof row.checkedAt === "number" && Number.isFinite(row.checkedAt) ? row.checkedAt : null,
+ settings: text(row.settings) ? row.settings : null });
+ }
}
return seeds;
},
diff --git a/server/harness/registry-start-read.test.ts b/server/harness/registry-start-read.test.ts
index 9501677057..66086e7a6f 100644
--- a/server/harness/registry-start-read.test.ts
+++ b/server/harness/registry-start-read.test.ts
@@ -9,7 +9,7 @@ import type { InstanceConfigMap } from "../contracts.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { makeFakeDriver, type FakeDriverOptions } from "../testing/fake-driver.ts";
import { snapshotFrom, STATUS_SAVE_DELAY_MS } from "./engine-status-file.ts";
-import { enginesByUse, ProviderRegistry, SNAPSHOT_DEADLINE_MS, START_READ_STEP_MS } from "./registry.ts";
+import { ENGINE_STATUS_FRESH_MS, enginesByUse, ProviderRegistry, SNAPSHOT_DEADLINE_MS, START_READ_STEP_MS } from "./registry.ts";
const AVAILABLE = { state: "available", version: "0.0.0-fake" } as const;
const GONE = { state: "unavailable", reason: "`fake` CLI not found" } as const;
@@ -24,6 +24,8 @@ const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
/** The recorded status is written a second after the last probe lands. */
const saved = async () => { await vi.advanceTimersByTimeAsync(STATUS_SAVE_DELAY_MS); };
const timersForTheFile = () => vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+/** A start long enough after the last run that its statuses are probed again. */
+const later = () => Date.now() + ENGINE_STATUS_FRESH_MS;
async function engines(options: Record<string, FakeDriverOptions>, registryOptions: ConstructorParameters<typeof ProviderRegistry>[1] = {}, configs?: InstanceConfigMap) {
const fakes = Object.entries(options).map(([kind, opts]) => {
@@ -123,13 +125,14 @@ describe("the start-up read", () => {
await lastRun.registry.describe();
expect(existsSync(file)).toBe(false);
await saved();
- expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ v: 1, engines: [{ instanceId: "fake", driverKind: "fake", cli: "fake-cli", snapshot: AVAILABLE }] });
+ expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ v: 1, engines: [{ instanceId: "fake", driverKind: "fake", cli: "fake-cli", snapshot: AVAILABLE,
+ checkedAt: expect.any(Number), settings: expect.stringMatching(/^[0-9a-f]{16}$/) }] });
if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
const probe = gate();
Object.assign(options, { holdSnapshot: probe.promise, answer: GONE });
const { registry, probes } = await engines({ fake: options }, { statusFile: file });
- const read = registry.readAtStart();
+ const read = registry.readAtStart([], () => {}, later());
const [listed] = await registry.describe({ known: true });
expect(listed.snapshot).toEqual(AVAILABLE);
expect(registry.knownSnapshot("fake")).toEqual(AVAILABLE);
@@ -163,7 +166,7 @@ describe("the start-up read", () => {
const probe = gate();
Object.assign(options, { holdSnapshot: probe.promise, answer: GONE });
const { registry, probes } = await engines({ fake: options }, { statusFile: file });
- const read = registry.readAtStart(["fake"]);
+ const read = registry.readAtStart(["fake"], () => {}, later());
expect(probes()).toEqual({ fake: 1 });
const warm = gate();
options.holdSnapshot = warm.promise;
@@ -185,7 +188,43 @@ describe("the start-up read", () => {
await (await engines({ fake: {} }, { statusFile: file })).registry.describe();
await saved();
const { registry } = await engines({ fake: {} }, { statusFile: file });
- expect((await registry.readAtStart()).changed).toBe(false);
+ expect((await registry.readAtStart([], () => {}, later())).changed).toBe(false);
+ });
+
+ it("takes an engine the last run found ready within the fresh window as read, and probes one it found unavailable or set up otherwise", async () => {
+ const file = statusFile();
+ const options: Record<string, FakeDriverOptions> = { ready: {}, gone: { answer: GONE }, rekeyed: {} };
+ timersForTheFile();
+ await (await engines(options, { statusFile: file })).registry.describe();
+ await saved();
+ const checkedAt = JSON.parse(readFileSync(file, "utf8")).engines[0].checkedAt as number;
+
+ const { registry, probes } = await engines(options, { statusFile: file },
+ { ready: { driver: "ready" }, gone: { driver: "gone" }, rekeyed: { driver: "rekeyed", environment: { FAKE_KEY: "other" } } });
+ const { changed } = await registry.readAtStart(["ready"], () => {}, checkedAt + ENGINE_STATUS_FRESH_MS - 1);
+ expect(probes()).toEqual({ ready: 0, gone: 1, rekeyed: 1 });
+ expect(changed).toBe(false);
+ expect(registry.lastSnapshot("ready")).toEqual(AVAILABLE);
+ expect(registry.provisional()).toBe(false);
+ await saved();
+ expect(JSON.parse(readFileSync(file, "utf8")).engines[0].checkedAt).toBe(checkedAt);
+ // The server's own reads answer from it (a later catalog's new-bot default must not probe every CLI)...
+ expect((await registry.describe()).find((engine) => engine.instanceId === "ready")?.snapshot).toEqual(AVAILABLE);
+ expect(probes().ready).toBe(0);
+ // ...and the list a person asks for probes it.
+ await registry.describe({ known: true });
+ expect(probes().ready).toBe(1);
+
+ const again = await engines(options, { statusFile: file },
+ { ready: { driver: "ready" }, gone: { driver: "gone" }, rekeyed: { driver: "rekeyed", environment: { FAKE_KEY: "other" } } });
+ await again.registry.readAtStart([], () => {}, checkedAt + ENGINE_STATUS_FRESH_MS - 1);
+ again.registry.forgetSnapshots();
+ await again.registry.describe();
+ expect(again.probes().ready).toBe(1);
+
+ const stale = await engines(options, { statusFile: file });
+ await stale.registry.readAtStart([], () => {}, checkedAt + ENGINE_STATUS_FRESH_MS);
+ expect(stale.probes()).toEqual({ ready: 1, gone: 1, rekeyed: 1 });
});
it("keeps no seed for an engine whose driver or CLI changed, or once the engines must be probed again", async () => {
diff --git a/server/harness/registry.ts b/server/harness/registry.ts
index ad664f0cc8..5fbb8f6eec 100644
--- a/server/harness/registry.ts
+++ b/server/harness/registry.ts
@@ -1,5 +1,8 @@
// Provider instance registry — port of upstream's ProviderInstanceRegistryLive behavior, minus Effect.
+import { createHash } from "node:crypto";
+
import { findCliCandidates } from "../env-path.ts";
+import { buildStamp } from "../environment.ts";
import { installNpmEngine, npmAvailable, serverInstallFor, standaloneLookupPath } from "../engine-install.ts";
import { installStandaloneEngine, isAppStandaloneCopy, type StandaloneInstalled } from "../engine-standalone.ts";
import { withEngineMemory } from "../engine-memory.ts";
@@ -80,6 +83,11 @@ function withinDeadline(read: () => Promise<ProviderSnapshot>): Promise<Provider
]).finally(() => clearTimeout(deadline));
}
+/** An engine the last run found ready this recently is taken as read at start, so a restart or a Cloud's wake probes no
+ * CLI; one it found unavailable or signed out is probed, since a restart is how a fix gets picked up. A probe that finds
+ * the same status refreshes the recorded time only once it is half this old, so it is not rewritten. */
+export const ENGINE_STATUS_FRESH_MS = 30 * 60_000;
+
/** How long the start-up read waits on one CLI before probing the next, so a stuck CLI holds back no other for long. */
export const START_READ_STEP_MS = 5_000;
@@ -106,6 +114,12 @@ export class ProviderRegistry {
private lastSnapshots = new Map<InstanceId, ProviderSnapshot>();
private seeds = new Map<InstanceId, ProviderSnapshot>();
private seedObjects = new WeakSet<ProviderSnapshot>();
+ private checkedAt = new Map<InstanceId, number>();
+ /** Engines taken as read at start and not probed since: the server's own reads answer from that status while it is fresh. */
+ private takenAsRead = new Set<InstanceId>();
+ /** A digest of each engine's settings and this server's build: a status probed under other settings (a key, a sign-out)
+ * or another build's CLIs is not fresh. */
+ private settings = new Map<InstanceId, string>();
/** Engines the start-up read has not probed yet; null outside that read. */
private unread: Set<InstanceId> | null = null;
private snapshotGeneration = 0;
@@ -172,6 +186,7 @@ export class ProviderRegistry {
// The RAW config: decodeConfig fills in the driver default, which would flag every instance as overridden.
const rawCli = cliOfRaw(entry.config);
if (rawCli) this.cliByInstance.set(instanceId, rawCli);
+ this.settings.set(instanceId, createHash("sha256").update(JSON.stringify([entry, buildStamp()])).digest("hex").slice(0, 16));
const live = withUnaskedStops(withEngineHomes(withEngineMemory(await driver.create({
instanceId,
displayName: entry.displayName ?? driver.metadata.displayName,
@@ -219,6 +234,7 @@ export class ProviderRegistry {
forgetSnapshots(): void {
this.snapshotGeneration += 1;
this.seeds.clear();
+ this.takenAsRead.clear();
}
/**
@@ -226,16 +242,24 @@ export class ProviderRegistry {
* each CLI is read from a cold disk with no other in the way; `afterFirst` runs once the first has answered; engines
* without a CLI are read at once. An engine the last run saw available that a probe now finds unavailable is probed
* once more, warm, before the read ends. Until the read reaches an engine, a turn on it probes that engine itself
- * (`engineRead`) and `describe({ known: true })` answers it from the last run's status.
+ * (`engineRead`) and `describe({ known: true })` answers it from the last run's status, unless that status is fresh
+ * (`ENGINE_STATUS_FRESH_MS`) and counts as read.
*/
- async readAtStart(first: readonly InstanceId[] = [], afterFirst: () => void = () => {}) {
+ async readAtStart(first: readonly InstanceId[] = [], afterFirst: () => void = () => {}, now = Date.now()) {
const live = this.instances().map((instance) => instance.instanceId);
- for (const [instanceId, snapshot] of this.status?.read((id) => this.byId.get(id)?.live ? this.cliTarget(id) : null) ?? []) {
+ const fresh = new Set<InstanceId>();
+ for (const [instanceId, { snapshot, checkedAt, settings }] of this.status?.read((id) => this.byId.get(id)?.live ? this.cliTarget(id) : null) ?? []) {
this.seeds.set(instanceId, snapshot);
- this.seedObjects.add(snapshot);
+ if (snapshot.state === "available" && snapshot.authenticated !== false && settings === this.settings.get(instanceId)
+ && checkedAt !== null && now - checkedAt >= 0 && now - checkedAt < ENGINE_STATUS_FRESH_MS) {
+ fresh.add(instanceId);
+ this.takenAsRead.add(instanceId);
+ this.lastSnapshots.set(instanceId, snapshot);
+ this.checkedAt.set(instanceId, checkedAt);
+ } else this.seedObjects.add(snapshot);
}
const seeded = new Map(this.seeds);
- this.unread = new Set(live);
+ this.unread = new Set(live.filter((id) => !fresh.has(id)));
try {
const withCli = new Set(live.filter((id) => this.cliTarget(id)?.cli));
const withoutCli = this.engineRead(...live.filter((id) => !withCli.has(id)));
@@ -399,12 +423,17 @@ export class ProviderRegistry {
return isAppStandaloneCopy(cli, this.enginesBaseDir, standaloneLookupPath(this.enginesBaseDir));
}
- /** `reuse`: answer from a status read since the last forgetSnapshots(); one older than `ms` is read again in the background
- * and `changed` runs when that read differs. */
+ /** `known` is the engine list a person asks for: it probes an engine taken as read at start, and answers one the
+ * start-up read has yet to reach from the last run's status. `reuse`: answer from a status read since the last
+ * forgetSnapshots(); one older than `ms` is read again in the background and `changed` runs when that read differs. */
describe(options: { known?: boolean; reuse?: { ms: number; changed(): void } } = {}) {
return this.describeWith((instance) => {
- const seed = options.known && this.unread?.has(instance.instanceId) ? this.seeds.get(instance.instanceId) : undefined;
- if (seed) return Promise.resolve(seed);
+ const { instanceId } = instance;
+ const seed = options.known && this.unread?.has(instanceId) ? this.seeds.get(instanceId) : undefined;
+ const taken = !options.known && this.takenAsRead.has(instanceId) && Date.now() - (this.checkedAt.get(instanceId) ?? 0) < ENGINE_STATUS_FRESH_MS
+ ? this.lastSnapshots.get(instanceId) : undefined;
+ const answer = seed ?? taken;
+ if (answer) return Promise.resolve(answer);
const last = options.reuse && this.readsOf.get(instance);
if (!options.reuse || !last || last.generation !== this.snapshotGeneration) return this.read(instance);
if (Date.now() - last.at >= options.reuse.ms) {
@@ -426,7 +455,11 @@ export class ProviderRegistry {
}
// Only while this is still the live instance: a reload may have replaced it during the read.
if (this.byId.get(instance.instanceId)?.live === instance) {
+ const before = this.lastSnapshots.get(instance.instanceId), checkedAt = this.checkedAt.get(instance.instanceId);
+ if (checkedAt === undefined || Date.now() - checkedAt >= ENGINE_STATUS_FRESH_MS / 2 || !before
+ || JSON.stringify(snapshotFrom(before)) !== JSON.stringify(snapshotFrom(snapshot))) this.checkedAt.set(instance.instanceId, Date.now());
this.lastSnapshots.set(instance.instanceId, snapshot);
+ this.takenAsRead.delete(instance.instanceId);
this.unread?.delete(instance.instanceId);
this.saveStatus();
}
@@ -436,7 +469,9 @@ export class ProviderRegistry {
private saveStatus(): void {
this.status?.save(this.instances().flatMap(({ instanceId, driverKind }) => {
const snapshot = this.lastSnapshots.get(instanceId) ?? this.seeds.get(instanceId);
- return snapshot ? [{ instanceId, driverKind, cli: this.cliTarget(instanceId)?.cli ?? null, snapshot }] : [];
+ const checkedAt = this.lastSnapshots.has(instanceId) ? this.checkedAt.get(instanceId) : undefined, settings = this.settings.get(instanceId);
+ return snapshot ? [{ instanceId, driverKind, cli: this.cliTarget(instanceId)?.cli ?? null, snapshot,
+ ...(checkedAt === undefined || settings === undefined ? {} : { checkedAt, settings }) }] : [];
}));
}
@@ -520,6 +555,9 @@ export class ProviderRegistry {
this.byId.clear();
this.cliByInstance.clear();
this.lastSnapshots.clear();
+ this.checkedAt.clear();
+ this.takenAsRead.clear();
+ this.settings.clear();
this.seeds.clear();
}
@@ -528,6 +566,9 @@ export class ProviderRegistry {
this.byId.delete(instanceId);
this.cliByInstance.delete(instanceId);
this.lastSnapshots.delete(instanceId);
+ this.checkedAt.delete(instanceId);
+ this.takenAsRead.delete(instanceId);
+ this.settings.delete(instanceId);
this.seeds.delete(instanceId);
await entry?.live?.dispose();
}
diff --git a/server/phone-secret.ts b/server/phone-secret.ts
index 62895e8d0d..3d893d1f00 100644
--- a/server/phone-secret.ts
+++ b/server/phone-secret.ts
@@ -1,12 +1,7 @@
import { createECDH, createHash, type webcrypto } from "node:crypto";
import { desktopCredentialSlot, isCredentialTargetId } from "../shared/credential-request.ts";
-import {
- Aes256Gcm,
- CipherSuite,
- DhkemP256HkdfSha256,
- HkdfSha256,
-} from "@hpke/core";
+import type { CipherSuite } from "@hpke/core";
export const PHONE_SECRET_PROTOCOL_VERSION = 1 as const;
export const PHONE_SECRET_INFO = "OpenMausBot phone credential v1";
@@ -60,11 +55,12 @@ export class PhoneSecretError extends Error {
}
}
-const suite = new CipherSuite({
+let hpkeSuite: Promise<CipherSuite> | undefined;
+const suite = () => hpkeSuite ??= import("@hpke/core").then(({ Aes256Gcm, CipherSuite, DhkemP256HkdfSha256, HkdfSha256 }) => new CipherSuite({
kem: new DhkemP256HkdfSha256(),
kdf: new HkdfSha256(),
aead: new Aes256Gcm(),
-});
+}));
const INFO = new TextEncoder().encode(PHONE_SECRET_INFO);
const decodeBase64URL = (value: unknown, expectedBytes?: number): Uint8Array | null => {
@@ -288,7 +284,7 @@ async function importIdentity(message: Record<string, unknown>): Promise<PhoneSe
} catch {
throw new PhoneSecretError("The desktop credential key is invalid", 503);
}
- const imported = await suite.kem.importKey("jwk", {
+ const imported = await (await suite()).kem.importKey("jwk", {
kty: "EC",
crv: "P-256",
x: privateKey.x,
@@ -406,7 +402,7 @@ export class PhoneSecretBridge {
let opened: ArrayBuffer;
try {
- opened = await suite.open(
+ opened = await (await suite()).open(
{ recipientKey: identity.privateKey, enc: encapsulatedKey, info: INFO },
ciphertext,
phoneSecretAAD(context),
diff --git a/server/server-launcher.ts b/server/server-launcher.ts
index a6bb4449f3..8bd4f95e19 100644
--- a/server/server-launcher.ts
+++ b/server/server-launcher.ts
@@ -1,10 +1,24 @@
// Container entry: restarts the server in place on RESTART_EXIT_CODE, since a container restart cuts off a Caddy sharing its network.
import { spawn, type ChildProcess } from "node:child_process";
-import { realpathSync } from "node:fs";
+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 { 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 } = {}) {
+ const bootstrap = join(here, "desktop-entry.mjs");
+ const cached = (options.exists ?? existsSync)(bootstrap);
+ const dataDir = env.OMB_DATA_DIR || join(homedir(), ".openmausbot");
+ 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,
+ };
+}
+
export function superviseServer(start: () => ChildProcess, options: { signals?: Pick<NodeJS.Process, "on" | "off">; now?: () => number } = {}): Promise<number> {
const signals = options.signals ?? process, now = options.now ?? Date.now;
return new Promise((done) => {
@@ -37,6 +51,6 @@ function isEntry(): boolean {
}
if (isEntry()) {
- const server = join(dirname(fileURLToPath(import.meta.url)), "index.js");
- void superviseServer(() => spawn(process.execPath, [server], { stdio: "inherit" })).then((code) => { process.exitCode = code; });
+ const server = serverCommand(dirname(fileURLToPath(import.meta.url)), process.env);
+ void superviseServer(() => spawn(process.execPath, server.args, { stdio: "inherit", env: server.env })).then((code) => { process.exitCode = code; });
}
diff --git a/server/startup-model-catalog.test.ts b/server/startup-model-catalog.test.ts
index d02d093961..5a0b230c93 100644
--- a/server/startup-model-catalog.test.ts
+++ b/server/startup-model-catalog.test.ts
@@ -8,12 +8,15 @@ import { createAcpDriver, type AcpSupport } from "./drivers/acp/core.ts";
import { ProviderRegistry } from "./harness/registry.ts";
import * as procs from "./procs.ts";
import { holdUntilFirstEngineRead } from "./first-engine-read.ts";
-import { openStartupModelCatalog, readStartupModelCache, writeStartupModelCache } from "./startup-model-catalog.ts";
+import { CodexDriver } from "./drivers/codex.ts";
+import { openStartupModelCatalog, readStartupModelCache, readStartupModelCacheEntry, STARTUP_MODEL_CACHE_FRESH_MS, unconfirmedModelCatalog, writeStartupModelCache } from "./startup-model-catalog.ts";
const CACHED: ModelCatalog = {
default: "cached-model",
options: [{ id: "cached-model", label: "Cached" }],
};
+/** Saved by a run long enough ago that a later start reads the list again. */
+const STALE = { checkedAt: Date.now() - STARTUP_MODEL_CACHE_FRESH_MS };
const FRESH: ModelCatalog = {
default: "fresh-model",
options: [{ id: "fresh-model", label: "Fresh" }],
@@ -117,7 +120,7 @@ describe("startup model catalogs", () => {
it("does not wait for a slow refresh when a later start already has a catalog", async () => {
seedBots();
- writeStartupModelCache("slow", CACHED);
+ writeStartupModelCache("slow", CACHED, STALE);
const gate = deferredCatalog();
const { driver } = slowDriver(gate.promise);
const registry = new ProviderRegistry([driver]);
@@ -135,7 +138,7 @@ describe("startup model catalogs", () => {
seedBots();
let refreshes = 0;
const open = (instanceId = "held") => openStartupModelCatalog({ instanceId, use: () => {}, current: () => CACHED, refresh: async () => { refreshes += 1; } });
- writeStartupModelCache("held", CACHED);
+ writeStartupModelCache("held", CACHED, STALE);
const release = holdUntilFirstEngineRead();
const opened = open() as { pending: Promise<void> };
for (let i = 0; i < 12; i += 1) await Promise.resolve();
@@ -146,6 +149,7 @@ describe("startup model catalogs", () => {
release();
await opened.pending;
expect(refreshes).toBe(1);
+ writeStartupModelCache("held", CACHED, STALE);
await (open() as { pending: Promise<void> }).pending;
expect(refreshes).toBe(2);
@@ -156,6 +160,62 @@ describe("startup model catalogs", () => {
releaseAgain();
});
+ it("uses a list read within the fresh window as it is, and reads an older one again", async () => {
+ seedBots();
+ let refreshes = 0;
+ const now = 1_800_000_000_000;
+ const open = (age: number) => {
+ writeStartupModelCache("timed", CACHED, { checkedAt: now - age });
+ let used: ModelCatalog | null = null;
+ const opened = openStartupModelCatalog({ instanceId: "timed", use: (catalog) => { used = catalog; }, current: () => CACHED,
+ refresh: async () => { refreshes += 1; }, now });
+ return { opened, used: () => used };
+ };
+ const fresh = open(STARTUP_MODEL_CACHE_FRESH_MS - 1);
+ expect(fresh.used()).toEqual(CACHED);
+ expect(await fresh.opened).toBeNull();
+ expect(refreshes).toBe(0);
+ await (open(STARTUP_MODEL_CACHE_FRESH_MS).opened as { pending: Promise<void> }).pending;
+ expect(refreshes).toBe(1);
+ // A clock set back is no proof the list is fresh, and another build's CLIs may list other models.
+ await (open(-60_000).opened as { pending: Promise<void> }).pending;
+ expect(refreshes).toBe(2);
+ writeStartupModelCache("timed", CACHED, { checkedAt: now, build: "0.0.1 an older image" });
+ await (openStartupModelCatalog({ instanceId: "timed", use: () => {}, current: () => CACHED, refresh: async () => { refreshes += 1; }, now }) as { pending: Promise<void> }).pending;
+ expect(refreshes).toBe(3);
+ expect(readStartupModelCacheEntry("timed")).toMatchObject({ catalog: CACHED, checkedAt: expect.any(Number), build: expect.any(String) });
+ });
+
+ it("reads a list the engine did not confirm again at the next start", async () => {
+ seedBots();
+ const standIn = { ...CACHED };
+ unconfirmedModelCatalog(standIn);
+ writeStartupModelCache("timed", standIn);
+ expect(readStartupModelCacheEntry("timed")?.checkedAt).toBe(0);
+ let refreshes = 0;
+ const opened = openStartupModelCatalog({ instanceId: "timed", use: () => {}, current: () => standIn, refresh: async () => { refreshes += 1; } }) as { pending: Promise<void> };
+ await opened.pending;
+ expect(refreshes).toBe(1);
+ });
+
+ it("a later start of Codex on a fresh list starts no app-server; on an older one it does, once the first engine is read", async () => {
+ seedBots();
+ const appServers = () => spawn.mock.calls.filter(([, args]) => (args as string[] | undefined)?.[0] === "app-server").length;
+ const spawn = vi.spyOn(procs, "spawnCli").mockImplementation(() => { throw new Error("spawned"); });
+ const start = () => CodexDriver.create({ instanceId: "codex-later", displayName: "Codex", environment: {}, enabled: true, config: CodexDriver.defaultConfig() });
+ writeStartupModelCache("codex-later", CACHED);
+ const fresh = await start();
+ expect(fresh.models).toEqual(CACHED);
+ expect(fresh.startupModelRefresh).toBeUndefined();
+ expect(appServers()).toBe(0);
+ await fresh.dispose();
+ writeStartupModelCache("codex-later", CACHED, STALE);
+ const stale = await start();
+ await stale.startupModelRefresh;
+ expect(appServers()).toBe(1);
+ await stale.dispose();
+ });
+
it("still waits for discovery on the first run, when nothing is cached", async () => {
const gate = deferredCatalog();
const { driver } = slowDriver(gate.promise);
@@ -170,7 +230,7 @@ describe("startup model catalogs", () => {
it("a turn waits for the in-flight refresh instead of the saved catalog", async () => {
seedBots();
- writeStartupModelCache("slow", CACHED);
+ writeStartupModelCache("slow", CACHED, STALE);
const gate = deferredCatalog();
const { driver, seenByTurn } = slowDriver(gate.promise);
const registry = new ProviderRegistry([driver]);
@@ -189,7 +249,7 @@ describe("startup model catalogs", () => {
it("an ACP engine serves a saved catalog and lets the turn wait for the refresh", async () => {
seedBots();
- writeStartupModelCache("cursor", CACHED);
+ writeStartupModelCache("cursor", CACHED, STALE);
const gate = deferredCatalog();
const spawn = vi.spyOn(procs, "spawnCli").mockImplementation(() => {
throw new Error("spawned");
diff --git a/server/startup-model-catalog.ts b/server/startup-model-catalog.ts
index 6fe3692390..84575517eb 100644
--- a/server/startup-model-catalog.ts
+++ b/server/startup-model-catalog.ts
@@ -4,9 +4,13 @@ import { dirname, join } from "node:path";
import { writeFileAtomic } from "./atomic.ts";
import { DATA_DIR } from "./config.ts";
import type { ModelCatalog } from "./contracts.ts";
+import { buildStamp } from "./environment.ts";
import { afterFirstEngineRead } from "./first-engine-read.ts";
const SAFE_INSTANCE_ID = /^[\w.-]+$/;
+/** A list this server's build read this recently is used as it is at start; an older one, or one an earlier build read,
+ * is read again in the background. A sleeping Cloud wakes many times an hour, and each read can start the engine's CLI. */
+export const STARTUP_MODEL_CACHE_FRESH_MS = 6 * 60 * 60_000;
export function startupModelCachePath(instanceId: string): string | null {
if (!SAFE_INSTANCE_ID.test(instanceId)) return null;
@@ -69,24 +73,47 @@ function catalogFrom(value: unknown): ModelCatalog | null {
return { default: raw.default, options };
}
-export function readStartupModelCache(instanceId: string): ModelCatalog | null {
+const unconfirmed = new WeakSet<ModelCatalog>();
+
+/** The engine did not give this list (its CLI timed out, or answered nothing): it is saved, but read again at the next start. */
+export function unconfirmedModelCatalog(catalog: ModelCatalog): void {
+ unconfirmed.add(catalog);
+}
+
+export interface StartupModelCacheEntry {
+ catalog: ModelCatalog;
+ checkedAt: number | null;
+ build: string | null;
+}
+
+export function readStartupModelCacheEntry(instanceId: string): StartupModelCacheEntry | null {
const path = startupModelCachePath(instanceId);
if (!path) return null;
try {
- return catalogFrom(JSON.parse(readFileSync(path, "utf8")) as unknown);
+ const raw = JSON.parse(readFileSync(path, "utf8")) as { checkedAt?: unknown; build?: unknown };
+ const catalog = catalogFrom(raw);
+ return catalog ? {
+ catalog,
+ checkedAt: typeof raw.checkedAt === "number" && Number.isFinite(raw.checkedAt) ? raw.checkedAt : null,
+ build: typeof raw.build === "string" ? raw.build : null,
+ } : null;
} catch {
return null;
}
}
-export function writeStartupModelCache(instanceId: string, catalog: ModelCatalog): void {
+export function readStartupModelCache(instanceId: string): ModelCatalog | null {
+ return readStartupModelCacheEntry(instanceId)?.catalog ?? null;
+}
+
+export function writeStartupModelCache(instanceId: string, catalog: ModelCatalog, read: { checkedAt?: number; build?: string } = {}): void {
if (!catalog.options.length) return;
const path = startupModelCachePath(instanceId);
if (!path) return;
const stored = catalogFrom(catalog);
if (!stored) return;
mkdirSync(dirname(path), { recursive: true });
- writeFileAtomic(path, JSON.stringify(stored), { durable: false });
+ writeFileAtomic(path, JSON.stringify({ ...stored, checkedAt: read.checkedAt ?? (unconfirmed.has(catalog) ? 0 : Date.now()), build: read.build ?? buildStamp() }), { durable: false });
}
/** An object, not a promise: an async function cannot hand back a promise without `await` following it. */
@@ -97,8 +124,10 @@ export function openStartupModelCatalog(input: {
use: (catalog: ModelCatalog) => void;
current: () => ModelCatalog;
refresh: () => Promise<void>;
+ now?: number;
}): Promise<null> | DeferredStartupModelRefresh {
- const cached = readStartupModelCache(input.instanceId);
+ const entry = readStartupModelCacheEntry(input.instanceId);
+ const cached = entry?.catalog ?? null;
if (cached) input.use(cached);
const persist = () => {
try {
@@ -112,6 +141,8 @@ export function openStartupModelCatalog(input: {
return null;
});
}
+ const age = (input.now ?? Date.now()) - (entry?.checkedAt ?? -Infinity);
+ if (cached && entry?.build === buildStamp() && age >= 0 && age < STARTUP_MODEL_CACHE_FRESH_MS) return Promise.resolve(null);
// A saved list stands in while the refresh waits; with none the engine would offer no model at all until it runs.
const startAfter = cached ? afterFirstEngineRead() : Promise.resolve();
return { pending: startAfter.then(() => input.refresh()).then(persist, () => undefined) };
diff --git a/server/workspace-backup.ts b/server/workspace-backup.ts
index c3e4ca81bb..1a4e26a046 100644
--- a/server/workspace-backup.ts
+++ b/server/workspace-backup.ts
@@ -10,7 +10,6 @@ import { homedir } from "node:os";
import { backup, DatabaseSync } from "node:sqlite";
import { pipeline } from "node:stream/promises";
import { Worker } from "node:worker_threads";
-import * as tar from "tar";
import { writeFileAtomic } from "./atomic.ts";
import { WORKSPACE_BACKUP_CLIENT_KEYS } from "../shared/workspace-backup-client.ts";
import { INSTRUCTION_FILE, restorePaths, validRelative } from "./workspace-backup-paths.ts";
@@ -422,6 +421,7 @@ export async function createWorkspaceBackupSnapshot(dataDir: string, options: Cr
const cipher = createCipheriv("aes-256-gcm", key, iv);
cipher.setAAD(header);
writeFileSync(path, header, { mode: 0o600, flag: "wx" });
+ const tar = await import("tar");
await pipeline(tar.c({ cwd: snapshot, portable: true, strict: true }, ["manifest.json", "data"]), cipher, createWriteStream(path, { flags: "a", mode: 0o600 }));
const fd = openSync(path, "a");
try { writeSync(fd, cipher.getAuthTag()); fsyncSync(fd); } finally { closeSync(fd); }
@@ -514,6 +514,7 @@ async function inspectTar(path: string): Promise<Map<string, { type: string; siz
const names = new Set<string>();
let bytes = 0;
let problem = "";
+ const tar = await import("tar");
await tar.t({ file: path, strict: true, brotli: false, zstd: false, onReadEntry(entry) {
const name = entry.type === "Directory" ? entry.path.replace(/\/$/, "") : entry.path;
const expectedRoot = name === "manifest.json" || name === "data" || name.startsWith("data/");
@@ -591,6 +592,7 @@ export async function stageWorkspaceBackup(dataDir: string, archivePath: string,
const expected = await inspectTar(plaintext);
const staged = join(job.directory, "staged");
folder(staged);
+ const tar = await import("tar");
await tar.x({ file: plaintext, cwd: staged, strict: true, preservePaths: false, umask: 0o077, noChmod: true, brotli: false, zstd: false });
const manifest = validateStaged(staged, expected);
const versions = [manifest.summary.appVersion, options.currentAppVersion ?? ""].map((version) => /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version)?.slice(1).map(Number));