Skip to content

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

Cloud home: tool caches into one folder per bot box HOME, behind OMB_CACHE_ROOT (off) (#7134)

Milind Soni0ed25b569191
diff --git a/docs/bot-box.md b/docs/bot-box.md
index df770d51e9..efb3372c74 100644
--- a/docs/bot-box.md
+++ b/docs/bot-box.md
@@ -58,6 +58,63 @@ the same).
Cost on Fly (measured, T0 build notes): about 5 ms and 3 MB per box, plus one socat per bridge.
+## Tool caches
+
+`server/bot-box/tool-caches.ts`, behind `OMB_CACHE_ROOT` (default off; `1`/`on` turns it on, only on a Cloud home, never
+on a desktop). With it on, the box gives each process the tools' own cache variables, so what a bot's tools download
+lands in one folder, `cache` in the box's HOME, instead of all over it:
+
+| Variable | Folder under `<box HOME>/cache` | Was | It beats (config files) |
+|---|---|---|---|
+| `npm_config_cache` (npx too) | `npm` | `~/.npm` | `cache=` in `~/.npmrc`, a project's `.npmrc`, the global npmrc |
+| `PIP_CACHE_DIR` | `pip` | `~/.cache/pip` | `cache-dir` in any `pip.conf` (global, user, a venv's) |
+| `UV_CACHE_DIR` | `uv` | `~/.cache/uv` | `cache-dir` in `uv.toml` or a project's `pyproject.toml` `[tool.uv]` |
+| `HF_HUB_CACHE`, `HF_XET_CACHE` | `huggingface/hub`, `huggingface/xet` | `~/.cache/huggingface/{hub,xet}` | none (Hugging Face reads only variables) |
+| `BUN_INSTALL_CACHE_DIR` | `bun` | `~/.bun/install/cache` | not checked against `bunfig.toml` `[install.cache] dir` |
+
+- **Where.** The box's HOME: `/data/cache` on a personal Cloud, `engine-homes/<audience>/cache` on a Team Cloud. So
+ the folder is shared exactly as `~/.npm` and `~/.cache` already are (every bot of a personal Cloud; one audience on a
+ Team Cloud, never another member's). It is under the HOME line of the plan, so no new mount is made: the bubblewrap
+ arguments are the same with the switch on or off (pinned by a test). The app's own rebuildable files stay in the data
+ folder's `cache/` (`NODE_COMPILE_CACHE`), which the box hides.
+- **Only a folder the server made.** On the first spawn for a HOME (never at start), the server makes `cache` there and
+ writes a `CACHEDIR.TAG` (the standard signature, plus a line naming OpenMausBot). A `cache` that is already there
+ without that tag and with anything in it is the person's own: nothing is written in it, and that HOME's tools keep
+ their own places. An empty one is marked and used (a start that made it may have stopped before writing the tag). A link
+ named `cache` is never the server's. The cache cap (below) works only in a tagged folder.
+- **A value in the environment wins; a value in a config file loses.** A cache variable the spawn was handed is kept:
+ one an engine's saved environment or an MCP server's environment passes through `allowEnv`, and one a driver merged in
+ without vouching (Claude's and Codex's instance environment), which goes back after the allow-list with its own value.
+ On a Cloud home the server's own environment carries none of these names (`SERVER_ENV_NAMES`). A cache whose place
+ something else the spawn was handed already decides is left alone: `XDG_CACHE_HOME` (pip, uv,
+ bun, Hugging Face), `HF_HOME`, `BUN_INSTALL`. What an engine or a shell sets for its own children (an MCP server's `env` in
+ the engine's config, an `export`) is set on top inside the box, so it wins too. But each variable beats the config
+ files in the table's last column, because each tool ranks its environment above them:
+ - what that costs is the place only: the tool downloads into ours what it would have found in the folder its config
+ names;
+ - what can fail: an install that must work offline from a cache folder a config file names (npm with `offline=true`
+ or `--offline`, uv with `offline = true` or `--offline`). It fails as it would with an empty cache. pip's cache
+ is never needed offline, and Hugging Face has no config file for its cache.
+- **Left alone on purpose.** `XDG_CACHE_HOME` (Hugging Face keeps its login token under it, and engines write there),
+ `HF_HOME` (the token), `CARGO_HOME` (credentials and installed programs), `GRADLE_USER_HOME` (properties that may hold
+ keys), `PNPM_HOME`, `UV_TOOL_DIR` and `UV_PYTHON_INSTALL_DIR` (installed programs and the Pythons venvs point into),
+ pnpm's store (a project's `node_modules` records it, and `npm_config_store_dir` makes every npm command warn), Yarn's
+ cache (a Berry project may keep it in the repository), Maven (no variable but `MAVEN_OPTS`), and:
+ - `PLAYWRIGHT_BROWSERS_PATH`: older `@playwright/mcp` releases (seen in 0.0.41, 0.0.70 and 0.0.75; 0.0.76 and later use
+ `~/.cache/ms-playwright-mcp`) keep the MCP browser's profile (cookies, site sign-ins) in that folder, so moving it
+ would sign the browser out;
+ - `PUPPETEER_CACHE_DIR`: it beats a project's `.puppeteerrc`, so a project keeping Chrome in its own folder would stop
+ finding it;
+ - `GOMODCACHE`: it beats `go env -w GOMODCACHE`, and a project building offline from its module cache would fail;
+ - `COREPACK_HOME`: its `lastKnownGood.json` records which package manager version is active, not only downloads;
+ - `GOCACHE`: it also holds Go's fuzzing corpus (`fuzz/`), which `go clean -cache` keeps.
+- **Nothing is moved or deleted.** The old folders stay; with the switch on, new downloads go to the new folder, and a
+ tool downloads once more what the old folder held (an npx package, a model). Something run offline from the old place
+ (`HF_HUB_OFFLINE=1` with a model there) fails until it is downloaded again. A later cleanup may delete the old folders
+ in the table's third column.
+- **Box off, no change.** A Cloud whose box is off (`OMB_BOT_BOX=0`, or no working bubblewrap) runs its bots unboxed
+ with today's environment.
+
## The self-check and the report
At boot, and by hand with `node dist-server/bot-box/box-check.js`, the server runs `box-probe.ts` inside a real box
diff --git a/server/bot-box/box.ts b/server/bot-box/box.ts
index 6d845d5af5..487cff773f 100644
--- a/server/bot-box/box.ts
+++ b/server/bot-box/box.ts
@@ -21,6 +21,7 @@ import { procHidepid } from "./hidepid.ts";
import { DENIED_SYSCALLS, seccompBytes, seccompSupported } from "./seccomp.ts";
import { RELAY_SOCKET_NAME, TEAM_FOLDER_KEPT, boxUploadsConversation, boxUploadsDir, teamFolderOf, under, bwrapArgs, inBoxSocket, planBox, taskWorkspaceIds, type BoxAudience, type BoxBridge, type BoxPlan, type BoxRequest, type BoxSetup } from "./plan.ts";
import { openBoxRelay, type BoxRelay } from "./relay.ts";
+import { CACHE_ROOT_SWITCH, ensureToolCacheRoot, toolCacheEnvironment, toolCacheRoot, toolCachesOn } from "./tool-caches.ts";
/** The loopback port inside a box that reaches the egress gate. The harness gate sits at the server's own port. */
export const BOX_EGRESS_PORT = 3128;
@@ -71,6 +72,10 @@ export interface RunnerOptions {
seccompFile?: string | null;
/** The broker to mint per-process tokens with; none leaves keys in the environment. */
broker?: { port: number; mintForProcess(input: { botId?: string | null; threadId?: string | null; grants: Record<string, BrokerGrant> }): { token: string }; revoke(token: string): void } | null;
+ /** Point the tools' download caches at the cache folder in the box's HOME (tool-caches.ts); off leaves the environment as is. */
+ toolCaches?: boolean;
+ /** Makes and marks a HOME's cache folder (tool-caches.ts ensureToolCacheRoot); a test passes its own. */
+ cacheRoot?: (root: string) => boolean | null;
}
/** Wraps spawns for one setup (the server's, or a self-check fixture's). */
@@ -80,8 +85,23 @@ export class BoxRunner {
private readonly lent = new Map<string, readonly string[]>();
private audiences: BoxAudienceScope | null = null;
+ /** Each HOME's cache folder: the server's (true) or the person's own (false), asked once per folder. */
+ private readonly cacheRoots = new Map<string, boolean>();
constructor(options: RunnerOptions) { this.options = options; }
+ /** Whether the tools' caches of a box whose HOME is `home` go into its cache folder: only one the server made. Made on
+ * the first spawn for that HOME, never at start. */
+ private cacheRootOurs(home: string): boolean {
+ const root = toolCacheRoot(home);
+ const known = this.cacheRoots.get(root);
+ if (known !== undefined) return known;
+ const ours = (this.options.cacheRoot ?? ensureToolCacheRoot)(root);
+ if (ours === null) return false;
+ this.cacheRoots.set(root, ours);
+ if (!ours) console.log(`bot box: ${root} was not made by the server, so the tools' caches of that HOME stay where each tool puts them (${CACHE_ROOT_SWITCH})`);
+ return ours;
+ }
+
/** A Team Cloud's audience rule for every box from now on; null takes it away. */
scopeAudiences(scope: BoxAudienceScope | null): void { this.audiences = scope; }
@@ -140,6 +160,9 @@ export class BoxRunner {
// The server's own PATH leaves out the programs in HOME (program-trust.ts); inside the box they are the bot's own.
const homePrograms = homeProgramDirs(resolve(request.home ?? this.options.setup.home)).filter((dir) => !(env.PATH ?? "").split(":").includes(dir));
if (homePrograms.length) env.PATH = [...(env.PATH ? [env.PATH] : []), ...homePrograms].join(":");
+ // After the allow-list, so a value the person gave for this spawn is the one kept.
+ const boxHome = request.home ?? this.options.setup.home;
+ if (this.options.toolCaches && this.cacheRootOurs(boxHome)) Object.assign(env, toolCacheEnvironment(boxHome, env, request.env));
if (plan.net === "isolated") {
const proxy = `http://127.0.0.1:${this.options.egressPort ?? BOX_EGRESS_PORT}`;
for (const name of BOX_PROXY_ENV) env[name] = proxy;
@@ -273,11 +296,13 @@ export class BotBox {
setup: { dataDir: options.dataDir, home: options.home, codeRoots: options.codeRoots ?? defaultCodeRoots(), engineRoots: options.engineRoots ?? engineInstallRoots(options.dataDir), bridges },
denyEnv: options.denyEnv, seccompFile: this.seccompFile,
broker: { port: BOX_BROKER_PORT, mintForProcess: this.credentials.mintForProcess, revoke: this.credentials.revoke },
+ toolCaches: toolCachesOn(env),
});
this.runner.scopeAudiences(this.audiences);
distrustHomePrograms(options.home, [options.dataDir], ["workspaces", "task-workspaces", "engine-homes", "team-files"].map((name) => join(options.dataDir, name)));
resetPathCache();
log(`bot box: on (bubblewrap, ${this.detection.tools.socat ? "socat" : "node"} bridges, credential broker, seccomp ${this.seccompFile ? "on" : "unsupported here"})`);
+ if (toolCachesOn(env)) log(`bot box: tool caches go to the cache folder in each box's HOME (${CACHE_ROOT_SWITCH})`);
return this.detection;
}
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 02a1d7f78b..16b122bfd7 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -14,7 +14,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_AZURE_OPENAI_LIVE_ENDPOINT", "OMB_BACKGROUND_TEXT_MAX", "OMB_BENCH", "OMB_BOAT_API", "OMB_BOTS_FULL_SAVE", "OMB_BOTS_SAVE_CHECK", "OMB_BOT_BOX", "OMB_BOT_MEMORY_MAX_MB", "OMB_BOX_CANARY", "OMB_BRAND_FILE",
"OMB_BROWSER_CONNECTION", "OMB_BROWSER_HOLD_IDLE_MS", "OMB_BROWSER_IDLE_HANDOVER_MS", "OMB_BROWSER_LANG", "OMB_BROWSER_LEGACY_SHELL",
"OMB_BROWSER_MAX_RUNNING", "OMB_BROWSER_SANDBOX", "OMB_BROWSER_SCREEN", "OMB_BROWSER_TIMEZONE", "OMB_BROWSER_TIMING",
- "OMB_BUG_REPORT_URL", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",
+ "OMB_BUG_REPORT_URL", "OMB_CACHE_ROOT", "OMB_CADDY_PATH", "OMB_CHECKPOINT_GIT_MAX", "OMB_CHROME_PATH", "OMB_CLAUDE_AUTOCOMPACT",
"OMB_CLAUDE_INHERIT_USER_CONFIG", "OMB_CLAUDE_SESSION_IDLE_", "OMB_CLI_OWNER_STDIN", "OMB_CLI_PREFIX", "OMB_CLINE_PROVIDER",
"OMB_CLOUDFLARED_PATH", "OMB_CLOUD_", "OMB_CLOUD_ADMIN_URL", "OMB_CLOUD_AI_TOKEN", "OMB_CLOUD_AI_URL",
"OMB_CLOUD_BOAT_TOKEN", "OMB_CLOUD_BOAT_URL", "OMB_CLOUD_BOOTSTRAP_SECRET", "OMB_CLOUD_CAPS_DROPPED",
diff --git a/server/bot-box/tool-caches.linux.test.ts b/server/bot-box/tool-caches.linux.test.ts
new file mode 100644
index 0000000000..cca4553f63
--- /dev/null
+++ b/server/bot-box/tool-caches.linux.test.ts
@@ -0,0 +1,69 @@
+// The tool cache folder in a real box, where one can run: Linux with an unprivileged bubblewrap (a Cloud home, CI's
+// Linux runner). Elsewhere the suite says so and skips, like the box's own self-check.
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { memberAudience } from "../audience.ts";
+import { audienceHome } from "../engine-homes/layout.ts";
+import { detectBox } from "./detect.ts";
+import { bwrapArgs, planBox, type BoxRequest } from "./plan.ts";
+import { toolCacheEnvironment } from "./tool-caches.ts";
+
+const detection = detectBox({ env: { ...process.env, OMB_BOT_BOX: "1" } });
+const available = detection.box === "bwrap" && detection.tools !== null;
+const root = mkdtempSync(join(tmpdir(), "omb-tool-caches-box-"));
+afterAll(() => rmSync(root, { recursive: true, force: true }));
+
+const home = join(root, "home"), dataDir = join(home, ".openmausbot");
+const ana = audienceHome(dataDir, memberAudience("p_ana")), ben = audienceHome(dataDir, memberAudience("p_ben"));
+const cwd = join(dataDir, "task-workspaces", "bot-a", "t1");
+
+/** A shell in a box whose HOME is `boxHome` (the server's, or an audience's engine home), with the tool cache variables. */
+function runInBox(boxHome: string, script: string): { output: string; env: Record<string, string> } {
+ const env = { PATH: "/usr/bin:/bin", HOME: boxHome, ...toolCacheEnvironment(boxHome, {}) };
+ const request: BoxRequest = { command: "/bin/sh", args: [], cwd, env, ...(boxHome === home ? {} : { home: boxHome }) };
+ const plan = planBox({ dataDir, home, codeRoots: [], engineRoots: [], bridges: [] }, request);
+ const ran = spawnSync(detection.tools!.bwrap, [...bwrapArgs(plan), "--", "/bin/sh", "-c", script], { env, encoding: "utf8", timeout: 30_000 });
+ return { output: `${ran.stdout}${ran.stderr}`, env };
+}
+
+describe.skipIf(!available)(`tool caches in a real box (${available ? "bubblewrap works here" : `skipped: ${detection.reason}`})`, () => {
+ beforeAll(() => {
+ mkdirSync(cwd, { recursive: true });
+ mkdirSync(join(dataDir, "cache", "node-compile"), { recursive: true });
+ writeFileSync(join(dataDir, "cache", "node-compile", "entry"), "the app's own");
+ for (const audience of [ana, ben]) mkdirSync(audience, { recursive: true });
+ mkdirSync(join(ben, "cache", "npm"), { recursive: true });
+ writeFileSync(join(ben, "cache", "npm", "index"), "ben's packages");
+ });
+
+ it("a personal Cloud's box writes each tool's cache under HOME/cache, and never sees the app's own cache folder", () => {
+ const { output, env } = runInBox(home, [
+ 'for d in "$npm_config_cache" "$PIP_CACHE_DIR" "$UV_CACHE_DIR" "$HF_HUB_CACHE" "$BUN_INSTALL_CACHE_DIR"; do mkdir -p "$d" && printf ok > "$d/probe" || echo "CANNOT-WRITE $d"; done',
+ `cat "${join(dataDir, "cache", "node-compile", "entry")}" 2>/dev/null || echo APP-CACHE-HIDDEN`,
+ ].join("\n"));
+ expect(output).not.toContain("CANNOT-WRITE");
+ expect(output).toContain("APP-CACHE-HIDDEN");
+ for (const name of ["npm_config_cache", "PIP_CACHE_DIR", "UV_CACHE_DIR", "HF_HUB_CACHE", "BUN_INSTALL_CACHE_DIR"]) {
+ expect(env[name]!.startsWith(join(home, "cache"))).toBe(true);
+ expect(readFileSync(join(env[name]!, "probe"), "utf8")).toBe("ok");
+ }
+ });
+
+ it("a Team Cloud member's box has its own cache folder in its engine home, and cannot read another member's", () => {
+ const { output, env } = runInBox(ana, [
+ 'mkdir -p "$npm_config_cache" && printf ok > "$npm_config_cache/probe" || echo CANNOT-WRITE',
+ `cat "${join(ben, "cache", "npm", "index")}" 2>/dev/null || echo BEN-UNREADABLE`,
+ `ls "${join(home, "cache")}" 2>/dev/null || echo SERVER-HOME-CACHE-ABSENT`,
+ ].join("\n"));
+ expect(output).not.toContain("CANNOT-WRITE");
+ expect(output).toContain("BEN-UNREADABLE");
+ expect(output).not.toContain("ben's packages");
+ expect(output).toContain("SERVER-HOME-CACHE-ABSENT");
+ expect(env.npm_config_cache).toBe(join(ana, "cache", "npm"));
+ expect(existsSync(join(ana, "cache", "npm", "probe"))).toBe(true);
+ });
+});
diff --git a/server/bot-box/tool-caches.test.ts b/server/bot-box/tool-caches.test.ts
new file mode 100644
index 0000000000..f537039e14
--- /dev/null
+++ b/server/bot-box/tool-caches.test.ts
@@ -0,0 +1,233 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { BotBox, BoxRunner, BOX_EGRESS_PORT } from "./box.ts";
+import { visibleInBox } from "./plan.ts";
+import { CACHE_TAG, CACHE_TAG_FILE, TOOL_CACHES, ensureToolCacheRoot, hasCacheTag, toolCacheEnvironment, toolCacheRoot, toolCachesOn } from "./tool-caches.ts";
+import { engineInstallRoots } from "../engine-roots.ts";
+import { memberAudience } from "../audience.ts";
+import { audienceHome } from "../engine-homes/layout.ts";
+
+const bridge = { socat: "/usr/bin/socat", bridgeScript: "/app/dist-server/bot-box/box-bridge.js", node: "/usr/local/bin/node" };
+const dataDir = "/data/.openmausbot", home = "/data";
+const setup = { dataDir, home, codeRoots: ["/app"], engineRoots: engineInstallRoots(dataDir), bridges: [{ name: "egress", port: BOX_EGRESS_PORT, socket: "/data/.openmausbot/box/egress.sock" }] };
+const turn = { command: "/usr/local/bin/claude", args: ["-p"], cwd: join(dataDir, "task-workspaces", "b1", "t1"), env: { PATH: "/usr/bin", HOME: home, ANTHROPIC_API_KEY: "k" } };
+// The cache folder is made on a real disk only in the BotBox.start tests below; here every HOME's is the server's.
+const runner = (toolCaches?: boolean, cacheRoot: (root: string) => boolean | null = () => true) =>
+ new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge, setup, denyEnv: new Set(), cacheRoot, ...(toolCaches === undefined ? {} : { toolCaches }) });
+const cacheNames = TOOL_CACHES.map((cache) => cache.name);
+
+describe("the switch", () => {
+ it("is on only on a Cloud home that sets it, never on a desktop", () => {
+ expect(toolCachesOn({})).toBe(false);
+ expect(toolCachesOn({ OMB_CLOUD_ROLE: "home" })).toBe(false);
+ for (const value of ["1", "on", "ON", "true", "yes", " on "]) expect(toolCachesOn({ OMB_CLOUD_ROLE: "home", OMB_CACHE_ROOT: value }), value).toBe(true);
+ expect(toolCachesOn({ OMB_CLOUD_ROLE: "team", OMB_CACHE_ROOT: "on" })).toBe(true);
+ for (const value of ["", "0", "off", "/data/cache", "maybe"]) expect(toolCachesOn({ OMB_CLOUD_ROLE: "home", OMB_CACHE_ROOT: value }), value).toBe(false);
+ // A desktop, even one that forces the box on for a test, never moves a tool's cache.
+ expect(toolCachesOn({ OMB_CACHE_ROOT: "on", OMB_BOT_BOX: "on" })).toBe(false);
+ expect(toolCachesOn({ OMB_CLOUD_ROLE: "desktop", OMB_CACHE_ROOT: "on" })).toBe(false);
+ });
+});
+
+describe("a box's environment", () => {
+ it("off, it is exactly today's: no cache variable is added, with the switch absent or false", () => {
+ const today = {
+ PATH: "/usr/bin", HOME: home, ANTHROPIC_API_KEY: "k",
+ HTTPS_PROXY: `http://127.0.0.1:${BOX_EGRESS_PORT}`, HTTP_PROXY: `http://127.0.0.1:${BOX_EGRESS_PORT}`, https_proxy: `http://127.0.0.1:${BOX_EGRESS_PORT}`, http_proxy: `http://127.0.0.1:${BOX_EGRESS_PORT}`,
+ NO_PROXY: "127.0.0.1,localhost,::1,[::1]", no_proxy: "127.0.0.1,localhost,::1,[::1]",
+ };
+ expect(runner().wrap(turn).env).toEqual(today);
+ expect(runner(false).wrap(turn).env).toEqual(today);
+ expect(runner(false).wrap(turn).args).toEqual(runner().wrap(turn).args);
+ });
+
+ it("off, the cache folder is never looked at or made", () => {
+ const asked: string[] = [];
+ for (const toolCaches of [undefined, false]) runner(toolCaches, (root) => { asked.push(root); return true; }).wrap(turn);
+ expect(asked).toEqual([]);
+ });
+
+ it("the bubblewrap arguments are the same with the switch on or off: no mount is added, a personal or a Team HOME", () => {
+ const member = audienceHome(dataDir, memberAudience("[email protected]"));
+ for (const request of [turn, { ...turn, home: member, env: { ...turn.env, HOME: member } }]) {
+ const on = runner(true).wrap(request), off = runner(false).wrap(request);
+ expect(on.env.npm_config_cache).toBeDefined();
+ expect(on.args).toEqual(off.args);
+ expect(on.plan).toEqual(off.plan);
+ }
+ });
+
+ it("on, a HOME whose cache folder the server did not make keeps every tool's own place; each folder is asked once", () => {
+ const asked: string[] = [];
+ const theirs = runner(true, (root) => { asked.push(root); return false; });
+ for (let i = 0; i < 3; i++) for (const name of cacheNames) expect(theirs.wrap(turn).env[name], name).toBeUndefined();
+ expect(asked).toEqual([toolCacheRoot(home)]);
+ // A HOME that is not there yet is asked again on the next spawn, not given up on.
+ let ready: boolean | null = null;
+ const later = runner(true, () => ready);
+ expect(later.wrap(turn).env.npm_config_cache).toBeUndefined();
+ ready = true;
+ expect(later.wrap(turn).env.npm_config_cache).toBe(join(toolCacheRoot(home), "npm"));
+ });
+
+ it("on, every cache variable names its folder in the box HOME's cache folder", () => {
+ const env = runner(true).wrap(turn).env;
+ const root = toolCacheRoot(home);
+ expect(root).toBe(join(resolve(home), "cache"));
+ expect(env).toMatchObject({
+ npm_config_cache: join(root, "npm"), PIP_CACHE_DIR: join(root, "pip"), UV_CACHE_DIR: join(root, "uv"),
+ HF_HUB_CACHE: join(root, "huggingface", "hub"), HF_XET_CACHE: join(root, "huggingface", "xet"),
+ BUN_INSTALL_CACHE_DIR: join(root, "bun"),
+ });
+ expect(Object.keys(env).filter((name) => cacheNames.includes(name)).sort()).toEqual([...cacheNames].sort());
+ for (const name of cacheNames) expect(env[name], name).toBeDefined();
+ // Nothing that holds a sign-in or installed programs is moved.
+ // Nor a browser (a Playwright MCP profile may sit beside its builds; a project's .puppeteerrc names its own), nor Go's
+ // module cache (a project may build offline from it).
+ for (const name of ["XDG_CACHE_HOME", "HF_HOME", "CARGO_HOME", "GRADLE_USER_HOME", "PNPM_HOME", "UV_TOOL_DIR", "UV_PYTHON_INSTALL_DIR", "npm_config_store_dir", "PLAYWRIGHT_BROWSERS_PATH", "PUPPETEER_CACHE_DIR", "GOMODCACHE", "GOPATH", "GOCACHE", "COREPACK_HOME"]) expect(env[name], name).toBeUndefined();
+ expect(env.HOME).toBe(home);
+ });
+
+ it("on, the person's own value wins: one the engine's saved settings pass in, npm's in any letter case", () => {
+ const env = runner(true).wrap({
+ ...turn, env: { ...turn.env, UV_CACHE_DIR: "/data/my-uv", NPM_CONFIG_CACHE: "/data/my-npm", HF_HUB_CACHE: "/data/hf-hub" },
+ allowEnv: ["UV_CACHE_DIR", "HF_HUB_CACHE"],
+ }).env;
+ expect(env.UV_CACHE_DIR).toBe("/data/my-uv");
+ expect(env.HF_HUB_CACHE).toBe("/data/hf-hub");
+ expect(env.NPM_CONFIG_CACHE).toBe("/data/my-npm");
+ expect(env.npm_config_cache).toBeUndefined();
+ expect(env.PIP_CACHE_DIR).toBe(join(toolCacheRoot(home), "pip"));
+ });
+
+ it("on, a variable that already decides a cache's place leaves that cache alone", () => {
+ const env = runner(true).wrap({ ...turn, env: { ...turn.env, XDG_CACHE_HOME: "/data/xdg", HF_HOME: "/data/hf", GOPATH: "/data/go", BUN_INSTALL: "/data/.bun" }, allowEnv: ["HF_HOME", "GOPATH", "BUN_INSTALL"] }).env;
+ for (const name of ["PIP_CACHE_DIR", "UV_CACHE_DIR", "HF_HUB_CACHE", "HF_XET_CACHE", "BUN_INSTALL_CACHE_DIR"]) expect(env[name], name).toBeUndefined();
+ expect(env.npm_config_cache).toBe(join(toolCacheRoot(home), "npm"));
+ });
+
+ it("on, a value the spawn was handed wins even where the allow-list would drop it: an engine's own environment that does not vouch", () => {
+ // Claude's and Codex's drivers merge the instance's environment into the spawn's without allowEnv; on a Cloud home the
+ // server's own environment never carries these names, so one here is the person's or the engine's.
+ const env = runner(true).wrap({ ...turn, env: { ...turn.env, PIP_CACHE_DIR: "/data/my-pip", HF_HOME: "/data/hf" } }).env;
+ expect(env.PIP_CACHE_DIR).toBe("/data/my-pip");
+ // A parent that decides a cache's place is not passed in, but its cache is left to the tool's default under it.
+ expect(env.HF_HOME).toBeUndefined();
+ expect(env.HF_HUB_CACHE).toBeUndefined();
+ expect(env.HF_XET_CACHE).toBeUndefined();
+ expect(env.UV_CACHE_DIR).toBe(join(toolCacheRoot(home), "uv"));
+ });
+
+ it("toolCacheEnvironment adds nothing a set name covers and never touches the given environment", () => {
+ const given = { npm_config_cache: "/x", HOME: home };
+ const added = toolCacheEnvironment(home, given);
+ expect(added.npm_config_cache).toBeUndefined();
+ expect(given).toEqual({ npm_config_cache: "/x", HOME: home });
+ expect(toolCacheEnvironment(home, { npm_config_cache: "" }).npm_config_cache).toBe(join(toolCacheRoot(home), "npm"));
+ expect(toolCacheEnvironment(home, {}, { PIP_CACHE_DIR: "/data/pp" }).PIP_CACHE_DIR).toBe("/data/pp");
+ expect(toolCacheEnvironment(home, { PIP_CACHE_DIR: "/data/kept" }, { PIP_CACHE_DIR: "/data/pp" }).PIP_CACHE_DIR).toBeUndefined();
+ });
+});
+
+// The box's paths are POSIX paths inside it, which Windows' path module would write with drive letters.
+describe.skipIf(process.platform === "win32")("what the box can reach", () => {
+ it("a personal Cloud: the cache folder is read-write in every bot's box, the app's own cache folder is hidden", () => {
+ const wrapped = runner(true).wrap(turn);
+ expect(visibleInBox(wrapped.plan, "/data/cache")).toBe("rw");
+ for (const name of cacheNames) expect(visibleInBox(wrapped.plan, wrapped.env[name]!), name).toBe("rw");
+ expect(visibleInBox(wrapped.plan, join(dataDir, "cache"))).toBe("none");
+ expect(visibleInBox(wrapped.plan, join(dataDir, "cache", "node-compile"))).toBe("none");
+ });
+
+ it("a Team Cloud: each audience's box has its own cache folder in its engine home, and no other audience's", () => {
+ const member = audienceHome(dataDir, memberAudience("[email protected]"));
+ const other = audienceHome(dataDir, memberAudience("[email protected]"));
+ expect(member).not.toBe(other);
+ const wrapped = runner(true).wrap({ ...turn, home: member, env: { ...turn.env, HOME: member } });
+ expect(wrapped.env.npm_config_cache).toBe(join(member, "cache", "npm"));
+ for (const name of cacheNames) expect(visibleInBox(wrapped.plan, wrapped.env[name]!), name).toBe("rw");
+ expect(visibleInBox(wrapped.plan, join(other, "cache"))).toBe("none");
+ expect(visibleInBox(wrapped.plan, "/data/cache")).toBe("none");
+ });
+});
+
+// On, the box's gates listen on unix sockets, which Windows refuses at a file path (box.test.ts says the same).
+describe.skipIf(process.platform === "win32")("BotBox.start", () => {
+ const boxes: BotBox[] = [];
+ const dirs: string[] = [];
+ afterEach(async () => {
+ for (const box of boxes.splice(0)) await box.stop();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+ });
+ const started = async (env: Record<string, string>) => {
+ const root = mkdtempSync(join(tmpdir(), "omb-tool-caches-"));
+ dirs.push(root);
+ const lines: string[] = [];
+ const box = new BotBox();
+ boxes.push(box);
+ await box.start({ dataDir: join(root, ".openmausbot"), home: root, port: 8799, denyEnv: new Set(), env, log: (line) => lines.push(line), detect: () => ({ box: "bwrap", reason: null, tools: { bwrap: "/usr/bin/bwrap", socat: null } }) });
+ return { box, root, lines, wrapped: box.wrap({ command: "/usr/bin/codex", args: [], env: { PATH: "/usr/bin" } })! };
+ };
+
+ it("reads the switch from the server's environment: a Cloud home with it on adds the variables and says so once", async () => {
+ const on = await started({ OMB_CLOUD_ROLE: "home", OMB_CACHE_ROOT: "on" });
+ expect(on.wrapped.env.npm_config_cache).toBe(join(on.root, "cache", "npm"));
+ // The folder is made on the first spawn, with the server's mark.
+ expect(readFileSync(join(on.root, "cache", CACHE_TAG_FILE), "utf8")).toBe(CACHE_TAG);
+ expect(on.lines).toContain("bot box: tool caches go to the cache folder in each box's HOME (OMB_CACHE_ROOT)");
+ for (const env of [{}, { OMB_CLOUD_ROLE: "home" }, { OMB_CACHE_ROOT: "on" }] as Record<string, string>[]) {
+ const off = await started(env);
+ for (const name of cacheNames) expect(off.wrapped.env[name], `${JSON.stringify(env)} ${name}`).toBeUndefined();
+ expect(off.lines.some((line) => line.includes("tool caches"))).toBe(false);
+ expect(existsSync(join(off.root, "cache"))).toBe(false);
+ }
+ });
+});
+
+describe("the cache folder the server makes", () => {
+ const dirs: string[] = [];
+ afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+ const scratch = () => { const dir = mkdtempSync(join(tmpdir(), "omb-cache-root-")); dirs.push(dir); return dir; };
+
+ it("is made and marked when HOME has none, and is the server's on every later start", () => {
+ const home = scratch(), root = toolCacheRoot(home);
+ expect(ensureToolCacheRoot(root)).toBe(true);
+ expect(readFileSync(join(root, CACHE_TAG_FILE), "utf8")).toBe(CACHE_TAG);
+ expect(hasCacheTag(root)).toBe(true);
+ expect(ensureToolCacheRoot(root)).toBe(true);
+ });
+
+ it("an empty cache folder without the mark (a start that stopped before writing it) is marked and the server's", () => {
+ const home = scratch(), root = toolCacheRoot(home);
+ mkdirSync(root);
+ expect(ensureToolCacheRoot(root)).toBe(true);
+ expect(readFileSync(join(root, CACHE_TAG_FILE), "utf8")).toBe(CACHE_TAG);
+ });
+
+ it("a cache folder the person made stays theirs: nothing is written in it, even a CACHEDIR.TAG of another tool", () => {
+ const home = scratch(), root = toolCacheRoot(home);
+ mkdirSync(root);
+ writeFileSync(join(root, "notes.md"), "mine");
+ expect(ensureToolCacheRoot(root)).toBe(false);
+ expect(existsSync(join(root, CACHE_TAG_FILE))).toBe(false);
+ writeFileSync(join(root, CACHE_TAG_FILE), "Signature: 8a477f597d28d172789f06886806bc55\n");
+ expect(ensureToolCacheRoot(root)).toBe(false);
+ expect(readFileSync(join(root, "notes.md"), "utf8")).toBe("mine");
+ });
+
+ it("a HOME that is not there yet is neither made nor given up on", () => {
+ const missing = join(scratch(), "not-yet");
+ expect(ensureToolCacheRoot(toolCacheRoot(missing))).toBeNull();
+ expect(existsSync(missing)).toBe(false);
+ });
+
+ it.skipIf(process.platform === "win32")("a link named cache is never the server's, wherever it points", () => {
+ const home = scratch(), elsewhere = join(home, "elsewhere");
+ expect(ensureToolCacheRoot(join(elsewhere))).toBe(true);
+ symlinkSync(elsewhere, toolCacheRoot(home));
+ expect(ensureToolCacheRoot(toolCacheRoot(home))).toBe(false);
+ });
+});
diff --git a/server/bot-box/tool-caches.ts b/server/bot-box/tool-caches.ts
new file mode 100644
index 0000000000..c1e574f44c
--- /dev/null
+++ b/server/bot-box/tool-caches.ts
@@ -0,0 +1,127 @@
+// Tool caches on a Cloud home (docs/bot-box.md, "Tool caches"). With OMB_CACHE_ROOT on, what a bot's tools download again
+// whenever it is missing (npm's and pip's packages, uv's wheels, Hugging Face models, …) goes into one folder, `cache` in
+// the box's HOME, through each tool's own variable, so "never back up, cap, clean" becomes one rule for one folder. The
+// box's HOME is /data on a personal Cloud and the audience's own engine home on a Team Cloud (server/engine-homes), so the
+// folder is shared exactly as ~/.npm and ~/.cache already are, never across audiences.
+//
+// Only pure download caches move. Left alone on purpose: a variable whose folder also holds sign-ins, tokens, settings or
+// installed programs (HF_HOME and XDG_CACHE_HOME, where Hugging Face keeps its login token; CARGO_HOME; GRADLE_USER_HOME;
+// PNPM_HOME; UV_TOOL_DIR and UV_PYTHON_INSTALL_DIR, which venvs and ~/.local/bin point into), and pnpm's store, which a
+// project's node_modules records (pnpm then refuses to install until node_modules is removed) and whose only variable,
+// npm_config_store_dir, makes every npm command warn. Also left alone: PLAYWRIGHT_BROWSERS_PATH (older Playwright MCP builds
+// keep the browser profile, with its cookies and site sign-ins, in that folder), PUPPETEER_CACHE_DIR (it beats a project's
+// .puppeteerrc, so a project keeping Chrome in its own folder stops finding it) and GOMODCACHE (it beats `go env -w`, and a
+// project building offline from its module cache would fail), COREPACK_HOME (its lastKnownGood.json records which
+// package manager version is active, not only downloads) and GOCACHE (it also holds Go's fuzzing corpus, which
+// `go clean -cache` keeps).
+//
+// The folder is used only when the server made it (ensureToolCacheRoot): it is marked with a CACHEDIR.TAG, and a `cache`
+// folder already in HOME without that mark is the person's own, so for that HOME nothing is routed into it.
+import { lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+import { cloudRole } from "./detect.ts";
+
+/** The switch: 1, on, true or yes on a Cloud home turns the tool cache folder on; anything else, or unset, leaves it off. */
+export const CACHE_ROOT_SWITCH = "OMB_CACHE_ROOT";
+
+/** The folder in the box's HOME that the tools' caches go to. */
+export const TOOL_CACHE_DIR = "cache";
+
+/** The mark the server leaves in a cache folder it made (https://bford.info/cachedir/): backup tools skip a tagged folder,
+ * and the cache cap (server/cache-sweep) works only in a folder with exactly this text. */
+export const CACHE_TAG_FILE = "CACHEDIR.TAG";
+export const CACHE_TAG = "Signature: 8a477f597d28d172789f06886806bc55\n# Made by OpenMausBot for its bots' tool caches (OMB_CACHE_ROOT). Everything here is downloaded again when missing.\n";
+
+export interface ToolCache {
+ /** The tool's own variable. */
+ name: string;
+ /** Its folder under the cache root. */
+ folder: string;
+ /** Variables that, set by the person or the engine, already decide where this cache goes: then it is left to them. */
+ yieldsTo: readonly string[];
+}
+
+/** Every cache this moves, each a folder only the tool's own downloads are in. A variable here beats the tool's config files
+ * (docs/bot-box.md says which): what that costs is a download again, never a sign-in or a project's own files. */
+export const TOOL_CACHES: readonly ToolCache[] = [
+ // npm reads its config from the environment in any letter case; npx keeps its packages in the same cache (_npx).
+ { name: "npm_config_cache", folder: "npm", yieldsTo: [] },
+ { name: "PIP_CACHE_DIR", folder: "pip", yieldsTo: ["XDG_CACHE_HOME"] },
+ // uv's wheels and source builds only; the Pythons and tools it installs stay where venvs and ~/.local/bin find them.
+ { name: "UV_CACHE_DIR", folder: "uv", yieldsTo: ["XDG_CACHE_HOME"] },
+ // The models and datasets' files only: HF_HOME, which holds the login token, is never set here.
+ { name: "HF_HUB_CACHE", folder: "huggingface/hub", yieldsTo: ["HF_HOME", "HUGGINGFACE_HUB_CACHE", "XDG_CACHE_HOME"] },
+ { name: "HF_XET_CACHE", folder: "huggingface/xet", yieldsTo: ["HF_HOME", "XDG_CACHE_HOME"] },
+ // bun's default follows BUN_INSTALL; it may also follow XDG_CACHE_HOME (not checked), so a person's value there wins too.
+ { name: "BUN_INSTALL_CACHE_DIR", folder: "bun", yieldsTo: ["BUN_INSTALL", "XDG_CACHE_HOME"] },
+];
+
+const ON = new Set(["1", "on", "true", "yes"]);
+
+/** Whether this server puts its bots' tool caches in the cache folder: a Cloud home with the switch on, never a desktop. */
+export function toolCachesOn(env: Record<string, string | undefined>): boolean {
+ return cloudRole(env) && ON.has((env[CACHE_ROOT_SWITCH] ?? "").trim().toLowerCase());
+}
+
+/** The cache folder of a box whose HOME is `home`. */
+export function toolCacheRoot(home: string): string {
+ return join(resolve(home), TOOL_CACHE_DIR);
+}
+
+const code = (error: unknown) => (error as NodeJS.ErrnoException)?.code ?? "";
+
+/** Whether `root` is a real folder (not a link) holding the server's own CACHEDIR.TAG. */
+export function hasCacheTag(root: string): boolean {
+ try {
+ if (!lstatSync(root).isDirectory()) return false;
+ const tag = join(root, CACHE_TAG_FILE);
+ return lstatSync(tag).isFile() && readFileSync(tag, "utf8") === CACHE_TAG;
+ } catch {
+ return false;
+ }
+}
+
+/** Makes the cache folder `root` when HOME has none, and marks it. True: the folder is the server's (made now, marked by
+ * an earlier start, or an empty folder, which is marked now: a start that made it may have stopped before its mark).
+ * False: a `cache` with something in it and no mark is the person's, so it is left alone. Null: it could not be made
+ * now (HOME missing): ask again on the next spawn. Never deletes or changes anything already in a folder. */
+export function ensureToolCacheRoot(root: string): boolean | null {
+ try {
+ mkdirSync(root, { mode: 0o755 });
+ } catch (error) {
+ if (code(error) !== "EEXIST") return null;
+ if (hasCacheTag(root)) return true;
+ if (!emptyFolder(root)) return false;
+ }
+ try {
+ writeFileSync(join(root, CACHE_TAG_FILE), CACHE_TAG, { flag: "wx", mode: 0o644 });
+ return true;
+ } catch {
+ return hasCacheTag(root);
+ }
+}
+
+function emptyFolder(path: string): boolean {
+ try { return lstatSync(path).isDirectory() && readdirSync(path).length === 0; } catch { return false; }
+}
+
+const named = (env: Readonly<Record<string, string | undefined>>) =>
+ new Map(Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined && entry[1] !== "").map(([name, value]) => [name.toLowerCase(), value]));
+
+/** The variables to add to a box's environment `env` (already allow-listed) whose HOME is `home`. `given` is what the
+ * spawn was handed before the allow-list: on a Cloud home the server's own environment carries none of these names
+ * (cloud-home-start.ts SERVER_ENV_NAMES), so one there is the person's or the engine's for this spawn. A cache whose
+ * variable, or a variable that decides its place, either names is left to them; its own variable that the allow-list
+ * dropped goes back with their value. Every other cache gets its folder in the cache root. */
+export function toolCacheEnvironment(home: string, env: Readonly<Record<string, string | undefined>>, given: Readonly<Record<string, string | undefined>> = {}): Record<string, string> {
+ const kept = named(env), handed = named(given);
+ const root = toolCacheRoot(home);
+ const added: Record<string, string> = {};
+ for (const cache of TOOL_CACHES) {
+ const name = cache.name.toLowerCase();
+ if (!kept.has(name) && handed.has(name)) added[cache.name] = handed.get(name)!;
+ else if (![name, ...cache.yieldsTo.map((other) => other.toLowerCase())].some((other) => kept.has(other) || handed.has(other))) added[cache.name] = join(root, ...cache.folder.split("/"));
+ }
+ return added;
+}
diff --git a/server/cloud-home-start.ts b/server/cloud-home-start.ts
index aae0354454..bee7e66cde 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",
+ // Tool caches into one folder in each bot box's HOME (server/bot-box/tool-caches.ts): off unless the Admin turns it on.
+ "OMB_CACHE_ROOT",
// 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).
diff --git a/server/cloud-home.test.ts b/server/cloud-home.test.ts
index 84032821ca..7e8cfed2d8 100644
--- a/server/cloud-home.test.ts
+++ b/server/cloud-home.test.ts
@@ -486,6 +486,14 @@ it("holds requests at the edge while the server starts only when the Admin asked
expect(edgeHold(" 045s ")).toBe("45s");
});
+it("hands the server the tool cache switch, and moves no cache of the server's own", () => {
+ const config = cloudHomeConfiguration(withGateway())!;
+ const server = cloudHomeChildEnvironments(config, { ...withGateway(), PATH: "/usr/bin", OMB_CACHE_ROOT: "on" }, "/data").server;
+ expect(server).toMatchObject({ OMB_CACHE_ROOT: "on", HOME: "/data", NODE_COMPILE_CACHE: "/data/.openmausbot/cache/node-compile" });
+ // Only the bot box adds the tools' variables (bot-box/tool-caches.ts), for each box's own HOME.
+ for (const name of ["npm_config_cache", "PIP_CACHE_DIR", "UV_CACHE_DIR", "HF_HUB_CACHE", "XDG_CACHE_HOME"]) expect(server).not.toHaveProperty(name);
+});
+
it("hands the server the Admin's export-only switch, so an ended Cloud started for its owner's export runs frozen", () => {
// Seen on a real staging test Cloud on Oct 22: the Admin booted the held Cloud with OMB_CLOUD_EXPORT_ONLY=1, the log said
// "not passed to the server: … OMB_CLOUD_EXPORT_ONLY …", and it ran its routines every 5 minutes for the whole export
diff --git a/server/perf/disk-categories.test.ts b/server/perf/disk-categories.test.ts
index 02817ea767..0838bef53c 100644
--- a/server/perf/disk-categories.test.ts
+++ b/server/perf/disk-categories.test.ts
@@ -24,6 +24,8 @@ describe("storage categories", () => {
["attachments/a.png", "attachments"], ["attachment-originals/a", "attachments"], ["box-uploads/b/t/f", "attachments"], ["browser-uploads/f", "attachments"],
["tool-results/t/r.json", "attachments"], ["meetings/m/rec.wav", "attachments"], ["browser/downloads/abc/file.zip", "attachments"],
["sync/lent/f", "synced"], ["sync/trash/123", "trash"], ["sync/uploads/part", "temp"], ["engine-homes/.held/old", "trash"],
+ ["engine-homes/member-0123456789abcdef/cache/uv/x", "caches"], ["engine-homes/member-0123456789abcdef/cache/huggingface/token", "other"],
+ ["engine-homes/member-0123456789abcdef/.claude/x", "engine_state"],
[".backups/job/staged/data", "backups"], ["doctor-backups/2026/x", "backups"],
["browser/profiles/abc/Default/Cookies", "browser_profiles"], ["browser/profiles/abc/Default/Login Data", "browser_profiles"],
["browser/profiles/abc/Local State", "browser_profiles"], ["browser/workspace-id", "browser_profiles"], ["agent-browser-profiles/abc/Default/Cookies", "browser_profiles"],
@@ -65,6 +67,9 @@ describe("storage categories", () => {
[".config/gh/hosts.yml", "settings"], [".omb-cloud-home.json", "settings"], [".omb-edge/caddy/x", "settings"],
["Synced/Desktop/a.txt", "synced"], [".local/share/Trash/files/x", "trash"],
["lost+found/x", "other"], ["acme-merger/plan.md", "other"], [".local/lib/x", "other"],
+ // The tools' cache folder (bot-box/tool-caches.ts): its own folders only; a token or a bot's file there is not a cache.
+ ["cache/npm/_cacache/x", "caches"], ["cache/bun/x.tgz", "caches"], ["cache/go-build/00/a-d", "other"], ["cache/ms-playwright/chromium-1/chrome", "other"],
+ ["cache/huggingface/hub/models--o--m/x", "caches"], ["cache/huggingface/token", "other"], ["cache/my-notes.md", "other"],
];
for (const [path, expected] of cases) expect([path, category("home", path)]).toEqual([path, expected]);
});
diff --git a/server/perf/disk-categories.ts b/server/perf/disk-categories.ts
index 1ec3442e64..e989d80fa2 100644
--- a/server/perf/disk-categories.ts
+++ b/server/perf/disk-categories.ts
@@ -2,6 +2,7 @@
// (/data, Dockerfile), and the data folder (OMB_DATA_DIR, /data/.openmausbot) sits inside it; a path is read as segments
// relative to one of the two. Privacy invariant: nothing here returns a name taken from the disk except a bot id (which the
// report shows only for bots the store knows) and a name from OTHER_NAMES.
+import { TOOL_CACHES, TOOL_CACHE_DIR } from "../bot-box/tool-caches.ts";
/** `precious`: losing it loses something only this home holds. `work`: what bots and people made or may still read,
* which only doing the work again would bring back. `rebuildable`: the code named next to it makes it again when it is
@@ -197,6 +198,9 @@ function dataPlacement(segments: readonly string[], directory: boolean): Placeme
if (second === undefined) return at("engine_state", false);
// engine-homes/layout.ts HELD_DIR: state from before the split, deleted after HELD_DAYS.
if (second === ".held") return at("trash");
+ // An audience's own tool cache folder (bot-box/tool-caches.ts, OMB_CACHE_ROOT); the rest of its home is engine state.
+ if (third === undefined) return at("engine_state", false);
+ if (third === TOOL_CACHE_DIR) return toolCachePlacement(segments.slice(3));
return at("engine_state");
}
if (first === "org-library") {
@@ -242,6 +246,23 @@ const HOME_CACHES: Readonly<Record<string, StorageCategory>> = {
opencode: "caches",
};
+/** The tool cache folder's own folders (bot-box/tool-caches.ts TOOL_CACHES), each a download cache; any other name in it
+ * (what a bot put in ~/cache before, a token) is `other`. By name only, like `~/.cache/<name>` above: a person's own
+ * `~/cache/npm` in a folder the server did not make (no CACHEDIR.TAG) is labelled a cache too. Only the storage report
+ * reads this; nothing deletes by it (the cache cap checks the mark itself, server/cache-sweep). */
+const TOOL_CACHE_FOLDERS = TOOL_CACHES.map((cache) => cache.folder.split("/"));
+function toolCachePlacement(rest: readonly string[]): Placement {
+ if (rest.length === 0) return at("caches", false);
+ let partial = false;
+ for (const parts of TOOL_CACHE_FOLDERS) {
+ const shared = Math.min(parts.length, rest.length);
+ if (!parts.slice(0, shared).every((part, index) => rest[index] === part)) continue;
+ if (rest.length >= parts.length) return at("caches");
+ partial = true;
+ }
+ return partial ? at("other", false) : at("other");
+}
+
function homePlacement(segments: readonly string[], directory: boolean): Placement {
const [first, second, third] = segments;
if (first === undefined) return at("other", false);
@@ -250,6 +271,8 @@ function homePlacement(segments: readonly string[], directory: boolean): Placeme
if (known) return at(known);
return OTHER_NAMES.has(first) ? { category: "other", otherName: first, final: true } : at("other");
}
+ // The tools' cache folder with OMB_CACHE_ROOT on (bot-box/tool-caches.ts TOOL_CACHE_DIR).
+ if (first === TOOL_CACHE_DIR) return toolCachePlacement(segments.slice(1));
if (first === ".cache") return second === undefined ? at("caches", false) : at(HOME_CACHES[second] ?? "other");
if (first === ".local") {
if (second === undefined) return at("other", false);