Skip to content

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

Persist Pi sessions across turns so the prompt cache can hit

koeria38ce8b09ba9a
diff --git a/server/drivers/pi-rpc.ts b/server/drivers/pi-rpc.ts
index 14d2744182..325433ac63 100644
--- a/server/drivers/pi-rpc.ts
+++ b/server/drivers/pi-rpc.ts
@@ -128,3 +128,18 @@ export function readPiPromptImages(turn: SendTurnInput): PiPromptImage[] {
mimeType: image.mime,
}));
}
+
+/** Native logs go into bug reports: keep the RPC shape and size, never image bytes. */
+export function piNativeLogMessage(message: Record<string, unknown>): Record<string, unknown> {
+ if (!Array.isArray(message.images)) return message;
+ return {
+ ...message,
+ images: message.images.map((image) => {
+ if (!image || typeof image !== "object") return image;
+ const value = image as Record<string, unknown>;
+ return typeof value.data === "string"
+ ? { ...value, data: `[image data: ${value.data.length} base64 chars]` }
+ : value;
+ }),
+ };
+}
diff --git a/server/drivers/pi-session.ts b/server/drivers/pi-session.ts
new file mode 100644
index 0000000000..c123b9f4e0
--- /dev/null
+++ b/server/drivers/pi-session.ts
@@ -0,0 +1,15 @@
+import { mkdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { DATA_DIR } from "../config.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");
+}
+
+export function piTurnArgs(): string[] {
+ const dir = piSessionDir();
+ mkdirSync(dir, { recursive: true });
+ return ["--mode", "rpc", "--session-dir", dir];
+}
diff --git a/server/drivers/pi.test.ts b/server/drivers/pi.test.ts
index 40215bbd4d..6c5d7f9333 100644
--- a/server/drivers/pi.test.ts
+++ b/server/drivers/pi.test.ts
@@ -5,13 +5,14 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { ensureDirs, NATIVE_DIR } from "../config.ts";
+import { DATA_DIR, ensureDirs, NATIVE_DIR } from "../config.ts";
import type { ProviderInstance, RuntimeEvent } from "../contracts.ts";
import { recordEvents, type EventRecorder } from "../testing/events.ts";
import { publishedMessages, replyProblems } from "../harness/text-items.testkit.ts";
import { caseTokens, LIVE_REPLY_CASES, liveReplyScripts } from "../testing/live-reply-cases.ts";
import { removeTempDir } from "../testing/cleanup.ts";
import { encodeInjectId, localHost } from "./local-inject.ts";
+import { piSessionDir } from "./pi-session.ts";
import { buildMcpServers } from "./pi-mcp-servers.ts";
import {
applyPiLocalCatalog,
@@ -479,6 +480,59 @@ describe("PiDriver turns (fake CLI)", () => {
expect(secondSession?.sessionId).toBe(firstSession?.sessionId);
});
+ it("starts conversation turns without --no-session and keeps catalog probes ephemeral", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-pi-session-dir-"));
+ const dump = join(dir, "dump.jsonl");
+ await create(undefined, { FAKE_PI_DUMP: dump });
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-pi-session-dir", text: "hi" });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId);
+ const rows = readFileSync(dump, "utf8")
+ .trim()
+ .split("\n")
+ .filter(Boolean)
+ .map((line) => JSON.parse(line) as { argv?: string[] });
+ const probes = rows.filter((row) => row.argv && !row.argv.includes("-e"));
+ const turns = rows.filter((row) => row.argv?.includes("-e"));
+ 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).not.toContain("--no-session");
+ }
+ expect(piSessionDir()).toBe(join(DATA_DIR, "pi-sessions"));
+ });
+
+ it("reads sessionFile from get_state when new_session omits it, then resumes with switch_session", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-pi-session-state-"));
+ const dump = join(dir, "dump.jsonl");
+ await create(undefined, { FAKE_PI_DUMP: dump, FAKE_PI_SESSION_FILE_IN_STATE_ONLY: "1" });
+ const first = await instance.adapter.sendTurn({ threadId: "t-pi-state-session", text: "first" });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === first.turnId);
+ 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/);
+
+ const second = await instance.adapter.sendTurn({
+ threadId: "t-pi-state-session",
+ text: "second",
+ resumeCursor: firstSession!.sessionId,
+ });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);
+ const secondSession = recorder.events.find((e) => e.type === "session.started" && e.turnId === second.turnId) as
+ | { sessionId: string }
+ | undefined;
+ expect(secondSession?.sessionId).toBe(firstSession?.sessionId);
+
+ const rpc = readFileSync(dump, "utf8")
+ .split("\n")
+ .filter(Boolean)
+ .map((line) => JSON.parse(line) as { rpc?: string; sessionPath?: string })
+ .filter((row) => row.rpc);
+ expect(rpc.map((row) => row.rpc)).toEqual(["new_session", "switch_session"]);
+ expect(rpc[1]?.sessionPath).toBe(firstSession?.sessionId);
+ });
+
it("delivers the full prompt once per session and rides volatile changes as notes", async () => {
const dir = mkdtempSync(join(tmpdir(), "omb-pi-split-"));
const dump = join(dir, "dump.jsonl");
diff --git a/server/drivers/pi.ts b/server/drivers/pi.ts
index 20c3a83609..39f081e255 100644
--- a/server/drivers/pi.ts
+++ b/server/drivers/pi.ts
@@ -1,8 +1,8 @@
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 --no-session`), not ACP. pi is BYOK and reads ~/.pi/agent/auth.json itself, so
-// this driver holds no key; resumeCursor is pi's `sessionFile` (switch_session).
+// (`pi --mode rpc`), not ACP. pi is BYOK and reads ~/.pi/agent/auth.json 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 { join } from "node:path";
@@ -48,14 +48,15 @@ import {
import { appendNative } from "./native.ts";
import { allowsTool, parseToolScope } from "../../shared/tool-scope.ts";
import { buildMcpServers } from "./pi-mcp-servers.ts";
+import { piTurnArgs } from "./pi-session.ts";
import { noticeFailure } from "../chat-notices.ts";
-import { decodePiFrame, PiRpcChunks, piLineReader, readPiPromptImages } from "./pi-rpc.ts";
+import { decodePiFrame, PiRpcChunks, piLineReader, piNativeLogMessage, readPiPromptImages } from "./pi-rpc.ts";
import { PiRunUsage, type PiUsage, type TurnUsage } from "./pi-usage.ts";
export { decodePiFrame, PiRpcChunks, piLineReader } from "./pi-rpc.ts";
const DRIVER_KIND = "piAgent";
-const PI_ARGS = ["--mode", "rpc", "--no-session"];
+const PI_ARGS = ["--mode", "rpc", "--no-session"]; // catalog probes only: do not write a session file
const PI_MODEL_UPDATE_ARGS = ["update", "--models", "--no-approve"];
/** omp's RPC transport caps a frame at 1 MiB and chunks bigger ones only after the client
* negotiates protocol 2. Vanilla pi has no handshake frame to wait for. */
@@ -70,21 +71,6 @@ const PI_SESSION_SLOW_MS = 20_000;
/** pi answered success:false: an explicit refusal from a live runtime, not a transport failure. */
class PiRpcRefusalError extends Error {}
-/** Native logs go into bug reports: keep the RPC shape and size, never image bytes. */
-function piNativeLogMessage(message: Record<string, unknown>): Record<string, unknown> {
- if (!Array.isArray(message.images)) return message;
- return {
- ...message,
- images: message.images.map((image) => {
- if (!image || typeof image !== "object") return image;
- const value = image as Record<string, unknown>;
- return typeof value.data === "string"
- ? { ...value, data: `[image data: ${value.data.length} base64 chars]` }
- : value;
- }),
- };
-}
-
export function piThinkingLevel(effort: EffortLevel): (typeof EFFORT_LEVELS)[number] | "off" {
return effort === "none" ? "off" : effort;
}
@@ -476,7 +462,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
} catch {}
throw err;
}
- const childArgs = [...PI_ARGS, "-e", SPAWNED_PROXIES.piMcpExtension];
+ const childArgs = [...piTurnArgs(), "-e", SPAWNED_PROXIES.piMcpExtension];
// spawnCli can throw synchronously, before settle() could remove the credential file.
const child = (() => {
@@ -827,7 +813,7 @@ export const PiDriver: ProviderDriver<PiConfig> = {
sessionReady = true;
sessionOpened = true;
} catch {
- // pi --no-session accepts a prompt without an explicit session.
+ // A prompt can still be accepted without an explicit session handshake.
}
if (settled) return { turnId };
@@ -846,12 +832,15 @@ export const PiDriver: ProviderDriver<PiConfig> = {
return { turnId };
}
}
- if (!chosen) {
+ // Official new_session returns only `{ cancelled }`; sessionFile is on get_state when persisted.
+ if (!chosen || (sessionOpened && !sessionFile)) {
try {
const statePromise = awaitResponse("get_state");
send({ type: "get_state" });
- const state = await statePromise as { model?: unknown } | undefined;
- confirmedModel = piModelId(state?.model);
+ const state = await statePromise as { model?: unknown; sessionFile?: string; sessionId?: string } | undefined;
+ if (!chosen) confirmedModel = piModelId(state?.model);
+ if (typeof state?.sessionFile === "string" && state.sessionFile) sessionFile = state.sessionFile;
+ sessionId = sessionFile ?? (typeof state?.sessionId === "string" ? state.sessionId : null) ?? sessionId;
} catch {}
}
if (settled) return { turnId };
diff --git a/server/testing/fake-pi-cli.ts b/server/testing/fake-pi-cli.ts
index 16fbe5f3c8..17c53377f1 100755
--- a/server/testing/fake-pi-cli.ts
+++ b/server/testing/fake-pi-cli.ts
@@ -7,6 +7,8 @@
// | session-slow (answers new_session after FAKE_PI_SESSION_DELAY_MS, default 800, and dumps {sessionReplied})
// FAKE_PI_MODELS provider/model pairs (default "ollama-cloud/glm-5.2,openai/gpt-4o")
// 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_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
@@ -359,7 +361,13 @@ function handle(cmd: any) {
}
sessionCounter += 1;
currentSessionFile = `/fake/pi-session-${sessionCounter}.json`;
- const sessionReply = { type: "response", command: "new_session", success: true, data: { sessionId: `s-${sessionCounter}`, sessionFile: currentSessionFile } };
+ const sessionData = process.env.FAKE_PI_SESSION_FILE_IN_STATE_ONLY
+ ? { cancelled: false }
+ : { sessionId: `s-${sessionCounter}`, sessionFile: currentSessionFile };
+ const sessionReply = { type: "response", command: "new_session", success: true, data: sessionData };
+ if (process.env.FAKE_PI_DUMP) {
+ try { appendFileSync(process.env.FAKE_PI_DUMP, JSON.stringify({ rpc: "new_session" }) + "\n"); } catch {}
+ }
if (mode !== "session-slow") {
send(sessionReply);
return;
@@ -375,7 +383,13 @@ function handle(cmd: any) {
return;
}
currentSessionFile = cmd.sessionPath ?? currentSessionFile;
- send({ type: "response", command: "switch_session", success: true, data: { sessionId: "s-resumed", sessionFile: currentSessionFile } });
+ const switchData = process.env.FAKE_PI_SESSION_FILE_IN_STATE_ONLY
+ ? { cancelled: false }
+ : { sessionId: "s-resumed", sessionFile: currentSessionFile };
+ if (process.env.FAKE_PI_DUMP) {
+ try { appendFileSync(process.env.FAKE_PI_DUMP, JSON.stringify({ rpc: "switch_session", sessionPath: currentSessionFile }) + "\n"); } catch {}
+ }
+ send({ type: "response", command: "switch_session", success: true, data: switchData });
return;
case "set_model": {
if (process.env.FAKE_PI_DUMP) {