Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Isolate persisted Pi sessions by audience and conversation
koeria26edd8dc124b
diff --git a/server/drivers/pi-session-spawn.test.ts b/server/drivers/pi-session-spawn.test.tsindex 6c2a2ef789..a05c588a01 100644--- a/server/drivers/pi-session-spawn.test.ts+++ b/server/drivers/pi-session-spawn.test.ts@@ -1,5 +1,5 @@-import { chmodSync, mkdirSync, mkdtempSync } from "node:fs";-import { homedir } from "node:os";+import { chmodSync, mkdirSync, mkdtempSync, readFileSync } from "node:fs";+import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";import { afterEach, describe, expect, it, vi } from "vitest";@@ -8,6 +8,7 @@ import { DATA_DIR, ensureDirs } from "../config.ts";import { planBox, visibleInBox } from "../bot-box/plan.ts";import * as procs from "../procs.ts";import { recordEvents } from "../testing/events.ts";+import { engineHomes } from "../engine-homes/engine-homes.ts";import { piSessionDir } from "./pi-session.ts";import { PiDriver } from "./pi.ts";@@ -18,41 +19,92 @@ vi.mock("node:fs", async (original) => {const cli = fileURLToPath(new URL("../testing/fake-pi-cli.ts", import.meta.url));const create = () => PiDriver.create({ instanceId: "pi-session-spawn", displayName: undefined, enabled: true, environment: {}, config: { cli, fullAuto: false } });-afterEach(() => { vi.restoreAllMocks(); vi.mocked(mkdirSync).mockRestore(); vi.mocked(mkdtempSync).mockClear(); });+afterEach(() => { engineHomes.stop(); vi.restoreAllMocks(); vi.mocked(mkdirSync).mockRestore(); vi.mocked(mkdtempSync).mockClear(); });describe("Pi session spawn setup", () => {- it.skipIf(process.platform === "win32")("binds persisted sessions through the data tmpfs without exposing sibling data", async () => {+ it.skipIf(process.platform === "win32")("isolates audience/conversation sandbox plans while resuming persisted turns", async () => {ensureDirs();chmodSync(cli, 0o755);- const instance = await create();+ const dump = join(mkdtempSync(join(tmpdir(), "omb-pi-audience-")), "rpc.jsonl");+ const instance = await PiDriver.create({ instanceId: "pi-session-spawn", displayName: undefined, enabled: true,+ environment: { FAKE_PI_DUMP: dump, FAKE_PI_PERSIST_SESSION: "1", FAKE_PI_SESSION_FILE_IN_STATE_ONLY: "1" }, config: { cli, fullAuto: false } });const recorder = recordEvents(instance.adapter);const spawned = vi.spyOn(procs, "spawnCli");- try {- const { turnId } = await instance.adapter.sendTurn({ threadId: "pi-box-session", text: "hi" });+ let audience: "member:alice" | "member:bob" | "team" = "member:alice";+ engineHomes.start({ dataDir: DATA_DIR, audienceOf: () => audience, threads: () => [] });+ // Keep the fake process environment unchanged; audience identity still comes from the real async context.+ vi.spyOn(engineHomes, "forSpawn").mockReturnValue(null);+ const turns: Array<{ dir: string; path: string; plan: ReturnType<typeof planBox> }> = [];+ const send = async (threadId: string, text: string, resumeCursor?: string) => engineHomes.within(threadId, async () => {+ const turn = { threadId, botId: "bot-a", text, resumeCursor };+ const dir = piSessionDir(turn, "pi-session-spawn");+ const before = spawned.mock.calls.length;+ const { turnId } = await instance.adapter.sendTurn(turn);await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);- const call = spawned.mock.calls.find(([, args]) => args.includes("--session-dir"));- expect(call).toBeDefined();- const options = call![2]!;- expect(options.box).toEqual({ rw: [piSessionDir()] });- // Put DATA_DIR under a home in the plan, reproducing the default hidden-data layout- // even when the test runner's OMB_DATA_DIR is outside the real home.- const home = join(DATA_DIR, "..");- const request = { command: cli, args: call![1], cwd: homedir(), env: { HOME: home } };- const setup = { dataDir: DATA_DIR, home, codeRoots: [], engineRoots: [], bridges: [] };- const hidden = planBox(setup, request);- expect(visibleInBox(hidden, piSessionDir())).toBe("none");- for (let turn = 0; turn < 2; turn++) {- const plan = planBox(setup, { ...request, ...(options.box as { rw: string[] }) });- expect(visibleInBox(plan, join(piSessionDir(), "saved.jsonl"))).toBe("rw");- expect(visibleInBox(plan, join(DATA_DIR, "config.json"))).toBe("none");- expect(visibleInBox(plan, join(DATA_DIR, "pi-sessions-other", "secret"))).toBe("none");+ const started = recorder.events.find((event) => event.type === "session.started" && event.turnId === turnId);+ if (started?.type !== "session.started" || !started.sessionId) throw new Error("missing session file");+ const call = spawned.mock.calls.slice(before).find(([, args]) => args.includes("--session-dir"))!;+ expect(call[2]!.box).toEqual({ rw: [dir] });+ const setup = { dataDir: DATA_DIR, home: join(DATA_DIR, ".."), codeRoots: [], engineRoots: [], bridges: [] };+ const request = { command: cli, args: call[1], env: {}, audience: { teamReadOnly: audience !== "team" } };+ expect(visibleInBox(planBox(setup, request), dir)).toBe("none");+ const plan = planBox(setup, { ...request, ...(call[2]!.box as { rw: string[] }) });+ turns.push({ dir, path: started.sessionId, plan });+ return started.sessionId;+ }, "bot-a");+ try {+ const first = await send("thread-a", "first");+ expect(await send("thread-a", "second", first)).toBe(first);+ expect(JSON.parse(readFileSync(first, "utf8"))).toEqual(["first", "second"]);+ const rows = readFileSync(dump, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line));+ expect(rows.find((row) => row.loadedHistory)?.loadedHistory).toEqual(["first"]);+ expect(rows.filter((row) => row.rpc).map((row) => row.rpc)).toEqual(["new_session", "switch_session"]);+ await engineHomes.within("thread-b", async () => {+ await expect(instance.adapter.sendTurn({ threadId: "thread-b", botId: "bot-a", text: "steal", resumeCursor: first }))+ .rejects.toThrow("another audience or conversation");+ });+ await send("thread-b", "another conversation");+ audience = "member:bob";+ await engineHomes.within("thread-a", async () => {+ const before = spawned.mock.calls.length;+ await expect(instance.adapter.sendTurn({ threadId: "thread-a", botId: "bot-a", text: "steal", resumeCursor: first }))+ .rejects.toThrow("another audience or conversation");+ expect(spawned.mock.calls.length).toBe(before);+ });+ await send("thread-a", "another audience");+ audience = "team";+ await send("thread-a", "team conversation");+ for (const own of turns) {+ expect(visibleInBox(own.plan, own.path)).toBe("rw");+ for (const other of turns.filter((entry) => entry.dir !== own.dir)) expect(visibleInBox(own.plan, other.path)).toBe("none");+ expect(visibleInBox(own.plan, join(DATA_DIR, "config.json"))).toBe("none");+ expect(visibleInBox(own.plan, join(DATA_DIR, "pi-sessions", "legacy.jsonl"))).toBe("none");}+ expect(new Set(turns.map((turn) => turn.dir)).size).toBe(4);+ engineHomes.stop();+ await expect(instance.adapter.sendTurn({ threadId: "different-thread", botId: "bot-a", text: "steal", resumeCursor: first }))+ .rejects.toThrow("another audience or conversation");} finally {recorder.stop();await instance.dispose();}});+ it("refuses a Team Cloud turn without audience context before creating credentials", async () => {+ ensureDirs();+ chmodSync(cli, 0o755);+ const instance = await create();+ engineHomes.start({ dataDir: DATA_DIR, audienceOf: () => "team", threads: () => [] });+ vi.mocked(mkdtempSync).mockClear();+ try {+ await expect(instance.adapter.sendTurn({ threadId: "missing-audience", text: "hi" }))+ .rejects.toThrow("requires an audience context");+ expect(mkdtempSync).not.toHaveBeenCalled();+ } finally {+ await instance.dispose();+ }+ });+it("creates no credential temp directory when the session directory cannot be prepared", async () => {ensureDirs();chmodSync(cli, 0o755);@@ -60,7 +112,7 @@ describe("Pi session spawn setup", () => {const originalMkdir = await vi.importActual<typeof import("node:fs")>("node:fs");vi.mocked(mkdtempSync).mockClear();vi.mocked(mkdirSync).mockImplementation((path, options) => {- if (path === piSessionDir()) throw new Error("session directory is not writable");+ if (String(path).startsWith(join(DATA_DIR, "pi-sessions"))) throw new Error("session directory is not writable");return originalMkdir.mkdirSync(path, options as { recursive: true });});const spawned = vi.spyOn(procs, "spawnCli");diff --git a/server/drivers/pi-session.ts b/server/drivers/pi-session.tsindex c123b9f4e0..136486079c 100644--- a/server/drivers/pi-session.ts+++ b/server/drivers/pi-session.ts@@ -1,15 +1,27 @@+import { createHash } from "node:crypto";import { mkdirSync } from "node:fs";-import { join } from "node:path";+import { dirname, join, resolve } from "node:path";import { DATA_DIR } from "../config.ts";+import type { SendTurnInput } from "../contracts.ts";+import { engineHomes } from "../engine-homes/engine-homes.ts";-/** Persist turn sessions under the OpenMausBot data dir, not the operator's ~/.pi/agent/sessions. */-export function piSessionDir(): string {- return join(DATA_DIR, "pi-sessions");+/** Explicit box grants bypass audience filtering: never grant the shared sessions root. */+export function piSessionDir(turn: Pick<SendTurnInput, "threadId" | "botId">, instanceId: string): string {+ const audience = engineHomes.scope();+ if (engineHomes.active() && audience === null) throw new Error("Pi session requires an audience context");+ const key = createHash("sha256").update(JSON.stringify([instanceId, turn.botId ?? null, turn.threadId])).digest("hex");+ return join(DATA_DIR, "pi-sessions", audience ?? "local", key);}-export function piTurnArgs(): string[] {- const dir = piSessionDir();- mkdirSync(dir, { recursive: true });+export function piTurnArgs(dir: string): string[] {+ mkdirSync(dir, { recursive: true, mode: 0o700 });return ["--mode", "rpc", "--session-dir", dir];}++/** Never resume another audience's or conversation's session, even with a stale cursor. */+export function piSessionPath(turn: Pick<SendTurnInput, "resumeCursor" | "sessionReset">, dir: string): string | null {+ if (turn.sessionReset || typeof turn.resumeCursor !== "string") return null;+ if (dirname(resolve(turn.resumeCursor)) !== resolve(dir)) throw new Error("Pi session belongs to another audience or conversation; reset this session before retrying");+ return turn.resumeCursor;+}diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.tsindex 6c5d7f9333..09c6675c03 100644--- a/server/drivers/pi.test.ts+++ b/server/drivers/pi.test.ts@@ -405,7 +405,7 @@ describe("PiDriver turns (fake CLI)", () => {expect(recorder.events.every((e) => e.turnId === turnId && e.provider === "piAgent")).toBe(true);const session = recorder.events.find((e) => e.type === "session.started")!;- expect((session as { sessionId: string }).sessionId).toMatch(/\/fake\/pi-session-\d+\.json/);+ expect((session as { sessionId: string }).sessionId).toMatch(/pi-session-\d+\.json$/);const text = recorder.events.find((e) => e.type === "item.completed" && (e as { itemType: string }).itemType === "assistant_text",@@ -466,7 +466,7 @@ describe("PiDriver turns (fake CLI)", () => {const firstSession = recorder.events.find((e) => e.type === "session.started" && e.turnId === first.turnId) as| { sessionId: string }| undefined;- expect(firstSession?.sessionId).toMatch(/\/fake\/pi-session-\d+\.json/);+ expect(firstSession?.sessionId).toMatch(/pi-session-\d+\.json$/);const second = await instance.adapter.sendTurn({threadId: "t-resume",@@ -496,10 +496,10 @@ describe("PiDriver turns (fake CLI)", () => {expect(probes.some((row) => row.argv!.join(" ") === "--mode rpc --no-session")).toBe(true);expect(turns.length).toBeGreaterThan(0);for (const row of turns) {- expect(row.argv).toEqual(["--mode", "rpc", "--session-dir", piSessionDir(), "-e", expect.any(String)]);+ expect(row.argv).toEqual(["--mode", "rpc", "--session-dir", piSessionDir({ threadId: "t-pi-session-dir" }, "pi-test"), "-e", expect.any(String)]);expect(row.argv).not.toContain("--no-session");}- expect(piSessionDir()).toBe(join(DATA_DIR, "pi-sessions"));+ expect(piSessionDir({ threadId: "t-pi-session-dir" }, "pi-test")).toContain(join(DATA_DIR, "pi-sessions", "local"));});it("reads sessionFile from get_state when new_session omits it, then resumes with switch_session", async () => {@@ -511,7 +511,7 @@ describe("PiDriver turns (fake CLI)", () => {const firstSession = recorder.events.find((e) => e.type === "session.started" && e.turnId === first.turnId) as| { sessionId: string }| undefined;- expect(firstSession?.sessionId).toMatch(/\/fake\/pi-session-\d+\.json/);+ expect(firstSession?.sessionId).toMatch(/pi-session-\d+\.json$/);const second = await instance.adapter.sendTurn({threadId: "t-pi-state-session",@@ -725,7 +725,7 @@ describe("PiDriver turns (fake CLI)", () => {system: "Standing rules.\n\nMemory: likes quiet hours.",systemStable: "Standing rules.",systemVolatile: "Memory: likes quiet hours.",- resumeCursor: "/fake/pi-session-1.json",+ resumeCursor: join(piSessionDir({ threadId }, "pi-test"), "pi-session-1.json"),});await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);const row = readFileSync(dump, "utf8").split("\n").filter(Boolean)diff --git a/server/drivers/pi.ts b/server/drivers/pi.tsindex 1f07fce31e..f566b95d07 100644--- a/server/drivers/pi.ts+++ b/server/drivers/pi.ts@@ -48,7 +48,7 @@ import {import { appendNative } from "./native.ts";import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";import { buildMcpServers } from "./pi-mcp-servers.ts";-import { piSessionDir, piTurnArgs } from "./pi-session.ts";+import { piSessionDir, piSessionPath, piTurnArgs } from "./pi-session.ts";import { noticeFailure } from "../chat-notices.ts";import { decodePiFrame, PiRpcChunks, piLineReader, piNativeLogMessage, readPiPromptImages } from "./pi-rpc.ts";@@ -451,7 +451,9 @@ export const PiDriver: ProviderDriver<PiConfig> = {// Written on every turn: the extension also carries ask_user.const mcpServers = buildMcpServers(turn);const askUser = toolScope === undefined || allowsTool(toolScope, { kind: "native", name: ASK_USER_TOOL });- const childArgs = [...piTurnArgs(), "-e", SPAWNED_PROXIES.piMcpExtension];+ const sessionDir = piSessionDir(turn, input.instanceId);+ const sessionPath = piSessionPath(turn, sessionDir);+ const childArgs = [...piTurnArgs(sessionDir), "-e", SPAWNED_PROXIES.piMcpExtension];const mcpTempDir = mkdtempSync(join(tmpdir(), "omb-pi-mcp-"));const scopeReadyPath = toolScope !== undefined ? join(mcpTempDir, "scope-ready.json") : undefined;try {@@ -470,7 +472,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {return spawnCli(config.cli, childArgs, {stdio: ["pipe", "pipe", "pipe"],cwd: turn.cwd,- box: { rw: [piSessionDir()] },+ box: { rw: [sessionDir] },env: piEnvironment({...process.env,...input.environment,@@ -797,7 +799,6 @@ export const PiDriver: ProviderDriver<PiConfig> = {emit({ ...base(threadId, turnId), type: "turn.started" });// The resumeCursor is pi's sessionFile, which switch_session takes as `sessionPath`.- const sessionPath = typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;let sessionFile = sessionPath;let sessionId: string | null = sessionFile;let sessionReady = false;diff --git a/server/testing/fake-pi-cli.ts b/server/testing/fake-pi-cli.tsindex 17c53377f1..f9927e5501 100755--- a/server/testing/fake-pi-cli.ts+++ b/server/testing/fake-pi-cli.ts@@ -9,10 +9,12 @@// FAKE_PI_DUMP path to append {argv, env} JSON to// FAKE_PI_SESSION_FILE_IN_STATE_ONLY new_session/switch_session return only {cancelled}, like official pi;// sessionFile is available from get_state+// FAKE_PI_PERSIST_SESSION persist prompts to disk and load them on switch_session// FAKE_PI_STEER_REFUSE answer a steer with an explicit success:false// FAKE_PI_STEER_OUT_OF_ORDER hold the first steer until a second arrives, then refuse the first and accept the second-import { appendFileSync, readFileSync } from "node:fs";+import { appendFileSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";import { playStreamScript, streamScript, type StreamScript } from "./stream-script.ts";const mode = process.env.FAKE_PI_MODE ?? "happy";@@ -360,7 +362,8 @@ function handle(cmd: any) {return;}sessionCounter += 1;- currentSessionFile = `/fake/pi-session-${sessionCounter}.json`;+ currentSessionFile = join(argv.includes("--session-dir") ? argv[argv.indexOf("--session-dir") + 1]! : "/fake", `pi-session-${sessionCounter}.json`);+ if (process.env.FAKE_PI_PERSIST_SESSION) writeFileSync(currentSessionFile, "[]");const sessionData = process.env.FAKE_PI_SESSION_FILE_IN_STATE_ONLY? { cancelled: false }: { sessionId: `s-${sessionCounter}`, sessionFile: currentSessionFile };@@ -383,6 +386,9 @@ function handle(cmd: any) {return;}currentSessionFile = cmd.sessionPath ?? currentSessionFile;+ if (process.env.FAKE_PI_PERSIST_SESSION && currentSessionFile && process.env.FAKE_PI_DUMP) {+ appendFileSync(process.env.FAKE_PI_DUMP, JSON.stringify({ loadedHistory: JSON.parse(readFileSync(currentSessionFile, "utf8")) }) + "\n");+ }const switchData = process.env.FAKE_PI_SESSION_FILE_IN_STATE_ONLY? { cancelled: false }: { sessionId: "s-resumed", sessionFile: currentSessionFile };@@ -409,6 +415,10 @@ function handle(cmd: any) {send({ type: "response", command: "set_thinking_level", success: true });return;case "prompt":+ if (process.env.FAKE_PI_PERSIST_SESSION && currentSessionFile) {+ const history = JSON.parse(readFileSync(currentSessionFile, "utf8"));+ writeFileSync(currentSessionFile, JSON.stringify([...history, cmd.message]));+ }if (mode === "prompt-reject") {// pi rejects a prompt submitted while a compaction runs.send({ type: "response", command: "prompt", success: false, error: "fake pi: compaction in progress" });