import { spawn } from "node:child_process"; export function createPiBackend(env) { const provider = env.PI_PROVIDER ?? env.OC_PROVIDER ?? "greenpt"; let model = env.PI_MODEL ?? env.OC_MODEL ?? "deepseek-v4-flash-0731"; const sessionId = env.PI_SESSION_ID ?? "pi-collab"; const name = env.OC_SESSION_TITLE ?? "pi-collab"; const version = env.PI_PACKAGE_VERSION ?? "0.84.4"; const cwd = env.PI_CWD ?? process.cwd(); const sessionDir = env.PI_SESSION_DIR ?? "data/pi/sessions"; // Sandbox mode: the agent runs inside a container (docker exec stdio // bridge) so it is confined — internal network, no git, egress only via the // proxy. Without it, the agent spawns via npx on the host (unsandboxed). const sandbox = env.PI_SANDBOX ?? ""; const sandboxContainer = env.PI_SANDBOX_CONTAINER ?? "pi-sandbox"; const listeners = new Set(); const emit = (ev) => { for (const fn of listeners) { try { fn(ev); } catch { /* listener errors are isolated */ } } }; let child = null; let buf = ""; let seq = 0; let stopped = false; const pendingResponses = new Map(); const thinkingActive = new Set(); const pendingText = new Map(); let currentMsgId = null; function textOf(msg) { return (msg?.content ?? []).filter((c) => c.type === "text").map((c) => c.text).join("\n"); } function sendLine(obj) { if (child && child.stdin.writable) child.stdin.write(JSON.stringify(obj) + "\n"); } function agentArgs() { // The session dir is inside the container (repo mounted at /workspace); // on the host the same files are at /data/pi/sessions. const dir = sandbox ? (sessionDir.startsWith("/") ? sessionDir : `/workspace/${sessionDir}`) : sessionDir; return [ "--mode", "rpc", "--provider", provider, "--model", model, "--session-id", sessionId, "--session-dir", dir, "--name", name, ]; } function start() { const args = sandbox ? [ "exec", "-i", "--user", "1000:1000", ...(env.DEBUG ? [] : []), sandboxContainer, "node", "/usr/local/lib/node_modules/@earendil-works/pi-coding-agent/dist/bundle/rpc-entry.js", ...agentArgs(), ] : [ "-y", `@earendil-works/pi-coding-agent@${version}`, ...agentArgs(), ]; child = spawn(sandbox ? "docker" : "npx", args, { cwd, stdio: ["pipe", "pipe", "pipe"], }); child.stderr.on("data", (d) => { if (env.DEBUG) console.error("[pi]", String(d).trim()); }); child.stdout.on("data", (d) => { buf += String(d); let i; while ((i = buf.indexOf("\n")) !== -1) { const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1); if (line) handleLine(line); } }); child.on("exit", (code, sig) => { console.error(`pi process exited (${code ?? sig}); restarting in 2s`); child = null; if (!stopped) setTimeout(start, 2000); }); } function respond(line) { const pending = pendingResponses.get(line.id); if (!pending) return; pendingResponses.delete(line.id); if (line.success) pending.resolve(line); else pending.reject(new Error(line.error ?? "pi command failed")); } function toolDetail(tool, args) { const a = args ?? {}; if (tool === "bash" || tool === "Bash") return a.command ?? ""; if (typeof a.filePath === "string") return a.filePath; if (typeof a.description === "string") return a.description; if (typeof a.pattern === "string") return a.pattern; if (typeof a.content === "string") return `(${a.content.length} chars)`; const keys = Object.keys(a).filter((k) => k !== "content"); return keys.join(", "); } function handleLine(line) { let m; try { m = JSON.parse(line); } catch { return; } if (env.DEBUG) console.error("[pi>]", JSON.stringify(m).slice(0, 400)); if (m.type === "response") { respond(m); return; } switch (m.type) { case "message_start": { const msg = m.message; if (msg.role !== "assistant") break; currentMsgId = `pi-${++seq}`; pendingText.set(currentMsgId, textOf(msg)); if ((msg.content ?? []).some((c) => c.type === "thinking")) { thinkingActive.add(currentMsgId); emit({ type: "thinking", active: true }); } const t = textOf(msg); if (t.trim()) emit({ type: "text", messageID: currentMsgId, text: t }); break; } case "message_update": { const ev = m.assistantMessageEvent; if (!ev) break; const msgId = currentMsgId; if (!msgId) break; if (ev.type === "text_delta") { const t = (pendingText.get(msgId) ?? "") + (ev.delta ?? ""); pendingText.set(msgId, t); if (env.DEBUG) console.error(`[ADAPT text] id=${msgId} len=${t.length} text=${JSON.stringify(t).slice(0, 60)}`); emit({ type: "text", messageID: msgId, text: t }); } else if (ev.type === "thinking_start" || ev.type === "thinking_delta") { if (ev.type === "thinking_start" || !thinkingActive.has(msgId)) { thinkingActive.add(msgId); emit({ type: "thinking", active: true }); } } else if (ev.type === "thinking_end") { if (thinkingActive.delete(msgId) && thinkingActive.size === 0) { emit({ type: "thinking", active: false }); } } else if (ev.type === "toolcall_start") { emit({ type: "tool", id: ev.toolCallId, tool: ev.toolName, detail: "", status: "running" }); } break; } case "message_end": { const msg = m.message; if (msg.role !== "assistant") break; const msgId = currentMsgId; currentMsgId = null; if (msgId && thinkingActive.delete(msgId) && thinkingActive.size === 0) { emit({ type: "thinking", active: false }); } if (!msgId) break; const t = textOf(msg) || pendingText.get(msgId) || ""; pendingText.delete(msgId); if (t.trim()) emit({ type: "final", messageID: msgId, text: t }); break; } case "tool_execution_start": { emit({ type: "tool", id: m.toolCallId, tool: m.toolName, detail: toolDetail(m.toolName, m.args), status: "running", }); break; } case "tool_execution_end": { emit({ type: "tool", id: m.toolCallId, tool: m.toolName, detail: toolDetail(m.toolName, m.args), status: m.isError ? "error" : "completed", }); break; } case "agent_settled": emit({ type: "idle" }); break; default: break; } } function request(cmd) { const id = `p${++seq}`; return new Promise((resolve, reject) => { pendingResponses.set(id, { resolve, reject }); sendLine({ id, ...cmd }); }); } return { name: "pi", async connect() { start(); await new Promise((resolve, reject) => { const t0 = Date.now(); const timer = setInterval(() => { if (child && child.stdin.writable) { clearInterval(timer); pendingResponses.set("boot", { resolve, reject }); sendLine({ id: "boot", type: "get_state" }); } else if (Date.now() - t0 > 30000) { clearInterval(timer); reject(new Error("pi process did not start in time")); } }, 200); }); return { provider, model }; }, getModel() { return model; }, prompt({ did, user, text }) { const id = `p${++seq}`; pendingResponses.set(id, { resolve: () => {}, reject: (err) => emit({ type: "error", text: err.message }), }); // Feed the human-facing name (nick or resolved handle) to the agent too, // not just the DID — the room already displays it, the agent should see it. const who = user && user !== did ? `${did} (${user})` : did; sendLine({ id, type: "prompt", message: `[${who}] ${text}`, streamingBehavior: "steer" }); }, async newSession() { await request({ type: "new_session" }); return "fresh pi session started"; }, async compact() { await request({ type: "compact" }); return "session context compacted"; }, async setModel(id) { await request({ type: "set_model", provider, modelId: id }); model = id; return `Model set to \`${id}\``; }, onEvent(fn) { listeners.add(fn); return () => listeners.delete(fn); }, dispose() { stopped = true; child?.kill(); listeners.clear(); }, }; }