Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
feat(byoa): add `pi` as a third BYOA engine (#7) (#20)
lylyad1620c87505
diff --git a/README.md b/README.mdindex 3c03487..555c5dd 100644--- a/README.md+++ b/README.md@@ -17,7 +17,7 @@ Cumora is cross-platform team chat where AI agents are first-class participantsTwo "brain" paths:- **Cumora Cloud** — each agent runs in a managed per-agent pod; turns run a multi-hop tool-calling loop on the OpenAI Responses API (bash, files, browser, email, memory, skills…).-- **BYOA (Bring Your Own Agent)** — pair your own Mac/VPS with `npx cumora agent computer` and the agent's brain becomes your local **Claude Code**, **Codex**, **Grok Build**, **Cursor Agent**, or **OpenCode** CLI, on your own provider account. The server never sees your provider keys. See [`docs/BYOA.md`](docs/BYOA.md).+- **BYOA (Bring Your Own Agent)** — pair your own Mac/VPS with `npx cumora agent computer` and the agent's brain becomes your local **Claude Code**, **Codex**, **Grok Build**, **Cursor Agent**, **OpenCode**, or **pi** CLI, on your own provider account. The server never sees your provider keys. See [`docs/BYOA.md`](docs/BYOA.md).## Architecturediff --git a/agent-cli/README.md b/agent-cli/README.mdindex 037f198..75a982b 100644--- a/agent-cli/README.md+++ b/agent-cli/README.md@@ -1,7 +1,7 @@# cumoraRun your [Cumora](https://cumora.ai) agents on your own machine or VPS,-powered by your **local Claude Code, Codex, Grok Build, Cursor Agent, or OpenCode CLI**+powered by your **local Claude Code, Codex, Grok Build, Cursor Agent, OpenCode, or pi CLI**(BYOA — Bring Your Own Agent). One daemon can host many agents; each gets its own isolatedworkspace, memory, and skills on that machine.@@ -21,5 +21,5 @@ npx cumora agent computer --server <your-server-url>```Requires **Node ≥ 18** and `claude` (Claude Code), `codex`, `grok` (Grok Build),-`cursor-agent` (Cursor), or `opencode` on your `PATH`. The daemon talks to the Cumora server over HTTPS only — it needs no+`cursor-agent` (Cursor), `opencode`, or `pi` on your `PATH`. The daemon talks to the Cumora server over HTTPS only — it needs nodatabase access.diff --git a/agent-cli/package.json b/agent-cli/package.jsonindex 38321c5..641b567 100644--- a/agent-cli/package.json+++ b/agent-cli/package.json@@ -1,7 +1,7 @@{"name": "cumora","version": "0.4.0",- "description": "Run Cumora agents on your own machine with Claude Code, Codex, Grok Build, Cursor Agent, or OpenCode (BYOA).",+ "description": "Run Cumora agents on your own machine with Claude Code, Codex, Grok Build, Cursor Agent, OpenCode, or pi (BYOA).","license": "MIT","type": "module","bin": {@@ -18,7 +18,8 @@"cumora","agent","claude-code",- "codex"+ "codex",+ "pi"],"scripts": {"build": "node build.mjs",diff --git a/agent-cli/src/cli.ts b/agent-cli/src/cli.tsindex 967d4dc..2a98864 100644--- a/agent-cli/src/cli.ts+++ b/agent-cli/src/cli.ts@@ -21,7 +21,7 @@ async function main(): Promise<void> {'Usage:\n' +' npx cumora@latest agent computer --pair <code> [--server <url>] pair this machine\n' +' npx cumora@latest agent computer [--server <url>] start the daemon\n\n' +- 'Needs `claude` (Claude Code), `codex`, `grok` (Grok Build), `cursor-agent` (Cursor), or `opencode` on PATH. Get a pairing code from\n' ++ 'Needs `claude` (Claude Code), `codex`, `grok` (Grok Build), `cursor-agent` (Cursor), `opencode`, or `pi` on PATH. Get a pairing code from\n' +'Cumora → You → Computers → Add a computer.\n',)process.exit(argv.length ? 1 : 0)diff --git a/docs/BYOA.md b/docs/BYOA.mdindex 00fb4f6..158bc71 100644--- a/docs/BYOA.md+++ b/docs/BYOA.md@@ -1,4 +1,4 @@-# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode as the engine)+# BYOA — Bring Your Own Agent (local Claude Code / Codex / Grok Build / Cursor Agent / OpenCode / pi as the engine)Every Cumora agent has a "brain" and a host. The managed path isserver-side: `runAgentTurn` in `server/src/agents/turn.ts` runs a@@ -7,8 +7,8 @@ a per-agent Kubernetes pod (the `agent-computer` image).**BYOA** lets a user supply the brain instead: a long-running daemon onthe user's own machine (laptop **or** VPS) drives a local **Claude Code**,-**Codex CLI**, **Grok Build** (`grok`), **Cursor Agent** (`cursor-agent`), or-**OpenCode** (`opencode`) as the reasoning engine, on the user's own provider+**Codex CLI**, **Grok Build** (`grok`), **Cursor Agent** (`cursor-agent`),+**OpenCode** (`opencode`), or **pi** (`pi`) as the reasoning engine, on the user's own provideraccount — the server never holds the user's provider credentials.One daemon hosts **many independent agents** — each with its own isolatedhome directory, memory, skills, and notes. In Cumora these still appear@@ -39,7 +39,7 @@ managed cloud agents and local agents into the same picture.user to set up; it's always online.- **Your computers** — machines you pair (your Mac, a VPS). Each runs the`cumora agent computer` daemon with a local engine (Claude Code /- Codex / Grok Build / Cursor Agent / OpenCode). Agents you place here are BYOA agents.+ Codex / Grok Build / Cursor Agent / OpenCode / pi). Agents you place here are BYOA agents.```Computers@@ -113,6 +113,7 @@ with rate-limit adaptation, and same-turn steering.│ → persistent EngineSession turn ││ claude --input/output-format stream-json … ││ codex app-server / grok ACP / cursor/opencode run │+ │ pi --mode rpc (JSON commands + events over stdio) ││ bash → cumora shim → POST /runtime/cli (per-agent JWT)│└─────────────────────────────────────────────────────────┘```@@ -204,20 +205,20 @@ interface EngineSession {}```-| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode |-| --- | --- | --- | --- | --- | --- |-| Persistent session | `claude -p --input-format stream-json --output-format stream-json --verbose [--resume <id>] [--model X]` | `codex app-server --listen stdio://`, driven over JSON-RPC (`thread/start` / `thread/resume`) | `grok agent --always-approve --no-leader … stdio`, driven over ACP | none in Cursor Agent `2026.08.11-e8db854` | none in the supported OpenCode `v1.18.20` contract; a new process resumes with `--session <id>` |-| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | `developerInstructions` on `thread/start` | ACP `_meta.rules` | inlined into each wake | inlined into each wake |-| One-shot fallback | `claude -p … --output-format stream-json` | `codex exec … --skip-git-repo-check` | `grok -p … --output-format streaming-messages-json` | `cursor-agent -p --output-format stream-json --force --trust [--resume <id>]` | `opencode run --format json --auto [--session <id>] [--model provider/model]` (prompt on stdin) |-| Fallback triggers | `CUMORA_CLAUDE_ARGS` set | `CUMORA_CODEX_ARGS` set, `CUMORA_CODEX_NO_APP_SERVER=1`, Windows, or git-init failure | `CUMORA_GROK_ARGS` set, `CUMORA_GROK_NO_ACP=1`, or Windows | always one-shot; `CUMORA_CURSOR_ARGS` overrides flags | always one-shot; `CUMORA_OPENCODE_ARGS` overrides run flags |-| Memory / persona file | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` plus `.opencode/skills/` |-| Triage (small brain) | `claude -p --model haiku --output-format json` | `codex exec --model gpt-5.4-mini` | `grok -p --model grok-4.5 --output-format json` | `cursor-agent --mode ask -p --output-format stream-json --trust` | `opencode run --format json --agent cumora-triage`; the injected agent denies every tool permission |+| Concern | Claude Code | Codex CLI | Grok Build | Cursor Agent | OpenCode | pi |+| --- | --- | --- | --- | --- | --- | --- |+| Persistent session | `claude -p --input-format stream-json --output-format stream-json --verbose [--resume <id>] [--model X]` | `codex app-server --listen stdio://`, driven over JSON-RPC (`thread/start` / `thread/resume`) | `grok agent --always-approve --no-leader … stdio`, driven over ACP | none in Cursor Agent `2026.08.11-e8db854` | none in the supported OpenCode `v1.18.20` contract; a new process resumes with `--session <id>` | `pi --mode rpc --session-id <id> --skill <home>/.pi/skills`; a turn is a `prompt` command, done at `agent_settled`; steering is pi's native `steer` |+| Standing prompt | `--append-system-prompt-file <home>/.cumora-standing-prompt.md` | `developerInstructions` on `thread/start` | ACP `_meta.rules` | inlined into each wake | inlined into each wake | `--append-system-prompt <home>/.cumora-standing-prompt.md` |+| One-shot fallback | `claude -p … --output-format stream-json` | `codex exec … --skip-git-repo-check` | `grok -p … --output-format streaming-messages-json` | `cursor-agent -p --output-format stream-json --force --trust [--resume <id>]` | `opencode run --format json --auto [--session <id>] [--model provider/model]` (prompt on stdin) | `pi <CUMORA_PI_ARGS> --session-id <id> -p` (print mode) |+| Fallback triggers | `CUMORA_CLAUDE_ARGS` set | `CUMORA_CODEX_ARGS` set, `CUMORA_CODEX_NO_APP_SERVER=1`, Windows, or git-init failure | `CUMORA_GROK_ARGS` set, `CUMORA_GROK_NO_ACP=1`, or Windows | always one-shot; `CUMORA_CURSOR_ARGS` overrides flags | always one-shot; `CUMORA_OPENCODE_ARGS` overrides run flags | `CUMORA_PI_ARGS` set |+| Memory / persona file | `CLAUDE.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` | `AGENTS.md` plus `.opencode/skills/` | `AGENTS.md` plus `.pi/skills/` (loaded via `--skill`) |+| Triage (small brain) | `claude -p --model haiku --output-format json` | `codex exec --model gpt-5.4-mini` | `grok -p --model grok-4.5 --output-format json` | `cursor-agent --mode ask -p --output-format stream-json --trust` | `opencode run --format json --agent cumora-triage`; the injected agent denies every tool permission | `pi --mode json --no-session --no-tools --no-extensions --no-skills --no-context-files [--model $CUMORA_TRIAGE_MODEL]` (multi-provider — no fixed cheap model; unset → pi's default) |Sessions carry a resume id (`~/.cumora/sessions/<agentId>.session`); afailed resume falls back to a fresh thread instead of wedging the agent.Engines run headless with their permission prompts disabled, scoped tothe agent's isolated home. On Windows the daemon resolves the real-`claude`/`codex`/`grok`/`cursor-agent`/`opencode` `.cmd` shims and routes large+`claude`/`codex`/`grok`/`cursor-agent`/`opencode`/`pi` `.cmd` shims and routes largeprompts via stdin. OpenCode JSONL `step_finish` events are recorded as individualprovider hops; uncached input, output+reasoning, and cache read/write tokens mapto Cumora's common usage ledger without double-counting. OpenCode may race its@@ -266,6 +267,7 @@ CUMORA_ENGINE_MODEL=local CUMORA_TRIAGE_MODEL=local-small cumora agent computer.claude/skills/<name>/SKILL.md ← this agent's skills (Claude).cursor/skills/ ← Cursor-native skill directory.opencode/skills/ ← OpenCode-native skill directory+ .pi/skills/ ← pi-native skill directory (via --skill).claude/settings.json ← permissions (allow Bash)bin/cumora ← the shim (see below); bin/.runtime-tokenmemory/MEMORY.md ← the agent's durable memory index@@ -295,7 +297,7 @@ credentials are keyed to that dir — so the daemon sets `cwd` to theagent's home and does **not** relocate config. Per-agent: project memory,skills, settings, notes, workspace. Shared across an owner's agents onone machine: the engine login and the user's global config (`~/.claude` /-`~/.codex` / `~/.grok`, Cursor's login store, or OpenCode's config/auth store).+`~/.codex` / `~/.grok` / `~/.pi/agent`, Cursor's login store, or OpenCode's config/auth store).Agents are independent in all project state and share one engine login per host.---@@ -309,7 +311,7 @@ CREATE TABLE computers (owner_user_id TEXT, -- null for the managed Cumora Cloud rowname TEXT NOT NULL, -- "Cumora Cloud", "MacBook Pro", …kind TEXT NOT NULL, -- 'cloud' | 'local' | 'vps'- available_engines JSONB, -- ['claude','codex','grok','cursor','opencode'] (daemon-detected)+ available_engines JSONB, -- ['claude','codex','grok','cursor','opencode','pi'] (daemon-detected)status TEXT NOT NULL, -- 'online' | 'offline' | 'busy'last_seen_at TIMESTAMP,credential_hash TEXT, -- SHA256 of the device token@@ -322,7 +324,7 @@ CREATE TABLE computers (-- participants carry their host + engine + models-- computer_id TEXT (FK → computers.id)--- engine TEXT ('managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode')+-- engine TEXT ('managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi')-- model TEXT (big-brain override)-- fast_model TEXT (small-brain override)```@@ -411,7 +413,7 @@ npx cumora@latest agent computer --pair <code> [--server <url>]## Boundaries- **Cost / rate limits are the operator's** (their Claude Code / Codex / Grok Build /- Cursor subscription or OpenCode provider account) — a stated BYOA benefit. The daemon's semaphores, spawn+ Cursor subscription, or OpenCode / pi provider account) — a stated BYOA benefit. The daemon's semaphores, spawnpacing, and cooldowns exist to stay inside those limits gracefully(COORDINATION.md 2-4).- **Local inner state is not mirrored to the server.** Memory, notes,diff --git a/scripts/guard-big-brain.mjs b/scripts/guard-big-brain.mjsindex 5edfb90..c59e4cc 100644--- a/scripts/guard-big-brain.mjs+++ b/scripts/guard-big-brain.mjs@@ -80,7 +80,7 @@ export function lineViolations(rel, raw) {out.push('big-brain engine spawn (adapter.run) outside the gated daemon path')}// R4 — a supported engine binary spawned directly, outside the adapter.- if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex|grok|cursor-agent|opencode)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {+ if (/(?:spawn|execFile\w*|exec)\s*\(\s*['"`](claude|codex|grok|cursor-agent|opencode|pi)['"`]/.test(code) && !ALLOW.engineSpawn.includes(rel)) {out.push('engine binary spawned outside the engine adapter (bypasses the classify=small / run=big split)')}return outdiff --git a/server/src/__tests__/agents-computer-engine-pi.test.ts b/server/src/__tests__/agents-computer-engine-pi.test.tsnew file mode 100644index 0000000..0a2f62b--- /dev/null+++ b/server/src/__tests__/agents-computer-engine-pi.test.ts@@ -0,0 +1,321 @@+/**+ * Unit tests for the BYOA `pi` engine adapter (server/src/agents/computer/engine.ts).+ *+ * pi is not installed in CI, so every test drives a FAKE `pi` — a small Node+ * script put first on PATH — that speaks the real protocol shapes we verified+ * against pi 0.83.0: `--mode json` (session header + events, exit 0) and+ * `--mode rpc` (JSON commands on stdin → `response` frames + events; exits when+ * stdin closes). Scenarios are selected via FAKE_PI_SCENARIO; everything the+ * fake sees (argv, commands) is appended to FAKE_PI_LOG so a test can assert on+ * what the adapter actually sent.+ *+ * Run: node --import tsx --test server/src/__tests__/agents-computer-engine-pi.test.ts+ */+import { mkdtemp, mkdir, writeFile, readFile, chmod, rm } from 'node:fs/promises'+import { existsSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { setTimeout as delay } from 'node:timers/promises'+import { afterEach, test } from 'node:test'+import assert from 'node:assert/strict'+import { getAdapter, type EngineHopReport } from '../agents/computer/engine.js'++const IS_WIN = process.platform === 'win32'+const tempDirs: string[] = []++afterEach(async () => {+ delete process.env.CUMORA_PI_ARGS+ await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))+})++const FAKE_PI = `#!/usr/bin/env node+'use strict'+const fs = require('node:fs')+const argv = process.argv.slice(2)+const record = (o) => { if (process.env.FAKE_PI_LOG) fs.appendFileSync(process.env.FAKE_PI_LOG, JSON.stringify(o) + '\\n') }+const out = (o) => process.stdout.write(JSON.stringify(o) + '\\n')+const scenario = process.env.FAKE_PI_SCENARIO || 'ok'+const mode = argv.includes('rpc') ? 'rpc' : argv.includes('json') ? 'json' : 'text'+const sidIdx = argv.indexOf('--session-id')+const SID = sidIdx >= 0 ? argv[sidIdx + 1] : 'fake-session-' + mode+record({ argv, cwd: process.cwd() })++// A turn's worth of events for prompt text \`text\` (same shapes as real pi).+function emitTurn(text, extra) {+ if (scenario === 'die') { process.stderr.write('Error: no models available. Run /login first.\\n'); process.exit(1) }+ out({ type: 'message_start', message: { role: 'assistant', content: [] } })+ out({ type: 'message_update', message: {}, assistantMessageEvent: { type: 'text_delta', delta: 'e' } })+ if (scenario === 'turn-error') {+ out({ type: 'message_end', message: { role: 'assistant', model: 'claude-test', stopReason: 'error', errorMessage: 'rate limit exceeded (429)', content: [] } })+ } else {+ out({ type: 'message_end', message: { role: 'assistant', model: 'claude-test',+ usage: { input: 2, output: 4, cacheRead: 687, cacheWrite: 10, cost: { total: 0.001 } },+ stopReason: 'stop', content: [{ type: 'text', text: 'echo:' + text + (extra || '') }] } })+ }+ out({ type: 'turn_end', message: {}, toolResults: [] })+ out({ type: 'agent_end', messages: [{}, {}], willRetry: false })+ out({ type: 'agent_settled' })+}++if (mode === 'json') {+ if (scenario === 'not-logged-in') { process.stderr.write('No models available. Set an API key or run /login.\\n'); process.exit(1) }+ out({ type: 'session', version: 3, id: SID, timestamp: 'now', cwd: process.cwd() })+ out({ type: 'agent_start' }); out({ type: 'turn_start' })+ const prompt = argv[argv.length - 1]+ out({ type: 'message_end', message: { role: 'user', content: [{ type: 'text', text: prompt }] } })+ emitTurn(prompt)+ process.exit(0)+}++if (mode === 'text') { process.stdout.write('OK\\n'); process.exit(0) }++// rpc+let buf = ''+let pendingPrompt = null+process.stdin.setEncoding('utf8')+process.stdin.on('data', (d) => {+ buf += d+ let nl+ while ((nl = buf.indexOf('\\n')) >= 0) {+ const line = buf.slice(0, nl); buf = buf.slice(nl + 1)+ if (!line.trim()) continue+ const cmd = JSON.parse(line)+ record({ cmd })+ if (cmd.type === 'get_state') {+ out({ type: 'response', command: 'get_state', id: cmd.id, success: true, data: { sessionId: SID, isStreaming: false, messageCount: 0 } })+ } else if (cmd.type === 'prompt') {+ if (scenario === 'reject') { out({ type: 'response', command: 'prompt', id: cmd.id, success: false, error: 'Agent is already streaming' }); continue }+ out({ type: 'response', command: 'prompt', id: cmd.id, success: true })+ out({ type: 'agent_start' }); out({ type: 'turn_start' })+ if (scenario === 'wait-steer') { pendingPrompt = cmd; continue }+ emitTurn(cmd.message)+ } else if (cmd.type === 'steer') {+ out({ type: 'response', command: 'steer', success: true })+ if (pendingPrompt) { const p = pendingPrompt; pendingPrompt = null; emitTurn(p.message, ' steered:' + cmd.message) }+ } else if (cmd.type === 'abort') {+ out({ type: 'response', command: 'abort', success: true })+ }+ }+})+process.stdin.on('end', () => process.exit(0))+`++interface Fixture { root: string; binDir: string; home: string; log: string; env: NodeJS.ProcessEnv }++async function fixture(scenario = 'ok'): Promise<Fixture> {+ const root = await mkdtemp(join(tmpdir(), 'cumora-engine-pi-'))+ tempDirs.push(root)+ const binDir = join(root, 'bin')+ const home = join(root, 'home')+ await mkdir(binDir)+ await mkdir(home)+ const fakePi = join(binDir, 'pi')+ await writeFile(fakePi, FAKE_PI, 'utf8')+ await chmod(fakePi, 0o755)+ const log = join(root, 'fake-pi.log')+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ PATH: `${binDir}:${process.env.PATH ?? ''}`,+ FAKE_PI_LOG: log,+ FAKE_PI_SCENARIO: scenario,+ }+ return { root, binDir, home, log, env }+}++async function fakeLog(f: Fixture): Promise<Array<{ argv?: string[]; cmd?: { type: string; id?: string; message?: string } }>> {+ if (!existsSync(f.log)) return []+ return (await readFile(f.log, 'utf8')).split('\n').filter(Boolean).map((l) => JSON.parse(l))+}++test('pi seedHome lays out AGENTS.md + .pi/skills; the persona file is system-owned and rewritten', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const pi = getAdapter('pi')+ await pi.seedHome(f.home, { id: 'a1', name: 'Iris', role: 'Designer', systemPrompt: 'Dry wit. Short sentences.' })+ const agentsMd = await readFile(join(f.home, 'AGENTS.md'), 'utf8')+ assert.match(agentsMd, /^# Iris — Designer/)+ assert.match(agentsMd, /## Your style\nDry wit\. Short sentences\./, 'persona systemPrompt lands in the header')+ assert.match(agentsMd, /`AGENTS\.md` \(this file\)/, 'the header must name the file pi actually reads')+ assert.match(agentsMd, /`\.pi\/skills\/` — your skills/)+ assert.ok(existsSync(join(f.home, '.pi', 'skills')))+ assert.ok(existsSync(join(f.home, 'memory', 'MEMORY.md')))+ // AGENTS.md is system-owned: a persona edit is picked up on the next seed+ // (matches Claude/Codex/Cursor). The agent's own files are never clobbered.+ await writeFile(join(f.home, 'memory', 'MEMORY.md'), 'agent notes', 'utf8')+ await pi.seedHome(f.home, { id: 'a1', name: 'Iris', role: 'Illustrator', systemPrompt: null })+ assert.match(await readFile(join(f.home, 'AGENTS.md'), 'utf8'), /^# Iris — Illustrator/)+ assert.equal(await readFile(join(f.home, 'memory', 'MEMORY.md'), 'utf8'), 'agent notes')+})++test('pi persistent session: one prompt → one turn, session id, summed usage, per-hop ledger report', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const hops: EngineHopReport[] = []+ const logs: string[] = []+ const session = getAdapter('pi').startSession?.({+ home: f.home, env: f.env, model: 'anthropic/claude-test', fastModel: null,+ resumeSessionId: 'resume-me-1234', standingPrompt: 'STANDING PROMPT BODY',+ onLog: (l) => logs.push(l), onHopUsage: (r) => hops.push(r),+ })+ assert.ok(session, 'pi has a persistent (rpc) session')+ assert.equal(session.carriesStandingPrompt, true, 'standing prompt travels via --append-system-prompt')++ const result = await session.send('hello agent')+ assert.equal(result.exitCode, 0, result.error)+ assert.equal(result.error, undefined)+ assert.equal(result.sessionId, 'resume-me-1234', 'the id we pinned with --session-id is the one pi reports back')+ assert.equal(result.model, 'claude-test')+ assert.deepEqual(result.usage, { input_tokens: 2, output_tokens: 4, cache_read_input_tokens: 687, cache_creation_input_tokens: 10 })+ assert.equal(hops.length, 1)+ assert.equal(hops[0].model, 'claude-test')+ assert.equal(hops[0].hopIndex, 1)+ assert.equal(hops[0].textChars, 'echo:hello agent'.length)+ assert.deepEqual(hops[0].usage, { input_tokens: 2, output_tokens: 4, cache_read_input_tokens: 687, cache_creation_input_tokens: 10 })++ // What the adapter actually sent pi.+ const seen = await fakeLog(f)+ const argv = seen[0]?.argv ?? []+ assert.ok(argv.includes('rpc'), `spawned in rpc mode: ${argv.join(' ')}`)+ assert.equal(argv[argv.indexOf('--session-id') + 1], 'resume-me-1234')+ assert.equal(argv[argv.indexOf('--model') + 1], 'anthropic/claude-test')+ assert.ok(argv.includes('--thinking') && argv[argv.indexOf('--thinking') + 1] === 'off', 'thinking off by default')+ const promptFile = argv[argv.indexOf('--append-system-prompt') + 1]+ assert.equal(await readFile(promptFile, 'utf8'), 'STANDING PROMPT BODY')+ assert.equal(argv[argv.indexOf('--skill') + 1], join(f.home, '.pi', 'skills'))+ const cmds = seen.map((s) => s.cmd).filter(Boolean)+ assert.deepEqual(cmds.map((c) => c!.type), ['get_state', 'prompt'])+ assert.equal(cmds[1]!.message, 'hello agent')+ // Streaming deltas are NOT logged; the assistant message_end is.+ assert.ok(!logs.some((l) => l.includes('message_update')), 'deltas are noise')+ assert.ok(logs.some((l) => l.includes('"message_end"')), 'message_end is logged verbatim')+ assert.ok(logs.some((l) => l === '[pi] agent_end (2 messages, willRetry=false)'), 'agent_end is collapsed to a one-liner')++ // A second turn reuses the process (no respawn) and resets the accumulators.+ hops.length = 0+ const r2 = await session.send('second')+ assert.equal(r2.exitCode, 0)+ assert.equal(hops.length, 1)+ assert.equal(hops[0].hopIndex, 1, 'hop index restarts per turn')+ assert.equal((await fakeLog(f)).filter((s) => s.argv).length, 1, 'still one process')+ session.stop()+})++test('pi persistent session: steer() rides pi\'s native steer command mid-turn; busy while a turn is in flight', { skip: IS_WIN }, async () => {+ const f = await fixture('wait-steer')+ const session = getAdapter('pi').startSession?.({ home: f.home, env: f.env, model: null, fastModel: null, onLog: () => {} })+ assert.ok(session)+ const turn = session.send('do the task')+ const busy = await session.send('another')+ assert.equal(busy.exitCode, 1)+ assert.match(busy.error ?? '', /busy/)+ await delay(150)+ session.steer('quick ping')+ const result = await turn+ assert.equal(result.exitCode, 0, result.error)+ const cmds = (await fakeLog(f)).map((s) => s.cmd).filter(Boolean)+ assert.deepEqual(cmds.map((c) => c!.type), ['get_state', 'prompt', 'steer'])+ assert.equal(cmds[2]!.message, 'quick ping')+ // Idle steer is a no-op (nothing in flight → the daemon's normal turn handles it).+ session.steer('too late')+ await delay(50)+ assert.equal((await fakeLog(f)).map((s) => s.cmd).filter(Boolean).length, 3)+ session.stop()+})++test('pi persistent session: a model error surfaces as a failed turn, not a hang', { skip: IS_WIN }, async () => {+ const f = await fixture('turn-error')+ const session = getAdapter('pi').startSession?.({ home: f.home, env: f.env, model: null, fastModel: null, onLog: () => {} })+ assert.ok(session)+ const result = await session.send('hi')+ assert.equal(result.exitCode, 1)+ assert.match(result.error ?? '', /rate limit exceeded \(429\)/)+ assert.equal(session.alive, true, 'the process is still up — only the turn failed')+ session.stop()+})++test('pi persistent session: a prompt rejected by pi settles immediately', { skip: IS_WIN }, async () => {+ const f = await fixture('reject')+ const session = getAdapter('pi').startSession?.({ home: f.home, env: f.env, model: null, fastModel: null, onLog: () => {} })+ assert.ok(session)+ const result = await session.send('hi')+ assert.equal(result.exitCode, 1)+ assert.match(result.error ?? '', /rejected the turn: Agent is already streaming/)+ session.stop()+})++test('pi persistent session: process death mid-turn fails the turn with stderr and is logged', { skip: IS_WIN }, async () => {+ const f = await fixture('die')+ const logs: string[] = []+ const session = getAdapter('pi').startSession?.({ home: f.home, env: f.env, model: null, fastModel: null, onLog: (l) => logs.push(l) })+ assert.ok(session)+ const result = await session.send('hi')+ assert.equal(result.exitCode, 1)+ assert.match(result.error ?? '', /no models available/i)+ assert.ok(logs.some((l) => /\[session\] engine process died MID-TURN/.test(l)), logs.join('\n'))+ assert.equal(session.alive, false)+ const dead = await session.send('again')+ assert.equal(dead.exitCode, 1)+ assert.match(dead.error ?? '', /no models available|not alive/i)+})++test('pi run() (one-shot) drives the same rpc path for exactly one turn and reports a resumable session id', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const hops: EngineHopReport[] = []+ const result = await getAdapter('pi').run({+ home: f.home, prompt: 'wake', env: f.env, model: null, fastModel: null,+ resumeSessionId: null, onLog: () => {}, onHopUsage: (r) => hops.push(r), signal: new AbortController().signal,+ })+ assert.equal(result.exitCode, 0, result.error)+ assert.ok(result.sessionId, 'a fresh session id is minted so the next wake can resume it')+ assert.equal(hops.length, 1)+ const seen = await fakeLog(f)+ assert.equal(seen[0]?.argv?.[seen[0].argv.indexOf('--session-id') + 1], result.sessionId)+ await delay(100) // stdin closed → the fake exits on its own; nothing to assert beyond no hang+})++test('pi classify() runs a bare json one-shot and returns text + usage + the real model', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const res = await getAdapter('pi').classify({+ cwd: f.home, prompt: '{"instructions":"triage"}', env: f.env, model: 'anthropic/claude-haiku-test', signal: new AbortController().signal,+ })+ assert.equal(res.error, undefined)+ assert.equal(res.text, 'echo:{"instructions":"triage"}')+ assert.equal(res.model, 'claude-test')+ assert.deepEqual(res.usage, { input_tokens: 2, output_tokens: 4, cache_read_input_tokens: 687, cache_creation_input_tokens: 10 })+ const argv = (await fakeLog(f))[0]?.argv ?? []+ for (const flag of ['--mode', 'json', '--no-session', '--no-tools', '--no-extensions', '--no-skills', '--no-context-files']) {+ assert.ok(argv.includes(flag), `bare triage spawn carries ${flag}: ${argv.join(' ')}`)+ }+ assert.equal(argv[argv.indexOf('--model') + 1], 'anthropic/claude-haiku-test')+ assert.equal(argv[argv.length - 1], '{"instructions":"triage"}', 'prompt travels as the last argv element on POSIX')+})++test('pi classify()/probe(): a not-logged-in engine surfaces its stderr as the error', { skip: IS_WIN }, async () => {+ const f = await fixture('not-logged-in')+ const res = await getAdapter('pi').classify({ cwd: f.home, prompt: 'x', env: f.env, signal: new AbortController().signal })+ assert.match(res.error ?? '', /No models available/)+ const probe = await getAdapter('pi').probe({ tier: 'big', cwd: f.home, env: f.env, signal: new AbortController().signal })+ assert.match(probe.error ?? '', /No models available/)+})++test('pi classify(): a turn-level model error is an error even though the process exits 0', { skip: IS_WIN }, async () => {+ const f = await fixture('turn-error')+ const res = await getAdapter('pi').classify({ cwd: f.home, prompt: 'x', env: f.env, signal: new AbortController().signal })+ assert.match(res.error ?? '', /rate limit exceeded/)+})++test('pi probeWake() round-trips get_state over rpc; skipped under a CUMORA_PI_ARGS override', { skip: IS_WIN }, async () => {+ const f = await fixture()+ const ok = await getAdapter('pi').probeWake({ cwd: f.home, env: f.env, signal: new AbortController().signal })+ assert.deepEqual(ok, { ok: true, detail: '' })+ const dead = await fixture('die')+ // 'die' only fires on a prompt; get_state still answers → still ok. Kill the+ // fake's answer by pointing PATH at a pi that exits at once instead.+ await writeFile(join(dead.binDir, 'pi'), '#!/bin/sh\necho "fatal: rpc mode unavailable" >&2\nexit 2\n', 'utf8')+ const bad = await getAdapter('pi').probeWake({ cwd: dead.home, env: dead.env, signal: new AbortController().signal })+ assert.equal(bad.ok, false)+ assert.match(bad.detail, /rpc process died before answering get_state .*fatal: rpc mode unavailable/)++ process.env.CUMORA_PI_ARGS = '--custom'+ const skipped = await getAdapter('pi').probeWake({ cwd: f.home, env: f.env, signal: new AbortController().signal })+ assert.equal(skipped.skipped, true)+ assert.equal(getAdapter('pi').startSession?.({ home: f.home, env: f.env, model: null, fastModel: null, onLog: () => {} }), null, 'override → no persistent path')+})diff --git a/server/src/agents/computer/daemon.ts b/server/src/agents/computer/daemon.tsindex 192b772..c83d436 100644--- a/server/src/agents/computer/daemon.ts+++ b/server/src/agents/computer/daemon.ts@@ -2,7 +2,7 @@* `cumora agent computer` — the BYOA daemon.** A long-running process on the user's machine (laptop or VPS) that hosts one- * or more of their Cumora agents, using a local engine (Claude Code / Codex /+ * or more of their Cumora agents, using a local engine (Claude Code / Codex / pi /* Grok Build / Cursor Agent / OpenCode) as each agent's brain. See docs/BYOA.md.** It talks to the Cumora server only over HTTP — no DB/Redis — so it can run@@ -635,6 +635,9 @@ function authFailureHint(engine: EngineId, detail: string): string {if (engine === 'opencode') {return 'Open a terminal on that computer and run `opencode providers login` (or fix the selected provider/model quota), then wake the agent again.'}+ if (engine === 'pi') {+ return 'Open pi on that computer and run `/login` for its provider (or fix the API key / quota), then wake the agent again.'+ }return 'Open Codex on that computer and refresh its login or quota, then wake the agent again.'}@@ -648,6 +651,7 @@ function missingEngineMessage(): string {' - Grok Build: install the `grok` CLI, then run `grok login` once',' - Cursor Agent: install Cursor (the `cursor-agent` CLI ships with it), then run `cursor-agent login`',' - OpenCode: install the `opencode` CLI, then run `opencode providers login` once',+ ' - pi: `npm install -g --ignore-scripts @earendil-works/pi-coding-agent`, then run `pi` once and `/login` a provider','','After that, rerun:',' npx cumora@latest agent computer --pair <code>',@@ -659,7 +663,7 @@ function helpText(): string {'cumora agent computer — run your Cumora agents on THIS machine (BYOA)','','The daemon talks to a Cumora server over HTTP and drives a local agent',- 'engine (Claude Code, Codex, Grok Build, Cursor Agent, or OpenCode). Pair once, then it runs in the background.',+ 'engine (Claude Code, Codex, Grok Build, Cursor Agent, OpenCode, or pi). Pair once, then it runs in the background.','','Usage:',' npx cumora@latest agent computer --pair <code> [--server <url>] [--engine <id>]',@@ -1506,15 +1510,16 @@ class AgentRunner {}}- /** Triage model id for pricing, honoring CUMORA_TRIAGE_MODEL. Cursor and- * OpenCode have no universal cheap alias, so a reported/pinned stream model- * wins and the agent model is only a fallback. */+ /** Triage model id for pricing, honoring CUMORA_TRIAGE_MODEL. Cursor,+ * OpenCode and pi have no universal cheap alias, so a reported/pinned stream+ * model wins and the agent model is only a fallback. */private triageModel(): string {if (process.env.CUMORA_TRIAGE_MODEL) return process.env.CUMORA_TRIAGE_MODELif (this.adapter.id === 'claude') return 'haiku'if (this.adapter.id === 'grok') return 'grok-4.5'if (this.adapter.id === 'codex') return 'gpt-5.4-mini'if (this.adapter.id === 'opencode') return this.agent.model ?? '<opencode-default>'+ if (this.adapter.id === 'pi') return this.agent.model ?? '<pi-default>'return this.agent.model ?? '<cursor-default>'}diff --git a/server/src/agents/computer/engine.ts b/server/src/agents/computer/engine.tsindex 4a43873..4da8ca3 100644--- a/server/src/agents/computer/engine.ts+++ b/server/src/agents/computer/engine.ts@@ -2,8 +2,8 @@* EngineAdapter — the pluggable "brain" for a BYOA agent.** A BYOA agent's reasoning loop is delegated to a local CLI engine running- * on the user's machine: Claude Code, Codex, Grok Build, Cursor Agent, or- * OpenCode. The daemon (daemon.ts) hands+ * on the user's machine: Claude Code, Codex, Grok Build, Cursor Agent,+ * OpenCode, or pi. The daemon (daemon.ts) hands* each wake to an adapter, which spawns the engine headlessly in the agent's* isolated home directory. The engine reads its persona + memory + skills* from that home natively (CLAUDE.md / AGENTS.md, .claude/skills, …) and acts@@ -16,11 +16,12 @@* across engine versions. We pick sensible defaults for an isolated,* user-owned runner and let the user override via env* (CUMORA_CLAUDE_ARGS / CUMORA_CODEX_ARGS / CUMORA_GROK_ARGS /- * CUMORA_CURSOR_ARGS / CUMORA_OPENCODE_ARGS, space-split). Correctness of the+ * CUMORA_CURSOR_ARGS / CUMORA_OPENCODE_ARGS / CUMORA_PI_ARGS, space-split). Correctness of the* loop does not depend on the structured output — the agent acts via the* `cumora` tool regardless of how we parse stdout.*/import { spawn, execFileSync, type ChildProcess } from 'node:child_process'+import { randomUUID } from 'node:crypto'import { mkdir, writeFile, access, mkdtemp } from 'node:fs/promises'import { existsSync, writeFileSync } from 'node:fs'import { homedir, tmpdir } from 'node:os'@@ -87,10 +88,10 @@ export function resolveSpawn(bin: string): { command: string; shell: boolean; wareturn { command: bin, shell: true, wantsStdinPrompt: true }}-export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'+export type EngineId = 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'/** The pairable engine ids, in the daemon's default detection order. */-export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode']+export const ENGINE_IDS: EngineId[] = ['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi']export interface EnginePersona {id: string@@ -2672,12 +2673,620 @@ class OpenCodeAdapter implements EngineAdapter {// wake; --session re-opens the same conversation in that fresh process.}+// ─── pi ──────────────────────────────────────────────────────────────────+//+// pi (https://pi.dev, npm `@earendil-works/pi-coding-agent`) is a multi-provider+// terminal coding agent. Two headless modes matter here, and they share ONE+// event stream (pi's AgentSessionEvent JSONL):+// - `pi --mode json …` one-shot: a `session` header line, then events, exit.+// - `pi --mode rpc` persistent: JSON commands on stdin (`prompt`, `steer`,+// `abort`, `get_state`, …), `response` frames + the same+// events on stdout. LF-delimited on both sides.+// A turn is finished at `agent_settled` — NOT `agent_end`, which pi can follow+// with an automatic retry / queued continuation. Model failures do NOT change+// the process exit code in json/rpc mode: they surface as an assistant message+// with `stopReason: "error" | "aborted"` + `errorMessage`, so we read the stream,+// not the exit status. Verified against pi 0.83.0.++const PI_LOG_RAW = process.env.CUMORA_PI_VERBOSE === '1'++/** pi's per-message token usage (`@earendil-works/pi-ai` Usage). `input`+ * EXCLUDES the cache-read portion — the same convention as Anthropic's+ * input_tokens — so it maps 1:1 onto the Claude-shaped EngineUsage the daemon+ * already prices (cacheWrite ↔ cache_creation, cacheRead ↔ cache_read). */+interface PiUsage { input?: number; output?: number; cacheRead?: number; cacheWrite?: number }++interface PiMessage {+ role?: unknown+ model?: unknown+ usage?: PiUsage+ stopReason?: unknown+ errorMessage?: unknown+ content?: unknown+}++/** The subset of pi's stream we act on (json + rpc). Everything else is logged+ * and ignored, so a new event type in a future pi never breaks a turn. */+interface PiEvent {+ type?: unknown+ id?: unknown+ command?: unknown+ success?: unknown+ error?: unknown+ message?: PiMessage+ data?: { sessionId?: unknown }+ willRetry?: unknown+ messages?: unknown+}++/** Streaming deltas: one line per token / per tool-output chunk. Never logged or+ * kept in the failure tail unless CUMORA_PI_VERBOSE=1 — the same fire-hose gate+ * Codex has (CUMORA_CODEX_VERBOSE). */+function isNoisyPiEvent(ev: PiEvent): boolean {+ return !PI_LOG_RAW && (ev.type === 'message_update' || ev.type === 'tool_execution_update')+}++/** What to log for one pi event. `turn_end` / `agent_end` embed the full+ * message list (the whole transcript slice) — collapse those to a one-liner so a+ * long turn doesn't dump kilobytes into the daemon log per hop; every other+ * event is logged verbatim (message_end included: that's the useful one). */+function piLogLine(ev: PiEvent, raw: string): string {+ if (PI_LOG_RAW) return raw+ if (ev.type === 'agent_end') return `[pi] agent_end (${Array.isArray(ev.messages) ? ev.messages.length : '?'} messages, willRetry=${ev.willRetry === true})`+ if (ev.type === 'turn_end') return '[pi] turn_end'+ return raw+}++function piUsageToEngineUsage(u: PiUsage | undefined): EngineUsage | undefined {+ if (!u || typeof u !== 'object') return undefined+ return {+ input_tokens: Number(u.input ?? 0) || 0,+ output_tokens: Number(u.output ?? 0) || 0,+ cache_read_input_tokens: Number(u.cacheRead ?? 0) || 0,+ cache_creation_input_tokens: Number(u.cacheWrite ?? 0) || 0,+ }+}++/** pi content items are `{type:'text'|'thinking'|'toolCall', …}` — the same+ * question countAssistantContent answers for Claude (did this hop's spend go+ * into tool routing or prose?), with pi's spelling of the tool item. */+function countPiContent(content: unknown): { toolUses: number; textChars: number } {+ if (!Array.isArray(content)) return { toolUses: 0, textChars: 0 }+ let toolUses = 0, textChars = 0+ for (const item of content) {+ if (!item || typeof item !== 'object') continue+ const it = item as { type?: unknown; text?: unknown }+ if (it.type === 'toolCall') toolUses += 1+ else if (it.type === 'text' && typeof it.text === 'string') textChars += it.text.length+ }+ return { toolUses, textChars }+}++function piTextOf(content: unknown): string {+ if (!Array.isArray(content)) return ''+ let out = ''+ for (const item of content) {+ if (!item || typeof item !== 'object') continue+ const it = item as { type?: unknown; text?: unknown }+ if (it.type === 'text' && typeof it.text === 'string') out += it.text+ }+ return out+}++/** Folds pi's event stream into what the daemon wants from a turn: the real+ * session id, ONE EngineHopReport per assistant message, the turn's summed+ * usage + last model (for the run row — pi has no Claude-style `result` total),+ * the assistant's final text (triage reads it), and the first hard error.+ * Shared by the persistent PiSession and the one-shot json spawn so both paths+ * ledger identically — the same split CursorTurnTracker serves for Cursor. */+class PiTurnTracker {+ sessionId: string | null = null+ model: string | null = null+ usage: EngineUsage | undefined+ text = ''+ error: string | null = null+ private hopIndex = 0+ private hopStartedAt: number | null = null++ constructor(private readonly onHopUsage?: (r: EngineHopReport) => void) {}++ /** Reset the per-turn accumulators (a persistent session runs many turns). */+ beginTurn(): void {+ this.usage = undefined+ this.text = ''+ this.error = null+ this.hopIndex = 0+ this.hopStartedAt = null+ }++ /** Feed one event. Returns true when the event terminates the turn. */+ observe(ev: PiEvent): boolean {+ if (ev.type === 'session') {+ if (typeof ev.id === 'string' && ev.id) this.sessionId = ev.id+ return false+ }+ // An assistant message begins streaming = one outbound model call begins.+ if (ev.type === 'message_start' && ev.message?.role === 'assistant' && this.hopStartedAt == null) {+ this.hopStartedAt = Date.now()+ return false+ }+ if (ev.type === 'message_end' && ev.message?.role === 'assistant') {+ const m = ev.message+ const model = typeof m.model === 'string' && m.model ? m.model : null+ if (model) this.model = model+ const usage = piUsageToEngineUsage(m.usage)+ if (usage) this.usage = addEngineUsage(this.usage, usage)+ const text = piTextOf(m.content)+ if (text) this.text = text+ if (m.stopReason === 'error' || m.stopReason === 'aborted') {+ this.error = typeof m.errorMessage === 'string' && m.errorMessage ? m.errorMessage : `pi turn ${String(m.stopReason)}`+ }+ // Per-hop trajectory — same contract as ClaudeSession.onStdout: one report+ // per model call so the universal ledger sees BYOA hops at the same+ // granularity as cloud hops.+ if (usage && model && this.onHopUsage) {+ const startedAt = this.hopStartedAt+ this.hopStartedAt = null+ this.hopIndex += 1+ const { toolUses, textChars } = countPiContent(m.content)+ try {+ this.onHopUsage({ model, usage, latencyMs: startedAt != null ? Date.now() - startedAt : undefined, hopIndex: this.hopIndex, toolUses, textChars })+ } catch { /* ledger is best-effort — never break the stream */ }+ } else {+ this.hopStartedAt = null+ }+ return false+ }+ return ev.type === 'agent_settled'+ }+}++/** Parse one stdout line of pi's stream. Non-JSON lines (banners, warnings that+ * land on stdout) come back as null and are logged verbatim by the caller. */+function parsePiLine(line: string): PiEvent | null {+ if (!line.startsWith('{')) return null+ try { return JSON.parse(line) as PiEvent } catch { return null }+}++/** One-shot `pi --mode json …`: spawn, fold the stream through a+ * PiTurnTracker, resolve on exit. The tracker's error is folded into the+ * result because pi's exit code says nothing about the model call (see the+ * module note above). Text is the last assistant message's text — what+ * classify()/probe() want. */+function spawnPiJson(+ command: string,+ args: string[],+ opts: { cwd: string; env: NodeJS.ProcessEnv; signal: AbortSignal; onLog?: (line: string) => void; shell: boolean; stdinText?: string; onHopUsage?: (r: EngineHopReport) => void },+): Promise<EngineRunResult & { text: string }> {+ return new Promise((resolve) => {+ const tracker = new PiTurnTracker(opts.onHopUsage)+ const child = spawn(command, args, {+ cwd: opts.cwd, env: opts.env,+ stdio: [opts.stdinText != null ? 'pipe' : 'ignore', 'pipe', 'pipe'],+ shell: opts.shell,+ })+ if (opts.stdinText != null) {+ try { child.stdin?.write(opts.stdinText); child.stdin?.end() } catch { /* the 'error' handler resolves */ }+ }+ const onAbort = (): void => { child.kill('SIGTERM') }+ opts.signal.addEventListener('abort', onAbort, { once: true })+ // StringDecoder + carried partial line, for the same reason spawnEngine has+ // them: a pipe read chops a long event (a big message_end) at an arbitrary+ // byte offset, and a naive per-chunk split would hand JSON.parse two halves.+ const decoder = new StringDecoder('utf8')+ let carry = ''+ const stderrTail: string[] = []+ const stdoutTail: string[] = []+ const takeLine = (raw: string): void => {+ const line = cleanLine(raw)+ if (!line) return+ const ev = parsePiLine(line)+ if (ev && isNoisyPiEvent(ev)) return+ const shown = ev ? piLogLine(ev, line) : line+ pushTail(stdoutTail, shown)+ opts.onLog?.(shown)+ if (ev) tracker.observe(ev)+ }+ const pump = (buf: Buffer | null): void => {+ const text = buf === null ? decoder.end() : decoder.write(buf)+ const lines = (carry + text).split('\n')+ carry = buf === null ? '' : (lines.pop() ?? '')+ for (const line of lines) takeLine(line)+ if (buf === null && carry === '' && lines.length === 0) return+ }+ child.stdout?.on('data', (buf: Buffer) => pump(buf))+ child.stderr?.on('data', (buf: Buffer) => {+ for (const raw of buf.toString('utf8').split('\n')) {+ const line = cleanLine(raw)+ if (!line) continue+ pushTail(stderrTail, line)+ opts.onLog?.(line)+ }+ })+ child.on('error', (err) => {+ opts.signal.removeEventListener('abort', onAbort)+ resolve({ exitCode: 1, error: err instanceof Error ? err.message : String(err), sessionId: null, text: '' })+ })+ child.on('close', (code, signalName) => {+ opts.signal.removeEventListener('abort', onAbort)+ pump(null) // flush a final line without a trailing newline+ const procExit = code ?? (signalName ? 128 : 1)+ const exitCode = procExit !== 0 ? procExit : (tracker.error ? 1 : 0)+ const error = procExit !== 0+ ? failurePreview({ exitCode: procExit, signalName, stderr: stderrTail, stdout: stdoutTail })+ : (tracker.error ? `engine turn error: ${tracker.error.slice(0, MAX_FAILURE_CHARS)}` : undefined)+ resolve({ exitCode, error, sessionId: tracker.sessionId, usage: tracker.usage, model: tracker.model, text: tracker.text })+ })+ })+}++/** A persistent pi process for ONE agent, driven over `pi --mode rpc` (see the+ * module note): each `send()` writes ONE `prompt` command and resolves at that+ * turn's `agent_settled`. Steering is native — `steer` is delivered by pi+ * itself before the agent's next model call — so there is no stream-boundary+ * bookkeeping here. The daemon calls send() serially. */+class PiSession implements EngineSession {+ private readonly child: ChildProcess+ private readonly onLog: (line: string) => void+ private readonly tracker: PiTurnTracker+ private readonly decoder = new StringDecoder('utf8')+ private outBuf = ''+ private exited = false+ private exitCode = 0+ private reqId = 0+ private pending: { id: string; resolve: (r: EngineRunResult) => void; stderr: string[]; stdout: string[] } | null = null+ private stderrTail: string[] = []+ private stdoutTail: string[] = []+ private pendingTimer: ReturnType<typeof setTimeout> | null = null+ private stopTimer: ReturnType<typeof setTimeout> | null = null+ readonly carriesStandingPrompt: boolean++ constructor(bin: string, args: string[], opts: EngineSessionArgs, sessionId: string, carriesStandingPrompt: boolean) {+ this.onLog = opts.onLog+ this.tracker = new PiTurnTracker(opts.onHopUsage)+ this.tracker.sessionId = sessionId+ this.carriesStandingPrompt = carriesStandingPrompt+ // Cross-platform spawn (Windows: `pi.cmd` via the shell). Everything travels+ // over stdin as JSON here, so there are no argv-quoting concerns.+ const { command, shell } = resolveSpawn(bin)+ this.child = spawn(command, args, { cwd: opts.home, env: opts.env, stdio: ['pipe', 'pipe', 'pipe'], shell })+ this.child.stdout?.on('data', (b: Buffer) => this.onStdout(b))+ this.child.stderr?.on('data', (b: Buffer) => this.onStderr(b))+ this.child.on('error', (err) => this.die(1, err.message))+ this.child.on('close', (code, signalName) =>+ this.die(code ?? (signalName ? 128 : 1), signalName ? `terminated by ${signalName}` : `exited with code ${code}`))+ // Ask pi which session it actually opened. It should be the --session-id we+ // passed; if a future pi ever rewrites it, we resume the REAL one next time.+ this.write({ id: 'state', type: 'get_state' })+ }++ get alive(): boolean { return !this.exited && this.child.stdin?.writable === true }+ get sessionId(): string | null { return this.tracker.sessionId }++ send(prompt: string): Promise<EngineRunResult> {+ if (this.pending) {+ return Promise.resolve({ exitCode: 1, error: 'engine session busy — a turn is already in flight', sessionId: this.sessionId })+ }+ if (!this.alive) {+ const exitCode = this.exitCode || 1+ const detail = failurePreview({ exitCode, signalName: null, stderr: this.stderrTail, stdout: this.stdoutTail })+ return Promise.resolve({ exitCode, error: detail || 'engine session is not alive (process gone)', sessionId: this.sessionId })+ }+ return new Promise<EngineRunResult>((resolve) => {+ const id = `turn-${++this.reqId}`+ this.pending = { id, resolve, stderr: [], stdout: [] }+ this.tracker.beginTurn()+ // Opt-in runaway backstop only (CUMORA_TURN_TIMEOUT_MS); OFF by default so a+ // legit long task is never killed mid-work. When set: abort the run, fail the+ // turn, tear the process down — the daemon respawns (--session-id) next wake.+ if (TURN_TIMEOUT_MS > 0) {+ this.pendingTimer = setTimeout(() => {+ this.write({ type: 'abort' })+ this.settle({ exitCode: 124, error: `engine turn exceeded CUMORA_TURN_TIMEOUT_MS (${Math.round(TURN_TIMEOUT_MS / 1000)}s) — aborted; session will respawn`, sessionId: this.sessionId })+ this.stop()+ }, TURN_TIMEOUT_MS)+ this.pendingTimer.unref?.()+ }+ if (!this.write({ id, type: 'prompt', message: stripLoneSurrogates(prompt) })) {+ this.settle({ exitCode: 1, error: 'failed to write turn to engine', sessionId: this.sessionId })+ }+ })+ }++ /** Same-turn steering: pi queues the message and delivers it after the current+ * assistant turn's tool calls, before the next model call — the exact "next+ * safe boundary" the Claude path has to compute by hand. No-op when idle (the+ * daemon's normal turn handles it then). */+ steer(text: string): void {+ if (this.pending && this.alive && text.trim()) this.write({ type: 'steer', message: stripLoneSurrogates(text) })+ }++ stop(): void {+ this.exited = true+ if (this.stopTimer) return+ // pi exits cleanly when stdin closes (it disposes the session and returns 0),+ // so close stdin first and only SIGTERM a process that hasn't gone by itself.+ try { this.child.stdin?.end() } catch { /* ignore */ }+ this.stopTimer = setTimeout(() => { try { this.child.kill('SIGTERM') } catch { /* ignore */ } }, 2000)+ this.stopTimer.unref?.()+ }++ private write(msg: object): boolean {+ try { this.child.stdin!.write(`${JSON.stringify(msg)}\n`); return true } catch { return false }+ }++ private onStdout(buf: Buffer): void {+ // StringDecoder so a multi-byte character split across a pipe chunk never+ // becomes U+FFFD inside a JSON line (same fix as the one-shot paths).+ this.outBuf += this.decoder.write(buf)+ let nl: number+ while ((nl = this.outBuf.indexOf('\n')) >= 0) {+ const line = cleanLine(this.outBuf.slice(0, nl))+ this.outBuf = this.outBuf.slice(nl + 1)+ if (!line) continue+ const ev = parsePiLine(line)+ if (ev && isNoisyPiEvent(ev)) continue+ const shown = ev ? piLogLine(ev, line) : line+ pushTail(this.stdoutTail, shown)+ if (this.pending) pushTail(this.pending.stdout, shown)+ this.onLog(shown)+ if (!ev) continue+ if (ev.type === 'response') { this.onResponse(ev); continue }+ // Observe pi's NATIVE auto-compaction (telemetry only), like the Claude path.+ if (ev.type === 'compaction_start') this.onLog('[pi] native context compaction started')+ else if (ev.type === 'compaction_end') this.onLog('[pi] native context compaction finished')+ if (this.tracker.observe(ev) && this.pending) {+ this.settle({+ exitCode: this.tracker.error ? 1 : 0,+ error: this.tracker.error ? `engine turn error: ${this.tracker.error.slice(0, MAX_FAILURE_CHARS)}` : undefined,+ sessionId: this.sessionId,+ usage: this.tracker.usage,+ model: this.tracker.model,+ })+ }+ }+ }++ private onResponse(ev: PiEvent): void {+ if (ev.id === 'state') {+ const sid = ev.data?.sessionId+ if (typeof sid === 'string' && sid) this.tracker.sessionId = sid+ return+ }+ // A prompt rejected BEFORE acceptance (`success:false`) gets no events at all+ // — settle now or the turn would hang until the daemon's timeout.+ if (this.pending && ev.id === this.pending.id && ev.command === 'prompt' && ev.success === false) {+ this.settle({ exitCode: 1, error: `pi rejected the turn: ${typeof ev.error === 'string' && ev.error ? ev.error : 'unknown error'}`, sessionId: this.sessionId })+ }+ }++ private onStderr(buf: Buffer): void {+ for (const raw of buf.toString('utf8').split('\n')) {+ const line = cleanLine(raw)+ if (!line) continue+ pushTail(this.stderrTail, line)+ if (this.pending) pushTail(this.pending.stderr, line)+ this.onLog(line)+ }+ }++ private settle(r: EngineRunResult): void {+ if (this.pendingTimer) { clearTimeout(this.pendingTimer); this.pendingTimer = null }+ const p = this.pending+ this.pending = null+ if (p) p.resolve(r)+ }++ /** Process died (error/close). Mark dead and fail any in-flight turn — always+ * logged, even when idle, for the same reason ClaudeSession does it. */+ private die(code: number, why: string): void {+ const alreadyDown = this.exited+ this.exited = true+ this.exitCode = code+ if (this.stopTimer) { clearTimeout(this.stopTimer); this.stopTimer = null }+ if (!alreadyDown) {+ this.onLog(`[session] engine process died ${this.pending ? 'MID-TURN' : 'while idle'}: ${why} (exit ${code})`)+ }+ if (this.pending) {+ const detail = failurePreview({ exitCode: code, signalName: null, stderr: this.pending.stderr, stdout: this.pending.stdout })+ this.settle({ exitCode: code, error: detail || why, sessionId: this.sessionId })+ }+ }+}++class PiAdapter implements EngineAdapter {+ readonly id = 'pi' as const+ readonly bin = 'pi'++ /** A clean, tool-free, persona-free one-shot: no session file, no built-in /+ * extension tools, no extensions, no skills, no AGENTS.md discovery. The pi+ * analogue of Claude's `--strict-mcp-config` triage spawn. */+ private static readonly BARE = ['--no-session', '--no-tools', '--no-extensions', '--no-skills', '--no-context-files']++ /** BYOA turns are short reactive cycles; extended thinking adds latency and,+ * in a group @all, makes the slowest agent bow out on the "don't duplicate"+ * rule (same reasoning as Claude's MAX_THINKING_TOKENS=0). pi's per-model+ * `provider/id:<level>` suffix is the user's opt-in — when the model carries+ * one, don't fight it. */+ private static thinking(model: string | null | undefined): string[] {+ return model && model.includes(':') ? [] : ['--thinking', 'off']+ }++ private oneShot(prompt: string, args: { cwd: string; env: NodeJS.ProcessEnv; signal: AbortSignal; onLog?: (line: string) => void; model?: string | null }): Promise<EngineRunResult & { text: string }> {+ const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)+ const model = args.model ? ['--model', args.model] : []+ // Windows: the .cmd shim runs via the shell, which can't carry a big+ // multi-line prompt as an argv element → stdin (pi reads a piped stdin as the+ // message when stdin isn't a TTY). POSIX: prompt in argv.+ const base = ['--mode', 'json', ...PiAdapter.BARE, ...PiAdapter.thinking(args.model), ...model]+ return spawnPiJson(command, wantsStdinPrompt ? base : [...base, prompt], {+ cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, shell,+ stdinText: wantsStdinPrompt ? prompt : undefined,+ })+ }++ async classify(args: EngineClassifyArgs): Promise<EngineClassifyResult> {+ // pi is multi-provider, so there is no single cheap "cerebellum" id to hard-+ // code (claude→haiku, codex→gpt-5.4-mini). CUMORA_TRIAGE_MODEL picks one+ // (`provider/id`); unset → pi's own default model, which keeps triage local+ // (never the cloud) at the cost of not being cheaper than the big brain.+ // The json stream names the model that actually ran, so the ledger prices+ // the real one either way.+ const flags = extraArgs('CUMORA_TRIAGE_ARGS')+ if (flags.length) {+ // User-owned flag set → plain print mode, raw text back (mirrors Claude's+ // override path: no envelope to unwrap, no usage).+ const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)+ const base = [...flags, '-p']+ return spawnCapture(command, wantsStdinPrompt ? base : [...base, args.prompt], {+ cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, shell,+ stdinText: wantsStdinPrompt ? args.prompt : undefined,+ })+ }+ const r = await this.oneShot(args.prompt, { cwd: args.cwd, env: args.env, signal: args.signal, onLog: args.onLog, model: args.model })+ return { text: r.text, error: r.error, usage: r.usage, model: r.model }+ }++ async probe(args: EngineProbeArgs): Promise<EngineClassifyResult> {+ // 'small' → whatever triage runs on (CUMORA_TRIAGE_MODEL, else pi's default —+ // the same model as 'big', honestly reported as such); 'big' → pi's default.+ const model = args.tier === 'small' ? (process.env.CUMORA_TRIAGE_MODEL || null) : null+ const r = await this.oneShot(DOCTOR_PROMPT, { cwd: args.cwd, env: args.env, signal: args.signal, model })+ return { text: r.text, error: r.error, usage: r.usage, model: r.model }+ }++ probeWake(args: EngineWakeProbeArgs): Promise<EngineWakeProbeResult> {+ // Same gate as startSession(): a CUMORA_PI_ARGS override collapses the wake to+ // one-shot print mode, which probe() already covers.+ if (extraArgs('CUMORA_PI_ARGS').length) return Promise.resolve({ ok: true, detail: '', skipped: true })+ // The real wake speaks the rpc protocol. The realistic breaks are: `--mode rpc`+ // renamed/removed, or the command/response framing changed. Drive the cheapest+ // round-trip there is — `get_state` needs no model call — and tear down.+ const { command, shell } = resolveSpawn(this.bin)+ return new Promise<EngineWakeProbeResult>((resolve) => {+ let settled = false+ const finish = (r: EngineWakeProbeResult): void => {+ if (settled) return+ settled = true+ try { child.stdin?.end() } catch { /* ignore */ }+ try { child.kill('SIGTERM') } catch { /* ignore */ }+ resolve(r)+ }+ const child = spawn(command, ['--mode', 'rpc', ...PiAdapter.BARE], {+ cwd: args.cwd, env: args.env, stdio: ['pipe', 'pipe', 'pipe'], shell,+ })+ const onAbort = (): void => finish({ ok: false, detail: 'aborted (timeout)' })+ if (args.signal.aborted) { onAbort(); return }+ args.signal.addEventListener('abort', onAbort, { once: true })+ let buf = ''+ let stderrTail = ''+ try { child.stdin?.write(`${JSON.stringify({ id: 'doctor', type: 'get_state' })}\n`) } catch { /* close handler reports */ }+ child.stdout?.on('data', (b: Buffer) => {+ buf += b.toString('utf8')+ for (;;) {+ const nl = buf.indexOf('\n')+ if (nl < 0) break+ const line = buf.slice(0, nl).trim()+ buf = buf.slice(nl + 1)+ const ev = parsePiLine(line)+ if (!ev || ev.type !== 'response' || ev.id !== 'doctor') continue+ if (ev.success === true) finish({ ok: true, detail: '' })+ else finish({ ok: false, detail: `rpc get_state failed: ${typeof ev.error === 'string' ? ev.error.slice(0, 240) : 'unknown error'}` })+ return+ }+ })+ child.stderr?.on('data', (b: Buffer) => {+ const tail = stderrTail + b.toString('utf8')+ stderrTail = tail.length > 2000 ? tail.slice(-2000) : tail+ })+ child.on('error', (err) => finish({ ok: false, detail: `spawn error: ${err.message}` }))+ child.on('close', (code, sig) => {+ if (settled) return+ finish({ ok: false, detail: `rpc process died before answering get_state (${sig ? `terminated by ${sig}` : `exit ${code}`}): ${salientError(stderrTail) || 'no stderr'}` })+ })+ })+ }++ async seedHome(home: string, persona: EnginePersona): Promise<void> {+ await ensureCommonHome(home)+ await mkdir(join(home, '.pi', 'skills'), { recursive: true })+ // Always rewrite AGENTS.md so persona edits land without requiring a fresh+ // home (matches Claude and Codex). pi discovers AGENTS.md from its cwd+ // natively; skills are loaded explicitly via --skill (see startSession) since+ // pi's non-interactive modes ignore project resources in an untrusted dir.+ await writeFile(+ join(home, 'AGENTS.md'),+ PERSONA_HEADER(persona, { personaFile: 'AGENTS.md', skillsDir: '.pi/skills/' }),+ 'utf8',+ )+ }++ async run(args: EngineRunArgs): Promise<EngineRunResult> {+ const flags = extraArgs('CUMORA_PI_ARGS')+ if (flags.length) {+ // User-owned flag set → one-shot print mode with their flags. We still pin+ // the session so context carries across wakes; nothing structured comes+ // back (no stream to sniff), so report the id we passed.+ const sid = args.resumeSessionId ?? randomUUID()+ const { command, shell, wantsStdinPrompt } = resolveSpawn(this.bin)+ const base = [...flags, '--session-id', sid, '-p']+ const r = await spawnEngine(command, wantsStdinPrompt ? base : [...base, args.prompt], args, { shell, stdinText: wantsStdinPrompt ? args.prompt : undefined })+ return { ...r, sessionId: r.sessionId ?? sid }+ }+ // Default: the persistent rpc path is the ONLY protocol we drive, so a one-shot+ // is simply a session that lives for one turn. Same parser, same ledger.+ const session = this.startSession({+ home: args.home, env: args.env, model: args.model, fastModel: args.fastModel,+ resumeSessionId: args.resumeSessionId, onLog: args.onLog, onHopUsage: args.onHopUsage,+ })+ if (!session) return { exitCode: 1, error: 'pi session could not be started', sessionId: args.resumeSessionId ?? null }+ const onAbort = (): void => session.stop()+ args.signal.addEventListener('abort', onAbort, { once: true })+ try {+ return await session.send(args.prompt)+ } finally {+ args.signal.removeEventListener('abort', onAbort)+ session.stop()+ }+ }++ startSession(args: EngineSessionArgs): EngineSession | null {+ // Respect a user's custom flag override by NOT using the persistent path —+ // those flags are tuned for one-shot print mode; fall back to run().+ if (extraArgs('CUMORA_PI_ARGS').length) return null+ // Continuous context across wakes: pin the session id ourselves (`--session-id`+ // creates it when missing, resumes it when present) so a respawn — daemon+ // restart, timeout, crash — picks up where the agent left off.+ const sid = args.resumeSessionId ?? randomUUID()+ const model = args.model ? ['--model', args.model] : []+ // The invariant standing prompt loads ONCE here (not re-sent every turn), so+ // the per-turn stdin messages stay small and pi's native auto-compaction keeps+ // up. `--append-system-prompt` takes a file path.+ let sys: string[] = []+ let carriesStanding = false+ if (args.standingPrompt) {+ const file = join(args.home, '.cumora-standing-prompt.md')+ try { writeFileSync(file, args.standingPrompt, { mode: 0o600 }); sys = ['--append-system-prompt', file]; carriesStanding = true }+ catch { /* couldn't write → leave it; the daemon inlines the standing prompt instead */ }+ }+ const argv = [+ '--mode', 'rpc', '--session-id', sid, ...sys, ...model, ...PiAdapter.thinking(args.model),+ // Load the agent's own skills explicitly: pi's non-interactive modes ignore+ // project-local resources in an untrusted directory, and trusting the home+ // outright (`--approve`) would also enable project settings/extensions.+ '--skill', join(args.home, '.pi', 'skills'),+ ]+ return new PiSession(this.bin, argv, args, sid, carriesStanding)+ }+}+const ADAPTERS: Record<EngineId, EngineAdapter> = {claude: new ClaudeAdapter(),codex: new CodexAdapter(),grok: new GrokAdapter(),cursor: new CursorAdapter(),opencode: new OpenCodeAdapter(),+ pi: new PiAdapter(),}export function getAdapter(id: EngineId): EngineAdapter {diff --git a/server/src/agents/computer/registry.ts b/server/src/agents/computer/registry.tsindex c1bff33..da76535 100644--- a/server/src/agents/computer/registry.ts+++ b/server/src/agents/computer/registry.ts@@ -20,7 +20,7 @@ import { publish, CH_STATUS } from '../../redis.js'import { signAgentToken } from '../runtime/jwt.js'export type ComputerKind = 'cloud' | 'local' | 'vps'-export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'export type ComputerStatus = 'online' | 'offline' | 'busy'/** How long a paired computer can go without a heartbeat before the sweep@@ -45,7 +45,7 @@ export async function announceComputerOnline(computerId: string, companyId: stri}/** Engines a paired (non-cloud) computer is allowed to advertise. */-const PAIRABLE_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex', 'grok', 'cursor', 'opencode'])+const PAIRABLE_ENGINES: ReadonlySet<string> = new Set(['claude', 'codex', 'grok', 'cursor', 'opencode', 'pi'])/** Merge a fresh PATH detection into a computer's advertised engine list.*@@ -407,7 +407,7 @@ export async function mintAgentRuntimeToken(args: {* When a row has no explicit model, fall back to the deploy-level default* (CUMORA_DEFAULT_CLAUDE_MODEL / CUMORA_DEFAULT_CODEX_MODEL /* CUMORA_DEFAULT_GROK_MODEL / CUMORA_DEFAULT_CURSOR_MODEL /- * CUMORA_DEFAULT_OPENCODE_MODEL) so every BYOA+ * CUMORA_DEFAULT_OPENCODE_MODEL / CUMORA_DEFAULT_PI_MODEL) so every BYOA* daemon gets a consistent pin — independent of whatever model the local* engine CLI happens to default to today. Critical: a model* upgrade in the underlying CLI (e.g. claude 4.7 → 4.8) silently changes@@ -426,6 +426,7 @@ export async function listAgentsForComputer(computerId: string): Promise<const grokDefault = process.env.CUMORA_DEFAULT_GROK_MODEL?.trim() || nullconst cursorDefault = process.env.CUMORA_DEFAULT_CURSOR_MODEL?.trim() || nullconst openCodeDefault = process.env.CUMORA_DEFAULT_OPENCODE_MODEL?.trim() || null+ const piDefault = process.env.CUMORA_DEFAULT_PI_MODEL?.trim() || nullreturn rows.map((r) => {if (r.model) return rconst dflt = r.engine === 'codex'@@ -438,7 +439,9 @@ export async function listAgentsForComputer(computerId: string): Promise<? cursorDefault: r.engine === 'opencode'? openCodeDefault- : null+ : r.engine === 'pi'+ ? piDefault+ : nullreturn dflt ? { ...r, model: dflt } : r})}diff --git a/server/src/agents/llm-ledger.ts b/server/src/agents/llm-ledger.tsindex 6525bfa..d0bafdb 100644--- a/server/src/agents/llm-ledger.ts+++ b/server/src/agents/llm-ledger.ts@@ -71,7 +71,7 @@ export type LlmCallPurpose =| 'agent-image'export type LlmCallStatus = 'ok' | 'rate_limited' | 'timeout' | 'failed'-export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi'/** Context bound to a tracked client. Every LLM call it makes carries this* shape into the ledger. `purpose` is mandatory; everything else scopes thediff --git a/server/src/agents/observability.ts b/server/src/agents/observability.tsindex 543f151..1295ad6 100644--- a/server/src/agents/observability.ts+++ b/server/src/agents/observability.ts@@ -3,7 +3,7 @@ import { pool } from '../db/pool.js'import { effectiveCostUsd, priceFor, modelPriceTable, EMPTY_USAGE, type TokenUsage } from './cost.js'export type AgentRunStatus = 'running' | 'completed' | 'failed' | 'skipped'-export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'+export type TriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi'export type AgentEventLevel = 'debug' | 'info' | 'warn' | 'error'const MAX_STRING_CHARS = 24_000diff --git a/server/src/agents/runtime/server.ts b/server/src/agents/runtime/server.tsindex 55c0b40..f70a9c5 100644--- a/server/src/agents/runtime/server.ts+++ b/server/src/agents/runtime/server.ts@@ -421,7 +421,7 @@ runtimeRouter.post('/triage', withAgent(async (c, req, res) => {// per turn-completed (Codex) and batches them into one POST per N hops or// every ~250ms (whichever first). This endpoint accepts a batch + inserts// one llm_calls row per hop with the appropriate source ('byoa-claude' |-// 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode').+// 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi').// Fire-and-forget; a DB hiccup must never break the wake.runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {const body = req.body as {@@ -445,7 +445,7 @@ runtimeRouter.post('/llm-calls', withAgent(async (c, req, res) => {const source = (body?.source === 'byoa-claude' || body?.source === 'byoa-codex' ||body?.source === 'byoa-grok' || body?.source === 'byoa-cursor' ||- body?.source === 'byoa-opencode'+ body?.source === 'byoa-opencode' || body?.source === 'byoa-pi') ? body.source : 'byoa-claude'const daemonVersion = typeof body?.daemonVersion === 'string' && body.daemonVersion.trim() ? body.daemonVersion.trim().slice(0, 32) : nullconst hops = Array.isArray(body?.hops) ? body!.hops : []diff --git a/server/src/api/router.ts b/server/src/api/router.tsindex 6de161a..d9ffa19 100644--- a/server/src/api/router.ts+++ b/server/src/api/router.ts@@ -1101,7 +1101,7 @@ api.post('/computers/pair', safe(async (req, res) => {if ((await companyTier(paired.companyId)) === 'free') {const engine = (engines[0] === 'claude' || engines[0] === 'codex' || engines[0] === 'grok' ||- engines[0] === 'cursor' || engines[0] === 'opencode'+ engines[0] === 'cursor' || engines[0] === 'opencode' || engines[0] === 'pi') ? engines[0] : 'claude'// Adopt only agents that are stranded on the managed Cumora Cloud (or// unassigned) onto the just-paired machine — earlier builds' boot backfilldiff --git a/server/src/db/migrate.ts b/server/src/db/migrate.tsindex e1b8fd0..43e59e9 100644--- a/server/src/db/migrate.ts+++ b/server/src/db/migrate.ts@@ -212,7 +212,7 @@ CREATE TABLE IF NOT EXISTS agent_triages (id TEXT PRIMARY KEY,agent_id TEXT NOT NULL,company_id TEXT,- source TEXT NOT NULL, -- cloud | byoa-claude | byoa-codex | byoa-grok | byoa-cursor | byoa-opencode+ source TEXT NOT NULL, -- cloud | byoa-claude | byoa-codex | byoa-grok | byoa-cursor | byoa-opencode | byoa-pimodel TEXT,actionable BOOLEAN NOT NULL DEFAULT FALSE, -- verdict: woke the big brain?reason TEXT,@@ -1473,7 +1473,7 @@ CREATE TABLE IF NOT EXISTS computers (owner_user_id TEXT, -- NULL for the managed Cumora Cloud rowname TEXT NOT NULL, -- "Cumora Cloud", "MacBook Pro", "prod-vps-01"kind TEXT NOT NULL, -- 'cloud' | 'local' | 'vps'- available_engines JSONB NOT NULL DEFAULT '[]'::jsonb, -- ['claude','codex','grok','cursor','opencode']; ['managed'] for cloud+ available_engines JSONB NOT NULL DEFAULT '[]'::jsonb, -- ['claude','codex','grok','cursor','opencode','pi']; ['managed'] for cloudstatus TEXT NOT NULL DEFAULT 'offline', -- 'online' | 'offline' | 'busy'last_seen_at TIMESTAMP WITH TIME ZONE,credential_hash TEXT, -- SHA256 of the device token; NULL for cloud@@ -1495,7 +1495,7 @@ ALTER TABLE computers ADD COLUMN IF NOT EXISTS daemon_supervised BOOLEAN;-- a 'cloud' computer, means managed (current pod behavior). A 'local' /-- 'vps' computer means BYOA: wakes go to the paired daemon, no pod.ALTER TABLE participants ADD COLUMN IF NOT EXISTS computer_id TEXT;-ALTER TABLE participants ADD COLUMN IF NOT EXISTS engine TEXT; -- 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'+ALTER TABLE participants ADD COLUMN IF NOT EXISTS engine TEXT; -- 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'-- Per-agent model overrides. "model" (added earlier) is the big-brain / main-- reasoning model; "fast_model" is the small-brain model for cheap auxiliary-- work. For BYOA agents these pass through to the engine as --model (big) and,diff --git a/src/admin/api.ts b/src/admin/api.tsindex 34ee47b..8679c57 100644--- a/src/admin/api.ts+++ b/src/admin/api.ts@@ -120,7 +120,7 @@ export type LlmCallPurpose =| 'palette' | 'gender' | 'avatar-image' | 'agent-image'export type LlmCallStatus = 'ok' | 'rate_limited' | 'timeout' | 'failed'-export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'+export type LlmCallSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi'export interface LlmSummary {sinceDays: numberdiff --git a/src/api/client.ts b/src/api/client.tsindex 7985187..8f4f2e7 100644--- a/src/api/client.ts+++ b/src/api/client.ts@@ -401,7 +401,7 @@ export interface ApiAgentRun {}// ── Triage cost-effectiveness ledger ──-export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode'+export type ApiTriageSource = 'cloud' | 'byoa-claude' | 'byoa-codex' | 'byoa-grok' | 'byoa-cursor' | 'byoa-opencode' | 'byoa-pi'export interface ApiTriageAgentRow {agentId: stringdiff --git a/src/components/AgentEditor.tsx b/src/components/AgentEditor.tsxindex 8ad207c..7f310ab 100644--- a/src/components/AgentEditor.tsx+++ b/src/components/AgentEditor.tsx@@ -241,7 +241,7 @@ export function AgentEditor({ agent, onClose }: Props) {<Fieldlabel={isByoa ? t('agent.modelLabelByoa') : t('agent.modelLabel')}hint={isByoa- ? `${t('agent.modelHintByoaPrefix')} ${engine === 'codex' ? t('agent.modelHintByoaCodex') : engine === 'grok' ? t('agent.modelHintByoaGrok') : engine === 'cursor' ? t('agent.modelHintByoaCursor') : engine === 'opencode' ? t('agent.modelHintByoaOpenCode') : t('agent.modelHintByoaClaude')} ${t('agent.modelHintByoaSuffix')}`+ ? `${t('agent.modelHintByoaPrefix')} ${engine === 'codex' ? t('agent.modelHintByoaCodex') : engine === 'grok' ? t('agent.modelHintByoaGrok') : engine === 'cursor' ? t('agent.modelHintByoaCursor') : engine === 'opencode' ? t('agent.modelHintByoaOpenCode') : engine === 'pi' ? t('agent.modelHintByoaPi') : t('agent.modelHintByoaClaude')} ${t('agent.modelHintByoaSuffix')}`: t('agent.modelHintCloud')}><Input@@ -265,7 +265,9 @@ export function AgentEditor({ agent, onClose }: Props) {? t('agent.fastHintByoaCursor'): engine === 'opencode'? t('agent.fastHintByoaOpenCode')- : t('agent.fastHintByoaClaude')}+ : engine === 'pi'+ ? t('agent.fastHintByoaPi')+ : t('agent.fastHintByoaClaude')}><Inputtype="text"diff --git a/src/desktop/MeView.tsx b/src/desktop/MeView.tsxindex aca7aa4..316201d 100644--- a/src/desktop/MeView.tsx+++ b/src/desktop/MeView.tsx@@ -759,7 +759,7 @@ function SkypeSoundSection() {// Brand and engine names stay in English in every locale. The values// below are display labels surfaced to users when we list computers —// products keep their own casing.-const ENGINE_LABEL: Record<string, string> = { managed: 'Cumora', claude: 'Claude Code', codex: 'Codex', grok: 'Grok Build', cursor: 'Cursor', opencode: 'OpenCode' }+const ENGINE_LABEL: Record<string, string> = { managed: 'Cumora', claude: 'Claude Code', codex: 'Codex', grok: 'Grok Build', cursor: 'Cursor', opencode: 'OpenCode', pi: 'pi' }const KIND_ICON: Record<string, string> = { cloud: '☁', local: '💻', vps: '🖥' }const STATUS_COLOR: Record<string, string> = { online: '#3BB273', busy: '#E6A23C', offline: 'var(--ink-300)' }@@ -775,7 +775,7 @@ function ComputersTab() {// Engine for a NEWLY added computer's starter/assigned agents. Claude is the// default (no flag → daemon auto-detects); every other pick is named// explicitly, or the daemon auto-detects and engines[0] silently wins.- const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'>('claude')+ const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'>('claude')// Default on: install the always-on service (auto-start/restart/update).const [asService, setAsService] = useState(true)// Per-computer re-pair (reconnect) command, keyed by computer id.@@ -921,7 +921,7 @@ function ComputersTab() {<div className="flex items-center gap-2.5 mb-2.5"><span className="text-[12px] text-ink-500">{t('me.engineLabel')}</span><div className="inline-flex rounded-[9px] p-0.5" style={{ background: 'var(--ink-100)' }}>- {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor'], ['opencode', 'OpenCode']] as const).map(([id, label]) => (+ {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor'], ['opencode', 'OpenCode'], ['pi', 'pi']] as const).map(([id, label]) => (<button key={id} type="button" onClick={() => setEngine(id)}className="px-3 py-1 rounded-[7px] text-[12px] font-semibold transition-colors duration-150"style={engine === iddiff --git a/src/desktop/Onboarding.tsx b/src/desktop/Onboarding.tsxindex da40d45..936ce83 100644--- a/src/desktop/Onboarding.tsx+++ b/src/desktop/Onboarding.tsx@@ -21,7 +21,7 @@ export function Onboarding() {// Claude is the default; ANY other pick must be named explicitly. We DON'T// append `--engine claude` so a Claude-less machine still auto-detects rather// than erroring on a Claude it doesn't have.- const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'>('claude')+ const [engine, setEngine] = useState<'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'>('claude')// Default to installing the always-on service: it auto-starts at sign-in,// auto-restarts on crash, and auto-updates — so the user isn't tied to a// terminal that must stay open. Appends `--install-service` to the command.@@ -87,7 +87,7 @@ export function Onboarding() {<div className="flex items-center gap-2.5 mb-2.5"><span className="text-[12px] text-ink-500">{t('onboard.engine')}</span><div className="inline-flex rounded-[9px] p-0.5" style={{ background: 'var(--ink-100)' }}>- {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor'], ['opencode', 'OpenCode']] as const).map(([id, label]) => (+ {([['claude', 'Claude Code'], ['codex', 'Codex'], ['grok', 'Grok Build'], ['cursor', 'Cursor'], ['opencode', 'OpenCode'], ['pi', 'pi']] as const).map(([id, label]) => (<button key={id} type="button" onClick={() => setEngine(id)}className="px-3 py-1 rounded-[7px] text-[12px] font-semibold transition-colors duration-150"style={engine === iddiff --git a/src/locales/en.ts b/src/locales/en.tsindex 008a402..7421d6f 100644--- a/src/locales/en.ts+++ b/src/locales/en.ts@@ -451,6 +451,7 @@ export const en = {'agent.modelHintByoaGrok': 'A Grok model (e.g. grok-4.6).','agent.modelHintByoaCursor': 'A Cursor model id or alias; blank = Auto.','agent.modelHintByoaOpenCode': 'An OpenCode provider/model id (e.g. anthropic/claude-sonnet-4-6).',+ 'agent.modelHintByoaPi': 'A pi model pattern, ideally provider/id (e.g. anthropic/claude-sonnet-4-6); add :<level> to enable thinking.','agent.modelHintByoaClaude': "A Claude alias or full name (e.g. opus, sonnet, claude-sonnet-4-6).",'agent.modelHintByoaSuffix': 'Blank = engine default.','agent.modelHintCloud': 'Optional — leave blank to use the system default. Any OpenAI model name works (e.g. gpt-5.5, gpt-5.5-pro, gpt-5.5-mini). Prefix with novita/ to run this agent on Novita instead (e.g. novita/deepseek/deepseek-v3.2).',@@ -459,6 +460,7 @@ export const en = {'agent.fastHintByoaGrok': 'Cheaper/faster Grok model for light auxiliary tasks (e.g. grok-4.5). Blank = engine default.','agent.fastHintByoaCursor': 'Not used by Cursor; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = Auto.','agent.fastHintByoaOpenCode': 'Not used by OpenCode; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = OpenCode default.',+ 'agent.fastHintByoaPi': 'Not used by pi; triage follows CUMORA_TRIAGE_MODEL on the computer. Blank = pi default.','agent.fastHintByoaClaude': "Cheaper/faster model for light auxiliary tasks — maps to Claude's ANTHROPIC_SMALL_FAST_MODEL. Blank = engine default.",'agent.defaultPh': '(default)','agent.runsOnLabel': 'Runs on',diff --git a/src/locales/zh-CN.ts b/src/locales/zh-CN.tsindex 454da87..1cf3a51 100644--- a/src/locales/zh-CN.ts+++ b/src/locales/zh-CN.ts@@ -453,6 +453,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {'agent.modelHintByoaGrok': 'Grok 模型(例如 grok-4.6)。','agent.modelHintByoaCursor': 'Cursor 模型 id 或别名;留空 = Auto。','agent.modelHintByoaOpenCode': 'OpenCode 的 provider/model id(例如 anthropic/claude-sonnet-4-6)。',+ 'agent.modelHintByoaPi': 'pi 的模型匹配串,建议用 provider/id(例如 anthropic/claude-sonnet-4-6);加 :<level> 后缀可开启思考。','agent.modelHintByoaClaude': 'Claude 别名或全名(例如 opus、sonnet、claude-sonnet-4-6)。','agent.modelHintByoaSuffix': '留空 = 使用引擎默认。','agent.modelHintCloud': '可选 — 留空使用系统默认。任意 OpenAI 模型名都可以(例如 gpt-5.5、gpt-5.5-pro、gpt-5.5-mini)。加 novita/ 前缀可改走 Novita(例如 novita/deepseek/deepseek-v3.2)。',@@ -461,6 +462,7 @@ export const zhCN: Partial<Record<keyof typeof en, string>> = {'agent.fastHintByoaGrok': '处理轻量辅助任务的更快更便宜的 Grok 模型(例如 grok-4.5)。留空 = 引擎默认。','agent.fastHintByoaCursor': 'Cursor 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = Auto。','agent.fastHintByoaOpenCode': 'OpenCode 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = OpenCode 默认模型。',+ 'agent.fastHintByoaPi': 'pi 用不到这一项;分流跟随该计算机上的 CUMORA_TRIAGE_MODEL。留空 = pi 默认模型。','agent.fastHintByoaClaude': "更便宜、更快的轻量任务模型 —— 对应 Claude 的 ANTHROPIC_SMALL_FAST_MODEL。留空 = 引擎默认。",'agent.defaultPh': '(默认)','agent.runsOnLabel': '运行于',diff --git a/src/types.ts b/src/types.tsindex 2a870e6..643550c 100644--- a/src/types.ts+++ b/src/types.ts@@ -7,7 +7,7 @@ export type Status = 'avail' | 'working' | 'thinking' | 'waiting' | 'resting'export type ComputerKind = 'cloud' | 'local' | 'vps'export type ComputerStatus = 'online' | 'offline' | 'busy'/** Engine an agent's host runs it on. 'managed' = Cumora's server-side loop. */-export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode'+export type EngineId = 'managed' | 'claude' | 'codex' | 'grok' | 'cursor' | 'opencode' | 'pi'export interface Computer {id: string