⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
feat(runner): add Pi and Oh My Pi unattended presets (#421)
Sinming1956a144551f
diff --git a/apps/web/messages/ar/teams.json b/apps/web/messages/ar/teams.jsonindex e855cb36..cd2de774 100644--- a/apps/web/messages/ar/teams.json+++ b/apps/web/messages/ar/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "على الجهاز اللي هيشغّل المنفّذ. المنفّذ مش هيقدر يسجّل دخولك بدالك.","runnerHelpRun": "احفظ الملفات في المكان اللي الوكيل هيشتغل فيه","runnerHelpTabCustom": "بتاعك إنت",+ "runnerHelpPiAdapter": "بي يقرأ .mcp.json عن طريق إضافة. ثبّتها مرة واحدة: pi install npm:pi-mcp-adapter","runnerHelpCheck": "اتأكد إنه متوصّل","runnerHelpCheckHint": "قسم المنفّذ هيبان فيه «شغّال».","runnerOnline": "المنفّذ شغّال",diff --git a/apps/web/messages/en/teams.json b/apps/web/messages/en/teams.jsonindex f7c6273f..2dac1e62 100644--- a/apps/web/messages/en/teams.json+++ b/apps/web/messages/en/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "On the machine that will run the runner. The runner cannot sign in for you.","runnerHelpRun": "Save the files where the agent should work","runnerHelpTabCustom": "Your own",+ "runnerHelpPiAdapter": "Pi reads .mcp.json through an extension. Install it once: pi install npm:pi-mcp-adapter","runnerHelpCheck": "Check it is connected","runnerHelpCheckHint": "The Runner section shows Online.","runnerOnline": "Runner online",diff --git a/apps/web/messages/es-ES/teams.json b/apps/web/messages/es-ES/teams.jsonindex 70c9532c..1af74675 100644--- a/apps/web/messages/es-ES/teams.json+++ b/apps/web/messages/es-ES/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "En la máquina que ejecutará al ejecutor. El ejecutor no puede iniciar sesión por ti.","runnerHelpRun": "Guardar los ficheros donde el agente tiene que trabajar","runnerHelpTabCustom": "El tuyo propio",+ "runnerHelpPiAdapter": "Pi lee .mcp.json mediante una extensión. Instálala una vez: pi install npm:pi-mcp-adapter","runnerHelpCheck": "Comprobar que está conectado","runnerHelpCheckHint": "La sección Ejecutor muestra En línea.","runnerOnline": "Ejecutor en línea",diff --git a/apps/web/messages/fr/teams.json b/apps/web/messages/fr/teams.jsonindex 85babb04..0682aa24 100644--- a/apps/web/messages/fr/teams.json+++ b/apps/web/messages/fr/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "Sur la machine qui fera tourner le runner. Le runner ne peut pas se connecter à votre place.","runnerHelpRun": "Enregistrez les fichiers là où l'agent doit travailler","runnerHelpTabCustom": "Le vôtre",+ "runnerHelpPiAdapter": "Pi lit .mcp.json via une extension. Installez-la une fois : pi install npm:pi-mcp-adapter","runnerHelpCheck": "Vérifiez qu'il est connecté","runnerHelpCheckHint": "La section Runner affiche En ligne.","runnerOnline": "Runner en ligne",diff --git a/apps/web/messages/id/teams.json b/apps/web/messages/id/teams.jsonindex 96242be8..2b4f3b63 100644--- a/apps/web/messages/id/teams.json+++ b/apps/web/messages/id/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "Di mesin yang akan menjalankan runner. Runner tidak dapat masuk untuk Anda.","runnerHelpRun": "Simpan file di tempat agen harus bekerja","runnerHelpTabCustom": "Milik Anda sendiri",+ "runnerHelpPiAdapter": "Pi membaca .mcp.json melalui ekstensi. Pasang sekali: pi install npm:pi-mcp-adapter","runnerHelpCheck": "Periksa apakah terhubung","runnerHelpCheckHint": "Bagian Runner menampilkan Online.","runnerOnline": "Runner online",diff --git a/apps/web/messages/pt-BR/teams.json b/apps/web/messages/pt-BR/teams.jsonindex 447ceafc..0d3688ce 100644--- a/apps/web/messages/pt-BR/teams.json+++ b/apps/web/messages/pt-BR/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "Na máquina que vai rodar o runner. O runner não consegue entrar por você.","runnerHelpRun": "Salvar os arquivos onde o agente deve trabalhar","runnerHelpTabCustom": "O seu",+ "runnerHelpPiAdapter": "O Pi lê o .mcp.json por meio de uma extensão. Instale-a uma vez: pi install npm:pi-mcp-adapter","runnerHelpCheck": "Verificar se está conectado","runnerHelpCheckHint": "A seção Runner mostra Online.","runnerOnline": "Runner online",diff --git a/apps/web/messages/ru/teams.json b/apps/web/messages/ru/teams.jsonindex 44666693..b7cd0367 100644--- a/apps/web/messages/ru/teams.json+++ b/apps/web/messages/ru/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "На машине, где будет работать раннер. Сам он войти за вас не может.","runnerHelpRun": "Сохраните файлы там, где агент должен работать","runnerHelpTabCustom": "Своя команда",+ "runnerHelpPiAdapter": "Pi читает .mcp.json через расширение. Установите его один раз: pi install npm:pi-mcp-adapter","runnerHelpCheck": "Проверьте связь","runnerHelpCheckHint": "В секции «Раннер» появится «На связи».","runnerOnline": "Раннер на связи",diff --git a/apps/web/messages/uk/teams.json b/apps/web/messages/uk/teams.jsonindex a54e16c4..5d254352 100644--- a/apps/web/messages/uk/teams.json+++ b/apps/web/messages/uk/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "На машині, де працюватиме раннер. Сам він увійти за вас не може.","runnerHelpRun": "Збережіть файли там, де агент має працювати","runnerHelpTabCustom": "Своя команда",+ "runnerHelpPiAdapter": "Pi читає .mcp.json через розширення. Встановіть його один раз: pi install npm:pi-mcp-adapter","runnerHelpCheck": "Перевірте зв'язок","runnerHelpCheckHint": "У секції «Раннер» з'явиться «На зв'язку».","runnerOnline": "Раннер на зв'язку",diff --git a/apps/web/messages/zh-CN/teams.json b/apps/web/messages/zh-CN/teams.jsonindex c854f5b0..49be3bb1 100644--- a/apps/web/messages/zh-CN/teams.json+++ b/apps/web/messages/zh-CN/teams.json@@ -394,6 +394,7 @@"runnerHelpToolHint": "在将要运行运行器的机器上。运行器无法替你登录。","runnerHelpRun": "把这些文件保存到智能体要工作的目录","runnerHelpTabCustom": "自定义",+ "runnerHelpPiAdapter": "Pi 通过扩展读取 .mcp.json。安装一次即可:pi install npm:pi-mcp-adapter","runnerHelpCheck": "确认已连接","runnerHelpCheckHint": "“运行器”一节会显示“在线”。","runnerOnline": "运行器在线",diff --git a/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsx b/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsxindex 6cbd4226..4cc51d05 100644--- a/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsx+++ b/apps/web/src/features/teams/components/ai-agents/AgentRunnerHelpSheet.tsx@@ -1,7 +1,14 @@-import { HelpCircle } from 'lucide-react';+import { HelpCircle, MoreHorizontal } from 'lucide-react';import { useTranslations } from 'next-intl';+import { useState } from 'react';import { API_URL } from '@/lib/api/core/client';import { Button } from '@/components/ui/button';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';import { AgentRunnerCodeBlock } from './AgentRunnerCodeBlock';@@ -100,14 +107,6 @@ const AGENTS = [args: ['--skip-git-repo-check'],files: [{ name: '~/.codex/config.toml', code: CODEX_TOML }],},- {- id: 'antigravity',- label: 'Antigravity CLI',- // The binary is `agy`. It has to be signed in once interactively: a headless run- // uses the credentials that session cached.- agent: 'antigravity',- files: [{ name: '~/.gemini/config/mcp_config.json', code: ANTIGRAVITY_MCP }],- },{id: 'copilot',label: 'Copilot CLI',@@ -121,6 +120,31 @@ const AGENTS = [agent: 'opencode',files: [{ name: 'opencode.json', code: OPENCODE_JSON }],},+ {+ id: 'antigravity',+ label: 'Antigravity CLI',+ // The binary is `agy`. It has to be signed in once interactively: a headless run+ // uses the credentials that session cached.+ agent: 'antigravity',+ files: [{ name: '~/.gemini/config/mcp_config.json', code: ANTIGRAVITY_MCP }],+ },+ {+ id: 'pi',+ label: 'Pi',+ // Pi reaches an MCP server through an extension rather than on its own, and the+ // extension is what reads .mcp.json from the directory the run starts in.+ agent: 'pi',+ note: 'runnerHelpPiAdapter',+ files: [{ name: '.mcp.json', code: MCP_JSON }],+ },+ {+ id: 'omp',+ label: 'Oh My Pi',+ // The binary is `omp`. It reads .mcp.json from the directory it runs in and+ // interpolates the variable in the header, so the key stays out of the file.+ agent: 'omp',+ files: [{ name: '.mcp.json', code: MCP_JSON }],+ },// A command of its own turns the preset off: the runner then knows nothing about// what it runs, keeps no session for it, and hands it the task on stdin.{@@ -131,6 +155,12 @@ const AGENTS = [},] as const;+// The CLIs most operators reach for keep a tab of their own; the rest sit behind the+// menu at the end of the row, which is what keeps the row from outgrowing the sheet as+// presets are added. The count is fixed rather than measured: the labels are short and+// known, and a row that re-counted itself on resize would move under the pointer.+const TABBED = 4;+// Only what the runner cannot work out on its own. `cwd` is where the agent's files// and the MCP config above are read from; concurrency, poll interval and timeout keep// their defaults.@@ -156,6 +186,11 @@ export const RUN_COMMAND = 'npx -y @itsaplan/runner';export function AgentRunnerHelpSheet() {const t = useTranslations('teams.agents');+ const tCommon = useTranslations('common');+ const [agent, setAgent] = useState<string>('claude');+ const hidden = AGENTS.slice(TABBED).find((a) => a.id === agent);+ const labelOf = (a: (typeof AGENTS)[number]) =>+ a.id === 'custom' ? t('runnerHelpTabCustom') : a.label;return (<Sheet>@@ -186,16 +221,38 @@ export function AgentRunnerHelpSheet() {</AgentRunnerHelpStep><AgentRunnerHelpStep n={4} title={t('runnerHelpRun')}>- <Tabs defaultValue="claude">+ <Tabs value={agent} onValueChange={setAgent}><TabsList variant="line">- {AGENTS.map((a) => (+ {AGENTS.slice(0, TABBED).map((a) => (<TabsTrigger key={a.id} value={a.id}>- {a.id === 'custom' ? t('runnerHelpTabCustom') : a.label}+ {labelOf(a)}</TabsTrigger>))}+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ type="button"+ // Matches TabsTrigger's line variant, and reads as the active tab+ // while the agent chosen from it is the one shown.+ data-state={hidden ? 'active' : 'inactive'}+ className="relative -mb-px inline-flex h-full items-center gap-1 border-b-2 border-transparent px-1 py-1 text-sm font-medium whitespace-nowrap text-muted-foreground transition-colors data-[state=active]:border-foreground data-[state=active]:text-foreground"+ >+ {hidden ? labelOf(hidden) : tCommon('more')}+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start">+ {AGENTS.slice(TABBED).map((a) => (+ <DropdownMenuItem key={a.id} onSelect={() => setAgent(a.id)}>+ {labelOf(a)}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu></TabsList>{AGENTS.map((a) => (<TabsContent key={a.id} value={a.id} className="space-y-3 pt-3">+ {'note' in a && <p className="text-xs text-muted-foreground">{t(a.note)}</p>}{a.files.map((f) => (<div key={f.name} className="space-y-1.5"><p className="font-mono text-xs text-muted-foreground">{f.name}</p>diff --git a/docs/runner.md b/docs/runner.mdindex 29898830..b68df863 100644--- a/docs/runner.md+++ b/docs/runner.md@@ -1,7 +1,7 @@# Coding agent setup[`@itsaplan/runner`](https://www.npmjs.com/package/@itsaplan/runner) runs an external agent-on your own machine. It has a preset for each of five coding agent CLIs. A preset builds+on your own machine. It has a preset for each of seven coding agent CLIs. A preset buildsthe command itself: the flags for an unattended run, and the session resume.Each preset needs two files in the working directory:@@ -202,3 +202,82 @@ thus stays out of the file:- Set `model` as `provider/model`. opencode supports many providers. Without this key, arun uses the model of the last interactive session. Run `opencode auth login` to make aprovider available.++## Pi++Pi reads MCP servers through the `pi-mcp-adapter` extension. Install it once:++```bash+pi install npm:pi-mcp-adapter+```++The extension reads `.mcp.json` from the working directory:++```json+{+ "mcpServers": {+ "itsaplan": {+ "type": "http",+ "url": "http://localhost:3000/mcp",+ "headers": { "Authorization": "Bearer ${ITSAPLAN_API_KEY}" }+ }+ }+}+```++`itsaplan-runner.json`:++```json+{+ "url": "http://localhost:3000",+ "apiKey": "the key you copied on creation",+ "agent": "pi",+ "cwd": "/path/to/working-dir"+}+```++- The preset passes `-p --mode json`. The stream gives the chat answer word by word, the+ tool calls, and the session id on the first line. `--session-id` resumes that session.+- `--append-system-prompt` gives Pi the context of the run.+- Print mode does not wait for tool approval. `--approve` is only project-trust for+ `.pi/settings.json`, not tool permission.+- Sign in once with `pi` interactively so a provider is available.+- Headers in `.mcp.json` expand `${ITSAPLAN_API_KEY}` only if your `pi-mcp-adapter` version+ does. If they stay literal, write the key in the file the way Copilot's config does.++## Oh My Pi++Oh My Pi reads `.mcp.json` from the working directory:++```json+{+ "mcpServers": {+ "itsaplan": {+ "type": "http",+ "url": "http://localhost:3000/mcp",+ "headers": { "Authorization": "Bearer ${ITSAPLAN_API_KEY}" }+ }+ }+}+```++`itsaplan-runner.json`:++```json+{+ "url": "http://localhost:3000",+ "apiKey": "the key you copied on creation",+ "agent": "omp",+ "cwd": "/path/to/working-dir"+}+```++- The binary is `omp`. Sign in once by running it interactively.+- The preset passes `-p --mode json --auto-approve`. No person is available to approve a+ tool. Repeat `--approval-mode` in `args` to pick `write` instead of skipping every+ prompt.+- `--mode json` is the same stream Pi writes. `--resume` takes the session id from the+ opening line.+- `--append-system-prompt` gives Oh My Pi the context of the run.+- Headers in `.mcp.json` expand `${ITSAPLAN_API_KEY}` only if your Oh My Pi build does.+ If they stay literal, write the key in the file the way Copilot's config does.diff --git a/packages/runner/README.md b/packages/runner/README.mdindex d49dee24..34b617a6 100644--- a/packages/runner/README.md+++ b/packages/runner/README.md@@ -7,8 +7,8 @@ This package runs such agents on your own machine — one, or several at once.- Polls your instance for the agent's queued runs. Runs each one with a coding agent CLI.Reports the result.-- Has presets for Claude Code, Codex, opencode, Antigravity CLI and GitHub Copilot CLI.- Each preset sets the unattended flags and the session resume.+- Has presets for Claude Code, Codex, opencode, Antigravity CLI, GitHub Copilot CLI,+ Pi, and Oh My Pi (`omp`). Each preset sets the unattended flags and the session resume.- Runs your own `command` instead, if you prefer. The command takes the task on stdin.- Answers the agent's chat. Sends the text and the tool calls while the CLI prints them.@@ -20,8 +20,9 @@ of kind External. The key appears one time only, at creation.**2. Enable MCP** for the project, in Settings, MCP Server. MCP is off by default. Theagent reads the issue and writes its result through it.-**3. Give the coding agent the address of that server.** Claude Code reads `.mcp.json`-from the folder it runs in. For the other four CLIs, see+**3. Give the coding agent the address of that server.** Claude Code, Oh My Pi, and Pi+(through `pi-mcp-adapter`) read `.mcp.json` from the folder they run in. For the other+CLIs, see[Coding agent setup](https://github.com/croffasia/itsaplan/blob/main/docs/runner.md).```json@@ -70,6 +71,8 @@ flags for an unattended run, and the session resume. Every preset keeps a chat s| `opencode` | opencode || `antigravity` | Antigravity CLI || `copilot` | GitHub Copilot CLI |+| `pi` | Pi |+| `omp` | Oh My Pi |Each preset needs the CLI's own MCP config.[Coding agent setup](https://github.com/croffasia/itsaplan/blob/main/docs/runner.md) holds@@ -188,7 +191,7 @@ npx -y @itsaplan/runner --agent claudeThe server writes the task text. The text states what occurred, what to do, and to postthe result as a comment on the issue. Your own `command` receives the text on **stdin**. Apreset gives it to its CLI in the way that CLI accepts it: on stdin for `claude` and-`codex`, as an argument for `antigravity`, `copilot` and `opencode`.+`codex`, as an argument for `antigravity`, `copilot`, `opencode`, `pi` and `omp`.The agent reads all other data through the MCP server at `$ITSAPLAN_URL/mcp`. The agentsends `$ITSAPLAN_API_KEY` as a bearer token, and acts as its own user with its role.@@ -235,7 +238,8 @@ calls with the answer. `outputFormat` tells the runner how to read the output:- `text` — all the output is the answer.- `claude-stream-json`, `codex-jsonl`, `opencode-json`, `antigravity-stream-json`,- `copilot-json` — the event stream of that CLI.+ `copilot-json`, `pi-json` — the event stream of that CLI. `pi` and `omp` both use+ `pi-json`.A preset sets `outputFormat` for you. Set it yourself only with your own `command`. If theoutput does not agree with the format, the runner sends the output as plain text.diff --git a/packages/runner/package.json b/packages/runner/package.jsonindex ab0f3e2a..925fdc5c 100644--- a/packages/runner/package.json+++ b/packages/runner/package.json@@ -1,6 +1,6 @@{"name": "@itsaplan/runner",- "version": "0.5.0",+ "version": "0.5.1","description": "Runs an Itsaplan external agent's queued tasks and answers its chat on your own machine","keywords": ["itsaplan",@@ -18,7 +18,9 @@"claude-code","codex","antigravity",- "opencode"+ "opencode",+ "pi",+ "omp"],"homepage": "https://github.com/croffasia/itsaplan/tree/main/packages/runner#readme","repository": {diff --git a/packages/runner/src/__tests__/agui.test.ts b/packages/runner/src/__tests__/agui.test.tsindex bbf0a635..9cdac6ab 100644--- a/packages/runner/src/__tests__/agui.test.ts+++ b/packages/runner/src/__tests__/agui.test.ts@@ -394,6 +394,105 @@ describe('answer stream', () => {expect(stream.startedSession()).toBe('c66bf000');});+ it("reads pi's json as text, tool calls and the session header", async () => {+ const sink = collect();+ const stream = new AnswerStream('pi-json', 'chat:1:u:x', '7', sink.send);++ stream.write(+ [+ JSON.stringify({ type: 'session', version: 3, id: 'sess-9' }),+ JSON.stringify({+ type: 'message_update',+ usage: { input: 12, cacheRead: 80, output: 3 },+ assistantMessageEvent: { type: 'text_delta', delta: 'Looking' },+ }),+ JSON.stringify({+ type: 'tool_execution_start',+ toolCallId: 'call_1',+ toolName: 'read',+ args: { path: 'alpha.txt' },+ }),+ JSON.stringify({+ type: 'tool_execution_end',+ toolCallId: 'call_1',+ toolName: 'read',+ result: { content: [{ type: 'text', text: 'hello from alpha' }] },+ isError: false,+ }),+ JSON.stringify({+ type: 'message_update',+ usage: { input: 40, cacheRead: 80, output: 9 },+ assistantMessageEvent: { type: 'text_delta', delta: ' it over.' },+ }),+ JSON.stringify({+ type: 'message_end',+ message: { role: 'assistant', content: [{ type: 'text', text: 'Looking it over.' }] },+ }),+ '',+ ].join('\n'),+ );+ await stream.finish('');++ expect(types(sink.events)).toEqual([+ 'RUN_STARTED',+ 'TEXT_MESSAGE_START',+ 'TEXT_MESSAGE_CONTENT',+ 'TOOL_CALL_START',+ 'TOOL_CALL_ARGS',+ 'TOOL_CALL_END',+ 'TOOL_CALL_RESULT',+ 'TEXT_MESSAGE_CONTENT',+ 'TEXT_MESSAGE_END',+ 'RUN_FINISHED',+ ]);+ expect(text(sink.events)).toBe('Looking it over.');+ expect(stream.startedSession()).toBe('sess-9');+ expect(stream.contextUsage()).toEqual({ inputTokens: 120, outputTokens: 9 });+ const result = sink.events.find((e) => e.type === 'TOOL_CALL_RESULT');+ expect((result as { content: string }).content).toBe('hello from alpha');+ });++ it('ignores the user message_end pi emits before the assistant text', async () => {+ const sink = collect();+ const stream = new AnswerStream('pi-json', 'chat:1:u:x', '7', sink.send);++ stream.write(+ [+ JSON.stringify({+ type: 'message_end',+ message: { role: 'user', content: [{ type: 'text', text: 'Reply with exactly: pong' }] },+ }),+ JSON.stringify({+ type: 'message_update',+ assistantMessageEvent: { type: 'text_delta', delta: 'pong' },+ }),+ JSON.stringify({+ type: 'message_end',+ message: { role: 'assistant', content: [{ type: 'text', text: 'pong' }] },+ }),+ '',+ ].join('\n'),+ );+ await stream.finish('');++ expect(text(sink.events)).toBe('pong');+ });++ it('takes the pi message_end text when no delta arrived', async () => {+ const sink = collect();+ const stream = new AnswerStream('pi-json', 'chat:1:u:x', '7', sink.send);++ stream.write(+ `${JSON.stringify({+ type: 'message_end',+ message: { role: 'assistant', content: [{ type: 'text', text: 'All done.' }] },+ })}\n`,+ );+ await stream.finish('');++ expect(text(sink.events)).toBe('All done.');+ });+it('reports what a denied Copilot tool call said', async () => {const sink = collect();const stream = new AnswerStream('copilot-json', 'chat:1:u:x', '7', sink.send);@@ -417,6 +516,7 @@ describe('answer stream', () => {'opencode-json','antigravity-stream-json','copilot-json',+ 'pi-json',] as const) {const sink = collect();const stream = new AnswerStream(format, 'chat:1:u:x', '7', sink.send);@@ -445,6 +545,11 @@ describe('answer stream', () => {const opencodeStream = new AnswerStream('opencode-json', 'chat:1:u:x', '7', opencode.send);opencodeStream.write(`${JSON.stringify({ type: 'step.started', sessionID: 'ses_9' })}\n`);expect(opencodeStream.startedSession()).toBe('ses_9');++ const pi = collect();+ const piStream = new AnswerStream('pi-json', 'chat:1:u:x', '7', pi.send);+ piStream.write(`${JSON.stringify({ type: 'session', id: 'sess-9' })}\n`);+ expect(piStream.startedSession()).toBe('sess-9');});it('keeps the first session it saw when later lines name another', async () => {diff --git a/packages/runner/src/__tests__/presets.test.ts b/packages/runner/src/__tests__/presets.test.tsindex f87cb953..aff2b865 100644--- a/packages/runner/src/__tests__/presets.test.ts+++ b/packages/runner/src/__tests__/presets.test.ts@@ -52,6 +52,36 @@ describe('preset arguments', () => {expect(resumed.slice(-4)).toEqual(['--session-id', 'c66bf000', '-p', 'do it']);});+ it('prints through pi json mode and resumes by session id, task last', () => {+ const fresh = presetArgv(PRESETS.pi, null, 'context', [], 'do it');+ expect(fresh.slice(0, 3)).toEqual(['-p', '--mode', 'json']);+ expect(fresh).not.toContain('--session-id');+ expect(fresh).toContain('--append-system-prompt');+ expect(fresh.at(-1)).toBe('do it');++ const resumed = presetArgv(PRESETS.pi, 'sess-9', '', [], 'do it');+ expect(resumed).toEqual(['-p', '--mode', 'json', '--session-id', 'sess-9', 'do it']);+ });++ it('prints through omp json mode unattended and resumes with --resume', () => {+ const fresh = presetArgv(PRESETS.omp, null, '', [], 'do it');+ expect(fresh).toContain('--auto-approve');+ expect(fresh).not.toContain('--resume');+ expect(fresh.at(-1)).toBe('do it');++ const resumed = presetArgv(PRESETS.omp, '01a0c317', 'context', [], 'do it');+ expect(resumed.slice(0, 6)).toEqual([+ '-p',+ '--mode',+ 'json',+ '--auto-approve',+ '--resume',+ '01a0c317',+ ]);+ expect(resumed).toContain('--append-system-prompt');+ expect(resumed.at(-1)).toBe('do it');+ });+it("appends the operator's arguments after the preset's, so a repeated flag wins", () => {const argv = presetArgv(PRESETS.claude, null, '', ['--permission-mode', 'plan'], 'do it');expect(argv.lastIndexOf('--permission-mode')).toBeGreaterThan(diff --git a/packages/runner/src/agui.ts b/packages/runner/src/agui.tsindex 38952875..3eb6d92e 100644--- a/packages/runner/src/agui.ts+++ b/packages/runner/src/agui.ts@@ -200,6 +200,49 @@ export class AnswerStream {case 'copilot-json':this.readCopilotLine(parsed as CopilotLine);break;+ case 'pi-json':+ this.readPiLine(parsed as PiJsonLine);+ break;+ }+ }++ // Pi and Oh My Pi share this stream. The first line is the session header. Text arrives+ // as text_delta; a tool is the pair of execution_start / execution_end. The stream emits+ // a message_end for the user turn before any text, so only the assistant's counts, and+ // only when no delta arrived.+ private readPiLine(message: PiJsonLine): void {+ if (message.type === 'session' && message.id) this.sessionId ??= message.id;+ switch (message.type) {+ case 'message_update': {+ const event = message.assistantMessageEvent;+ if (event?.type === 'text_delta' && event.delta) {+ this.sawPartialText = true;+ this.appendText(event.delta);+ }+ return;+ }+ case 'tool_execution_start':+ if (message.toolCallId && !this.openToolCalls.has(message.toolCallId)) {+ this.openToolCalls.add(message.toolCallId);+ this.pushToolCall(+ message.toolCallId,+ message.toolName ?? 'tool',+ JSON.stringify(message.args ?? {}),+ );+ }+ return;+ case 'tool_execution_end': {+ if (!message.toolCallId || this.closedToolCalls.has(message.toolCallId)) return;+ this.closedToolCalls.add(message.toolCallId);+ this.pushToolResult(message.toolCallId, piResultText(message.result));+ return;+ }+ case 'message_end':+ if (message.message?.role === 'assistant' && !this.sawAnyText && message.message.content) {+ const body = textOfResult(message.message.content);+ if (body) this.appendText(body);+ }+ return;}}@@ -458,6 +501,9 @@ export class UsageReader {case 'antigravity-stream-json':this.readAntigravity(parsed as AntigravityLine);return;+ case 'pi-json':+ this.readPi(parsed as PiJsonLine);+ return;}}@@ -516,13 +562,23 @@ export class UsageReader {outputTokens: (usage.output_tokens ?? 0) + (usage.thinking_tokens ?? 0),};}++ // Pi reports the latest cumulative usage on each message_update. Cache reads sit+ // beside the rest of the input, the same split Claude uses.+ private readPi(message: PiJsonLine): void {+ const usage = message.usage;+ if (!usage) return;+ this.last = {+ inputTokens: (usage.input ?? usage.input_tokens ?? 0) + (usage.cacheRead ?? 0),+ outputTokens: usage.output ?? usage.output_tokens ?? 0,+ };+ }}function tail(text: string, limit: number): string {return text.length <= limit ? text : `…${text.slice(-limit)}`;}-// A tool result is either a string or the block list the model was shown.function textOfResult(content: unknown): string {if (typeof content === 'string') return content;if (Array.isArray(content)) {@@ -533,6 +589,14 @@ function textOfResult(content: unknown): string {return '';}+function piResultText(result: unknown): string {+ if (result && typeof result === 'object' && !Array.isArray(result) && 'content' in result) {+ return textOfResult(result.content);+ }+ const text = textOfResult(result);+ return text || (result == null ? '' : JSON.stringify(result));+}+// The parts of Claude Code's stream-json this adapter reads. `session_id` rides on every// line, including the first.interface StreamJsonLine {@@ -636,6 +700,26 @@ interface CopilotLine {};}+// The parts of pi / omp --mode json this adapter reads. The session id is on the+// opening header; usage rides on message_update.+interface PiJsonLine {+ type?: string;+ id?: string;+ usage?: {+ input?: number;+ output?: number;+ cacheRead?: number;+ input_tokens?: number;+ output_tokens?: number;+ };+ assistantMessageEvent?: { type?: string; delta?: string };+ toolCallId?: string;+ toolName?: string;+ args?: unknown;+ result?: unknown;+ message?: { role?: string; content?: unknown };+}+interface StreamEvent {type?: string;delta?: { type?: string; text?: string };diff --git a/packages/runner/src/config.ts b/packages/runner/src/config.tsindex 790c5b20..47763abd 100644--- a/packages/runner/src/config.ts+++ b/packages/runner/src/config.ts@@ -43,6 +43,7 @@ const OUTPUT_FORMATS = ['opencode-json','antigravity-stream-json','copilot-json',+ 'pi-json',] as const;export type OutputFormat = (typeof OUTPUT_FORMATS)[number];diff --git a/packages/runner/src/presets.ts b/packages/runner/src/presets.tsindex 594f3bde..ad102e97 100644--- a/packages/runner/src/presets.ts+++ b/packages/runner/src/presets.ts@@ -9,7 +9,7 @@ import type { OutputFormat } from './config';// Anything else about the invocation — MCP servers, model, working directory — is the// operator's, passed through `args` and the `--` tail.-export type PresetName = 'claude' | 'codex' | 'opencode' | 'antigravity' | 'copilot';+export type PresetName = 'claude' | 'codex' | 'opencode' | 'antigravity' | 'copilot' | 'pi' | 'omp';export interface Preset {bin: string;@@ -114,6 +114,39 @@ export const PRESETS: Record<PresetName, Preset> = {],tail: ['-p'],},++ // --mode json writes one event per line. The opening `session` line names the id that+ // --session-id resumes. Print mode does not wait for tool approval.+ pi: {+ bin: 'pi',+ outputFormat: 'pi-json',+ promptVia: 'arg',+ systemPromptFlag: '--append-system-prompt',+ head: (sessionId) => [+ '-p',+ '--mode',+ 'json',+ ...(sessionId ? ['--session-id', sessionId] : []),+ ],+ tail: [],+ },++ // Same JSON stream as pi. --auto-approve is required: without it a tool waits for a+ // person who is not there. --resume takes the session id the stream named.+ omp: {+ bin: 'omp',+ outputFormat: 'pi-json',+ promptVia: 'arg',+ systemPromptFlag: '--append-system-prompt',+ head: (sessionId) => [+ '-p',+ '--mode',+ 'json',+ '--auto-approve',+ ...(sessionId ? ['--resume', sessionId] : []),+ ],+ tail: [],+ },};export const PRESET_NAMES = Object.keys(PRESETS) as PresetName[];