Skip to content

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

Cloud home: run the image's engine CLIs over older data-folder copies (OMB_IMAGE_ENGINES, off by default) (#7137)

Milind Soni10bd164e9f42
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.md
index 16917ea999..b3da9b7581 100644
--- a/docs/cloud-pro.md
+++ b/docs/cloud-pro.md
@@ -1110,6 +1110,46 @@ The app files are the last layers, so an image built from a later commit
differs from the previous one only in those (a few MB) unless Chrome, an
engine, Grok's pin, or the Node base image changed in between.
+**What a new home downloads before its bots can work: nothing.** Claude Code,
+Codex and Grok run from `/usr/local/bin`, agent-browser from its global npm
+install, and both browser drivers (agent-browser's launcher and OpenMausBot's
+own `engine: "chrome"`) run the Chrome the image names in
+`AGENT_BROWSER_EXECUTABLE_PATH` (`server/browser/chrome/resolve.ts`, "named"),
+so `tools/chrome/` stays empty on a Cloud. The data folder gains tools only for
+what someone uses later: an engine installed from Settings (`tools/npm`,
+`tools/standalone`), a Bitwarden vault (`tools/bitwarden`, 46 MB), a spreadsheet or
+database read by the Data tools (`duckdb-extensions/<duckdb version>`, 4 to
+15 MB each). None of these are in backups or moves.
+
+**Engine copies in the data folder.** The data folder's npm prefix
+(`tools/npm/bin`) goes ahead of `/usr/local/bin` on the engines' PATH, so a copy
+installed there runs even when the image carries a newer one, and the engine
+updater keeps it current. With `OMB_IMAGE_ENGINES=1` in a home's environment
+(passed to the server by `serverEnvironmentAllowed`; off by default, never on
+Windows, desktop unchanged), `server/image-engines.ts` changes that for a
+package both places hold:
+
+- the image's copy runs unless the data folder's is newer (a newer copy
+ someone installed from Settings, or one an update installed because the
+ image's copy is below what the driver needs, keeps running);
+- while the image's copies run, the updater downloads nothing for a
+ data-folder copy no newer than the image's, unless the image's copy is
+ below the engine's `minimum` or an exact
+ `target` in `server/engine-versions.ts`, or a CLI path saved on the engine
+ runs that copy (`configuredClis`);
+- PATH is one list, so when any shared package is newer in the data folder,
+ the data folder's bin stays first for all of them, as today;
+- a CLI path saved on the engine always wins, as before.
+
+Nothing is removed. A later cleanup may remove, on a home with the switch on:
+`tools/npm/lib/node_modules/@anthropic-ai/claude-code` and `@openai/codex`
+(and their `tools/npm/bin` links) when no newer than the image's, and
+`tools/npm-home/cache`; `tools/chrome/*`, which a Cloud never runs;
+`tools/agent-browser/<version>` when the image carries the same version;
+`duckdb-extensions/<older duckdb versions>`; and
+`cache/node-compile/v<older node>-*` (a home runs `index.js` with
+`NODE_COMPILE_CACHE`, which keeps every Node version's entries).
+
At boot the launcher, running as root, hands the volume's mount point to the
`maus` user, locks the volume for as long as it runs (`flock` on the volume's
root: a second home on a volume a live home holds refuses to start, which
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index c3b601b136..b0337ac786 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_IDLE_ENGINES_MAX", "OMB_INSTALLATION_CREDENTIAL",
+ "OMB_HOSTED_", "OMB_HOSTED_MODELS", "OMB_HOSTED_MODEL_TOKEN", "OMB_HOSTED_MODEL_URL", "OMB_IDLE_ENGINES_MAX", "OMB_IMAGE_ENGINES", "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/browser/chrome/launcher.test.ts b/server/browser/chrome/launcher.test.ts
index 4197ff2de9..1de88a22e2 100644
--- a/server/browser/chrome/launcher.test.ts
+++ b/server/browser/chrome/launcher.test.ts
@@ -317,6 +317,31 @@ describe("the Chrome launcher", () => {
await expect(runsLauncher(slow, process.env, 5_000)).rejects.toThrow(/the browser launcher does not run here/);
});
+ it.skipIf(process.platform === "win32")("downloads no second Chrome on the server image: both drivers run the Chrome the image names", async () => {
+ const root = mkdtempSync(join(tmpdir(), "omb-launcher-"));
+ folders.push(root);
+ const imageChrome = join(root, "opt", "openmausbot-browser", "chrome");
+ mkdirSync(dirname(imageChrome), { recursive: true });
+ writeFileSync(imageChrome, "#!/bin/sh\n", { mode: 0o755 });
+ const dataDir = join(root, "data");
+ // The image's ENV (Dockerfile runtime stage), on linux/x64, where Chrome for Testing has a pin to download.
+ const env = { HOME: root, AGENT_BROWSER_EXECUTABLE_PATH: imageChrome };
+ expect(chromeForTestingPin("linux", "x64")).not.toBeNull();
+ const real = chromeHost({ dataDir, env, platform: "linux", arch: "x64", enginePath: () => "/usr/local/bin:/usr/bin:/bin" });
+ const host = { ...real, exists: (path: string) => path.startsWith(root) && existsSync(path), list: (folder: string) => folder.startsWith(root) ? real.list(folder) : [] };
+ const install = vi.fn(async () => { throw new Error("no download on the image"); });
+ const common = { dataDir, env, platform: "linux" as const, arch: "x64", host, install, calibrate: async () => identity("158", "Not_A Brand"), screen: async () => ({ width: 1440, height: 900 }), sidecars: sidecars(), log: () => {}, checkLauncher: async () => {} };
+ // agent-browser's launcher, and OpenMausBot's own driver (server/browser/engines.ts: no wrapper, a managed engine).
+ const agentBrowser = new ChromeLauncher({ ...common, engine: () => ({ managed: true }) });
+ const own = new ChromeLauncher({ ...common, engine: () => ({ managed: true }), wrapper: false });
+ await agentBrowser.ready(headless(agentBrowser.env().AGENT_BROWSER_EXECUTABLE_PATH!));
+ expect(await own.binary()).toMatchObject({ path: imageChrome, source: "named" });
+ expect(agentBrowser.describe()).toMatch(/\(named by OMB_CHROME_PATH or AGENT_BROWSER_EXECUTABLE_PATH\)$/);
+ expect(readFileSync(agentBrowser.path, "utf8")).toContain(imageChrome);
+ expect(install).not.toHaveBeenCalled();
+ expect(existsSync(join(dataDir, "tools", "chrome"))).toBe(false);
+ });
+
it("changes nothing on OMB_BROWSER_LEGACY_SHELL=1", async () => {
const machine = mac({ env: { OMB_BROWSER_LEGACY_SHELL: "1", OMB_RESOURCES_PATH: "/Applications/OpenMausBot.app/Contents/Resources" } });
const calibrate = vi.fn();
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index c04a6001d4..457648c99d 100644
--- a/server/cloud-home-start.ts
+++ b/server/cloud-home-start.ts
@@ -42,6 +42,8 @@ const SERVER_ENV_NAMES = new Set([
"OMB_CLOUD_LEGACY_ORIGINS",
// The bot box switch (server/bot-box/detect.ts): the Admin may turn a home's box off for support.
"OMB_BOT_BOX",
+ // The image's own engine CLIs before older copies in the data folder (server/image-engines.ts), for one test Cloud first.
+ "OMB_IMAGE_ENGINES",
// An ended Cloud started only for its owner's export: the server runs frozen (server/move-freeze.ts).
"OMB_CLOUD_EXPORT_ONLY",
// The idle task workspaces' dependency sweep (server/host/start-upkeep.ts), off unless set: the Admin may turn it on.
diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.ts
index d7ecc0e3e6..84032821ca 100644
--- a/server/cloud-home.test.ts
+++ b/server/cloud-home.test.ts
@@ -393,8 +393,8 @@ it("gives the edge only its routing name and the server the contract, never a ga
expect(server).toMatchObject({ HOME: "/data", OMB_DATA_DIR: "/data/.openmausbot", NODE_COMPILE_CACHE: "/data/.openmausbot/cache/node-compile", OMB_PORT: "8799", OMB_WEBHOOK_PORT: "8800",
OMB_PUBLIC_URL: "https://omb-u-1a2b3c4d5e6f.fly.dev", OMB_WEBHOOK_PUBLIC_URL: "https://omb-u-1a2b3c4d5e6f.fly.dev", OMB_CLOUD_SECRETS_FD: "3" });
for (const key of CLOUD_IGNORED_KEYS) expect(server).not.toHaveProperty(key);
- // The bot box switch reaches the server; an unknown name does not.
- expect(cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin", OMB_BOT_BOX: "0", OMB_SOMETHING_ELSE: "x" }, "/data").server).toMatchObject({ OMB_BOT_BOX: "0" });
+ // The bot box and image-engines switches reach the server; an unknown name does not.
+ expect(cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin", OMB_BOT_BOX: "0", OMB_IMAGE_ENGINES: "1", OMB_SOMETHING_ELSE: "x" }, "/data").server).toMatchObject({ OMB_BOT_BOX: "0", OMB_IMAGE_ENGINES: "1" });
expect(cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin", OMB_SOMETHING_ELSE: "x" }, "/data").server).not.toHaveProperty("OMB_SOMETHING_ELSE");
expect(JSON.stringify(server)).not.toContain(token);
expect(secrets).toEqual({ OMB_CLOUD_BOOTSTRAP_SECRET: secret, ...relay });
diff --git a/server/engine-install.ts b/server/engine-install.ts
index 2d4b249416..786a48c02f 100644
--- a/server/engine-install.ts
+++ b/server/engine-install.ts
@@ -10,6 +10,7 @@ import { registerStandaloneBinDirs, standaloneAssetFor, standaloneRunEnv } from
import { STANDALONE_RELEASES } from "./standalone-releases.ts";
import { augmentedPath, findCliCandidates, registerPathDir, resetPathCache } from "./env-path.ts";
import { botBox } from "./bot-box/box.ts";
+import { orderImageEngines } from "./image-engines.ts";
import { execCli, killCliTree, spawnCli } from "./procs.ts";
const MAX_OUTPUT = 64 * 1024;
@@ -44,10 +45,12 @@ export function npmCopyVersion(pkg: string, baseDir = DATA_DIR): string | null {
}
}
-/** Called once at boot: engines npm installed here win over any other copy on PATH. A standalone build the app installed
- * goes last instead, so a copy the person installs themselves takes over. */
+/** Called once at boot: engines npm installed here win over any other copy on PATH, except a Cloud image's own copies
+ * with OMB_IMAGE_ENGINES=1 (image-engines.ts). A standalone build the app installed goes last instead, so a copy the
+ * person installs themselves takes over. */
export function registerEnginesBinDir(baseDir = DATA_DIR, releases: readonly StandaloneRelease[] = STANDALONE_RELEASES): void {
registerPathDir(enginesBinDir(baseDir));
+ orderImageEngines(baseDir);
registerStandaloneBinDirs(baseDir, releases);
}
@@ -185,6 +188,7 @@ async function installOnce(pkg: string, options: InstallOptions): Promise<void>
await runInstall(pkg, args, env, prefix, timeoutMs);
const binDir = enginesBinDir(options.baseDir);
registerPathDir(binDir);
+ orderImageEngines(options.baseDir ?? DATA_DIR);
resetPathCache();
if (!options.cli) return;
const installed = findCliCandidates(options.cli).find((path) => path.startsWith(binDir));
diff --git a/server/engine-updates.ts b/server/engine-updates.ts
index d70e1183b6..39f80dbe72 100644
--- a/server/engine-updates.ts
+++ b/server/engine-updates.ts
@@ -15,6 +15,7 @@ import { enginesBinDir, enginesPrefix, npmCopyVersion, npmLatestVersion, npmModu
import { EngineInUse, npmCommandNames, removeNpmCopy, sweepNpmLeftovers, updateNpmEngineStaged, type StagedNpmUpdate } from "./engine-npm-update.ts";
import { installStandaloneEngine, standaloneAssetFor, standaloneCurrentVersion, standaloneEngineDir, type StandaloneInstallOptions } from "./engine-standalone.ts";
import { ENGINE_VERSIONS, LATEST, type EngineVersionPin } from "./engine-versions.ts";
+import { imageCopyTooOld, orderImageEngines, runningImageVersion } from "./image-engines.ts";
import { liveCliCommands } from "./procs.ts";
import { isNewerVersion } from "./update-check.ts";
@@ -75,6 +76,11 @@ export interface UpdateSteps {
standaloneVersion(release: StandaloneRelease, baseDir: string): string | null;
installStandalone(release: StandaloneRelease, options: StandaloneInstallOptions): Promise<unknown>;
handshake(command: string, args: readonly string[], env: NodeJS.ProcessEnv): Promise<string | null>;
+ /** The version of the Cloud image's own copy of an npm package when that copy is the one that runs, with
+ * OMB_IMAGE_ENGINES=1 (image-engines.ts); else null. */
+ imageVersion(pkg: string, baseDir: string): string | null;
+ /** After an npm copy changed: whether the image's copies or the data folder's go first on PATH. */
+ orderPath(baseDir: string): void;
}
const STEPS: UpdateSteps = {
@@ -86,6 +92,8 @@ const STEPS: UpdateSteps = {
standaloneVersion: standaloneCurrentVersion,
installStandalone: installStandaloneEngine,
handshake: acpHandshake,
+ imageVersion: (pkg, baseDir) => runningImageVersion(pkg, baseDir),
+ orderPath: (baseDir) => { orderImageEngines(baseDir); },
};
export interface EngineUpdaterOptions {
@@ -255,6 +263,10 @@ export function createEngineUpdater(options: EngineUpdaterOptions): EngineUpdate
async function updateNpm(plan: EnginePlan, pkg: string): Promise<Outcome> {
const current = steps.npmVersion(pkg, baseDir);
if (current === null) return { kind: "absent" };
+ // The image's copy runs instead of one here no newer than it: nothing to download, unless the driver needs a newer
+ // one than the image carries, or a saved CLI path runs this copy.
+ const image = steps.imageVersion(pkg, baseDir);
+ if (image !== null && !isNewerVersion(current, image) && !imageCopyTooOld(plan.pin, image) && !configuredInto(pkg)) return { kind: "current" };
if (engineBusy(plan)) return { kind: "busy" };
let target = plan.pin.target;
if (target === LATEST) {
@@ -272,6 +284,7 @@ export function createEngineUpdater(options: EngineUpdaterOptions): EngineUpdate
if (aborted.busy || error instanceof EngineInUse) return { kind: "waiting" };
return { kind: "failed", from: current, to: target, reason: error instanceof Error ? error.message : String(error) };
}
+ steps.orderPath(baseDir);
return { kind: "updated", from: current, to: target };
}
diff --git a/server/env-path.ts b/server/env-path.ts
index 2c20a9326f..9e5d081531 100644
--- a/server/env-path.ts
+++ b/server/env-path.ts
@@ -88,6 +88,13 @@ export function registerPathDir(dir: string): void {
resetPathCache();
}
+export function unregisterPathDir(dir: string): void {
+ const at = registeredDirs.indexOf(dir);
+ if (at === -1) return;
+ registeredDirs.splice(at, 1);
+ resetPathCache();
+}
+
// App-installed standalone builds go last: a copy the person installs themselves, anywhere, takes over.
const fallbackDirs: string[] = [];
diff --git a/server/image-engines.test.ts b/server/image-engines.test.ts
new file mode 100644
index 0000000000..c1dc7d8df6
--- /dev/null
+++ b/server/image-engines.test.ts
@@ -0,0 +1,220 @@
+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { BUILT_IN_DRIVERS } from "./drivers/builtIn.ts";
+import { enginesBinDir, registerEnginesBinDir } from "./engine-install.ts";
+import { npmEnginesPrefix } from "./engine-roots.ts";
+import type { StagedNpmUpdate } from "./engine-npm-update.ts";
+import { createEngineUpdater, enginePlans } from "./engine-updates.ts";
+import { ENGINE_VERSIONS } from "./engine-versions.ts";
+import { findCliCandidates, resetPathCacheForTests } from "./env-path.ts";
+import { dataCopyWins, imageBinFirst, imageCopyTooOld, imageEnginesOn, imagePrefix, runningImageVersion, sharedCopies } from "./image-engines.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+const CLAUDE = "@anthropic-ai/claude-code";
+const CODEX = "@openai/codex";
+const CLI: Record<string, string> = { [CLAUDE]: "claude", [CODEX]: "codex" };
+
+const folders: string[] = [];
+afterAll(async () => { for (const folder of folders) await removeTempDir(folder); });
+
+/** An npm prefix laid out as `npm install -g` leaves it: lib/node_modules/<pkg> and its command in bin/. */
+function install(prefix: string, pkg: string, version: string): string {
+ const dir = join(prefix, "lib", "node_modules", ...pkg.split("/"));
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "package.json"), JSON.stringify({ name: pkg, version, bin: { [CLI[pkg]!]: "cli.js" } }));
+ mkdirSync(join(prefix, "bin"), { recursive: true });
+ const command = join(prefix, "bin", CLI[pkg]!);
+ writeFileSync(command, `#!/bin/sh\necho ${version}\n`, { mode: 0o755 });
+ return command;
+}
+
+function machine() {
+ const root = mkdtempSync(join(tmpdir(), "omb-image-engines-"));
+ folders.push(root);
+ const image = join(root, "usr-local");
+ const data = join(root, "data");
+ return { root, image, data, dataPrefix: npmEnginesPrefix(data) };
+}
+
+describe("the switch", () => {
+ it("is off unless set to 1 or an absolute prefix, and always off on Windows", () => {
+ expect(imageEnginesOn({ env: {}, platform: "linux" })).toBe(false);
+ expect(imageEnginesOn({ env: { OMB_IMAGE_ENGINES: "0" }, platform: "linux" })).toBe(false);
+ expect(imageEnginesOn({ env: { OMB_IMAGE_ENGINES: "true" }, platform: "linux" })).toBe(false);
+ expect(imageEnginesOn({ env: { OMB_IMAGE_ENGINES: "relative/prefix" }, platform: "linux" })).toBe(false);
+ expect(imageEnginesOn({ env: { OMB_IMAGE_ENGINES: "1" }, platform: "linux" })).toBe(true);
+ expect(imageEnginesOn({ env: { OMB_IMAGE_ENGINES: "/usr/local" }, platform: "linux" })).toBe(true);
+ expect(imageEnginesOn({ env: { OMB_IMAGE_ENGINES: "1" }, platform: "win32" })).toBe(false);
+ expect(imageEnginesOn({ env: { OMB_IMAGE_ENGINES: "1" }, platform: "darwin" })).toBe(true);
+ });
+
+ it("finds the image's prefix from Node's own place, or the absolute prefix it names", () => {
+ expect(imagePrefix({ env: { OMB_IMAGE_ENGINES: "/opt/image" } })).toBe("/opt/image");
+ expect(imagePrefix({ env: { OMB_IMAGE_ENGINES: "1" } })).toBe(join(process.execPath, "..", ".."));
+ expect(runningImageVersion(CLAUDE, "/nowhere", { env: {} })).toBeNull();
+ });
+});
+
+describe("which copy wins", () => {
+ it("is the data folder's only when it is newer, or a version cannot be read", () => {
+ expect(dataCopyWins({ image: "2.1.330", data: "2.1.329" })).toBe(false);
+ expect(dataCopyWins({ image: "2.1.330", data: "2.1.330" })).toBe(false);
+ expect(dataCopyWins({ image: "2.1.330", data: "2.1.331" })).toBe(true);
+ expect(dataCopyWins({ image: "0.171.0", data: "0.172.0-alpha.1" })).toBe(true);
+ expect(dataCopyWins({ image: null, data: "1.0.0" })).toBe(true);
+ expect(dataCopyWins({ image: "1.0.0", data: "not a version" })).toBe(true);
+ expect(imageBinFirst([])).toBe(false);
+ expect(imageBinFirst([{ pkg: CLAUDE, image: "2.1.330", data: "2.1.300" }, { pkg: CODEX, image: "0.171.0", data: "0.171.0" }])).toBe(true);
+ // One newer copy in the data folder keeps today's order for both: PATH is one list.
+ expect(imageBinFirst([{ pkg: CLAUDE, image: "2.1.330", data: "2.1.340" }, { pkg: CODEX, image: "0.171.0", data: "0.167.0" }])).toBe(false);
+ });
+
+ it("asks for a newer copy only when the image's is below the driver's minimum, or below an exact target", () => {
+ expect(imageCopyTooOld({ target: "latest", minimum: "2.1.267" }, "2.1.330")).toBe(false);
+ expect(imageCopyTooOld({ target: "latest", minimum: "2.1.267" }, "2.1.200")).toBe(true);
+ expect(imageCopyTooOld({ target: "0.167.0", minimum: "0.146.0" }, "0.171.0")).toBe(false);
+ expect(imageCopyTooOld({ target: "0.167.0", minimum: "0.146.0" }, "0.160.0")).toBe(true);
+ });
+});
+
+describe.skipIf(process.platform === "win32")("the PATH engines run from", () => {
+ beforeEach(() => resetPathCacheForTests());
+ afterEach(() => { vi.unstubAllEnvs(); resetPathCacheForTests(); });
+
+ function boot(m: ReturnType<typeof machine>, switchOn: boolean) {
+ vi.stubEnv("PATH", `${join(m.image, "bin")}:/usr/bin:/bin`);
+ vi.stubEnv("OMB_TEST_SEALED_PATH", "1");
+ vi.stubEnv("OMB_IMAGE_ENGINES", switchOn ? m.image : "");
+ registerEnginesBinDir(m.data, []);
+ }
+
+ it("keeps today's order with the switch off: the data folder's copy first, even when older (desktop and every server)", () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ const data = install(m.dataPrefix, CLAUDE, "2.1.300");
+ boot(m, false);
+ expect(findCliCandidates("claude")[0]).toBe(data);
+ });
+
+ it("runs the image's copy over an older or equal one in the data folder", () => {
+ const m = machine();
+ const image = install(m.image, CLAUDE, "2.1.330");
+ install(m.image, CODEX, "0.171.0");
+ install(m.dataPrefix, CLAUDE, "2.1.300");
+ install(m.dataPrefix, CODEX, "0.171.0");
+ boot(m, true);
+ expect(findCliCandidates("claude")[0]).toBe(image);
+ expect(findCliCandidates("codex")[0]).toBe(join(m.image, "bin", "codex"));
+ expect(sharedCopies(m.data, { env: { OMB_IMAGE_ENGINES: m.image } }).map((copy) => copy.pkg).sort()).toEqual([CLAUDE, CODEX]);
+ });
+
+ it("runs a newer copy someone installed in the data folder", () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ const data = install(m.dataPrefix, CLAUDE, "2.1.331");
+ boot(m, true);
+ expect(findCliCandidates("claude")[0]).toBe(data);
+ });
+
+ it("still finds an engine only the data folder has, ahead of the rest of PATH", () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ install(m.dataPrefix, CLAUDE, "2.1.300");
+ const gemini = join(enginesBinDir(m.data), "gemini");
+ writeFileSync(gemini, "#!/bin/sh\n", { mode: 0o755 });
+ boot(m, true);
+ expect(findCliCandidates("gemini")[0]).toBe(gemini);
+ });
+
+ it("leaves a CLI path someone saved on the engine alone", () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ const data = install(m.dataPrefix, CLAUDE, "2.1.300");
+ boot(m, true);
+ expect(findCliCandidates(data)).toEqual([data]);
+ });
+});
+
+describe.skipIf(process.platform === "win32")("the engine updater with image copies", () => {
+ afterEach(() => { vi.unstubAllEnvs(); resetPathCacheForTests(); });
+
+ const plans = enginePlans(BUILT_IN_DRIVERS).filter((plan) => plan.npm === CLAUDE || plan.npm === CODEX);
+
+ /** The data folder's copies on disk, as the updater and the PATH order read them. */
+ function updater(m: ReturnType<typeof machine>, versions: Record<string, string>, configuredClis: string[] = []) {
+ for (const [pkg, version] of Object.entries(versions)) install(m.dataPrefix, pkg, version);
+ const npmLatest = vi.fn(async () => "2.1.350");
+ const updateNpm = vi.fn(async (_options: StagedNpmUpdate) => {});
+ const installStandalone = vi.fn(async () => { throw new Error("no standalone download in this test"); });
+ const engines = createEngineUpdater({
+ plans, baseDir: m.data, statePath: join(m.root, "engine-updates.json"), turnRunning: () => false, liveCommands: () => [], configuredClis: () => configuredClis, log: () => {},
+ steps: { sweep: async () => {}, npmVersion: (pkg) => versions[pkg] ?? null, standaloneVersion: () => null, npmLatest, updateNpm, installStandalone },
+ });
+ return { engines, npmLatest, updateNpm, installStandalone };
+ }
+
+ it("downloads nothing while the image's copies are at least as new as the data folder's", async () => {
+ expect(plans.map((plan) => plan.npm).sort()).toEqual([CLAUDE, CODEX]);
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ install(m.image, CODEX, "0.171.0");
+ vi.stubEnv("OMB_IMAGE_ENGINES", m.image);
+ const { engines, npmLatest, updateNpm, installStandalone } = updater(m, { [CLAUDE]: "2.1.300", [CODEX]: "0.160.0" });
+ await engines.check();
+ expect(npmLatest).not.toHaveBeenCalled();
+ expect(updateNpm).not.toHaveBeenCalled();
+ expect(installStandalone).not.toHaveBeenCalled();
+ });
+
+ it("updates the data folder's copies as today with the switch off", async () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ install(m.image, CODEX, "0.171.0");
+ const { engines, npmLatest, updateNpm } = updater(m, { [CLAUDE]: "2.1.300", [CODEX]: "0.160.0" });
+ await engines.check();
+ expect(npmLatest).toHaveBeenCalledOnce();
+ expect(updateNpm.mock.calls.map(([options]) => [options.pkg, options.version]).sort())
+ .toEqual([[CLAUDE, "2.1.350"], [CODEX, ENGINE_VERSIONS.codex!.target]]);
+ });
+
+ it("keeps a newer copy in the data folder up to date, as today", async () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ vi.stubEnv("OMB_IMAGE_ENGINES", m.image);
+ const { engines, updateNpm } = updater(m, { [CLAUDE]: "2.1.340" });
+ await engines.check();
+ expect(updateNpm).toHaveBeenCalledOnce();
+ expect(updateNpm.mock.calls[0]![0]).toMatchObject({ pkg: CLAUDE, version: "2.1.350" });
+ });
+
+ it("installs a newer copy when the image's is below what the driver needs", async () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.200");
+ vi.stubEnv("OMB_IMAGE_ENGINES", m.image);
+ const { engines, updateNpm } = updater(m, { [CLAUDE]: "2.1.100" });
+ await engines.check();
+ expect(updateNpm.mock.calls[0]![0]).toMatchObject({ pkg: CLAUDE, version: "2.1.350" });
+ });
+
+ it("keeps updating an older copy that still runs because another engine's newer copy keeps the data folder first", async () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ install(m.image, CODEX, "0.171.0");
+ vi.stubEnv("OMB_IMAGE_ENGINES", m.image);
+ const { engines, updateNpm } = updater(m, { [CLAUDE]: "2.1.300", [CODEX]: "0.172.0" });
+ await engines.check();
+ expect(updateNpm.mock.calls.map(([options]) => options.pkg)).toEqual([CLAUDE]);
+ });
+
+ it("keeps updating a data-folder copy a saved CLI path runs", async () => {
+ const m = machine();
+ install(m.image, CLAUDE, "2.1.330");
+ vi.stubEnv("OMB_IMAGE_ENGINES", m.image);
+ const { engines, updateNpm } = updater(m, { [CLAUDE]: "2.1.300" }, [join(enginesBinDir(m.data), "claude")]);
+ await engines.check();
+ expect(updateNpm).toHaveBeenCalledOnce();
+ });
+});
diff --git a/server/image-engines.ts b/server/image-engines.ts
new file mode 100644
index 0000000000..e389058350
--- /dev/null
+++ b/server/image-engines.ts
@@ -0,0 +1,103 @@
+// A Cloud home's image carries engine CLIs in Node's own global npm prefix (/usr/local: the Dockerfile's
+// CLOUD_HOME_ENGINES), and the app installs and updates engines into the data folder's npm prefix (tools/npm), whose bin/
+// goes first on PATH. So a copy there shadows the image's even when the image's is newer, and the updater keeps
+// downloading it. With OMB_IMAGE_ENGINES=1 the image's copy is used unless the data folder holds a newer copy of the same
+// package (installed from Settings, or by an update a driver needs), and the updater leaves a copy that is not used alone.
+// Off by default, and never on Windows: desktop installs and every other server keep today's order. Nothing is removed.
+// The switch's value is `1` (the image's prefix is Node's own) or an absolute prefix.
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { dirname, isAbsolute, join } from "node:path";
+
+import { npmEnginesPrefix } from "./engine-roots.ts";
+import { registerPathDir, unregisterPathDir } from "./env-path.ts";
+import { LATEST, type EngineVersionPin } from "./engine-versions.ts";
+import { isNewerVersion } from "./update-check.ts";
+
+export const IMAGE_ENGINES_ENV = "OMB_IMAGE_ENGINES";
+
+const VERSION = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+
+export interface ImageEngineOptions {
+ env?: NodeJS.ProcessEnv;
+ platform?: NodeJS.Platform;
+}
+
+const switchValue = (options: ImageEngineOptions) => (options.env ?? process.env)[IMAGE_ENGINES_ENV]?.trim() ?? "";
+
+export function imageEnginesOn(options: ImageEngineOptions = {}): boolean {
+ const value = switchValue(options);
+ return (options.platform ?? process.platform) !== "win32" && (value === "1" || (value.startsWith("/") && isAbsolute(value)));
+}
+
+/** The switch's absolute prefix, else Node's own: `/usr/local` for the image's `/usr/local/bin/node`. */
+export function imagePrefix(options: ImageEngineOptions = {}): string {
+ const value = switchValue(options);
+ return value.startsWith("/") ? value : dirname(dirname(process.execPath));
+}
+
+const modulesIn = (prefix: string) => join(prefix, "lib", "node_modules");
+
+function versionIn(modules: string, pkg: string): string | null {
+ try {
+ const manifest = JSON.parse(readFileSync(join(modules, ...pkg.split("/"), "package.json"), "utf8")) as { version?: unknown };
+ return typeof manifest.version === "string" && manifest.version ? manifest.version : null;
+ } catch {
+ return null;
+ }
+}
+
+function packagesIn(modules: string): string[] {
+ const list = (dir: string) => { try { return readdirSync(dir); } catch { return []; } };
+ return list(modules).flatMap((name) => name.startsWith("@") ? list(join(modules, name)).map((inner) => `${name}/${inner}`) : name.startsWith(".") ? [] : [name]);
+}
+
+export interface SharedCopy {
+ pkg: string;
+ /** The image's version, null when its manifest cannot be read. */
+ image: string | null;
+ data: string | null;
+}
+
+/** Every package installed both in the image's prefix and the data folder's, with each copy's version. */
+export function sharedCopies(baseDir: string, options: ImageEngineOptions = {}): SharedCopy[] {
+ const image = modulesIn(imagePrefix(options));
+ const data = modulesIn(npmEnginesPrefix(baseDir));
+ if (!existsSync(image)) return [];
+ return packagesIn(data).filter((pkg) => existsSync(join(image, ...pkg.split("/")))).map((pkg) => ({ pkg, image: versionIn(image, pkg), data: versionIn(data, pkg) }));
+}
+
+/** The data folder's copy is used: newer than the image's, or either version unreadable (today's order then). */
+export function dataCopyWins(copy: Pick<SharedCopy, "image" | "data">): boolean {
+ if (!copy.image || !copy.data || !VERSION.test(copy.image.trim()) || !VERSION.test(copy.data.trim())) return true;
+ return isNewerVersion(copy.data, copy.image);
+}
+
+/** PATH order is one list for every engine, so the image's bin goes ahead of the data folder's npm bin only when no
+ * package the two share is newer in the data folder: a newer copy someone installed always runs, and then an older one
+ * of another engine there still does too, as today. */
+export function imageBinFirst(copies: readonly SharedCopy[]): boolean {
+ return copies.length > 0 && !copies.some(dataCopyWins);
+}
+
+/** Puts the image's bin ahead of the data folder's npm bin, or takes it out again; called at boot and after each npm
+ * install or update. A no-op with the switch off. */
+export function orderImageEngines(baseDir: string, options: ImageEngineOptions = {}): boolean {
+ if (!imageEnginesOn(options)) return false;
+ const bin = join(imagePrefix(options), "bin");
+ const first = imageBinFirst(sharedCopies(baseDir, options));
+ unregisterPathDir(bin);
+ if (first) registerPathDir(bin);
+ return first;
+}
+
+/** The image's version of `pkg` when the image's copy is the one that runs (`imageBinFirst`); null with the switch off,
+ * when the image has none, or when the data folder's bin goes first and its copy runs instead. */
+export function runningImageVersion(pkg: string, baseDir: string, options: ImageEngineOptions = {}): string | null {
+ if (!imageEnginesOn(options) || !imageBinFirst(sharedCopies(baseDir, options))) return null;
+ return versionIn(modulesIn(imagePrefix(options)), pkg);
+}
+
+/** The image's copy is older than this release's driver needs (its minimum), or than an exact target it pins. */
+export function imageCopyTooOld(pin: Pick<EngineVersionPin, "target" | "minimum">, image: string): boolean {
+ return isNewerVersion(pin.minimum, image) || (pin.target !== LATEST && isNewerVersion(pin.target, image));
+}