Skip to content

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

Bot box: the server's engine model reads run in the box (#5308)

Milind Soni7c8a3cc9e803
diff --git a/server/bot-box/probe-box.test.ts b/server/bot-box/probe-box.test.ts
new file mode 100644
index 0000000000..997b71963c
--- /dev/null
+++ b/server/bot-box/probe-box.test.ts
@@ -0,0 +1,81 @@
+// The engine reads the server makes on its own (model lists, sign-in checks) load the engine's settings, extensions and
+// MCP servers from HOME, which a boxed bot can write: each asks for the bot box, which runs it there where the box is on.
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { fetchDeepSeekCatalog } from "../drivers/acp/deepseek.ts";
+import { fetchHermesAcpModels } from "../drivers/acp/hermes.ts";
+import { discoverOpenCodeModels } from "../drivers/acp/opencode-go.ts";
+import { fetchPiModels, updatePiModelCatalog } from "../drivers/pi.ts";
+import { execCliBoxed } from "../procs.ts";
+import { botBox } from "./box.ts";
+import type { BoxRequest } from "./plan.ts";
+
+const posix = process.platform !== "win32";
+
+describe.skipIf(!posix)("the server's own engine reads ask for the bot box", () => {
+ let dir: string;
+ let asked: BoxRequest[];
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), "omb-probe-box-"));
+ asked = [];
+ // The box is off on this machine: wrap answers null and the spawn runs as is, but every request is seen.
+ vi.spyOn(botBox, "wrap").mockImplementation((request) => { asked.push(request); return null; });
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ /** A stand-in CLI that answers nothing useful and exits. */
+ function cli(name: string): string {
+ const file = join(dir, name);
+ writeFileSync(file, "#!/bin/sh\nexit 0\n");
+ chmodSync(file, 0o755);
+ return file;
+ }
+
+ const env = (extra: Record<string, string> = {}) => ({ PATH: "/usr/bin:/bin", HOME: dir, ...extra });
+
+ it("Pi's model list and its catalog update", async () => {
+ const pi = cli("pi");
+ await fetchPiModels(pi, env({ NANO_KEY: "k" }), ["NANO_KEY"]);
+ await updatePiModelCatalog(pi, env(), []);
+ expect(asked.map((request) => [request.command, request.args[0], request.allowEnv])).toEqual([
+ [pi, "--mode", ["NANO_KEY"]], [pi, "update", []],
+ ]);
+ });
+
+ it("OpenCode's session probe and its models reads, with the instance's own keys", async () => {
+ const opencode = cli("opencode");
+ mkdirSync(join(dir, "data"), { recursive: true });
+ await discoverOpenCodeModels(env({ VENICE_API_KEY: "v" }), opencode, { refresh: true, settleMs: 1, allowEnv: ["VENICE_API_KEY"] });
+ const seen = asked.map((request) => request.args.join(" "));
+ expect(seen).toEqual(expect.arrayContaining(["models --refresh", "acp", "models --verbose"]));
+ for (const request of asked) expect(request.allowEnv).toEqual(["VENICE_API_KEY"]);
+ });
+
+ it("Hermes' and DeepSeek's catalogs", async () => {
+ await fetchHermesAcpModels(cli("hermes"), env(), ["HERMES_KEY"]);
+ await fetchDeepSeekCatalog(cli("dsh"), env(), dir, ["DEEPSEEK_API_KEY"]).catch(() => {});
+ expect(asked.map((request) => [request.args.join(" "), request.allowEnv])).toEqual([["acp", ["HERMES_KEY"]], ["--profile acp", ["DEEPSEEK_API_KEY"]]]);
+ });
+
+ it("execCliBoxed answers as execCli does: output, a failing exit and a timeout", async () => {
+ const script = join(dir, "say");
+ writeFileSync(script, "#!/bin/sh\nif [ \"$1\" = fail ]; then echo no >&2; exit 3; fi\nif [ \"$1\" = hang ]; then sleep 30; fi\necho \"hello $1\"\n");
+ chmodSync(script, 0o755);
+ const run = (arg: string, timeout = 5_000) => new Promise<{ err: (Error & { code?: unknown; killed?: boolean }) | null; stdout: string; stderr: string }>((resolve) =>
+ execCliBoxed(script, [arg], { env: env(), timeout, box: { allowEnv: [] } }, (err, stdout, stderr) => resolve({ err, stdout, stderr })));
+ expect(await run("there")).toEqual({ err: null, stdout: "hello there\n", stderr: "" });
+ const failed = await run("fail");
+ expect(failed.err?.code).toBe(3);
+ expect(failed.stderr).toBe("no\n");
+ const hung = await run("hang", 200);
+ expect(hung.err?.killed).toBe(true);
+ expect(asked.every((request) => request.command === script)).toBe(true);
+ });
+});
diff --git a/server/drivers/acp/background-text.ts b/server/drivers/acp/background-text.ts
index 08bf4ca26a..f181c7e902 100644
--- a/server/drivers/acp/background-text.ts
+++ b/server/drivers/acp/background-text.ts
@@ -1,7 +1,7 @@
// One tool-free ACP exchange for memory upkeep: a fresh process and session, no MCP servers, an empty
// folder. It fails closed: any agent request, or any tool call it reports, ends the call.
import type { TextGenerationOptions, TextGenerationUsage } from "../../contracts.ts";
-import type { killCliTree, spawnCli } from "../../procs.ts";
+import type { BoxSpawnOptions, killCliTree, spawnCli } from "../../procs.ts";
export const BACKGROUND_TEXT_TIMEOUT_MS = 120_000;
export const BACKGROUND_TEXT_MAX_CHARS = 200_000;
@@ -11,6 +11,9 @@ export interface AcpOneShotInput {
displayName: string;
spawn: typeof spawnCli;
kill: typeof killCliTree;
+ /** Security: while the bot box is on, the engine runs in it, as a bot's turn does, so nothing it loads from a HOME a
+ * bot can write runs outside the box. */
+ box?: BoxSpawnOptions["box"];
command: string;
argv: string[];
env: Record<string, string | undefined>;
@@ -34,7 +37,7 @@ export function runAcpOneShot(input: AcpOneShotInput): Promise<string> {
const name = input.displayName;
if (signal?.aborted) return Promise.reject(new Error(`${name} background call aborted`));
return new Promise<string>((resolve, reject) => {
- const child = input.spawn(input.command, input.argv, { cwd: input.cwd, env: input.env, stdio: ["pipe", "pipe", "pipe"], botWork: true });
+ const child = input.spawn(input.command, input.argv, { cwd: input.cwd, env: input.env, stdio: ["pipe", "pipe", "pipe"], botWork: true, ...(input.box ? { box: input.box } : {}) });
let settled = false;
let buffer = "";
let received = 0;
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index 1916cbe4b9..5a2e3ecdaa 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -107,12 +107,12 @@ export interface AcpSupport {
modelVariants?: boolean;
/** Default CLI binary name if the instance config doesn't override it. */
defaultCli: string;
- /** Optional live model catalog; a failed lookup keeps the last usable one. `config` lets a support ask the binary
- * it will spawn, not whatever is on PATH; `fresh` is the person's Refresh, which may bypass the CLI's own cache. */
+ /** Optional live model catalog; a failed lookup keeps the last usable one. `config` lets a support ask the binary it will
+ * spawn, not whatever is on PATH; `fresh` is the person's Refresh; `allowEnv`, the instance's own keys for the bot box. */
resolveModels?(
environment: Record<string, string | undefined>,
config: AcpConfig,
- instanceId: string, fresh?: boolean,
+ instanceId: string, fresh?: boolean, allowEnv?: readonly string[],
): ModelCatalog | Promise<ModelCatalog>;
/** Some managed agents are not probed at app startup; their Refresh is the only lookup. */
resolveModelsOnCreate?: boolean;
@@ -216,7 +216,7 @@ export interface AcpSupport {
isAuthenticated(
env: Record<string, string | undefined>,
config: AcpConfig,
- instanceId: string,
+ instanceId: string, allowEnv?: readonly string[],
): boolean | Promise<boolean>;
/** Refuse a first-party cloud turn before spawning when snapshot auth is
* false. Local injected models deliberately bypass this subscription gate. */
@@ -351,7 +351,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
instanceId,
fixed: support.models,
startFromSaved: Boolean(support.resolveModels) && support.resolveModelsOnCreate === false,
- resolve: support.resolveModels && ((fresh) => support.resolveModels!(childEnv(), config, instanceId, fresh)),
+ resolve: support.resolveModels && ((fresh) => { const env = childEnv(); return support.resolveModels!(env, config, instanceId, fresh, instanceEnvNames(input.environment, env)); }),
});
const refreshModels = (fresh?: boolean) => catalog.refresh(fresh);
let startupModelRefresh: Promise<void> | null = null;
@@ -1040,7 +1040,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
support.requireAuthenticationBeforeSpawn
&& !skipSubscriptionAuthForLocalInject(turn.model)
) {
- const authenticated = await support.isAuthenticated(env, turnConfig, instanceId);
+ const authenticated = await support.isAuthenticated(env, turnConfig, instanceId, instanceEnvNames(input.environment, env));
requireRunning();
if (!authenticated) {
emit({ ...base(threadId, turnId), type: "turn.started" });
@@ -1602,7 +1602,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
});
});
if (!probe.version) return { state: "unavailable", reason: probe.reason, ...(probe.other ? { notEngineCli: true } : {}) };
- return { state: "available", version: probe.version, authenticated: await support.isAuthenticated(env, config, instanceId) };
+ return { state: "available", version: probe.version, authenticated: await support.isAuthenticated(env, config, instanceId, instanceEnvNames(input.environment, env)) };
};
/** Memory upkeep's one-shot: a fresh process and session, no MCP servers, an empty folder, and
@@ -1611,7 +1611,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
if (startupModelRefresh) await startupModelRefresh;
const turnConfig: AcpConfig = { ...config, fullAuto: false };
const env = childEnv(turnConfig);
- if (support.requireAuthenticationBeforeSpawn && !(await support.isAuthenticated(env, turnConfig, instanceId))) {
+ if (support.requireAuthenticationBeforeSpawn && !(await support.isAuthenticated(env, turnConfig, instanceId, instanceEnvNames(input.environment, env)))) {
throw new Error(support.loginNote);
}
const cwd = mkdtempSync(join(await support.oneShotFolder?.() ?? tmpdir(), "omb-acp-memory-"));
@@ -1622,8 +1622,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const spawnEnv = launch.env ?? env;
return await runAcpOneShot({
displayName: support.displayName,
- spawn: spawnCli,
- kill: killCliTree,
+ spawn: spawnCli, kill: killCliTree, box: { allowEnv: instanceEnvNames(input.environment, spawnEnv) },
command: launch.command,
argv: [...(launch.args ?? []), ...support.spawnArgs(turnConfig, turn)],
env: spawnEnv,
diff --git a/server/drivers/acp/deepseek.ts b/server/drivers/acp/deepseek.ts
index 627c071edb..f29985641f 100644
--- a/server/drivers/acp/deepseek.ts
+++ b/server/drivers/acp/deepseek.ts
@@ -23,7 +23,6 @@
// Picker ids are `<provider>/<model>` so bot settings, badges and config.json
// stay readable; resolveTurnModel turns them into dsh's wire pair just before
// the core selects the model.
-import { spawn } from "node:child_process";
import { readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -31,7 +30,7 @@ import { parse as parseYaml } from "yaml";
import type { ModelCatalog } from "../../contracts.ts";
import { harnessHome } from "../../env-path.ts";
-import { resolveCli } from "../../procs.ts";
+import { resolveCli, spawnCli } from "../../procs.ts";
import { createAcpDriver, type AcpSupport } from "./core.ts";
export const DEEPSEEK_MODELS: ModelCatalog = {
@@ -188,12 +187,14 @@ export function fetchDeepSeekCatalog(
cli: string,
env: Record<string, string | undefined>,
cwd: string,
+ allowEnv: readonly string[] = [],
): Promise<ModelCatalog> {
return new Promise((resolve, reject) => {
- let child: ReturnType<typeof spawn>;
+ let child: ReturnType<typeof spawnCli>;
try {
- const resolved = resolveCli(cli, ["--profile", "acp"], env);
- child = spawn(resolved.command, resolved.args, { stdio: ["pipe", "pipe", "ignore"], env: env as NodeJS.ProcessEnv, windowsHide: true });
+ // Security: while the bot box is on, dsh runs in it, as a bot's turn does: it reads ~/.dsh, which a bot can write.
+ const resolved = resolveCli(cli, ["--profile", "acp"], env as NodeJS.ProcessEnv);
+ child = spawnCli(resolved.command, resolved.args, { stdio: ["pipe", "pipe", "ignore"], env: env as NodeJS.ProcessEnv, box: { allowEnv } });
} catch (error) {
return reject(error instanceof Error ? error : new Error(String(error)));
}
@@ -312,7 +313,7 @@ export const deepseekSupport: AcpSupport = {
// ("session is already active"), so a turn with new tools needs a new process.
restartOnMcpChange: true,
// Refresh only: a fresh profile boot can take long, and startup must not wait on it.
- resolveModels: (env, config) => fetchDeepSeekCatalog(config.cli || "dsh", env, tmpdir()),
+ resolveModels: (env, config, _instanceId, _fresh, allowEnv) => fetchDeepSeekCatalog(config.cli || "dsh", env, tmpdir(), allowEnv),
resolveModelsOnCreate: false,
// initialize advertises no auth methods; the key rides in the child env or
diff --git a/server/drivers/acp/hermes.ts b/server/drivers/acp/hermes.ts
index 47ad0484f2..ab3f63804e 100644
--- a/server/drivers/acp/hermes.ts
+++ b/server/drivers/acp/hermes.ts
@@ -1,7 +1,6 @@
// Hermes Agent (Nous Research's `hermes acp`), custom-only. ACP ignores `hermes -m` (cmd_acp does not
// forward it), and OPENAI_API_KEY makes provider:auto resolve to OpenRouter without its key ("HTTP 401:
// Missing Authentication header"), so injects write providers.<host> and set_model `custom:<host>:<model>`.
-import { spawn } from "node:child_process";
import { accessSync, constants, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
@@ -9,7 +8,7 @@ import { parse as parseYaml } from "yaml";
import type { ModelCatalog } from "../../contracts.ts";
import { findCliCandidates, harnessHome, resolveCliSpawn, splitCliString, whichWin } from "../../env-path.ts";
-import { resolveCli } from "../../procs.ts";
+import { resolveCli, spawnCli } from "../../procs.ts";
import { decodeInjectId, hostApiKey, INJECT_SEP, localHost, mergeLocalInject } from "../local-inject.ts";
import { createAcpDriver, type AcpSupport } from "./core.ts";
@@ -270,16 +269,20 @@ function hermesAcpModelsTimeoutMs(env: Record<string, string | undefined>): numb
: HERMES_ACP_MODELS_DEFAULT_TIMEOUT_MS;
}
-/** Hermes advertises its whole catalog on session/new and has no `hermes models` subcommand. */
+/** Hermes advertises its whole catalog on session/new and has no `hermes models` subcommand. Security: while the bot box
+ * is on, it runs in the box, as a bot's turn does, since Hermes reads its settings from a HOME a bot can write.
+ * `allowEnv`: the keys the instance's own settings put in `env`. */
export async function fetchHermesAcpModels(
cli: string,
env: Record<string, string | undefined>,
+ allowEnv: readonly string[] = [],
): Promise<{ id: string; label: string; custom: true }[]> {
return await new Promise((resolve) => {
- let child: ReturnType<typeof spawn>;
+ let child: ReturnType<typeof spawnCli>;
try {
- const resolved = resolveCli(cli, ["acp"], env);
- child = spawn(resolved.command, resolved.args, { stdio: ["pipe", "pipe", "ignore"], env: env as NodeJS.ProcessEnv, windowsHide: true });
+ // Resolved on the supplied PATH (Windows npm shims), then spawned by spawnCli, which resolves on the app's.
+ const resolved = resolveCli(cli, ["acp"], env as NodeJS.ProcessEnv);
+ child = spawnCli(resolved.command, resolved.args, { stdio: ["pipe", "pipe", "ignore"], env: env as NodeJS.ProcessEnv, box: { allowEnv } });
} catch {
return resolve([]);
}
@@ -372,11 +375,12 @@ export async function fetchHermesAcpModels(
export async function resolveHermesModels(
env: Record<string, string | undefined>,
config?: { cli?: string },
+ allowEnv: readonly string[] = [],
): Promise<ModelCatalog> {
const cli = config?.cli || "hermes";
const catalog = await mergeLocalInject(EMPTY, env);
const configured = hermesConfiguredModel(env);
- const remote = configured ? await fetchHermesAcpModels(cli, env) : [];
+ const remote = configured ? await fetchHermesAcpModels(cli, env, allowEnv) : [];
const seen = new Set<string>();
const options = [...(configured ? [configured] : []), ...remote, ...catalog.options].filter((o) => {
if (seen.has(o.id)) return false;
@@ -409,7 +413,7 @@ const support: AcpSupport = {
displayName: "Hermes",
access: "custom",
models: EMPTY,
- resolveModels: (env: Record<string, string | undefined>, config: any) => resolveHermesModels(env, config),
+ resolveModels: (env: Record<string, string | undefined>, config: any, _instanceId: string, _fresh?: boolean, allowEnv?: readonly string[]) => resolveHermesModels(env, config, allowEnv),
resolveTurnModel: (model, env) => {
// Never inherit a broad or stale compatibility grant from the parent; bind one concrete model.
bindHermesScreenshotCompat(env, model);
diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.ts
index 2037463254..f5ab63849d 100644
--- a/server/drivers/acp/opencode-go.ts
+++ b/server/drivers/acp/opencode-go.ts
@@ -25,7 +25,7 @@ import {
import { openCodePromptUnreachedModel } from "./opencode-unreached.ts";
import { parseOpenCodeLogLine } from "./quiet-status.ts";
import type { ModelCatalog, ModelVariantOption, ProviderDriver, ProviderErrorCode } from "../../contracts.ts";
-import { execCli } from "../../procs.ts";
+import { execCliBoxed } from "../../procs.ts";
import {
catalogFromOpenCodeSession,
DISCOVERY_TIMEOUT_MS,
@@ -56,7 +56,8 @@ const discoveryProbeCache = new Map<string, { expiresAt: number; result: Promise
export type OpenCodeCatalogLoader = (
environment: Record<string, string | undefined>,
cli: string,
- options?: { refresh?: boolean; settleMs?: number },
+ /** `allowEnv`: the keys the instance's own settings put in `environment`, which the reads keep in the bot box. */
+ options?: { refresh?: boolean; settleMs?: number; allowEnv?: readonly string[] },
) => Promise<ModelCatalog>;
function localModelRecord(record: Record<string, unknown>): boolean {
@@ -185,12 +186,13 @@ export function parseOpenCodeModelsOutput(stdout: string): ModelCatalog | null {
function runOpenCodeModelsVerbose(
cli: string,
environment: Record<string, string | undefined>,
+ allowEnv: readonly string[],
): Promise<string> {
return new Promise((resolve, reject) => {
- execCli(
+ execCliBoxed(
cli,
["models", "--verbose"],
- { timeout: 20_000, maxBuffer: 8 * 1024 * 1024, env: environment },
+ { timeout: 20_000, maxBuffer: 8 * 1024 * 1024, env: environment, box: { allowEnv } },
(error, stdout, stderr) => {
if (error) {
reject(Object.assign(new Error(stderr?.trim() || error.message, { cause: error }), {
@@ -210,9 +212,9 @@ function runOpenCodeModelsVerbose(
* processes refetches its catalog itself, in the background, at start. */
const MODELS_REFRESH_TIMEOUT_MS = 75_000;
-function refreshOpenCodeModelCache(cli: string, environment: Record<string, string | undefined>): Promise<boolean> {
+function refreshOpenCodeModelCache(cli: string, environment: Record<string, string | undefined>, allowEnv: readonly string[]): Promise<boolean> {
return new Promise((resolve) => {
- execCli(cli, ["models", "--refresh"], { timeout: MODELS_REFRESH_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, env: environment }, (error) => resolve(!error));
+ execCliBoxed(cli, ["models", "--refresh"], { timeout: MODELS_REFRESH_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, env: environment, box: { allowEnv } }, (error) => resolve(!error));
});
}
@@ -236,15 +238,16 @@ function withEfforts(
export async function discoverOpenCodeModels(
environment: Record<string, string | undefined>,
cli = "opencode",
- options: { refresh?: boolean; settleMs?: number } = {},
+ options: { refresh?: boolean; settleMs?: number; allowEnv?: readonly string[] } = {},
): Promise<ModelCatalog> {
- const settleMs = options.refresh && !await refreshOpenCodeModelCache(cli, environment)
+ const allowEnv = options.allowEnv ?? [];
+ const settleMs = options.refresh && !await refreshOpenCodeModelCache(cli, environment, allowEnv)
? options.settleMs ?? SELF_REFRESH_SETTLE_MS
: 0;
// A listing ends long before a catalog refetch would: it reads the cache, unless it waits for OpenCode 2's own refetch.
const listing = settleMs ? environment : { ...environment, OPENCODE_DISABLE_MODELS_FETCH: "1" };
- const probeSession = () => probeOpenCodeSession(cli, listing, DISCOVERY_TIMEOUT_MS, settleMs);
- const readMetadata = () => runOpenCodeModelsVerbose(cli, listing).then(parseOpenCodeModels);
+ const probeSession = () => probeOpenCodeSession(cli, listing, DISCOVERY_TIMEOUT_MS, settleMs, allowEnv);
+ const readMetadata = () => runOpenCodeModelsVerbose(cli, listing, allowEnv).then(parseOpenCodeModels);
let [session, verbose] = await Promise.allSettled([probeSession(), readMetadata()]);
// Two OpenCode processes starting together in a fresh home race to create its database and one fails
// (1 in 8 fresh homes). A timed-out half is not retried.
@@ -285,12 +288,13 @@ export async function canRunOpenCode(
environment: Record<string, string | undefined>,
cli: string,
discover: OpenCodeCatalogLoader = discoverOpenCodeModels,
+ allowEnv: readonly string[] = [],
): Promise<boolean> {
if (lastSuccessfulCatalog.get(cli)?.options.length) return true;
const cached = discoveryProbeCache.get(cli);
if (cached && cached.expiresAt > Date.now()) return cached.result;
const entry = { expiresAt: Number.POSITIVE_INFINITY, result: Promise.resolve(false) };
- entry.result = discover(environment, cli)
+ entry.result = discover(environment, cli, { allowEnv })
.then((catalog) => catalog.options.length > 0, () => false)
.finally(() => {
entry.expiresAt = Date.now() + DISCOVERY_PROBE_TTL_MS;
@@ -710,21 +714,21 @@ const support = (
},
pickAuthMethod: () => null,
authFailure: "continue",
- isAuthenticated: async (env, config, instanceId) => {
+ isAuthenticated: async (env, config, instanceId, allowEnv) => {
ownAccess.set(instanceId, ownOpenCodeAccess(env));
return Boolean(env.OPENCODE_API_KEY)
|| hasStoredOpenCodeAuth(env)
- || await canRunOpenCode(env, config.cli, loadCatalog);
+ || await canRunOpenCode(env, config.cli, loadCatalog, allowEnv);
},
classifyError: classifyOpenCodeError,
promptUnreachedModel: openCodePromptUnreachedModel,
limitFacts: openCodeLimitFacts,
describeAccountError: describeOpenCodeAccountError,
- resolveModels: async (environment, config, instanceId, fresh) => {
+ resolveModels: async (environment, config, instanceId, fresh, allowEnv) => {
if (fresh) markOpenCodeCatalogRefreshed(instanceId, (sources.now ?? Date.now)());
await refreshLiveModelLists(environment, { lists: sources.liveLists, fetch: sources.fetch, now: sources.now });
declareLiveOpenCodeModels(environment, sources.liveLists);
- return mergeLocalInject(await loadCatalog(environment, config.cli, { refresh: fresh === true }), environment);
+ return mergeLocalInject(await loadCatalog(environment, config.cli, { refresh: fresh === true, allowEnv }), environment);
},
buildPromptText: (turn) => turn.system ? `${turn.system}\n\n${turn.text}` : turn.text,
});
diff --git a/server/drivers/acp/opencode-probe.ts b/server/drivers/acp/opencode-probe.ts
index 444264a743..165c21045f 100644
--- a/server/drivers/acp/opencode-probe.ts
+++ b/server/drivers/acp/opencode-probe.ts
@@ -1,6 +1,6 @@
// OpenCode's model discovery probe: an `opencode acp` in its own folder, opened just long enough to list the models.
import { execFile } from "node:child_process";
-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { writeFileAtomic } from "../../atomic.ts";
@@ -59,14 +59,16 @@ export function catalogFromOpenCodeSession(result: unknown): { options: ModelCat
: null;
}
+/** Security: the folder is the boxed probe's to write, and HOME may be a boxed bot's, so git reads no config but the
+ * fresh repository's own, and none that runs a program. */
function runGit(directory: string, args: string[]): Promise<void> {
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")));
return new Promise((resolveRun, rejectRun) => {
execFile("git", [
"-c", "user.name=OpenMaus", "-c", "[email protected]",
- "-c", "commit.gpgsign=false", "-c", `core.hooksPath=${join(directory, ".git", "no-hooks")}`,
+ "-c", "commit.gpgsign=false", "-c", `core.hooksPath=${join(directory, ".git", "no-hooks")}`, "-c", "core.fsmonitor=false",
...args,
- ], { cwd: directory, env: { ...env, GIT_TERMINAL_PROMPT: "0" }, timeout: 10_000, windowsHide: true }, (error) => {
+ ], { cwd: directory, env: { ...env, GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" }, timeout: 10_000, windowsHide: true }, (error) => {
if (error) rejectRun(error);
else resolveRun();
});
@@ -88,6 +90,8 @@ export function discoveryDirectory(): Promise<string> {
const marker = join(directory, ".openmaus-project");
if (!existsSync(marker)) {
try {
+ rmSync(directory, { recursive: true, force: true });
+ mkdirSync(directory, { recursive: true });
await runGit(directory, ["init", "-q"]);
await runGit(directory, ["commit", "-q", "--allow-empty", "--no-verify", "-m", "OpenMaus model discovery"]);
writeFileSync(marker, "OpenCode files this folder's sessions under its own project.\n");
@@ -155,18 +159,21 @@ async function deleteProbeSessions(
/** `settleMs` keeps the process open that long after it starts, then lists again: OpenCode 2's own catalog refresh
* reaches a running process's later sessions only. */
+/** Security: OpenCode starts the plugins and MCP servers its config names (~/.config/opencode), so while the bot box is
+ * on the probe runs in the box, as a bot's turn does. `allowEnv`: the keys the instance's own settings put in `environment`. */
export async function probeOpenCodeSession(
cli: string,
environment: Record<string, string | undefined>,
timeoutMs = DISCOVERY_TIMEOUT_MS,
settleMs = 0,
+ allowEnv: readonly string[] = [],
): Promise<OpenCodeSessionProbe> {
const cwd = await discoveryDirectory();
const deadline = Date.now() + timeoutMs;
return new Promise((resolve, reject) => {
let child: ReturnType<typeof spawnCli>;
try {
- child = spawnCli(cli, ["acp"], { cwd, env: environment, stdio: ["pipe", "pipe", "pipe"] });
+ child = spawnCli(cli, ["acp"], { cwd, env: environment, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv } });
} catch (error) {
reject(error);
return;
diff --git a/server/drivers/muse-code.ts b/server/drivers/muse-code.ts
index f0c1527c1b..ccfd285a6a 100644
--- a/server/drivers/muse-code.ts
+++ b/server/drivers/muse-code.ts
@@ -292,8 +292,8 @@ export const MuseCodeDriver: ProviderDriver<MuseConfig> = {
const startHost = async (args: string[], cwd: string, key: string, requestMcp: boolean, owner: CliOwner): Promise<Host> => {
const { command, args: argv } = launch(args);
const env = childEnv();
- const child = spawnCli(command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"],
- ...(owner === "bot" ? { box: { allowEnv: instanceEnvNames(input.environment, env) } } : {}) }, owner);
+ // Security: the model list runs in the bot box too while it is on: Muse reads its settings from a HOME a bot can write.
+ const child = spawnCli(command, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { allowEnv: instanceEnvNames(input.environment, env) } }, owner);
let spawnError: NodeJS.ErrnoException | undefined;
child.once("error", (error) => { spawnError = error; });
const exited = new Promise<void>((resolve) => child.once("close", () => resolve()));
diff --git a/server/drivers/pi.ts b/server/drivers/pi.ts
index 1bf53d2430..20c3a83609 100644
--- a/server/drivers/pi.ts
+++ b/server/drivers/pi.ts
@@ -10,7 +10,8 @@ import { join } from "node:path";
import { PROVIDER_CREDENTIAL_ENV, stripWorkspaceCredentialEnv } from "../config.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 { describeSpawnFailure, execCliBoxed, killCliTree, spawnCli } from "../procs.ts";
+import { instanceEnvNames } from "../bot-box/env.ts";
import {
deletePromptSplitReceipt,
promptHalves,
@@ -257,11 +258,14 @@ function readPiDefaultModel(env: Record<string, string | undefined>): string {
}
}
+/** Security: Pi loads its extensions from ~/.pi/agent on every start, so while the bot box is on its model list runs in
+ * the box, as a bot's turn does. `allowEnv`: the keys the instance's own settings put in `env`. */
export async function fetchPiModels(
cli: string,
env: Record<string, string | undefined>,
+ allowEnv: readonly string[] = [],
): Promise<ModelCatalog> {
- const child = spawnCli(cli, PI_ARGS, { stdio: ["pipe", "pipe", "pipe"], env });
+ const child = spawnCli(cli, PI_ARGS, { stdio: ["pipe", "pipe", "pipe"], env, box: { allowEnv } });
return new Promise((resolve) => {
let done = false;
const fallbackDefault = readPiDefaultModel(env);
@@ -298,14 +302,10 @@ export async function fetchPiModels(
export async function updatePiModelCatalog(
cli: string,
env: Record<string, string | undefined>,
+ allowEnv: readonly string[] = [],
): Promise<boolean> {
return new Promise((resolve) => {
- execCli(
- cli,
- PI_MODEL_UPDATE_ARGS,
- { env, timeout: 60_000, maxBuffer: 1024 * 1024 },
- (error) => resolve(!error),
- );
+ execCliBoxed(cli, PI_MODEL_UPDATE_ARGS, { env, timeout: 60_000, maxBuffer: 1024 * 1024, box: { allowEnv } }, (error) => resolve(!error));
});
}
@@ -382,7 +382,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
const readModels = async () => {
let base = models, listed = false;
try {
- const resolved = await fetchPiModels(config.cli, catalogEnv);
+ const resolved = await fetchPiModels(config.cli, catalogEnv, instanceEnvNames(input.environment, catalogEnv));
if (resolved.options.length) [base, listed] = [resolved, true];
} catch {}
try {
@@ -394,7 +394,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
try { if (!listed) unconfirmedModelCatalog(models); writeStartupModelCache(instanceId, models); } catch {}
};
const refreshModels = async () => {
- await updatePiModelCatalog(config.cli, catalogEnv);
+ await updatePiModelCatalog(config.cli, catalogEnv, instanceEnvNames(input.environment, catalogEnv));
await readModels();
};
const startupModelRefresh = (await openStartupModelCatalog({
diff --git a/server/procs.ts b/server/procs.ts
index 33eb014f10..bce4993523 100644
--- a/server/procs.ts
+++ b/server/procs.ts
@@ -263,6 +263,44 @@ export function spawnCli(
return child;
}
+/** execCli's answer for a spawn that runs in the bot box where it is on (`box`), as a bot's own would: an engine's
+ * status or catalog read that loads the engine's settings, extensions or MCP servers from a HOME a bot can write. */
+export function execCliBoxed(
+ cli: string,
+ args: string[],
+ opts: { env: NodeJS.ProcessEnv | Record<string, string | undefined>; cwd?: string; timeout: number; maxBuffer?: number; box: NonNullable<BoxSpawnOptions["box"]> },
+ cb: (err: (Error & { code?: number | string | null; killed?: boolean }) | null, stdout: string, stderr: string) => void,
+): void {
+ const limit = opts.maxBuffer ?? 1024 * 1024;
+ let child: ChildProcessByStdio<Writable, Readable, Readable>;
+ try {
+ child = spawnCli(cli, args, { env: opts.env as NodeJS.ProcessEnv, cwd: opts.cwd, stdio: ["pipe", "pipe", "pipe"], box: opts.box });
+ } catch (error) {
+ queueMicrotask(() => cb(error instanceof Error ? error : new Error(String(error)), "", ""));
+ return;
+ }
+ child.stdin.end();
+ let stdout = "", stderr = "", done = false, timedOut = false;
+ const finish = (err: (Error & { code?: number | string | null; killed?: boolean }) | null) => {
+ if (done) return;
+ done = true;
+ clearTimeout(timer);
+ cb(err, stdout, stderr);
+ };
+ child.stdout.on("data", (chunk: Buffer) => { if (stdout.length < limit) stdout += chunk.toString("utf8").slice(0, limit - stdout.length); });
+ child.stderr.on("data", (chunk: Buffer) => { if (stderr.length < limit) stderr += chunk.toString("utf8").slice(0, limit - stderr.length); });
+ const timer = setTimeout(() => {
+ timedOut = true;
+ void killCliTree(child, 0);
+ }, opts.timeout);
+ timer.unref?.();
+ child.once("error", (error) => finish(error));
+ child.once("close", (code) => {
+ if (timedOut) finish(cutOffError(cli, opts.timeout));
+ else finish(code === 0 ? null : Object.assign(new Error(`${cli} exited with code ${code}`), { code }));
+ });
+}
+
const EXEC_KILL_GRACE_MS = 2_000;
export function execCli(