Skip to content

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

Give Pi bot turns their own agent folder, so the person's ~/.pi/agent stays out (#6756)

Milind Soni4aba61196a2c
diff --git a/server/bot-box/plan.test.ts b/server/bot-box/plan.test.ts
index cb2aee7b19..198ccaedeb 100644
--- a/server/bot-box/plan.test.ts
+++ b/server/bot-box/plan.test.ts
@@ -176,6 +176,13 @@ linuxBox("the box plan", () => {
expect(visibleInBox(plan, join(dataDir, "providers", "key"))).toBe("none");
});
+ it("MausBot's own Pi agent folder (PI_CODING_AGENT_DIR) goes back read-write, and no other instance's", () => {
+ const own = join(dataDir, "providers", "pi-own", "a".repeat(64), "agent");
+ const plan = planBox(setup(), { command: "/usr/bin/pi", args: ["--mode", "rpc"], cwd, env: { HOME: home, PI_CODING_AGENT_DIR: own } });
+ expect(visibleInBox(plan, join(own, "models.json"))).toBe("rw");
+ expect(visibleInBox(plan, join(dataDir, "providers", "pi-own", "b".repeat(64), "agent", "models.json"))).toBe("none");
+ });
+
it("a cwd outside the data folder is the turn's folder; a bot named by the caller gets its own folder", () => {
const plan = planBox(setup(), { command: "/usr/bin/codex", args: [], cwd: "/data/projects/site", env: { HOME: home }, botId: "bot-z" });
expect(plan.botId).toBe("bot-z");
diff --git a/server/bot-box/plan.ts b/server/bot-box/plan.ts
index 67b6ee240d..c93c0617d4 100644
--- a/server/bot-box/plan.ts
+++ b/server/bot-box/plan.ts
@@ -165,7 +165,7 @@ export function argvPaths(args: readonly string[]): string[] {
}
/** Environment values that name folders the engine writes: its own config and caches. */
-export const PATH_ENV_NAMES = ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "GROK_HOME", "OPENCODE_HOME", "HERMES_HOME", "GEMINI_HOME", "TMPDIR"] as const;
+export const PATH_ENV_NAMES = ["CLAUDE_CONFIG_DIR", "CODEX_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "GROK_HOME", "OPENCODE_HOME", "HERMES_HOME", "GEMINI_HOME", "PI_CODING_AGENT_DIR", "TMPDIR"] as const;
/** The only part of /sys the box has: how many CPUs the machine has. Programs built with TCMalloc (Google's Antigravity
* runtime) read `possible` at start and stop themselves (SIGABRT, exit 134) when it is missing. */
diff --git a/server/drivers/pi-agent-dir.test.ts b/server/drivers/pi-agent-dir.test.ts
new file mode 100644
index 0000000000..8ec61d2bdc
--- /dev/null
+++ b/server/drivers/pi-agent-dir.test.ts
@@ -0,0 +1,111 @@
+import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { removeTempDir } from "../testing/cleanup.ts";
+import { ensurePiInjectModel } from "./pi.ts";
+import { ownPiAgentDir, piAgentDir, readPiDefaultModel, withOwnPiAgentDir } from "./pi-agent-dir.ts";
+import { encodeInjectId } from "./local-inject.ts";
+
+/** The same file or folder: a link on most systems, a hard link where Windows refuses a file link. */
+const same = (a: string, b: string) => {
+ const [x, y] = [statSync(a, { bigint: true }), statSync(b, { bigint: true })];
+ return x.ino === y.ino && x.dev === y.dev;
+};
+
+describe("MausBot's own Pi agent folder", () => {
+ let root: string, home: string, dataDir: string, person: string;
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "omb-pi-agent-dir-"));
+ home = join(root, "home");
+ dataDir = join(home, ".openmausbot");
+ person = join(home, ".pi", "agent");
+ mkdirSync(join(person, "extensions"), { recursive: true });
+ mkdirSync(join(person, "bin"), { recursive: true });
+ writeFileSync(join(person, "AGENTS.md"), "My own instructions\n");
+ writeFileSync(join(person, "APPEND_SYSTEM.md"), "Always do it my way\n");
+ writeFileSync(join(person, "mcp.json"), '{"mcpServers":{}}');
+ writeFileSync(join(person, "trust.json"), "{}");
+ writeFileSync(join(person, "extensions", "edit.ts"), "export default () => {};\n");
+ writeFileSync(join(person, "bin", "rg"), "");
+ writeFileSync(join(person, "auth.json"), '{"anthropic":{"type":"oauth"}}');
+ writeFileSync(join(person, "models.json"), '{"providers":{"mine":{"models":[]}}}');
+ writeFileSync(join(person, "settings.json"), JSON.stringify({
+ defaultProvider: "anthropic", defaultModel: "claude-x", transport: "sse", packages: ["npm:mine"], extensions: ["x"], skills: ["s"], prompts: ["p"],
+ }));
+ });
+ afterEach(async () => { await removeTempDir(root); });
+
+ const env = () => ({ HOME: home });
+
+ it("carries the login, providers and model settings over, and none of the person's instructions, extensions or MCP servers", () => {
+ const own = ownPiAgentDir(env(), "pi-1", dataDir, false)!;
+ expect(own.startsWith(join(dataDir, "providers", "pi-own"))).toBe(true);
+ expect(readdirSync(own).filter((name) => !name.startsWith(".")).sort()).toEqual(["auth.json", "bin", "models.json", "settings.json"]);
+ expect(same(join(own, "auth.json"), join(person, "auth.json"))).toBe(true);
+ expect(same(join(own, "bin"), join(person, "bin"))).toBe(true);
+ expect(lstatSync(join(own, "models.json")).isSymbolicLink()).toBe(false);
+ expect(JSON.parse(readFileSync(join(own, "settings.json"), "utf8"))).toEqual({ defaultProvider: "anthropic", defaultModel: "claude-x", transport: "sse" });
+ expect(readPiDefaultModel({ ...env(), PI_CODING_AGENT_DIR: own })).toBe("anthropic/claude-x");
+ // Each instance gets its own.
+ expect(ownPiAgentDir(env(), "pi-2", dataDir, false)).not.toBe(own);
+ });
+
+ it("points the environment at it, and leaves it alone on a Team Cloud or when the person's folder is MausBot's already", () => {
+ const pointed = withOwnPiAgentDir(env(), "pi-1", dataDir, false);
+ expect(piAgentDir(pointed)).toBe(pointed.PI_CODING_AGENT_DIR);
+ expect(pointed.PI_CODING_AGENT_DIR!.startsWith(dataDir)).toBe(true);
+ expect(withOwnPiAgentDir(env(), "pi-1", dataDir, true)).toEqual(env());
+ const inData = { ...env(), PI_CODING_AGENT_DIR: join(dataDir, "elsewhere") };
+ expect(withOwnPiAgentDir(inData, "pi-1", dataDir, false)).toEqual(inData);
+ });
+
+ it("copies from a Pi agent folder the person named themselves", () => {
+ const named = join(root, "pi-work");
+ mkdirSync(named, { recursive: true });
+ writeFileSync(join(named, "auth.json"), "{}");
+ writeFileSync(join(named, "AGENTS.md"), "Work instructions\n");
+ const own = ownPiAgentDir({ ...env(), PI_CODING_AGENT_DIR: named }, "pi-1", dataDir, false)!;
+ expect(same(join(own, "auth.json"), join(named, "auth.json"))).toBe(true);
+ expect(existsSync(join(own, "AGENTS.md"))).toBe(false);
+ });
+
+ it("keeps MausBot's local models out of the person's models.json, and picks up the person's later changes", () => {
+ const pointed = withOwnPiAgentDir(env(), "pi-1", dataDir, false);
+ const own = pointed.PI_CODING_AGENT_DIR!;
+ ensurePiInjectModel(encodeInjectId("omlx", "MiniMax-M3-4bit"), pointed);
+ expect(readFileSync(join(person, "models.json"), "utf8")).toBe('{"providers":{"mine":{"models":[]}}}');
+ expect(JSON.parse(readFileSync(join(own, "models.json"), "utf8")).providers.omlx).toBeDefined();
+ // Unchanged on the person's side: the turn's own rows stay.
+ ownPiAgentDir(env(), "pi-1", dataDir, false);
+ expect(JSON.parse(readFileSync(join(own, "models.json"), "utf8")).providers.omlx).toBeDefined();
+ writeFileSync(join(person, "models.json"), '{"providers":{"mine":{"models":[]},"theirs":{"models":[]}}}');
+ ownPiAgentDir(env(), "pi-1", dataDir, false);
+ expect(JSON.parse(readFileSync(join(own, "models.json"), "utf8")).providers.theirs).toBeDefined();
+ });
+
+ it("works with nothing to carry over, and links a login the person makes later", () => {
+ rmSync(join(home, ".pi"), { recursive: true, force: true });
+ const own = ownPiAgentDir(env(), "pi-1", dataDir, false)!;
+ expect(readdirSync(own)).toEqual([]);
+ // What Pi wrote for itself while the person had no login gives way to theirs.
+ writeFileSync(join(own, "auth.json"), "{}");
+ mkdirSync(person, { recursive: true });
+ writeFileSync(join(person, "auth.json"), '{"openai":{"type":"api_key"}}');
+ ownPiAgentDir(env(), "pi-1", dataDir, false);
+ expect(same(join(own, "auth.json"), join(person, "auth.json"))).toBe(true);
+ });
+
+ it.skipIf(process.platform === "win32")("drops a link to a login the person removed, so Pi never writes through it", () => {
+ const own = ownPiAgentDir(env(), "pi-1", dataDir, false)!;
+ rmSync(join(person, "auth.json"));
+ ownPiAgentDir(env(), "pi-1", dataDir, false);
+ expect(() => lstatSync(join(own, "auth.json"))).toThrow();
+ // A link MausBot did not make that points elsewhere is replaced too.
+ writeFileSync(join(person, "auth.json"), "{}");
+ symlinkSync(join(root, "elsewhere.json"), join(own, "auth.json"));
+ ownPiAgentDir(env(), "pi-1", dataDir, false);
+ expect(same(join(own, "auth.json"), join(person, "auth.json"))).toBe(true);
+ });
+});
diff --git a/server/drivers/pi-agent-dir.ts b/server/drivers/pi-agent-dir.ts
new file mode 100644
index 0000000000..178943d086
--- /dev/null
+++ b/server/drivers/pi-agent-dir.ts
@@ -0,0 +1,144 @@
+// MausBot's Pi turns run in a Pi agent folder of its own (PI_CODING_AGENT_DIR, pi-coding-agent 1.6.0), so a bot's turn
+// never loads what the person set up for their own Pi in ~/.pi/agent: their AGENTS.md or CLAUDE.md, SYSTEM.md and
+// APPEND_SYSTEM.md, skills, prompts, themes, extensions and packages, MCP servers (mcp.json) and project trust. Only what
+// Pi needs to reach the person's providers comes along: their sign-ins and keys (auth.json, linked, so a refreshed login
+// stays theirs), their own providers (models.json) and the model and connection parts of settings.json (both copied, so
+// MausBot's local models never land in their files), and the search tools Pi downloaded (bin, linked).
+import { createHash } from "node:crypto";
+import { linkSync, lstatSync, mkdirSync, readFileSync, rmSync, statSync, symlinkSync } from "node:fs";
+import { homedir } from "node:os";
+import { isAbsolute, join, relative, resolve } from "node:path";
+
+import { writeFileAtomic } from "../atomic.ts";
+import { DATA_DIR } from "../config.ts";
+import { engineHomes } from "../engine-homes/engine-homes.ts";
+
+/** settings.json entries that choose a model and how Pi reaches it (pi-coding-agent 1.6.0 SettingsManager). Never its
+ * packages, extensions, skills or prompts. */
+const SETTINGS_KEPT = ["defaultProvider", "defaultModel", "defaultThinkingLevel", "transport", "retry", "httpProxy",
+ "httpIdleTimeoutMs", "websocketConnectTimeoutMs", "shellPath"] as const;
+
+const noted = new Set<string>();
+function note(path: string, message: string): void {
+ if (noted.has(path)) return;
+ noted.add(path);
+ console.error(`pi: ${message}`);
+}
+
+const inside = (parent: string, child: string) => {
+ const path = relative(parent, child);
+ return path === "" || (!path.startsWith("..") && !isAbsolute(path));
+};
+
+/** The Pi agent folder `env` points Pi at: PI_CODING_AGENT_DIR when set, else ~/.pi/agent. */
+export function piAgentDir(env: Record<string, string | undefined>): string {
+ const home = env.HOME || env.USERPROFILE || homedir();
+ const named = env.PI_CODING_AGENT_DIR;
+ if (!named) return join(home, ".pi", "agent");
+ return named === "~" ? home : named.startsWith("~/") ? join(home, named.slice(2)) : resolve(named);
+}
+
+/** `provider/model` from the agent folder's settings.json; "" when unset or unreadable. */
+export function readPiDefaultModel(env: Record<string, string | undefined>): string {
+ try {
+ const s = JSON.parse(readFileSync(join(piAgentDir(env), "settings.json"), "utf8")) as { defaultProvider?: string; defaultModel?: string };
+ return s.defaultProvider && s.defaultModel ? `${s.defaultProvider}/${s.defaultModel}` : "";
+ } catch {
+ return "";
+ }
+}
+
+/** Links the person's entry into MausBot's folder; true when it is there (or the person has none). */
+function linked(target: string, link: string): boolean {
+ let want;
+ try {
+ want = statSync(target, { bigint: true });
+ } catch {
+ // A link left from when the person had one would send Pi's writes to a file that is gone.
+ try { statSync(link); } catch { rmSync(link, { force: true }); }
+ return true;
+ }
+ try {
+ const have = statSync(link, { bigint: true });
+ if (have.ino === want.ino && have.dev === want.dev) return true;
+ } catch {}
+ // A link that points elsewhere (removed as a link, never followed), or what Pi made here while the person had none.
+ let stale;
+ try { stale = lstatSync(link); } catch {}
+ if (stale) rmSync(link, { recursive: stale.isDirectory() && !stale.isSymbolicLink(), force: true });
+ const folder = want.isDirectory();
+ try {
+ symlinkSync(target, link, folder ? "junction" : "file");
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return true;
+ }
+ if (folder) return false;
+ // Windows refuses a file link without Developer Mode; Pi writes auth.json in place, so a hard link stays shared.
+ try {
+ linkSync(target, link);
+ return true;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "EEXIST";
+ }
+}
+
+/** Copies `text` (the person's version, or null when they have none) into MausBot's folder when it changed since the
+ * last copy. When the person never had one, MausBot's own stays (the local models a turn adds to models.json). */
+function seeded(own: string, name: string, text: string | null): void {
+ const path = join(own, name), mark = join(own, `.${name}.from`);
+ const hash = text === null ? null : createHash("sha256").update(text).digest("hex");
+ let last: string | null = null;
+ try { last = readFileSync(mark, "utf8"); } catch {}
+ if (hash === last) return;
+ if (text === null || hash === null) {
+ rmSync(path, { force: true });
+ rmSync(mark, { force: true });
+ return;
+ }
+ writeFileAtomic(path, text, { mode: 0o600 });
+ writeFileAtomic(mark, hash, { mode: 0o600 });
+}
+
+function settingsText(path: string): string | null {
+ let parsed: unknown;
+ try { parsed = JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
+ const kept: Record<string, unknown> = {};
+ for (const key of SETTINGS_KEPT) if ((parsed as Record<string, unknown>)[key] !== undefined) kept[key] = (parsed as Record<string, unknown>)[key];
+ return `${JSON.stringify(kept, null, 2)}\n`;
+}
+
+/** MausBot's Pi agent folder for this instance, made and brought up to date with the person's. Null when the person's
+ * folder stays in use: on a Team Cloud (each audience's engine home already has its own, with only auth.json shared),
+ * when theirs is MausBot's already (in the data folder), or when their login cannot be linked in. */
+export function ownPiAgentDir(env: Record<string, string | undefined>, instanceId: string, dataDir = DATA_DIR,
+ teamCloud = engineHomes.active()): string | null {
+ const person = piAgentDir(env);
+ const own = join(resolve(dataDir), "providers", "pi-own", createHash("sha256").update(instanceId).digest("hex"), "agent");
+ if (teamCloud || inside(resolve(dataDir), person) || inside(person, own)) return null;
+ try {
+ mkdirSync(own, { recursive: true, mode: 0o700 });
+ if (!linked(join(person, "auth.json"), join(own, "auth.json"))) {
+ note(own, "could not link your Pi login into MausBot's Pi folder, so turns use your own ~/.pi/agent");
+ return null;
+ }
+ // A download cache only: Pi fetches fd and rg again when it cannot be linked.
+ linked(join(person, "bin"), join(own, "bin"));
+ let models: string | null = null;
+ try { models = readFileSync(join(person, "models.json"), "utf8"); } catch {}
+ seeded(own, "models.json", models);
+ seeded(own, "settings.json", settingsText(join(person, "settings.json")));
+ } catch (error) {
+ note(own, `could not make MausBot's Pi folder, so turns use your own ~/.pi/agent: ${(error as Error).message}`);
+ return null;
+ }
+ return own;
+}
+
+/** `env` with Pi pointed at MausBot's own agent folder for this instance; `env` itself where the person's stays in use. */
+export function withOwnPiAgentDir(env: Record<string, string | undefined>, instanceId: string, dataDir = DATA_DIR,
+ teamCloud = engineHomes.active()): Record<string, string | undefined> {
+ const own = ownPiAgentDir(env, instanceId, dataDir, teamCloud);
+ return own ? { ...env, PI_CODING_AGENT_DIR: own } : env;
+}
diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.ts
index 98525e7d2a..f396a74370 100644
--- a/server/drivers/pi.test.ts
+++ b/server/drivers/pi.test.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -330,6 +330,30 @@ describe("PiDriver catalog (fake CLI)", () => {
}
});
+ it("probes the model list with a Pi login the person makes after the instance started", async () => {
+ const home = mkdtempSync(join(tmpdir(), "omb-pi-later-login-"));
+ const dump = join(home, "launches.jsonl");
+ const instance = await PiDriver.create({
+ instanceId: "pi-later-login",
+ displayName: undefined,
+ environment: { HOME: home, FAKE_PI_DUMP: dump },
+ enabled: true,
+ config: { cli: FAKE_CLI, fullAuto: false },
+ });
+ try {
+ mkdirSync(join(home, ".pi", "agent"), { recursive: true });
+ writeFileSync(join(home, ".pi", "agent", "auth.json"), '{"openai":{"type":"api_key","key":"sk-later"}}');
+ writeFileSync(dump, "");
+ await instance.refreshModels?.();
+ const rows = readFileSync(dump, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { agentDir?: string | null });
+ const own = rows.at(-1)!.agentDir!;
+ expect(own.startsWith(join(DATA_DIR, "providers", "pi-own"))).toBe(true);
+ expect(statSync(join(own, "auth.json"), { bigint: true }).ino).toBe(statSync(join(home, ".pi", "agent", "auth.json"), { bigint: true }).ino);
+ } finally {
+ await instance.dispose();
+ }
+ });
+
it("reports update failure without preventing a cached catalog probe", async () => {
expect(await updatePiModelCatalog(FAKE_CLI, {
PATH: process.env.PATH ?? "",
@@ -1206,9 +1230,22 @@ describe("PiDriver turns (fake CLI)", () => {
expect(done).toMatchObject({ ok: true, stopReason: "cancelled" });
});
- it("writes models.json and set_model for a host::model inject pick", async () => {
+ it("writes models.json and set_model for a host::model inject pick, in MausBot's own Pi folder", async () => {
const home = mkdtempSync(join(tmpdir(), "omb-pi-turn-inject-"));
const dump = join(home, "dump.jsonl");
+ // The person's own Pi setup: what a bot's turn must not load, and the login and providers it needs.
+ const person = join(home, ".pi", "agent");
+ mkdirSync(join(person, "extensions"), { recursive: true });
+ mkdirSync(join(person, "skills", "mine"), { recursive: true });
+ writeFileSync(join(person, "AGENTS.md"), "My own instructions\n");
+ writeFileSync(join(person, "SYSTEM.md"), "My own system prompt\n");
+ writeFileSync(join(person, "mcp.json"), '{"mcpServers":{"mine":{"command":"mine"}}}');
+ writeFileSync(join(person, "extensions", "edit.ts"), "export default () => {};\n");
+ writeFileSync(join(person, "skills", "mine", "SKILL.md"), "---\nname: mine\n---\n");
+ writeFileSync(join(person, "settings.json"), JSON.stringify({ defaultProvider: "openai", defaultModel: "gpt-4o", packages: ["npm:mine"], extensions: ["./x.ts"], skills: ["./s"] }));
+ writeFileSync(join(person, "auth.json"), '{"openai":{"type":"api_key","key":"sk-person"}}');
+ const personModels = '{"providers":{"mine":{"baseUrl":"http://127.0.0.1:9/v1","models":[{"id":"m"}]}}}';
+ writeFileSync(join(person, "models.json"), personModels);
await create(undefined, { HOME: home, FAKE_PI_DUMP: dump });
const { turnId } = await instance.adapter.sendTurn({
threadId: "t-inject",
@@ -1224,11 +1261,21 @@ describe("PiDriver turns (fake CLI)", () => {
expect(dumps.some((row) => row.setModel?.provider === "omlx" && row.setModel?.modelId === "MiniMax-M3-4bit")).toBe(
true,
);
- const written = JSON.parse(readFileSync(join(home, ".pi", "agent", "models.json"), "utf8")) as {
- providers: { omlx: { baseUrl: string; models: Array<{ id: string }> } };
+ const agentDirs = new Set(dumps.map((row) => (row as { agentDir?: string | null }).agentDir).filter((dir) => dir !== undefined));
+ expect(agentDirs.size).toBe(1);
+ const own = [...agentDirs][0]!;
+ expect(own.startsWith(join(DATA_DIR, "providers", "pi-own"))).toBe(true);
+ expect(readdirSync(own).filter((name) => !name.startsWith(".")).sort()).toEqual(["auth.json", "models.json", "settings.json"]);
+ expect(statSync(join(own, "auth.json"), { bigint: true }).ino).toBe(statSync(join(person, "auth.json"), { bigint: true }).ino);
+ expect(JSON.parse(readFileSync(join(own, "settings.json"), "utf8"))).toEqual({ defaultProvider: "openai", defaultModel: "gpt-4o" });
+ const written = JSON.parse(readFileSync(join(own, "models.json"), "utf8")) as {
+ providers: { mine: unknown; omlx: { baseUrl: string; models: Array<{ id: string }> } };
};
+ expect(written.providers.mine).toBeDefined();
expect(written.providers.omlx.baseUrl).toBe("http://127.0.0.1:8080/v1");
expect(written.providers.omlx.models.some((m) => m.id === "MiniMax-M3-4bit")).toBe(true);
+ // MausBot's local model stays out of the person's own file.
+ expect(readFileSync(join(person, "models.json"), "utf8")).toBe(personModels);
});
});
diff --git a/server/drivers/pi.ts b/server/drivers/pi.ts
index 6a4a509c0c..6cef845b36 100644
--- a/server/drivers/pi.ts
+++ b/server/drivers/pi.ts
@@ -1,10 +1,10 @@
import { piModelId } from "./pi-model-id.ts";
import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts";
// The pi coding agent (@earendil-works/pi-coding-agent) over its own stdio JSON-RPC mode
-// (`pi --mode rpc`), not ACP. pi is BYOK and reads ~/.pi/agent/auth.json itself, so this driver
+// (`pi --mode rpc`), not ACP. pi is BYOK and reads auth.json from its agent folder itself, so this driver
// holds no key; resumeCursor is pi's `sessionFile` (switch_session).
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
-import { homedir, tmpdir } from "node:os";
+import { tmpdir } from "node:os";
import { join } from "node:path";
import { PROVIDER_CREDENTIAL_ENV, stripWorkspaceCredentialEnv } from "../config.ts";
@@ -49,6 +49,7 @@ import { appendNative } from "./native.ts";
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { buildMcpServers } from "./pi-mcp-servers.ts";
import { piSessionDir, piSessionPath, piTurnArgs } from "./pi-session.ts";
+import { piAgentDir, readPiDefaultModel, withOwnPiAgentDir } from "./pi-agent-dir.ts";
import { noticeFailure } from "../chat-notices.ts";
import { decodePiFrame, PiRpcChunks, piLineReader, piNativeLogMessage, readPiPromptImages } from "./pi-rpc.ts";
@@ -152,11 +153,7 @@ export async function applyPiLocalCatalog(
return preferPiInjectRows(await mergeLocalInject(catalog, env, fetchImpl));
}
-function piAgentDir(env: Record<string, string | undefined>): string {
- return join(env.HOME || env.USERPROFILE || homedir(), ".pi", "agent");
-}
-
-/** Upsert a live local host into ~/.pi/agent/models.json so `set_model` can reach it. */
+/** Upsert a live local host into the Pi agent folder's models.json so `set_model` can reach it. */
export function ensurePiInjectModel(
modelId: string,
env: Record<string, string | undefined> = process.env,
@@ -231,20 +228,7 @@ export function ensurePiInjectModel(
return split;
}
-function readPiDefaultModel(env: Record<string, string | undefined>): string {
- const home = env.HOME || env.USERPROFILE || homedir();
- try {
- const s = JSON.parse(readFileSync(`${home}/.pi/agent/settings.json`, "utf8")) as {
- defaultProvider?: string;
- defaultModel?: string;
- };
- return s.defaultProvider && s.defaultModel ? `${s.defaultProvider}/${s.defaultModel}` : "";
- } catch {
- return "";
- }
-}
-
-/** Security: Pi loads its extensions from ~/.pi/agent on every start, so while the bot box is on its model list runs in
+/** Security: Pi loads its extensions from its agent folder 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,
@@ -363,10 +347,12 @@ export const PiDriver: ProviderDriver<PiConfig> = {
async create(input: DriverCreateInput<PiConfig>): Promise<ProviderInstance> {
const { instanceId, config } = input;
- const catalogEnv = piEnvironment({ ...process.env, ...input.environment });
+ // Made again on every read, so a login or provider the person adds later reaches the model list.
+ const catalogEnvironment = () => piEnvironment(withOwnPiAgentDir({ ...process.env, ...input.environment }, instanceId));
let models = EMPTY;
const readModels = async () => {
let base = models, listed = false;
+ const catalogEnv = catalogEnvironment();
try {
const resolved = await fetchPiModels(config.cli, catalogEnv, instanceEnvNames(input.environment, catalogEnv));
if (resolved.options.length) [base, listed] = [resolved, true];
@@ -380,6 +366,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
try { if (!listed) unconfirmedModelCatalog(models); writeStartupModelCache(instanceId, models); } catch {}
};
const refreshModels = async () => {
+ const catalogEnv = catalogEnvironment();
await updatePiModelCatalog(config.cli, catalogEnv, instanceEnvNames(input.environment, catalogEnv));
await readModels();
};
@@ -443,9 +430,8 @@ export const PiDriver: ProviderDriver<PiConfig> = {
const images = readPiPromptImages(turn);
// Before any credential-bearing temp file, so a model setup failure leaves nothing to clean up.
- if (typeof turn.model === "string" && turn.model) {
- ensurePiInjectModel(turn.model, { ...process.env, ...input.environment });
- }
+ const turnEnv = withOwnPiAgentDir({ ...process.env, ...input.environment }, instanceId);
+ if (typeof turn.model === "string" && turn.model) ensurePiInjectModel(turn.model, turnEnv);
// The MCP config carries credentials: a 0600 temp file removed at settle, never argv.
// Written on every turn: the extension also carries ask_user.
@@ -475,11 +461,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
stdio: ["pipe", "pipe", "pipe"],
cwd: turn.cwd,
box: { rw: [sessionDir, mcpTempDir] },
- env: piEnvironment({
- ...process.env,
- ...input.environment,
- OMB_MCP_CONFIG: join(mcpTempDir, "mcp.json"),
- }),
+ env: piEnvironment({ ...turnEnv, OMB_MCP_CONFIG: join(mcpTempDir, "mcp.json") }),
}, "bot");
} catch (err) {
try {
diff --git a/server/engine-homes/layout.test.ts b/server/engine-homes/layout.test.ts
index f96647f7b8..f8e8bcdb2a 100644
--- a/server/engine-homes/layout.test.ts
+++ b/server/engine-homes/layout.test.ts
@@ -53,6 +53,17 @@ linux("an audience's engine home", () => {
expect(other.env.CODEX_HOME!.slice(owner.length)).toBe(homed.env.CODEX_HOME!.slice(bob.length));
});
+ it("follows a Pi agent folder the environment names, with its login, and keeps ~/.pi/agent's otherwise", () => {
+ expect(homedSpawn({ HOME: serverHome }, { dataDir, serverHome, home: bob }).shared)
+ .toContainEqual({ source: "/data/.pi/agent/auth.json", target: `${bob}/.pi/agent/auth.json` });
+ const own = join(dataDir, "providers", "pi-own", "abc", "agent");
+ const homed = homedSpawn({ HOME: serverHome, PI_CODING_AGENT_DIR: own }, { dataDir, serverHome, home: bob });
+ expect(homed.env.PI_CODING_AGENT_DIR).toMatch(new RegExp(`^${bob}/\\.omb-folders/PI_CODING_AGENT_DIR-[0-9a-f]{12}$`));
+ expect(homed.folders).toContain(homed.env.PI_CODING_AGENT_DIR);
+ expect(homed.shared).toContainEqual({ source: `${own}/auth.json`, target: `${homed.env.PI_CODING_AGENT_DIR}/auth.json` });
+ expect(homedSpawn({ HOME: serverHome, PI_CODING_AGENT_DIR: "/data/.pi-work" }, { dataDir, serverHome, home: bob }).env.PI_CODING_AGENT_DIR).toBe(`${bob}/.pi-work`);
+ });
+
it("an environment already in an engine home is the server's again, so nothing is moved twice", () => {
const once = homedSpawn({ HOME: serverHome, CLAUDE_CONFIG_DIR: "/data/.claude-work" }, { dataDir, serverHome, home: bob });
const twice = homedSpawn(once.env, { dataDir, serverHome, home: bob });
diff --git a/server/engine-homes/layout.ts b/server/engine-homes/layout.ts
index e49133bd0b..13ade75133 100644
--- a/server/engine-homes/layout.ts
+++ b/server/engine-homes/layout.ts
@@ -62,7 +62,7 @@ export const ENGINE_FOLDERS: readonly EngineFolder[] = [
{ env: "XDG_CONFIG_HOME", home: ".config", shared: ["muse/auth.json"] },
{ env: "XDG_DATA_HOME", home: ".local/share", shared: ["opencode/auth.json"] },
{ home: ".gemini", shared: ["oauth_creds.json", "google_accounts.json", "settings.json"] },
- { home: ".pi/agent", shared: ["auth.json"] },
+ { env: "PI_CODING_AGENT_DIR", home: ".pi/agent", shared: ["auth.json"] },
];
/** Folder variables that move with HOME besides those above. */
diff --git a/server/testing/fake-pi-cli.ts b/server/testing/fake-pi-cli.ts
index 33d6043c79..95807db534 100755
--- a/server/testing/fake-pi-cli.ts
+++ b/server/testing/fake-pi-cli.ts
@@ -50,6 +50,7 @@ if (process.env.FAKE_PI_DUMP) {
(k) => process.env[k] !== undefined,
),
mcpConfig,
+ agentDir: process.env.PI_CODING_AGENT_DIR ?? null,
}) + "\n",
);
} catch {}
diff --git a/server/testing/setup.ts b/server/testing/setup.ts
index bae32da789..7c25eb6cf4 100644
--- a/server/testing/setup.ts
+++ b/server/testing/setup.ts
@@ -20,6 +20,8 @@ process.env.OMB_DISABLE_MODEL_MANIFEST_FETCH = "1";
delete process.env.HERMES_HOME;
// A ChatGPT-plan turn links the person's Codex home ($CODEX_HOME or ~/.codex) into its own: keep it in the throwaway home.
delete process.env.CODEX_HOME;
+// Pi turns copy from the person's Pi agent folder ($PI_CODING_AGENT_DIR or ~/.pi/agent): keep it in the throwaway home.
+delete process.env.PI_CODING_AGENT_DIR;
// No server in a test downloads the project's announcement cards; its tests hand the store a fake fetch.
process.env.OMB_DISABLE_ANNOUNCEMENTS = "1";
// Named explicitly although homedir() already covers it: the device tests delete this directory wholesale.