From accca11d1ecc2df5296a4bc297a743b63dcdaea0 Mon Sep 17 00:00:00 2001 From: Zishan Ahmed Date: Thu, 30 Apr 2026 14:10:28 +0100 Subject: [PATCH 01/11] feat: add Pi RPC adapter --- readme.md | 11 +- src/cli/commands/agent.ts | 2 +- src/cli/commands/doctor.ts | 2 + src/cli/commands/init.ts | 2 +- src/container.ts | 3 + src/domain/default-agents.ts | 4 +- src/domain/model-tiers.ts | 11 +- src/infrastructure/adapters/pi.ts | 379 ++++++++++++++++++++ src/tui/wizardConfigs.ts | 12 +- test/unit/domain/model-tiers.test.ts | 10 +- test/unit/infrastructure/pi-adapter.test.ts | 304 ++++++++++++++++ 11 files changed, 725 insertions(+), 15 deletions(-) create mode 100644 src/infrastructure/adapters/pi.ts create mode 100644 test/unit/infrastructure/pi-adapter.test.ts diff --git a/readme.md b/readme.md index ab9cafe..1077a6d 100644 --- a/readme.md +++ b/readme.md @@ -7,7 +7,7 @@

Open-source orchestration for zero-human companies, processes and departments.
- Run multiple AI agents on one project — without babysitting any of them.
Coordinate Claude, Codex, Cursor and any CLI tool in parallel. One npm install. Zero infrastructure.
+ Run multiple AI agents on one project — without babysitting any of them.
Coordinate Claude, Codex, Pi, Cursor and any CLI tool in parallel. One npm install. Zero infrastructure.

@@ -209,6 +209,7 @@ ORCH itself is lightweight (~120 MB). The RAM goes to the **agent CLI processes* | Claude Code CLI | 200-400 MB | Full Node.js runtime + context window | | OpenCode | 200-400 MB | Node.js + provider SDK | | Codex CLI | 150-300 MB | Python runtime + OpenAI SDK | +| Pi coding agent | 200-400 MB | Node.js runtime + Pi tools/extensions | | Cursor CLI | 200-400 MB | Electron-based agent | | Shell scripts | 10-50 MB | Depends on the tool | @@ -287,7 +288,7 @@ ORCH orchestrates **any process** — not just code. The shell adapter runs any | Department | Agents | What they do | |-----------|--------|-------------| -| **Engineering** | Claude, Codex, Cursor | Write code, fix bugs, refactor | +| **Engineering** | Claude, Codex, Pi, Cursor | Write code, fix bugs, refactor | | **Editorial** | Claude (writer), Claude (editor), Shell (grammarly) | Write articles, edit, check grammar, publish | | **Sales Ops** | Shell (CRM scripts), Claude (copywriter), Shell (email sender) | Generate leads, write sequences, send outreach | | **Analytics** | Shell (pandas, duckdb), Claude (analyst), Shell (matplotlib) | Clean data, compute KPIs, generate reports | @@ -325,7 +326,7 @@ Every department gets the same superpowers: state machine governance, retry, mes - Adapters: Claude, OpenCode, Codex, Cursor, Shell + Adapters: Claude, OpenCode, Codex, Pi, Cursor, Shell
@@ -603,7 +604,7 @@ src/ ├── domain/ # Models, state machine, errors ├── application/ # Orchestrator engine, services, event bus ├── infrastructure/ -│ ├── adapters/ # Claude, OpenCode, Codex, Cursor, Shell +│ ├── adapters/ # Claude, OpenCode, Codex, Pi, Cursor, Shell │ ├── storage/ # File-based (YAML/JSON/JSONL) │ ├── process/ # PID management, graceful kill │ ├── template/ # LiquidJS prompt templates @@ -705,7 +706,7 @@ ORCH is open-source (MIT license). You pay only for the AI APIs you already use
-Five adapters: **Claude Code**, **OpenCode** (Gemini, DeepSeek, any OpenRouter model), **Codex**, **Cursor**, and **Shell** (any CLI tool). Your API keys, your tools — ORCH coordinates them. +Six adapters: **Claude Code**, **OpenCode** (Gemini, DeepSeek, any OpenRouter model), **Codex**, **Pi**, **Cursor**, and **Shell** (any CLI tool). Your API keys, your tools — ORCH coordinates them. diff --git a/src/cli/commands/agent.ts b/src/cli/commands/agent.ts index 93e18d9..51f9f39 100644 --- a/src/cli/commands/agent.ts +++ b/src/cli/commands/agent.ts @@ -26,7 +26,7 @@ export function registerAgentCommand(program: Command, container: LightContainer agent .command('add ') .description('Add a new agent') - .requiredOption('--adapter ', 'Adapter type: claude, opencode, codex, cursor, shell') + .requiredOption('--adapter ', 'Adapter type: claude, opencode, codex, cursor, pi, shell') .option('--role ', 'Agent role description') .option('--command ', 'Shell command (for shell adapter)') .option('--model ', 'Model name (for AI adapters)') diff --git a/src/cli/commands/doctor.ts b/src/cli/commands/doctor.ts index f409f1a..840dcf3 100644 --- a/src/cli/commands/doctor.ts +++ b/src/cli/commands/doctor.ts @@ -11,6 +11,7 @@ import { ProcessManager } from '../../infrastructure/process/process-manager.js' import { AdapterRegistry } from '../../infrastructure/adapters/registry.js'; import { ClaudeAdapter } from '../../infrastructure/adapters/claude.js'; import { ShellAdapter } from '../../infrastructure/adapters/shell.js'; +import { PiAdapter } from '../../infrastructure/adapters/pi.js'; import { DoctorService } from '../../application/doctor-service.js'; import { Paths } from '../../infrastructure/storage/paths.js'; import { getIcon, amber, dim } from '../output.js'; @@ -35,6 +36,7 @@ export function registerDoctorCommand(program: Command, container?: Container): const registry = new AdapterRegistry(); registry.register(new ClaudeAdapter(pm)); registry.register(new ShellAdapter(pm)); + registry.register(new PiAdapter(pm)); doctorService = new DoctorService(registry, pm, process.cwd()); paths = new Paths(process.cwd()); } diff --git a/src/cli/commands/init.ts b/src/cli/commands/init.ts index e3628bb..b1e7add 100644 --- a/src/cli/commands/init.ts +++ b/src/cli/commands/init.ts @@ -250,7 +250,7 @@ export function registerInitCommand(program: Command): void { .command('init') .description('Initialize .orchestry/ in the current directory') .option('--name ', 'Project name') - .option('--adapter ', 'Default agent adapter (claude, opencode, codex, cursor, shell)') + .option('--adapter ', 'Default agent adapter (claude, opencode, codex, cursor, pi, shell)') .action(async (opts: { name?: string; adapter?: string }) => { if (opts.adapter && !isAdapterKind(opts.adapter)) { printError(`Unknown adapter "${opts.adapter}"`, `Supported: ${SUPPORTED_ADAPTERS.join(', ')}`); diff --git a/src/container.ts b/src/container.ts index 4b094b4..cbeeacd 100644 --- a/src/container.ts +++ b/src/container.ts @@ -161,6 +161,7 @@ export async function buildFullContainer(context: CliContext): Promise> = { balanced: 'auto', fast: 'auto', }, + pi: { + capable: 'openai-codex/gpt-5.5', + balanced: 'openai-codex/gpt-5.5', + fast: 'openai-codex/gpt-5.5', + }, shell: { capable: '', balanced: '', @@ -79,4 +84,4 @@ export function isModelTier(value: string): value is ModelTier { } /** All supported adapter names in display order. */ -export const SUPPORTED_ADAPTERS: readonly AdapterKind[] = ['claude', 'opencode', 'codex', 'cursor', 'shell']; +export const SUPPORTED_ADAPTERS: readonly AdapterKind[] = ['claude', 'opencode', 'codex', 'cursor', 'pi', 'shell']; diff --git a/src/infrastructure/adapters/pi.ts b/src/infrastructure/adapters/pi.ts new file mode 100644 index 0000000..07ad34b --- /dev/null +++ b/src/infrastructure/adapters/pi.ts @@ -0,0 +1,379 @@ +/** + * Pi coding agent adapter. + * + * Spawns `pi --mode rpc` in headless RPC mode. + * Sends the ORCH prompt as a JSONL `prompt` command over stdin and maps Pi + * RPC events from stdout into ORCH AgentEvents. Pi extensions/skills/context + * remain enabled by default; UI-only extension events are ignored. + */ + +import type { IAgentAdapter, AdapterTestResult, ExecuteParams, AgentEvent, ExecuteHandle } from './interface.js'; +import type { IProcessManager } from '../process/process-manager.js'; +import { readLines } from '../process/process-manager.js'; +import { createTokenUsage, type TokenUsage } from '../../domain/run.js'; +import { classifyAdapterError } from '../../domain/errors.js'; +import { execFile } from 'node:child_process'; + +export class PiAdapter implements IAgentAdapter { + readonly kind = 'pi'; + + constructor(private readonly processManager: IProcessManager) {} + + async test(): Promise { + try { + const stdout = await new Promise((resolve, reject) => { + execFile('pi', ['--version'], (err, out) => { + if (err) reject(err); + else resolve(out); + }); + }); + return { ok: true, version: stdout.trim() }; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + return { + ok: false, + error: 'Pi CLI not found. Install: npm i -g @mariozechner/pi-coding-agent', + errorKind: classifyAdapterError(msg), + }; + } + } + + execute(params: ExecuteParams): ExecuteHandle { + const args = [ + '--mode', 'rpc', + ]; + + if (params.config.model) { + args.push('--model', params.config.model); + } + + if (params.config.effort) { + args.push('--thinking', params.config.effort); + } + + // Preserve Pi's own coding-agent harness prompt. ORCH's system prompt is + // appended as additional project/task governance rather than replacing it. + const effectiveSystemPrompt = params.systemPrompt ?? params.config.system_prompt; + if (effectiveSystemPrompt) { + args.push('--append-system-prompt', effectiveSystemPrompt); + } + + const { process: proc, pid } = this.processManager.spawn('pi', args, { + cwd: params.workspace, + env: { ...process.env, ...params.env }, + signal: params.signal, + stdio: ['pipe', 'pipe', 'pipe'], + }); + + // Avoid stderr backpressure if extensions emit warnings during startup. + proc.stderr?.resume(); + + if (proc.stdin) { + proc.stdin.write(JSON.stringify({ + id: `orch-${Date.now()}`, + type: 'prompt', + message: params.prompt, + }) + '\n'); + } + + const events = createPiRpcEvents(proc, pid, this.processManager, params.signal); + return { pid, events }; + } + + async stop(pid: number): Promise { + await this.processManager.killWithGrace(pid); + } +} + +function createPiRpcEvents( + proc: import('node:child_process').ChildProcess, + pid: number, + processManager: IProcessManager, + signal?: AbortSignal, +): AsyncGenerator { + async function* generate(): AsyncGenerator { + let gotDoneEvent = false; + let finalText = ''; + let lastTokens: TokenUsage | undefined; + let exitCode: number | null = null; + let exitError: Error | null = null; + + const exitPromise = new Promise((resolve) => { + proc.on('close', (code) => { exitCode = code; resolve(); }); + proc.on('error', (err) => { exitError = err; resolve(); }); + }); + + try { + if (proc.stdout) { + for await (const line of readLines(proc.stdout)) { + if (signal?.aborted) break; + const event = parsePiRpcEvent(line, { finalText, lastTokens }); + if (!event) continue; + + if (event.finalText !== undefined) finalText = event.finalText; + if (event.tokens) lastTokens = event.tokens; + + if (event.agentEvent) { + if (event.agentEvent.type === 'done') gotDoneEvent = true; + yield event.agentEvent; + if (event.agentEvent.type === 'done') { + // Pi RPC is a long-lived process. ORCH tasks are one-shot runs, so + // stop Pi after the terminal event instead of waiting forever. + await processManager.killWithGrace(pid, 1_000).catch(() => {}); + return; + } + } + } + } + } finally { + proc.stdout?.destroy(); + } + + await exitPromise; + + const spawnError = exitError as Error | null; + if (spawnError && !signal?.aborted && !gotDoneEvent) { + const classified = classifyAdapterError(spawnError.message, exitCode ?? undefined); + throw Object.assign(new Error(spawnError.message), { errorKind: classified }); + } + if (exitCode !== 0 && exitCode !== null && !signal?.aborted && !gotDoneEvent) { + const msg = `Pi process exited with code ${exitCode}`; + const classified = classifyAdapterError(msg, exitCode); + throw Object.assign(new Error(msg), { errorKind: classified }); + } + } + + return generate(); +} + +interface ParseState { + finalText: string; + lastTokens?: TokenUsage; +} + +interface ParsedPiEvent { + agentEvent?: AgentEvent; + finalText?: string; + tokens?: TokenUsage; +} + +function parsePiRpcEvent(line: string, state: ParseState): ParsedPiEvent | null { + if (!line.trim()) return null; + + let parsed: Record; + try { + parsed = JSON.parse(line) as Record; + } catch { + return { agentEvent: { type: 'output', timestamp: new Date().toISOString(), data: line } }; + } + + const timestamp = new Date().toISOString(); + const type = typeof parsed.type === 'string' ? parsed.type : ''; + + switch (type) { + case 'extension_ui_request': + case 'agent_start': + case 'turn_start': + case 'message_start': + case 'message_end': + case 'turn_end': + case 'queue_update': + case 'compaction_start': + case 'compaction_end': + case 'auto_retry_start': + case 'auto_retry_end': + return extractPassiveUpdate(parsed, state); + + case 'response': { + if (parsed.success === false) { + const errMsg = typeof parsed.error === 'string' ? parsed.error : JSON.stringify(parsed); + return { + agentEvent: { type: 'error', timestamp, data: parsed, errorKind: classifyAdapterError(errMsg) }, + }; + } + return null; + } + + case 'message_update': + return parseMessageUpdate(parsed, timestamp, state); + + case 'tool_execution_start': + return { + agentEvent: { + type: 'tool_call', + timestamp, + data: { name: parsed.toolName, input: parsed.args, raw: parsed }, + }, + }; + + case 'tool_execution_update': + return { + agentEvent: { + type: 'output', + timestamp, + data: parsed, + }, + }; + + case 'tool_execution_end': + return parseToolExecutionEnd(parsed, timestamp); + + case 'agent_end': { + const final = extractFinalText(parsed) ?? state.finalText; + const tokens = extractPiTokensFromAgentEnd(parsed) ?? state.lastTokens; + return { + finalText: final, + tokens, + agentEvent: { + type: 'done', + timestamp, + data: { result: final, raw: parsed }, + tokens, + }, + }; + } + + case 'extension_error': { + const errMsg = typeof parsed.message === 'string' ? parsed.message : JSON.stringify(parsed); + return { + agentEvent: { type: 'error', timestamp, data: parsed, errorKind: classifyAdapterError(errMsg) }, + }; + } + + default: + return { agentEvent: { type: 'output', timestamp, data: parsed } }; + } +} + +function parseMessageUpdate(parsed: Record, timestamp: string, state: ParseState): ParsedPiEvent | null { + const assistantMessageEvent = parsed.assistantMessageEvent as Record | undefined; + const updateType = typeof assistantMessageEvent?.type === 'string' ? assistantMessageEvent.type : ''; + + if (updateType === 'text_delta') { + const delta = typeof assistantMessageEvent?.delta === 'string' ? assistantMessageEvent.delta : ''; + return { + finalText: state.finalText + delta, + agentEvent: { type: 'output', timestamp, data: { text: delta, raw: parsed } }, + }; + } + + if (updateType === 'text_end') { + const content = typeof assistantMessageEvent?.content === 'string' ? assistantMessageEvent.content : state.finalText; + return { finalText: content }; + } + + if (updateType === 'error') { + const reason = typeof assistantMessageEvent?.reason === 'string' ? assistantMessageEvent.reason : JSON.stringify(parsed); + return { + agentEvent: { type: 'error', timestamp, data: parsed, errorKind: classifyAdapterError(reason) }, + }; + } + + return null; +} + +function parseToolExecutionEnd(parsed: Record, timestamp: string): ParsedPiEvent { + const toolName = typeof parsed.toolName === 'string' ? parsed.toolName : ''; + const args = parsed.args as Record | undefined; + + if (parsed.isError === true) { + const errMsg = JSON.stringify(parsed.result ?? parsed); + return { + agentEvent: { type: 'error', timestamp, data: parsed, errorKind: classifyAdapterError(errMsg) }, + }; + } + + if (toolName === 'bash') { + return { + agentEvent: { + type: 'command', + timestamp, + data: { command: args?.command, result: parsed.result, raw: parsed }, + }, + }; + } + + if (/^(write|edit)$/i.test(toolName)) { + const path = extractPath(args); + if (path) { + return { + agentEvent: { + type: 'file_change', + timestamp, + data: { paths: [path], raw: parsed }, + }, + }; + } + } + + return { agentEvent: { type: 'output', timestamp, data: parsed } }; +} + +function extractPassiveUpdate(parsed: Record, state: ParseState): ParsedPiEvent | null { + const tokens = extractPiTokensFromMessage(parsed); + if (tokens) return { tokens }; + return state.finalText ? null : null; +} + +function extractFinalText(parsed: Record): string | undefined { + const messages = parsed.messages; + if (!Array.isArray(messages)) return undefined; + + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i] as Record; + if (message.role !== 'assistant') continue; + const text = extractTextFromContent(message.content); + if (text) return text; + } + return undefined; +} + +function extractTextFromContent(content: unknown): string | undefined { + if (typeof content === 'string') return content; + if (!Array.isArray(content)) return undefined; + const parts = content + .map((part) => { + const p = part as Record; + return typeof p.text === 'string' ? p.text : ''; + }) + .filter(Boolean); + return parts.length ? parts.join('') : undefined; +} + +function extractPath(args: Record | undefined): string | undefined { + if (!args) return undefined; + if (typeof args.path === 'string') return args.path; + if (typeof args.file_path === 'string') return args.file_path; + return undefined; +} + +function extractPiTokensFromAgentEnd(parsed: Record): TokenUsage | undefined { + const messages = parsed.messages; + if (!Array.isArray(messages)) return undefined; + + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i] as Record; + if (message.role !== 'assistant') continue; + const tokens = extractPiTokensFromMessage(message); + if (tokens) return tokens; + } + return undefined; +} + +function extractPiTokensFromMessage(parsed: Record): TokenUsage | undefined { + const usage = parsed.usage as Record | undefined; + if (!usage) return undefined; + + const input = numberField(usage.input) ?? numberField(usage.input_tokens) ?? 0; + const output = numberField(usage.output) ?? numberField(usage.output_tokens) ?? 0; + const reasoning = numberField(usage.reasoning) ?? numberField(usage.reasoning_tokens) ?? 0; + const cache_read = numberField(usage.cacheRead) ?? numberField(usage.cache_read) ?? numberField(usage.cache_read_input_tokens) ?? 0; + const cache_write = numberField(usage.cacheWrite) ?? numberField(usage.cache_write) ?? numberField(usage.cache_creation_input_tokens) ?? 0; + + if (input === 0 && output === 0 && reasoning === 0 && cache_read === 0 && cache_write === 0) return undefined; + return createTokenUsage(input, output, { reasoning, cache_read, cache_write }); +} + +function numberField(value: unknown): number | undefined { + return typeof value === 'number' ? value : undefined; +} diff --git a/src/tui/wizardConfigs.ts b/src/tui/wizardConfigs.ts index 984f12b..7727567 100644 --- a/src/tui/wizardConfigs.ts +++ b/src/tui/wizardConfigs.ts @@ -57,6 +57,13 @@ const OPENCODE_MODELS = [ { value: 'opencode/big-pickle', label: 'Big Pickle', hint: 'opencode native' }, ]; +const PI_MODELS = [ + { value: 'openai-codex/gpt-5.5', label: 'GPT-5.5', hint: 'Pi OpenAI Codex provider' }, + { value: 'openai-codex/gpt-5.4', label: 'GPT-5.4', hint: 'Pi OpenAI Codex provider' }, + { value: 'openai-codex/gpt-5.3-codex', label: 'GPT-5.3 Codex', hint: 'Pi OpenAI Codex provider' }, + { value: '', label: 'Default', hint: 'use Pi configured default' }, +]; + const SHELL_MODELS = [ { value: '', label: 'Default', hint: 'use shell adapter default' }, ]; @@ -71,7 +78,7 @@ const EFFORT_OPTIONS = [ ]; /** Adapters that support the --effort flag */ -const EFFORT_ADAPTERS = new Set(['claude']); +const EFFORT_ADAPTERS = new Set(['claude', 'pi']); // ── Adapter catalog ── @@ -80,6 +87,7 @@ const ADAPTERS = [ { value: 'opencode', label: 'OpenCode', hint: 'OpenCode — multi-provider' }, { value: 'codex', label: 'Codex', hint: 'OpenAI Codex CLI' }, { value: 'cursor', label: 'Cursor', hint: 'Cursor Agent CLI' }, + { value: 'pi', label: 'Pi', hint: 'Pi coding agent RPC' }, { value: 'shell', label: 'Shell', hint: 'custom shell command' }, ]; @@ -230,6 +238,7 @@ export function getAgentWizardSteps(agents?: Agent[], teams?: Team[]): WizardSte if (vals.adapter === 'opencode') return OPENCODE_MODELS; if (vals.adapter === 'codex') return CODEX_MODELS; if (vals.adapter === 'cursor') return CURSOR_MODELS; + if (vals.adapter === 'pi') return PI_MODELS; if (vals.adapter === 'shell') return SHELL_MODELS; return CLAUDE_MODELS; }, @@ -460,6 +469,7 @@ export function getEditAgentWizardSteps(agent: Agent, agents?: Agent[], teams?: agent.adapter === 'opencode' ? OPENCODE_MODELS : agent.adapter === 'codex' ? CODEX_MODELS : agent.adapter === 'cursor' ? CURSOR_MODELS : + agent.adapter === 'pi' ? PI_MODELS : agent.adapter === 'shell' ? SHELL_MODELS : CLAUDE_MODELS; diff --git a/test/unit/domain/model-tiers.test.ts b/test/unit/domain/model-tiers.test.ts index 736c055..137ed20 100644 --- a/test/unit/domain/model-tiers.test.ts +++ b/test/unit/domain/model-tiers.test.ts @@ -37,6 +37,10 @@ describe('resolveModel', () => { expect(resolveModel('codex', 'balanced')).toBe('gpt-5.3-codex'); }); + it('pi balanced → openai-codex/gpt-5.5', () => { + expect(resolveModel('pi', 'balanced')).toBe('openai-codex/gpt-5.5'); + }); + it('shell returns empty string for all tiers', () => { expect(resolveModel('shell', 'capable')).toBe(''); expect(resolveModel('shell', 'balanced')).toBe(''); @@ -59,6 +63,7 @@ describe('defaultModelForAdapter', () => { it('returns balanced tier model', () => { expect(defaultModelForAdapter('claude')).toBe('claude-sonnet-4-6'); expect(defaultModelForAdapter('codex')).toBe('gpt-5.3-codex'); + expect(defaultModelForAdapter('pi')).toBe('openai-codex/gpt-5.5'); expect(defaultModelForAdapter('shell')).toBe(''); }); }); @@ -81,6 +86,7 @@ describe('isAdapterKind', () => { expect(isAdapterKind('opencode')).toBe(true); expect(isAdapterKind('codex')).toBe(true); expect(isAdapterKind('cursor')).toBe(true); + expect(isAdapterKind('pi')).toBe(true); expect(isAdapterKind('shell')).toBe(true); }); @@ -104,8 +110,8 @@ describe('isModelTier', () => { }); describe('SUPPORTED_ADAPTERS', () => { - it('has 5 entries', () => { - expect(SUPPORTED_ADAPTERS).toHaveLength(5); + it('has 6 entries', () => { + expect(SUPPORTED_ADAPTERS).toHaveLength(6); }); it('matches MODEL_TIER_MAP keys', () => { diff --git a/test/unit/infrastructure/pi-adapter.test.ts b/test/unit/infrastructure/pi-adapter.test.ts new file mode 100644 index 0000000..051d966 --- /dev/null +++ b/test/unit/infrastructure/pi-adapter.test.ts @@ -0,0 +1,304 @@ +import { describe, it, expect, vi } from 'vitest'; +import { PiAdapter } from '../../../src/infrastructure/adapters/pi.js'; +import type { IProcessManager } from '../../../src/infrastructure/process/process-manager.js'; +import type { AgentEvent, ExecuteParams } from '../../../src/infrastructure/adapters/interface.js'; +import { AdapterErrorKind } from '../../../src/domain/errors.js'; +import { PassThrough } from 'node:stream'; +import { EventEmitter } from 'node:events'; + +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + execFile: vi.fn((...args: unknown[]) => { + const cb = args.at(-1) as (err: Error | null, stdout: string, stderr: string) => void; + cb(null, 'pi 1.0.0', ''); + return {}; + }), + }; +}); + +function createMockProcess() { + const proc = new EventEmitter() as EventEmitter & { + stdout: PassThrough; + stderr: PassThrough; + stdin: PassThrough; + pid: number; + kill: () => void; + }; + proc.stdout = new PassThrough(); + proc.stderr = new PassThrough(); + proc.stdin = new PassThrough(); + proc.pid = 8888; + proc.kill = vi.fn(); + return proc; +} + +function createMockProcessManager(proc: ReturnType): IProcessManager { + return { + isAlive: vi.fn(() => true), + kill: vi.fn(), + killWithGrace: vi.fn(async () => {}), + spawn: vi.fn(() => ({ process: proc as any, pid: proc.pid })), + }; +} + +function makeParams(overrides?: Partial): ExecuteParams { + return { + prompt: 'pi prompt', + workspace: '/tmp/pi-ws', + config: { adapter: 'pi' }, + ...overrides, + }; +} + +async function collectEvents(handle: { events: AsyncGenerator }, proc: ReturnType): Promise { + proc.stdout.end(); + setTimeout(() => proc.emit('close', 0), 20); + const events: AgentEvent[] = []; + for await (const ev of handle.events) events.push(ev); + return events; +} + +describe('PiAdapter', () => { + describe('execute', () => { + it('spawns pi in rpc mode with stdin pipe and session persistence enabled by default', () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + + adapter.execute(makeParams()); + + expect(pm.spawn).toHaveBeenCalledWith( + 'pi', + expect.arrayContaining(['--mode', 'rpc']), + expect.objectContaining({ + cwd: '/tmp/pi-ws', + stdio: ['pipe', 'pipe', 'pipe'], + }), + ); + const args = (pm.spawn as ReturnType).mock.calls[0][1]; + expect(args).not.toContain('--no-session'); + }); + + it('passes model and effort as --model and --thinking', () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + + adapter.execute(makeParams({ config: { adapter: 'pi', model: 'openai-codex/gpt-5.5', effort: 'high' } })); + + const args = (pm.spawn as ReturnType).mock.calls[0][1]; + expect(args).toContain('--model'); + expect(args).toContain('openai-codex/gpt-5.5'); + expect(args).toContain('--thinking'); + expect(args).toContain('high'); + }); + + it('appends orchestrator systemPrompt without replacing Pi harness prompt', () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + + adapter.execute(makeParams({ systemPrompt: 'system instructions' })); + + const args = (pm.spawn as ReturnType).mock.calls[0][1]; + expect(args).toContain('--append-system-prompt'); + expect(args).toContain('system instructions'); + expect(args).not.toContain('--system-prompt'); + }); + + it('writes a prompt command to stdin as JSONL', () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const writeSpy = vi.spyOn(proc.stdin, 'write'); + + adapter.execute(makeParams({ prompt: 'do work' })); + + expect(writeSpy).toHaveBeenCalledTimes(1); + const line = String(writeSpy.mock.calls[0][0]); + expect(line.endsWith('\n')).toBe(true); + expect(JSON.parse(line)).toMatchObject({ type: 'prompt', message: 'do work' }); + }); + + it('ignores extension_ui_request events', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stdout.write(JSON.stringify({ type: 'extension_ui_request', method: 'setTitle', title: 'noise' }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events).toEqual([]); + }); + + it('maps text_delta message updates to output events', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stdout.write(JSON.stringify({ + type: 'message_update', + assistantMessageEvent: { type: 'text_delta', delta: 'hello' }, + }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events[0]!.type).toBe('output'); + expect((events[0]!.data as any).text).toBe('hello'); + }); + + it('maps tool execution events to tool_call and output events', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stdout.write(JSON.stringify({ type: 'tool_execution_start', toolName: 'read', args: { path: 'a.ts' } }) + '\n'); + proc.stdout.write(JSON.stringify({ type: 'tool_execution_end', toolName: 'read', result: { content: [{ type: 'text', text: 'ok' }] }, isError: false }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events[0]!.type).toBe('tool_call'); + expect((events[0]!.data as any).name).toBe('read'); + expect(events[1]!.type).toBe('output'); + }); + + it('maps bash tool execution to command events', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stdout.write(JSON.stringify({ + type: 'tool_execution_end', + toolName: 'bash', + args: { command: 'npm test' }, + result: { content: [{ type: 'text', text: 'passed' }], details: { exitCode: 0 } }, + isError: false, + }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events[0]!.type).toBe('command'); + expect((events[0]!.data as any).command).toBe('npm test'); + }); + + it('maps write/edit tool execution to file_change events', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stdout.write(JSON.stringify({ + type: 'tool_execution_end', + toolName: 'write', + args: { path: 'src/new.ts' }, + result: { content: [{ type: 'text', text: 'written' }] }, + isError: false, + }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events[0]!.type).toBe('file_change'); + expect((events[0]!.data as any).paths).toEqual(['src/new.ts']); + }); + + it('maps agent_end to done with final text and tokens', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stdout.write(JSON.stringify({ + type: 'message_update', + assistantMessageEvent: { type: 'text_delta', delta: 'done text' }, + }) + '\n'); + proc.stdout.write(JSON.stringify({ + type: 'agent_end', + messages: [{ role: 'assistant', content: [{ type: 'text', text: 'done text' }], usage: { input: 10, output: 4, totalTokens: 14 } }], + }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events.at(-1)!.type).toBe('done'); + expect((events.at(-1)!.data as any).result).toBe('done text'); + expect(events.at(-1)!.tokens).toEqual({ input: 10, output: 4, reasoning: 0, total: 14, cache_read: 0, cache_write: 0 }); + }); + + it('maps response failure to error', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stdout.write(JSON.stringify({ type: 'response', command: 'prompt', success: false, error: 'bad request' }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events[0]!.type).toBe('error'); + expect(events[0]!.errorKind).toBe(AdapterErrorKind.UNKNOWN); + }); + }); + + describe('test', () => { + it('returns ok when pi --version succeeds', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + + const result = await adapter.test(); + + expect(result.ok).toBe(true); + expect(result.version).toBe('pi 1.0.0'); + }); + + it('returns SPAWN_FAILED when pi is missing', async () => { + const { execFile } = await import('node:child_process'); + vi.mocked(execFile).mockImplementationOnce( + ( + _cmd: unknown, + _args: unknown, + cb: (err: Error | null, stdout: string, stderr: string) => void, + ) => { + const err = new Error('spawn pi ENOENT'); + (err as NodeJS.ErrnoException).code = 'ENOENT'; + cb(err, '', ''); + return {} as ReturnType; + }, + ); + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + + const result = await adapter.test(); + + expect(result.ok).toBe(false); + expect(result.errorKind).toBe(AdapterErrorKind.SPAWN_FAILED); + }); + }); + + describe('stop', () => { + it('calls killWithGrace', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + + await adapter.stop(8888); + + expect(pm.killWithGrace).toHaveBeenCalledWith(8888); + }); + }); + + describe('kind', () => { + it('returns pi', () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + expect(new PiAdapter(pm).kind).toBe('pi'); + }); + }); +}); From 2fb32531ce17527398e6766750f5a531dea4a929 Mon Sep 17 00:00:00 2001 From: Zishan Ahmed Date: Thu, 30 Apr 2026 14:35:13 +0100 Subject: [PATCH 02/11] fix: handle large Pi RPC terminal events --- src/infrastructure/adapters/pi.ts | 31 +++++++++++++++++++-- test/unit/infrastructure/pi-adapter.test.ts | 18 ++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/infrastructure/adapters/pi.ts b/src/infrastructure/adapters/pi.ts index 07ad34b..e6c6501 100644 --- a/src/infrastructure/adapters/pi.ts +++ b/src/infrastructure/adapters/pi.ts @@ -9,7 +9,7 @@ import type { IAgentAdapter, AdapterTestResult, ExecuteParams, AgentEvent, ExecuteHandle } from './interface.js'; import type { IProcessManager } from '../process/process-manager.js'; -import { readLines } from '../process/process-manager.js'; +import type { Readable } from 'node:stream'; import { createTokenUsage, type TokenUsage } from '../../domain/run.js'; import { classifyAdapterError } from '../../domain/errors.js'; import { execFile } from 'node:child_process'; @@ -105,7 +105,7 @@ function createPiRpcEvents( try { if (proc.stdout) { - for await (const line of readLines(proc.stdout)) { + for await (const line of readPiRpcLines(proc.stdout)) { if (signal?.aborted) break; const event = parsePiRpcEvent(line, { finalText, lastTokens }); if (!event) continue; @@ -377,3 +377,30 @@ function extractPiTokensFromMessage(parsed: Record): TokenUsage function numberField(value: unknown): number | undefined { return typeof value === 'number' ? value : undefined; } + +/** + * Pi RPC can emit very large JSONL records (notably agent_end with the full + * message transcript). Do not use the generic process readLines helper here: + * it caps lines at 16 KB, which corrupts large JSON records before the adapter + * can parse the terminal event. + */ +async function* readPiRpcLines(stream: Readable): AsyncGenerator { + let pending: Buffer = Buffer.alloc(0); + + for await (const chunk of stream) { + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string, 'utf-8'); + pending = pending.length ? Buffer.concat([pending, buf]) : buf; + + let newlineIdx: number; + while ((newlineIdx = pending.indexOf(0x0a)) !== -1) { + const line = pending.subarray(0, newlineIdx).toString('utf-8'); + pending = pending.subarray(newlineIdx + 1); + if (line) yield line.endsWith('\r') ? line.slice(0, -1) : line; + } + } + + if (pending.length) { + const line = pending.toString('utf-8'); + if (line) yield line.endsWith('\r') ? line.slice(0, -1) : line; + } +} diff --git a/test/unit/infrastructure/pi-adapter.test.ts b/test/unit/infrastructure/pi-adapter.test.ts index 051d966..cb9577a 100644 --- a/test/unit/infrastructure/pi-adapter.test.ts +++ b/test/unit/infrastructure/pi-adapter.test.ts @@ -208,6 +208,24 @@ describe('PiAdapter', () => { expect((events[0]!.data as any).paths).toEqual(['src/new.ts']); }); + it('maps large agent_end lines to done without truncating JSON', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + const largeText = 'x'.repeat(20_000); + + proc.stdout.write(JSON.stringify({ + type: 'agent_end', + messages: [{ role: 'assistant', content: [{ type: 'text', text: largeText }], usage: { input: 10, output: 4, totalTokens: 14 } }], + }) + '\n'); + + const events = await collectEvents(handle, proc); + + expect(events.at(-1)!.type).toBe('done'); + expect((events.at(-1)!.data as any).result).toBe(largeText); + }); + it('maps agent_end to done with final text and tokens', async () => { const proc = createMockProcess(); const pm = createMockProcessManager(proc); From 55e39290195d5ec5f3544dca4be6b02cc7e10788 Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 16:52:14 +0300 Subject: [PATCH 03/11] fix(pi): harden RPC stream lifecycle per PR review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review feedback on the Pi RPC adapter — all changes are correctness fixes around stream lifecycle and diagnostics, no design changes. Blockers: - B1: close stdin after writing prompt so Pi --mode rpc sees EOF and emits agent_end. Without this the orchestrator hangs and only recovers via the external kill path that never fires. - B2: in the finally block, if we exit without a 'done' event due to abort or a stream error, schedule killWithGrace(pid, 1_000). This unblocks exitPromise and releases the 'close'/'error' listeners that pin the ChildProcess. - B3: wrap the stdout for-await in try/catch. A pre-first-byte stdout 'error' (ECONNRESET, EPIPE, …) previously escaped as an unhandled rejection; now it is classified via classifyAdapterError and yielded as an AgentEvent of type 'error'. Important: - I1: simplify extractPassiveUpdate — both branches returned null; drop the unused ParseState argument and reduce to a single return. - I3: drop Buffer generic in readPiRpcLines — the generic form requires @types/node 22+, but the project pins ^20.17.0. Use plain Buffer with a null sentinel to keep TS strict-mode happy. - I4: remove `proc as any` from the test mock — cast through `unknown` to ChildProcess (CLAUDE.md forbids `as any`). - I6: collapse the token-alias spread (8 keys across 5 fields) into a single PI_TOKEN_ALIASES map with a comment explaining why aliases exist — Pi versions plus Anthropic-style fallthrough. - I8: replace `proc.stderr?.resume()` with createStderrTailCapture(), retaining the last 4 KB of stderr so auth/extension-load failures surface in the non-zero-exit error message instead of vanishing. Tests: - New: closes stdin after writing prompt (B1) - New: kills the process when the abort signal fires before a done event (B2) - New: yields an error event when stdout emits an error before any line (B3) - New: appends stderr tail to error message on non-zero exit (I8) - Updated: createMockProcessManager casts through unknown (I4) Verified: npm run typecheck (clean), npm test (1947 passed, 2 skipped). Co-Authored-By: Claude Opus 4.7 (1M context) --- src/infrastructure/adapters/pi.ts | 157 +++++++++++++++----- test/unit/infrastructure/pi-adapter.test.ts | 92 ++++++++++-- 2 files changed, 200 insertions(+), 49 deletions(-) diff --git a/src/infrastructure/adapters/pi.ts b/src/infrastructure/adapters/pi.ts index e6c6501..f4df457 100644 --- a/src/infrastructure/adapters/pi.ts +++ b/src/infrastructure/adapters/pi.ts @@ -65,8 +65,9 @@ export class PiAdapter implements IAgentAdapter { stdio: ['pipe', 'pipe', 'pipe'], }); - // Avoid stderr backpressure if extensions emit warnings during startup. - proc.stderr?.resume(); + // Capture stderr tail so auth/extension-load errors surface in non-zero exits + // rather than being silently drained. Drains backpressure at the same time. + const stderrTail = createStderrTailCapture(proc.stderr); if (proc.stdin) { proc.stdin.write(JSON.stringify({ @@ -74,9 +75,12 @@ export class PiAdapter implements IAgentAdapter { type: 'prompt', message: params.prompt, }) + '\n'); + // Pi --mode rpc reads stdin until EOF. ORCH runs one prompt per process, + // so close stdin immediately or Pi will keep waiting and never emit agent_end. + proc.stdin.end(); } - const events = createPiRpcEvents(proc, pid, this.processManager, params.signal); + const events = createPiRpcEvents(proc, pid, this.processManager, stderrTail, params.signal); return { pid, events }; } @@ -89,10 +93,12 @@ function createPiRpcEvents( proc: import('node:child_process').ChildProcess, pid: number, processManager: IProcessManager, + stderrTail: () => string, signal?: AbortSignal, ): AsyncGenerator { async function* generate(): AsyncGenerator { let gotDoneEvent = false; + let streamErrorYielded = false; let finalText = ''; let lastTokens: TokenUsage | undefined; let exitCode: number | null = null; @@ -103,49 +109,81 @@ function createPiRpcEvents( proc.on('error', (err) => { exitError = err; resolve(); }); }); + let streamError: Error | null = null; try { if (proc.stdout) { - for await (const line of readPiRpcLines(proc.stdout)) { - if (signal?.aborted) break; - const event = parsePiRpcEvent(line, { finalText, lastTokens }); - if (!event) continue; - - if (event.finalText !== undefined) finalText = event.finalText; - if (event.tokens) lastTokens = event.tokens; - - if (event.agentEvent) { - if (event.agentEvent.type === 'done') gotDoneEvent = true; - yield event.agentEvent; - if (event.agentEvent.type === 'done') { - // Pi RPC is a long-lived process. ORCH tasks are one-shot runs, so - // stop Pi after the terminal event instead of waiting forever. - await processManager.killWithGrace(pid, 1_000).catch(() => {}); - return; + try { + for await (const line of readPiRpcLines(proc.stdout)) { + if (signal?.aborted) break; + const event = parsePiRpcEvent(line, { finalText, lastTokens }); + if (!event) continue; + + if (event.finalText !== undefined) finalText = event.finalText; + if (event.tokens) lastTokens = event.tokens; + + if (event.agentEvent) { + if (event.agentEvent.type === 'done') gotDoneEvent = true; + yield event.agentEvent; + if (event.agentEvent.type === 'done') { + // Pi RPC is a long-lived process. ORCH tasks are one-shot runs, so + // stop Pi after the terminal event instead of waiting forever. + await processManager.killWithGrace(pid, 1_000).catch(() => {}); + return; + } } } + } catch (err) { + // stdout emitted 'error' (ECONNRESET, EPIPE, etc) before a terminal event. + // Without this catch the rejection propagates out of the async generator + // as an unhandled error and the orchestrator only sees the run hang. + streamError = err instanceof Error ? err : new Error(String(err)); + if (!signal?.aborted && !gotDoneEvent) { + streamErrorYielded = true; + yield { + type: 'error', + timestamp: new Date().toISOString(), + data: { message: streamError.message }, + errorKind: classifyAdapterError(streamError.message), + }; + } } } } finally { proc.stdout?.destroy(); + // Pi RPC is long-lived. If we leave via abort/break without a 'done' event, + // the process is still alive — kill it so exitPromise resolves and the + // generator doesn't pin the ChildProcess via dangling 'close' / 'error' listeners. + if (!gotDoneEvent && (signal?.aborted || streamError)) { + processManager.killWithGrace(pid, 1_000).catch(() => {}); + } } await exitPromise; + // streamError was already surfaced as an error event — don't double-report. + if (streamErrorYielded) return; + const spawnError = exitError as Error | null; if (spawnError && !signal?.aborted && !gotDoneEvent) { - const classified = classifyAdapterError(spawnError.message, exitCode ?? undefined); - throw Object.assign(new Error(spawnError.message), { errorKind: classified }); + const message = appendStderrTail(spawnError.message, stderrTail()); + const classified = classifyAdapterError(message, exitCode ?? undefined); + throw Object.assign(new Error(message), { errorKind: classified }); } if (exitCode !== 0 && exitCode !== null && !signal?.aborted && !gotDoneEvent) { - const msg = `Pi process exited with code ${exitCode}`; - const classified = classifyAdapterError(msg, exitCode); - throw Object.assign(new Error(msg), { errorKind: classified }); + const baseMsg = `Pi process exited with code ${exitCode}`; + const message = appendStderrTail(baseMsg, stderrTail()); + const classified = classifyAdapterError(message, exitCode); + throw Object.assign(new Error(message), { errorKind: classified }); } } return generate(); } +function appendStderrTail(message: string, tail: string): string { + return tail ? `${message}\n--- pi stderr (tail) ---\n${tail}` : message; +} + interface ParseState { finalText: string; lastTokens?: TokenUsage; @@ -182,7 +220,7 @@ function parsePiRpcEvent(line: string, state: ParseState): ParsedPiEvent | null case 'compaction_end': case 'auto_retry_start': case 'auto_retry_end': - return extractPassiveUpdate(parsed, state); + return extractPassiveUpdate(parsed); case 'response': { if (parsed.success === false) { @@ -309,10 +347,9 @@ function parseToolExecutionEnd(parsed: Record, timestamp: strin return { agentEvent: { type: 'output', timestamp, data: parsed } }; } -function extractPassiveUpdate(parsed: Record, state: ParseState): ParsedPiEvent | null { +function extractPassiveUpdate(parsed: Record): ParsedPiEvent | null { const tokens = extractPiTokensFromMessage(parsed); - if (tokens) return { tokens }; - return state.finalText ? null : null; + return tokens ? { tokens } : null; } function extractFinalText(parsed: Record): string | undefined { @@ -360,22 +397,64 @@ function extractPiTokensFromAgentEnd(parsed: Record): TokenUsag return undefined; } +// Pi exposes usage under multiple key shapes across versions and across the +// `message_*` vs `agent_end` paths — Pi-native names, snake_case shims, and +// Anthropic-style names when Pi forwards Claude usage records unchanged. +// First match per field wins, in this order. +const PI_TOKEN_ALIASES: Record<'input' | 'output' | 'reasoning' | 'cache_read' | 'cache_write', readonly string[]> = { + input: ['input', 'input_tokens'], + output: ['output', 'output_tokens'], + reasoning: ['reasoning', 'reasoning_tokens'], + cache_read: ['cacheRead', 'cache_read', 'cache_read_input_tokens'], + cache_write: ['cacheWrite', 'cache_write', 'cache_creation_input_tokens'], +}; + function extractPiTokensFromMessage(parsed: Record): TokenUsage | undefined { const usage = parsed.usage as Record | undefined; if (!usage) return undefined; - const input = numberField(usage.input) ?? numberField(usage.input_tokens) ?? 0; - const output = numberField(usage.output) ?? numberField(usage.output_tokens) ?? 0; - const reasoning = numberField(usage.reasoning) ?? numberField(usage.reasoning_tokens) ?? 0; - const cache_read = numberField(usage.cacheRead) ?? numberField(usage.cache_read) ?? numberField(usage.cache_read_input_tokens) ?? 0; - const cache_write = numberField(usage.cacheWrite) ?? numberField(usage.cache_write) ?? numberField(usage.cache_creation_input_tokens) ?? 0; + const pick = (keys: readonly string[]): number => { + for (const k of keys) { + const v = usage[k]; + if (typeof v === 'number') return v; + } + return 0; + }; + + const input = pick(PI_TOKEN_ALIASES.input); + const output = pick(PI_TOKEN_ALIASES.output); + const reasoning = pick(PI_TOKEN_ALIASES.reasoning); + const cache_read = pick(PI_TOKEN_ALIASES.cache_read); + const cache_write = pick(PI_TOKEN_ALIASES.cache_write); if (input === 0 && output === 0 && reasoning === 0 && cache_read === 0 && cache_write === 0) return undefined; return createTokenUsage(input, output, { reasoning, cache_read, cache_write }); } -function numberField(value: unknown): number | undefined { - return typeof value === 'number' ? value : undefined; +/** + * Drain stderr while keeping the last STDERR_TAIL_BYTES bytes for diagnostics. + * Returns a closure that yields the captured tail as a UTF-8 string. + * + * Without draining, a chatty stderr can fill the pipe buffer and stall Pi. + * Without the tail, auth or extension-load failures vanish on non-zero exit. + */ +const STDERR_TAIL_BYTES = 4096; +function createStderrTailCapture(stderr: Readable | null | undefined): () => string { + if (!stderr) return () => ''; + const chunks: Buffer[] = []; + let total = 0; + stderr.on('data', (chunk: Buffer | string) => { + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8'); + chunks.push(buf); + total += buf.length; + while (total > STDERR_TAIL_BYTES && chunks.length > 0) { + const head = chunks.shift()!; + total -= head.length; + } + }); + // Swallow late 'error' on stderr — we already have what we need from 'data'. + stderr.on('error', () => {}); + return () => Buffer.concat(chunks).toString('utf-8').slice(-STDERR_TAIL_BYTES).trimEnd(); } /** @@ -385,11 +464,11 @@ function numberField(value: unknown): number | undefined { * can parse the terminal event. */ async function* readPiRpcLines(stream: Readable): AsyncGenerator { - let pending: Buffer = Buffer.alloc(0); + let pending: Buffer | null = null; for await (const chunk of stream) { - const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string, 'utf-8'); - pending = pending.length ? Buffer.concat([pending, buf]) : buf; + const buf: Buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string, 'utf-8'); + pending = pending ? Buffer.concat([pending, buf]) : buf; let newlineIdx: number; while ((newlineIdx = pending.indexOf(0x0a)) !== -1) { @@ -399,7 +478,7 @@ async function* readPiRpcLines(stream: Readable): AsyncGenerator { } } - if (pending.length) { + if (pending && pending.length) { const line = pending.toString('utf-8'); if (line) yield line.endsWith('\r') ? line.slice(0, -1) : line; } diff --git a/test/unit/infrastructure/pi-adapter.test.ts b/test/unit/infrastructure/pi-adapter.test.ts index cb9577a..02dab42 100644 --- a/test/unit/infrastructure/pi-adapter.test.ts +++ b/test/unit/infrastructure/pi-adapter.test.ts @@ -5,6 +5,7 @@ import type { AgentEvent, ExecuteParams } from '../../../src/infrastructure/adap import { AdapterErrorKind } from '../../../src/domain/errors.js'; import { PassThrough } from 'node:stream'; import { EventEmitter } from 'node:events'; +import type { ChildProcess } from 'node:child_process'; vi.mock('node:child_process', async (importOriginal) => { const actual = await importOriginal(); @@ -18,14 +19,16 @@ vi.mock('node:child_process', async (importOriginal) => { }; }); -function createMockProcess() { - const proc = new EventEmitter() as EventEmitter & { - stdout: PassThrough; - stderr: PassThrough; - stdin: PassThrough; - pid: number; - kill: () => void; - }; +type MockProcess = EventEmitter & { + stdout: PassThrough; + stderr: PassThrough; + stdin: PassThrough; + pid: number; + kill: () => void; +}; + +function createMockProcess(): MockProcess { + const proc = new EventEmitter() as MockProcess; proc.stdout = new PassThrough(); proc.stderr = new PassThrough(); proc.stdin = new PassThrough(); @@ -34,12 +37,12 @@ function createMockProcess() { return proc; } -function createMockProcessManager(proc: ReturnType): IProcessManager { +function createMockProcessManager(proc: MockProcess): IProcessManager { return { isAlive: vi.fn(() => true), kill: vi.fn(), killWithGrace: vi.fn(async () => {}), - spawn: vi.fn(() => ({ process: proc as any, pid: proc.pid })), + spawn: vi.fn(() => ({ process: proc as unknown as ChildProcess, pid: proc.pid })), }; } @@ -122,6 +125,17 @@ describe('PiAdapter', () => { expect(JSON.parse(line)).toMatchObject({ type: 'prompt', message: 'do work' }); }); + it('closes stdin after writing prompt so Pi RPC sees EOF', () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const endSpy = vi.spyOn(proc.stdin, 'end'); + + adapter.execute(makeParams({ prompt: 'do work' })); + + expect(endSpy).toHaveBeenCalled(); + }); + it('ignores extension_ui_request events', async () => { const proc = createMockProcess(); const pm = createMockProcessManager(proc); @@ -261,6 +275,64 @@ describe('PiAdapter', () => { expect(events[0]!.type).toBe('error'); expect(events[0]!.errorKind).toBe(AdapterErrorKind.UNKNOWN); }); + + it('yields an error event when stdout emits an error before any line', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + // Trigger 'error' on stdout before any data — the for await must catch it + // and surface an error event instead of throwing an unhandled rejection. + setTimeout(() => proc.stdout.emit('error', new Error('ECONNRESET')), 5); + setTimeout(() => proc.emit('close', 1), 20); + + const events: AgentEvent[] = []; + for await (const ev of handle.events) events.push(ev); + + expect(events).toHaveLength(1); + expect(events[0]!.type).toBe('error'); + expect((events[0]!.data as { message: string }).message).toContain('ECONNRESET'); + // Pi adapter must clean up the process when the stream dies before 'done'. + expect(pm.killWithGrace).toHaveBeenCalledWith(proc.pid, 1_000); + }); + + it('kills the process when the abort signal fires before a done event', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const controller = new AbortController(); + const handle = adapter.execute(makeParams({ signal: controller.signal })); + + // Emit a non-terminal event, then abort. The generator must break and + // schedule killWithGrace via the finally block. + proc.stdout.write(JSON.stringify({ type: 'message_update', assistantMessageEvent: { type: 'text_delta', delta: 'partial' } }) + '\n'); + setTimeout(() => { + controller.abort(); + proc.stdout.end(); + proc.emit('close', null); + }, 10); + + const events: AgentEvent[] = []; + for await (const ev of handle.events) events.push(ev); + + expect(pm.killWithGrace).toHaveBeenCalledWith(proc.pid, 1_000); + }); + + it('appends stderr tail to error message on non-zero exit', async () => { + const proc = createMockProcess(); + const pm = createMockProcessManager(proc); + const adapter = new PiAdapter(pm); + const handle = adapter.execute(makeParams()); + + proc.stderr.write('error: failed to load extension foo\n'); + proc.stdout.end(); + setTimeout(() => proc.emit('close', 2), 20); + + await expect(async () => { + for await (const _ev of handle.events) { void _ev; } + }).rejects.toThrow(/failed to load extension foo/); + }); }); describe('test', () => { From 0a52296a06a9d811ffe483398220890df0d7c4fe Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 17:02:55 +0300 Subject: [PATCH 04/11] test(pi): parameterized adapter coverage for pi Mirror the existing claude/codex/opencode test rows with a pi case in suites that already enumerate adapters one-by-one. Tightens the safety net for the new adapter without changing behavior. - agent-factory: pi resolves to openai-codex/gpt-5.5; MCP skills filtered - commands-init: getDefaultAgents('pi') uses pi adapter + pi-tier model; MCP skills excluded (only claude keeps them) - wizard-effort: effort step is shown for pi (matches EFFORT_ADAPTERS) Co-Authored-By: Claude Opus 4.7 (1M context) --- test/unit/application/agent-factory.test.ts | 11 +++++++++++ test/unit/cli/commands-init.test.ts | 3 +++ test/unit/tui/wizard-effort.test.ts | 6 ++++++ 3 files changed, 20 insertions(+) diff --git a/test/unit/application/agent-factory.test.ts b/test/unit/application/agent-factory.test.ts index 31d8bd9..aeef92f 100644 --- a/test/unit/application/agent-factory.test.ts +++ b/test/unit/application/agent-factory.test.ts @@ -47,6 +47,17 @@ describe('templateToAgentInput', () => { expect(input.model).toBeUndefined(); // empty string → undefined }); + it('resolves model for pi adapter', () => { + const input = templateToAgentInput(baseTemplate, 'pi'); + expect(input.adapter).toBe('pi'); + expect(input.model).toBe('openai-codex/gpt-5.5'); + }); + + it('filters MCP skills for pi adapter', () => { + const input = templateToAgentInput(baseTemplate, 'pi'); + expect(input.skills).toEqual(['review', 'careful']); + }); + it('keeps all skills for claude adapter', () => { const input = templateToAgentInput(baseTemplate, 'claude'); expect(input.skills).toEqual(['review', 'careful', 'feature-dev:feature-dev', 'testing-suite:generate-tests']); diff --git a/test/unit/cli/commands-init.test.ts b/test/unit/cli/commands-init.test.ts index d7a7973..98289ef 100644 --- a/test/unit/cli/commands-init.test.ts +++ b/test/unit/cli/commands-init.test.ts @@ -90,11 +90,13 @@ describe('getDefaultAgents()', () => { it('uses provided adapter', () => { expect(getDefaultAgents('opencode')[0].adapter).toBe('opencode'); expect(getDefaultAgents('codex')[0].adapter).toBe('codex'); + expect(getDefaultAgents('pi')[0].adapter).toBe('pi'); }); it('resolves model from adapter tier', () => { expect(getDefaultAgents('claude')[0].config.model).toBe('claude-sonnet-4-6'); expect(getDefaultAgents('codex')[0].config.model).toBe('gpt-5.3-codex'); + expect(getDefaultAgents('pi')[0].config.model).toBe('openai-codex/gpt-5.5'); }); it('includes MCP skills for claude adapter', () => { @@ -104,6 +106,7 @@ describe('getDefaultAgents()', () => { it('excludes MCP skills for non-claude adapters', () => { expect(getDefaultAgents('opencode')[0].config.skills).toEqual([]); expect(getDefaultAgents('codex')[0].config.skills).toEqual([]); + expect(getDefaultAgents('pi')[0].config.skills).toEqual([]); }); it('agent has approval_policy=suggest', () => { diff --git a/test/unit/tui/wizard-effort.test.ts b/test/unit/tui/wizard-effort.test.ts index efb950d..73373f0 100644 --- a/test/unit/tui/wizard-effort.test.ts +++ b/test/unit/tui/wizard-effort.test.ts @@ -53,6 +53,12 @@ describe('Agent wizard — effort step', () => { expect(effortStep.skip!({ adapter: 'claude' })).toBe(false); }); + it('effort step is shown for pi adapter', () => { + const steps = getAgentWizardSteps(); + const effortStep = steps.find((s) => s.id === 'effort')!; + expect(effortStep.skip!({ adapter: 'pi' })).toBe(false); + }); + it('effort step is skipped for codex adapter', () => { const steps = getAgentWizardSteps(); const effortStep = steps.find((s) => s.id === 'effort')!; From fa007c7beecf3ecbad301149c5d52e9518576b99 Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 17:05:34 +0300 Subject: [PATCH 05/11] fix(tui): mention pi and opencode in agents onboarding tip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The empty-state onboarding tip for the Agents tab listed only four of the six adapters ORCH ships ("claude, codex, cursor, shell") — pi and opencode were missing. New users on the Agents tab couldn't discover them without reading docs. Update the description to enumerate all six and export ONBOARDING_AGENTS so a regression test can assert it stays in sync with SUPPORTED_ADAPTERS. Future adapter additions will fail the test if the tip isn't updated. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/tui/App.tsx | 7 ++++--- test/unit/tui/onboarding-agents.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) create mode 100644 test/unit/tui/onboarding-agents.test.ts diff --git a/src/tui/App.tsx b/src/tui/App.tsx index 4788d27..1e38dbb 100644 --- a/src/tui/App.tsx +++ b/src/tui/App.tsx @@ -93,12 +93,13 @@ const ONBOARDING_TASKS: OnboardingConfig = { nudge: 'Add more tasks to keep agents busy.', }; -const ONBOARDING_AGENTS: OnboardingConfig = { +// Exported so tests can assert the adapter list stays in sync with SUPPORTED_ADAPTERS. +export const ONBOARDING_AGENTS: OnboardingConfig = { title: 'Agents', description: [ 'AI workers that execute your tasks.', - 'Each agent uses an adapter (claude, codex,', - 'cursor, shell) and has its own role.', + 'Each agent uses an adapter (claude,', + 'codex, opencode, cursor, pi, shell).', ], hints: [{ key: 'N', label: 'new agent' }, { key: 'W', label: 'start orchestrator' }], nudge: 'Add more agents to increase parallelism.', diff --git a/test/unit/tui/onboarding-agents.test.ts b/test/unit/tui/onboarding-agents.test.ts new file mode 100644 index 0000000..f8810ee --- /dev/null +++ b/test/unit/tui/onboarding-agents.test.ts @@ -0,0 +1,22 @@ +/** + * Onboarding invariant: the Agents onboarding tip must enumerate every + * adapter ORCH ships. If a new adapter is added to SUPPORTED_ADAPTERS but + * not mentioned in the tip, new users won't know it exists. + */ + +import { describe, it, expect } from 'vitest'; +import { ONBOARDING_AGENTS } from '../../../src/tui/App.js'; +import { SUPPORTED_ADAPTERS } from '../../../src/domain/model-tiers.js'; + +describe('ONBOARDING_AGENTS', () => { + it('lists every adapter from SUPPORTED_ADAPTERS', () => { + const joined = ONBOARDING_AGENTS.description.join(' ').toLowerCase(); + for (const adapter of SUPPORTED_ADAPTERS) { + expect(joined, `adapter "${adapter}" must appear in the onboarding tip`).toContain(adapter); + } + }); + + it('keeps the description at most 3 lines so it fits the onboarding box', () => { + expect(ONBOARDING_AGENTS.description.length).toBeLessThanOrEqual(3); + }); +}); From 7b01adb7e8dc6106652fcac9b7a71724ae00e78f Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 17:11:09 +0300 Subject: [PATCH 06/11] docs: refresh test count to 1952 across readme + CONTRIBUTING The "1694 tests" claim is from before the Pi adapter, the parametrized adapter tests, the Pi stream-lifecycle hardening, and the onboarding regression test all landed on this branch. Bump the badge, the `npm test` comment in the Development section, and the Quick Start checklist in CONTRIBUTING.md to the current count. Co-Authored-By: Claude Opus 4.7 (1M context) --- CONTRIBUTING.md | 2 +- readme.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0803e8b..1bb370e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,7 @@ npm install # 3. Run in dev mode (no build needed) npm run dev -# 4. Run tests — all 1694 should pass +# 4. Run tests — all 1952 should pass npm test # 5. Type-check diff --git a/readme.md b/readme.md index 1077a6d..e35ccf1 100644 --- a/readme.md +++ b/readme.md @@ -15,7 +15,7 @@ Website  npm  MIT License  - Tests + Tests


@@ -622,7 +622,7 @@ src/ ```bash npm run dev # Run via tsx npm run build # Build ESM + DTS -npm test # 1694 tests via Vitest +npm test # 1952 tests via Vitest npm run typecheck # Strict TypeScript ``` From 86a18f5d45a50c93c594b116ec2fba23609c0deb Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 17:22:24 +0300 Subject: [PATCH 07/11] test(integration): pi adapter end-to-end through Orchestrator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the first integration test under test/integration/ that drives one task through the entire orchestrator pipeline with a real PiAdapter and a mocked ProcessManager.spawn — no subprocess, no network, ~12ms in CI. What "from-and-to" covers in this single test: 1. Dispatch: real Orchestrator.tick() pulls the todo task, matches the idle pi agent via AgentService.findBestAgent, calls PiAdapter.execute which actually spawns (mocked), writes the prompt JSONL to stdin, and closes stdin (B1 invariant — checked via spy on proc.stdin.end). 2. Stream parsing: we feed Pi RPC JSONL lines through the real PassThrough stdout — message_update (text_delta), tool_execution_start (read), tool_execution_end (bash + write), agent_end with usage — and assert they map to the right RunEvent types in the real run store. 3. State machine: assert the full transition trace todo → in_progress → review → done (auto-approve, because makeAgent defaults to approval_policy=auto). The transitions are read from the real event bus, not from internal orchestrator methods. 4. Agent cleanup: after the run, the agent is back to idle, current_task is cleared, and tasks_completed is incremented. 5. Lifecycle: PiAdapter calls processManager.killWithGrace(pid, 1000) after the terminal event — verified. 6. Tokens: usage from agent_end propagates onto the Run, with total including input + output + reasoning and cache_read/write treated as informational (matches the comment in domain/run.ts). This file is the template for adapter e2e tests. For a new adapter, copy this file, swap PiAdapter, and rewrite only the stdout JSONL payloads plus parse-specific assertions. Test count bumped to 1953 across readme + CONTRIBUTING. Co-Authored-By: Claude Opus 4.7 (1M context) --- CONTRIBUTING.md | 2 +- readme.md | 4 +- test/integration/pi-adapter.e2e.test.ts | 249 ++++++++++++++++++++++++ 3 files changed, 252 insertions(+), 3 deletions(-) create mode 100644 test/integration/pi-adapter.e2e.test.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1bb370e..ef68042 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,7 @@ npm install # 3. Run in dev mode (no build needed) npm run dev -# 4. Run tests — all 1952 should pass +# 4. Run tests — all 1953 should pass npm test # 5. Type-check diff --git a/readme.md b/readme.md index e35ccf1..500d82b 100644 --- a/readme.md +++ b/readme.md @@ -15,7 +15,7 @@ Website  npm  MIT License  - Tests + Tests


@@ -622,7 +622,7 @@ src/ ```bash npm run dev # Run via tsx npm run build # Build ESM + DTS -npm test # 1952 tests via Vitest +npm test # 1953 tests via Vitest npm run typecheck # Strict TypeScript ``` diff --git a/test/integration/pi-adapter.e2e.test.ts b/test/integration/pi-adapter.e2e.test.ts new file mode 100644 index 0000000..ebf3c09 --- /dev/null +++ b/test/integration/pi-adapter.e2e.test.ts @@ -0,0 +1,249 @@ +/** + * Pi adapter — end-to-end through the Orchestrator. + * + * Drives one task through the full lifecycle using a real PiAdapter, a real + * Orchestrator, real state machine + JSONL run storage, and a mocked + * ProcessManager.spawn() that returns a controllable child process. + * + * What this test asserts "from-and-to": + * 1. Dispatch: orchestrator pulls a todo task, finds the pi agent, calls + * PiAdapter.execute() — which spawns, writes the prompt JSONL to stdin, + * and closes stdin (B1). + * 2. Stream: feeding RPC events to stdout (text_delta, tool_execution_start, + * bash + write tool ends, agent_end with usage) produces the matching + * AgentEvents on the orchestrator's event bus. + * 3. Collect + state machine: each event is appended to the run's JSONL, + * and the task transitions todo → in_progress → review → done + * (auto-approve, because makeAgent() sets approval_policy=auto). + * 4. Cleanup: after the terminal `done` event, PiAdapter kills the long-lived + * Pi RPC process via processManager.killWithGrace(pid, 1000). + * 5. Tokens: usage from agent_end propagates onto the done event. + * + * This is the template for "e2e through Orchestrator" adapter tests. For a new + * adapter: copy this file, swap PiAdapter for the new adapter, and rewrite the + * stdout JSONL payloads + parse-specific assertions. + */ + +import { describe, it, expect, vi } from 'vitest'; +import { PassThrough } from 'node:stream'; +import { EventEmitter } from 'node:events'; +import type { ChildProcess } from 'node:child_process'; +import type { SpawnResult, IProcessManager } from '../../src/infrastructure/process/process-manager.js'; +import { Orchestrator } from '../../src/application/orchestrator.js'; +import { PiAdapter } from '../../src/infrastructure/adapters/pi.js'; +import { AdapterRegistry } from '../../src/infrastructure/adapters/registry.js'; +import type { OrchestratorEvent } from '../../src/domain/events.js'; +import { + buildDeps, + makeTask, + makeAgent, + createMockTaskStore, + createMockAgentStore, + createMockRunStore, + createMockStateStore, + cleanupOrch, +} from '../unit/application/helpers.js'; + +type MockProc = EventEmitter & { + stdout: PassThrough; + stderr: PassThrough; + stdin: PassThrough; + pid: number; + kill: ReturnType; +}; + +function createMockProcess(pid = 24601): MockProc { + const proc = new EventEmitter() as MockProc; + proc.stdout = new PassThrough(); + proc.stderr = new PassThrough(); + proc.stdin = new PassThrough(); + proc.pid = pid; + proc.kill = vi.fn(); + return proc; +} + +/** Wait until `predicate()` returns truthy, polling at 5 ms intervals. */ +async function waitFor(predicate: () => Promise | T | null | undefined, timeoutMs = 2000): Promise { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const value = await predicate(); + if (value) return value; + await new Promise((r) => setTimeout(r, 5)); + } + throw new Error(`waitFor: predicate did not become truthy within ${timeoutMs}ms`); +} + +describe('Pi adapter — end-to-end through Orchestrator', () => { + it('drives a task todo → in_progress → review → done via real PiAdapter + mocked spawn', async () => { + // ── 1. Mock child process and ProcessManager ─────────────────────────── + const proc = createMockProcess(); + const stdinEndSpy = vi.spyOn(proc.stdin, 'end'); + + const killWithGrace = vi.fn(async (_pid: number, _timeoutMs?: number) => { + // Mirror real ProcessManager behavior: a graceful kill closes the process. + setImmediate(() => proc.emit('close', 0)); + }); + + const processManager: IProcessManager = { + isAlive: vi.fn(() => true), + kill: vi.fn(), + killWithGrace, + spawn: vi.fn((): SpawnResult => ({ process: proc as unknown as ChildProcess, pid: proc.pid })), + }; + + // ── 2. Seed stores with one pi agent and one todo task ───────────────── + const agent = makeAgent({ + id: 'agt_pi', + name: 'pi-engineer', + adapter: 'pi', + status: 'idle', + // approval_policy=auto comes from makeAgent default — review auto-approves. + }); + const task = makeTask({ + id: 'tsk_pi', + title: 'Implement feature X', + status: 'todo', + }); + + const taskStore = createMockTaskStore([task]); + const agentStore = createMockAgentStore([agent]); + const runStore = createMockRunStore(); + const stateStore = createMockStateStore(); + + // ── 3. Real PiAdapter wired into a real AdapterRegistry ──────────────── + const adapterRegistry = new AdapterRegistry(); + adapterRegistry.register(new PiAdapter(processManager)); + + const deps = buildDeps({ + taskStore, + agentStore, + runStore, + stateStore, + processManager, + adapterRegistry, + }); + + // Record every orchestrator event so we can assert on the trace afterwards. + const events: OrchestratorEvent[] = []; + deps.eventBus.onAny((e: OrchestratorEvent) => { + events.push(e); + }); + + const orch = new Orchestrator(deps); + await (orch as { loadState: () => Promise }).loadState(); + + // ── 4. Tick 1 — dispatch (synchronous up to adapter.execute) ────────── + await (orch as { tick: () => Promise }).tick(); + + expect(processManager.spawn).toHaveBeenCalledOnce(); + const spawnCall = (processManager.spawn as ReturnType).mock.calls[0]!; + expect(spawnCall[0]).toBe('pi'); + expect(spawnCall[1]).toEqual(expect.arrayContaining(['--mode', 'rpc'])); + + // B1 invariant: PiAdapter must close stdin after writing the prompt JSONL. + expect(stdinEndSpy).toHaveBeenCalled(); + + // After dispatch, the task is in_progress and the agent is busy. + const dispatchedTask = await taskStore.get('tsk_pi'); + expect(dispatchedTask!.status).toBe('in_progress'); + const busyAgent = await agentStore.get('agt_pi'); + expect(busyAgent!.status).toBe('running'); + expect(busyAgent!.current_task).toBe('tsk_pi'); + + // ── 5. Feed the Pi RPC event stream ──────────────────────────────────── + // Each chunk mirrors what `pi --mode rpc` emits as JSONL on stdout. + proc.stdout.write(JSON.stringify({ + type: 'message_update', + assistantMessageEvent: { type: 'text_delta', delta: 'Reading sources…' }, + }) + '\n'); + + proc.stdout.write(JSON.stringify({ + type: 'tool_execution_start', + toolName: 'read', + args: { path: 'src/foo.ts' }, + }) + '\n'); + + proc.stdout.write(JSON.stringify({ + type: 'tool_execution_end', + toolName: 'bash', + args: { command: 'npm test' }, + result: { content: [{ type: 'text', text: 'passed' }], details: { exitCode: 0 } }, + isError: false, + }) + '\n'); + + proc.stdout.write(JSON.stringify({ + type: 'tool_execution_end', + toolName: 'write', + args: { path: 'src/foo.ts' }, + result: { content: [{ type: 'text', text: 'written' }] }, + isError: false, + }) + '\n'); + + proc.stdout.write(JSON.stringify({ + type: 'agent_end', + messages: [{ + role: 'assistant', + content: [{ type: 'text', text: 'Implementation complete.' }], + usage: { input: 42, output: 17, reasoning: 3, cache_read: 5, cache_write: 0 }, + }], + }) + '\n'); + + // ── 6. Wait for the state machine to settle on `done` ────────────────── + const finalTask = await waitFor(async () => { + const t = await taskStore.get('tsk_pi'); + return t?.status === 'done' ? t : null; + }); + + // ── 7. Assertions on the full trace ──────────────────────────────────── + + // State machine: every transition this task should have gone through. + const taskTransitions = events + .filter((e): e is Extract => + e.type === 'task:status_changed' && (e as { taskId?: string }).taskId === 'tsk_pi', + ) + .map((e) => `${e.from}→${e.to}`); + expect(taskTransitions).toEqual(['todo→in_progress', 'in_progress→review', 'review→done']); + + // Final state: task done, agent idle again. + expect(finalTask.status).toBe('done'); + const freedAgent = await agentStore.get('agt_pi'); + expect(freedAgent!.status).toBe('idle'); + expect(freedAgent!.current_task).toBeUndefined(); + expect(freedAgent!.stats.tasks_completed).toBe(1); + + // Adapter lifecycle: killWithGrace called by PiAdapter after the terminal event + // (the orchestrator may also call it during cleanup; only the first call matters). + expect(killWithGrace).toHaveBeenCalled(); + expect(killWithGrace.mock.calls[0]![0]).toBe(proc.pid); + + // Run events: the JSONL stream produced one event per emitted line, in order. + const runs = await runStore.listAll(); + expect(runs).toHaveLength(1); + const runId = runs[0]!.id; + const runEvents = await runStore.readEvents(runId); + const runEventTypes = runEvents.map((e) => e.type); + // RunEvent types are the orchestrator-side names that AgentEvent types map to. + expect(runEventTypes).toEqual([ + 'agent_output', // text_delta + 'tool_call', // tool_execution_start (read) + 'command_run', // tool_execution_end (bash) + 'file_changed', // tool_execution_end (write) + 'done', // agent_end + ]); + + // Tokens: agent_end usage propagated onto the run after finish(). + // Cache tokens are informational and intentionally NOT added to `total`. + const finalRun = await runStore.get(runId); + expect(finalRun!.status).toBe('succeeded'); + expect(finalRun!.tokens).toEqual({ + input: 42, + output: 17, + reasoning: 3, + cache_read: 5, + cache_write: 0, + total: 62, // input + output + reasoning (cache_read/write are informational) + }); + + cleanupOrch(orch); + }); +}); From c6274fc4b9ac766e6a5a50b3b271073b572c8491 Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 17:45:53 +0300 Subject: [PATCH 08/11] =?UTF-8?q?fix(pi):=20revert=20stdin.end()=20?= =?UTF-8?q?=E2=80=94=20pi=20RPC=20is=20a=20long-lived=20session?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reproduced live against pi-coding-agent 0.73.1 with a real OpenRouter run of one prompt-and-write task: - With proc.stdin.end() (the B1 fix per review): pi emits the {type:"response",success:true} preflight, then agent_start, turn_start, user message_start + message_end, and stalls. The LLM call never runs, the assistant message_start never arrives, agent_end is never produced. The orchestrator timed the run out with only one event in run.jsonl (the echoed user message_start), and the task was marked succeeded without files_changed or tokens — and no hello.md on disk. - Without proc.stdin.end(), the same prompt produces the full event stream — text_delta deltas, tool_execution_start, tool_execution_end for `write`, turn_end, agent_end with usage — and hello.md is written on disk. End-to-end run.jsonl has 19 events and tokens populate on the Run (input + output + cache_read). Root cause: `pi --mode rpc` (see dist/modes/rpc/rpc-mode.js in 0.73.1) is explicitly a persistent server-mode session: `case "prompt"` schedules `session.prompt(...)` asynchronously and the preflight response is emitted back through stdout. Closing stdin between the write and the response breaks the session. The B1 review note had it the other way around. The original PR design (long-lived process killed via processManager.killWithGrace(pid, 1000) after the terminal `done` event) is correct, and `createPiRpcEvents` already does that. Changes: - pi.ts: remove `proc.stdin.end()`; replace the misleading "Pi reads stdin until EOF" comment with a precise note that pi --mode rpc is persistent and we terminate it via killWithGrace on `agent_end`. - pi-adapter.test.ts: the test that asserted stdin.end() was called now asserts stdin.end() is NOT called, with a comment pointing at the rationale and the verified pi version. - pi-adapter.e2e.test.ts: matching update — the "B1 invariant" line was inverted. Other B-fixes (B2 abort/kill, B3 stream-error try/catch) remain. Verified: - npm run typecheck: clean - npm test: 1953 passed, 2 skipped - live: `orch run tsk_XscoAUP` with pi 0.73.1 + openrouter writes hello.md, task transitions todo → in_progress → review → done on attempt 1/3. Co-Authored-By: Claude Opus 4.7 (1M context) --- .gitignore | 1 + src/infrastructure/adapters/pi.ts | 11 ++++++++--- test/integration/pi-adapter.e2e.test.ts | 7 +++++-- test/unit/infrastructure/pi-adapter.test.ts | 8 ++++++-- 4 files changed, 20 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 010e0d8..bfca192 100644 --- a/.gitignore +++ b/.gitignore @@ -45,3 +45,4 @@ npm-debug.log* archive docs +.env.local diff --git a/src/infrastructure/adapters/pi.ts b/src/infrastructure/adapters/pi.ts index f4df457..4b84374 100644 --- a/src/infrastructure/adapters/pi.ts +++ b/src/infrastructure/adapters/pi.ts @@ -75,9 +75,14 @@ export class PiAdapter implements IAgentAdapter { type: 'prompt', message: params.prompt, }) + '\n'); - // Pi --mode rpc reads stdin until EOF. ORCH runs one prompt per process, - // so close stdin immediately or Pi will keep waiting and never emit agent_end. - proc.stdin.end(); + // DO NOT call proc.stdin.end() here. Pi --mode rpc is a long-lived + // persistent session: it sends a prompt preflight response, then drives + // the LLM call asynchronously, streaming message_update / turn_end / + // agent_end as the model responds. Closing stdin after the write breaks + // that pipeline — verified on pi-coding-agent 0.73.1: pi stalls right + // after the user-message_end event and never produces an assistant turn. + // We terminate the long-lived process via processManager.killWithGrace + // immediately after the terminal `done` event (see createPiRpcEvents). } const events = createPiRpcEvents(proc, pid, this.processManager, stderrTail, params.signal); diff --git a/test/integration/pi-adapter.e2e.test.ts b/test/integration/pi-adapter.e2e.test.ts index ebf3c09..fb5ca75 100644 --- a/test/integration/pi-adapter.e2e.test.ts +++ b/test/integration/pi-adapter.e2e.test.ts @@ -140,8 +140,11 @@ describe('Pi adapter — end-to-end through Orchestrator', () => { expect(spawnCall[0]).toBe('pi'); expect(spawnCall[1]).toEqual(expect.arrayContaining(['--mode', 'rpc'])); - // B1 invariant: PiAdapter must close stdin after writing the prompt JSONL. - expect(stdinEndSpy).toHaveBeenCalled(); + // Pi --mode rpc is a long-lived persistent session — stdin must stay open + // so the LLM call can run. Closing stdin stalls pi after user-message_end + // (verified on pi-coding-agent 0.73.1). The adapter terminates pi via + // killWithGrace once the terminal `done` event arrives. + expect(stdinEndSpy).not.toHaveBeenCalled(); // After dispatch, the task is in_progress and the agent is busy. const dispatchedTask = await taskStore.get('tsk_pi'); diff --git a/test/unit/infrastructure/pi-adapter.test.ts b/test/unit/infrastructure/pi-adapter.test.ts index 02dab42..43d1f96 100644 --- a/test/unit/infrastructure/pi-adapter.test.ts +++ b/test/unit/infrastructure/pi-adapter.test.ts @@ -125,7 +125,11 @@ describe('PiAdapter', () => { expect(JSON.parse(line)).toMatchObject({ type: 'prompt', message: 'do work' }); }); - it('closes stdin after writing prompt so Pi RPC sees EOF', () => { + it('keeps stdin open so Pi RPC long-lived session can drive the LLM call', () => { + // Pi --mode rpc is persistent: the prompt write is a request, the LLM + // call runs asynchronously inside pi, and closing stdin stalls it after + // user-message_end (verified on pi-coding-agent 0.73.1). We terminate + // pi via killWithGrace after the terminal `done` event instead. const proc = createMockProcess(); const pm = createMockProcessManager(proc); const adapter = new PiAdapter(pm); @@ -133,7 +137,7 @@ describe('PiAdapter', () => { adapter.execute(makeParams({ prompt: 'do work' })); - expect(endSpy).toHaveBeenCalled(); + expect(endSpy).not.toHaveBeenCalled(); }); it('ignores extension_ui_request events', async () => { From 9bc41dc75b7cfa64607f4d2a5c61caba486ba130 Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 17:56:41 +0300 Subject: [PATCH 09/11] test(integration): pi agent TUI lifecycle via ink-testing-library MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Companion to pi-adapter.e2e.test.ts. Covers the UI half of the smoke run: how a pi agent + a todo task appear, update, and settle inside the Ink/React TUI as the orchestrator pumps events through the React state. Walks the rendered output across four phases: 1. initial Tasks tab — todo row with !!! priority indicator and title 2. switch to Agents tab (`a` key) — `pi-bot` row with `pi` adapter chip and IDLE status 3. dispatch — task flips to in_progress, agent to running, with status change + agent:started events emitted through onSubscribeEvents 4. live activity — agent:output (pi text_delta payload) and agent:file_changed (hello.md) appear in the activity feed; agent:completed plus review→done transitions land the task on done with a ✓ Verified locally — the ink-testing-library frames show the activity feed exactly as a real user would see it: ▍ now pi-bot ▶ Started task ▏ │ {"text":"Writing hello.md…","raw":{}} ▏ ✎ hello.md ▏ ▶ Completed successfully now ♦ in_progress → review ✓ Create hello.md via pi Task completed by pi-bot Bumps the test count badge + CONTRIBUTING quickstart to 1954. Co-Authored-By: Claude Opus 4.7 (1M context) --- CONTRIBUTING.md | 2 +- readme.md | 4 +- test/integration/pi-tui.e2e.test.tsx | 173 +++++++++++++++++++++++++++ 3 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 test/integration/pi-tui.e2e.test.tsx diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef68042..f50e9ed 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,7 @@ npm install # 3. Run in dev mode (no build needed) npm run dev -# 4. Run tests — all 1953 should pass +# 4. Run tests — all 1954 should pass npm test # 5. Type-check diff --git a/readme.md b/readme.md index 500d82b..9e07677 100644 --- a/readme.md +++ b/readme.md @@ -15,7 +15,7 @@ Website  npm  MIT License  - Tests + Tests


@@ -622,7 +622,7 @@ src/ ```bash npm run dev # Run via tsx npm run build # Build ESM + DTS -npm test # 1953 tests via Vitest +npm test # 1954 tests via Vitest npm run typecheck # Strict TypeScript ``` diff --git a/test/integration/pi-tui.e2e.test.tsx b/test/integration/pi-tui.e2e.test.tsx new file mode 100644 index 0000000..d7ed299 --- /dev/null +++ b/test/integration/pi-tui.e2e.test.tsx @@ -0,0 +1,173 @@ +/** + * Pi agent in TUI — end-to-end UI lifecycle test. + * + * Renders App.tsx with a real pi-adapter agent and a todo task, then walks the + * dataflow + event stream that ORCH would emit while dispatching the task: + * 1. agent appears with `pi` adapter chip on the Agents tab + * 2. on dispatch the task flips to in_progress and the agent to running + * 3. activity feed shows agent:output and agent:file_changed events + * 4. on completion the agent returns to idle and the task lands on done + * + * Asserts visible UI affordances at each step. Mirrors what a user would see + * in `orch tui` while a pi run is in flight. Companion to + * test/integration/pi-adapter.e2e.test.ts (which covers the engine path). + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import React from 'react'; +import { render } from 'ink-testing-library'; +import { App } from '../../src/tui/App.js'; +import { _resetAnimTick } from '../../src/tui/components/useAnimTick.js'; +import type { Task } from '../../src/domain/task.js'; +import type { Agent } from '../../src/domain/agent.js'; +import type { OrchestratorEvent } from '../../src/domain/events.js'; +import { DEFAULT_STATE, type OrchestratorState } from '../../src/domain/state.js'; + +const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +afterEach(() => { _resetAnimTick(); }); + +function makeTask(overrides: Partial & { id: string; title: string }): Task { + return { + description: '', + status: 'todo', + priority: 3, + labels: [], + depends_on: [], + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + attempts: 0, + max_attempts: 3, + ...overrides, + }; +} + +function makeAgent(overrides: Partial & { id: string; name: string }): Agent { + return { + adapter: 'pi', + config: { + approval_policy: 'auto', + max_turns: 50, + timeout_ms: 3_600_000, + stall_timeout_ms: 300_000, + }, + status: 'idle', + stats: { tasks_completed: 0, tasks_failed: 0, total_runs: 0, total_runtime_ms: 0 }, + ...overrides, + }; +} + +describe('Pi agent — TUI lifecycle', () => { + it('shows pi agent on Agents tab and walks todo → running → done with activity feed', async () => { + const piAgent = makeAgent({ id: 'agt_pi', name: 'pi-bot', adapter: 'pi' }); + const piTask = makeTask({ + id: 'tsk_pi', + title: 'Create hello.md via pi', + description: 'smoke task', + priority: 1, + assignee: 'agt_pi', + }); + + // Start with the initial todo state; we mutate and rerender as the + // orchestrator would write to disk between phases. + let tasks: Task[] = [piTask]; + let agents: Agent[] = [piAgent]; + let state: OrchestratorState = { ...DEFAULT_STATE }; + + let eventHandler: ((e: OrchestratorEvent) => void) | null = null; + const onSubscribeEvents = (h: (e: OrchestratorEvent) => void) => { + eventHandler = h; + return () => { eventHandler = null; }; + }; + + const baseProps = { projectName: 'pi-demo', onSubscribeEvents }; + + const { stdin, lastFrame, rerender } = render( + React.createElement(App, { ...baseProps, tasks, agents, state }), + ); + + // ── Initial frame: Tasks tab visible with the todo pi task ──────────── + const initial = lastFrame()!; + expect(initial).toContain('Create hello.md via pi'); + expect(initial).toContain('!!!'); // P1 priority indicator + expect(initial).toContain('TODO'); + + // ── Switch to Agents tab (A) — pi-bot visible with `pi` adapter chip ── + stdin.write('a'); + await delay(80); + const agentsFrame = lastFrame()!; + expect(agentsFrame).toContain('pi-bot'); + expect(agentsFrame).toContain('pi'); // adapter chip column + + // ── Back to Tasks (T) for the lifecycle assertions ──────────────────── + stdin.write('t'); + await delay(80); + + // ── Dispatch phase: orchestrator writes new state, emits events ─────── + tasks = [{ ...piTask, status: 'in_progress' }]; + agents = [{ ...piAgent, status: 'running', current_task: 'tsk_pi' }]; + state = { + ...DEFAULT_STATE, + running: { + tsk_pi: { + runId: 'run_pi', + taskId: 'tsk_pi', + agentId: 'agt_pi', + pid: 4242, + started_at: new Date().toISOString(), + }, + }, + }; + rerender(React.createElement(App, { ...baseProps, tasks, agents, state })); + eventHandler?.({ type: 'task:status_changed', taskId: 'tsk_pi', from: 'todo', to: 'in_progress' }); + eventHandler?.({ type: 'agent:started', agentId: 'agt_pi', taskId: 'tsk_pi', runId: 'run_pi' }); + // The TUI batches event renders at 80 ms; wait past the flush. + await delay(120); + + const runningFrame = lastFrame()!; + // The running task still appears with its title (status icon changes to the + // braille spinner ⠋ on running rows). + expect(runningFrame).toContain('Create hello.md via pi'); + + // ── Streaming pi events flow into the activity feed ─────────────────── + eventHandler?.({ + type: 'agent:output', + runId: 'run_pi', + agentId: 'agt_pi', + // Pi adapter feeds this as the text_delta payload from pi-coding-agent + data: JSON.stringify({ text: 'Writing hello.md…', raw: {} }), + }); + eventHandler?.({ + type: 'agent:file_changed', + runId: 'run_pi', + agentId: 'agt_pi', + path: 'hello.md', + }); + await delay(120); + + const liveFrame = lastFrame()!; + expect(liveFrame).toContain('hello.md'); + + // ── Completion: orchestrator finalizes, task lands on done ──────────── + eventHandler?.({ type: 'agent:completed', runId: 'run_pi', agentId: 'agt_pi', success: true }); + tasks = [{ ...piTask, status: 'done', assignee: 'agt_pi' }]; + agents = [piAgent]; // back to idle + state = { ...DEFAULT_STATE, running: {} }; + rerender(React.createElement(App, { ...baseProps, tasks, agents, state })); + eventHandler?.({ type: 'task:status_changed', taskId: 'tsk_pi', from: 'in_progress', to: 'review' }); + eventHandler?.({ type: 'task:status_changed', taskId: 'tsk_pi', from: 'review', to: 'done' }); + await delay(120); + + const doneFrame = lastFrame()!; + expect(doneFrame).toContain('Create hello.md via pi'); + // Done icon ✓ appears on the row of a completed task. + expect(doneFrame).toContain('✓'); // ✓ + + // Switch back to Agents — pi-bot is idle again, no longer pinned to tsk_pi. + stdin.write('a'); + await delay(80); + const finalAgents = lastFrame()!; + expect(finalAgents).toContain('pi-bot'); + expect(finalAgents).toContain('IDLE'); // status chip — uppercase + }); +}); From 57ad2e3933bcc91d136bdd1d2a5552df020c9da5 Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 18:19:59 +0300 Subject: [PATCH 10/11] refactor: simplify pi adapter buffers + extract onboarding configs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three small wins from a /simplify pass on the PR diff — no behavior change. 1. readPiRpcLines: O(n²) → O(n) The old loop did Buffer.concat([pending, buf]) on every chunk, which copies the whole accumulator each time. Switched to the same chunks[]/totalLen/offset pattern that readLines() in process-manager.ts already uses for the cap-applied path: concat once per chunk arrival, scan with an offset, subarray() the remainder. Algorithmically identical, just without the per-chunk copy. 2. createStderrTailCapture: drop the chunks[] array + shift() Now keeps a single Buffer and on overflow does buf.subarray(buf.length - STDERR_TAIL_BYTES) — zero-copy and O(1). The tail getter also no longer concats per call: it just toString()s the current Buffer, which is already at most STDERR_TAIL_BYTES bytes. 3. Onboarding configs extracted to src/tui/onboarding-config.ts App.tsx no longer has to export ONBOARDING_AGENTS purely for tests. ONBOARDING_GOALS, _TASKS, _AGENTS live in a small module that both App.tsx and the regression test import. Also drops the now-unused `OnboardingConfig` type import from App.tsx. Bonus: pi-tui.e2e.test.tsx now imports makeTask/makeAgent from test/unit/application/helpers.ts instead of duplicating the factories locally (they were drifting from helpers — local makeAgent defaulted to adapter='pi', helpers defaults to 'shell', so the test now explicitly passes adapter: 'pi' through overrides like other adapter tests do). Verified: - npm run typecheck: clean - npm test (full suite): 1954 passed, 2 skipped - Live re-run: pi adapter still writes the file end-to-end through the Orchestrator (tool_execution_end 'Successfully wrote 26 bytes' in the run jsonl — confirms the buffer rewrites didn't break parsing). Co-Authored-By: Claude Opus 4.7 (1M context) --- src/infrastructure/adapters/pi.ts | 67 ++++++++++++++++--------- src/tui/App.tsx | 39 +------------- src/tui/onboarding-config.ts | 41 +++++++++++++++ test/integration/pi-tui.e2e.test.tsx | 31 +----------- test/unit/tui/onboarding-agents.test.ts | 2 +- 5 files changed, 88 insertions(+), 92 deletions(-) create mode 100644 src/tui/onboarding-config.ts diff --git a/src/infrastructure/adapters/pi.ts b/src/infrastructure/adapters/pi.ts index 4b84374..14ec5ff 100644 --- a/src/infrastructure/adapters/pi.ts +++ b/src/infrastructure/adapters/pi.ts @@ -440,51 +440,70 @@ function extractPiTokensFromMessage(parsed: Record): TokenUsage * Drain stderr while keeping the last STDERR_TAIL_BYTES bytes for diagnostics. * Returns a closure that yields the captured tail as a UTF-8 string. * - * Without draining, a chatty stderr can fill the pipe buffer and stall Pi. - * Without the tail, auth or extension-load failures vanish on non-zero exit. + * Single backing Buffer with subarray-based truncation — no array shifts, no + * repeated concats on overflow. Without draining a chatty stderr can fill the + * pipe buffer and stall Pi; without the tail, auth or extension-load failures + * vanish on non-zero exit. */ const STDERR_TAIL_BYTES = 4096; function createStderrTailCapture(stderr: Readable | null | undefined): () => string { if (!stderr) return () => ''; - const chunks: Buffer[] = []; - let total = 0; + let buf: Buffer = Buffer.alloc(0); stderr.on('data', (chunk: Buffer | string) => { - const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8'); - chunks.push(buf); - total += buf.length; - while (total > STDERR_TAIL_BYTES && chunks.length > 0) { - const head = chunks.shift()!; - total -= head.length; + const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8'); + buf = buf.length === 0 ? next : Buffer.concat([buf, next], buf.length + next.length); + if (buf.length > STDERR_TAIL_BYTES) { + buf = buf.subarray(buf.length - STDERR_TAIL_BYTES); } }); - // Swallow late 'error' on stderr — we already have what we need from 'data'. stderr.on('error', () => {}); - return () => Buffer.concat(chunks).toString('utf-8').slice(-STDERR_TAIL_BYTES).trimEnd(); + return () => buf.toString('utf-8').trimEnd(); } /** * Pi RPC can emit very large JSONL records (notably agent_end with the full - * message transcript). Do not use the generic process readLines helper here: - * it caps lines at 16 KB, which corrupts large JSON records before the adapter - * can parse the terminal event. + * message transcript). Do not use the generic process `readLines` helper: it + * caps lines at 16 KB, which corrupts large JSON records before the adapter + * can parse the terminal event. Same algorithm otherwise — see readLines() in + * src/infrastructure/process/process-manager.ts for the cap-applied variant. + * + * Concats once per chunk arrival and scans with an offset to avoid the + * O(n²) "concat([pending, buf]) per chunk" anti-pattern. */ async function* readPiRpcLines(stream: Readable): AsyncGenerator { - let pending: Buffer | null = null; + const chunks: Buffer[] = []; + let totalLen = 0; for await (const chunk of stream) { - const buf: Buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string, 'utf-8'); - pending = pending ? Buffer.concat([pending, buf]) : buf; + const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string, 'utf-8'); + if (buf.length === 0) continue; + chunks.push(buf); + totalLen += buf.length; + const buffer = chunks.length === 1 ? chunks[0]! : Buffer.concat(chunks, totalLen); + chunks.length = 0; + totalLen = 0; + + let offset = 0; let newlineIdx: number; - while ((newlineIdx = pending.indexOf(0x0a)) !== -1) { - const line = pending.subarray(0, newlineIdx).toString('utf-8'); - pending = pending.subarray(newlineIdx + 1); - if (line) yield line.endsWith('\r') ? line.slice(0, -1) : line; + while ((newlineIdx = buffer.indexOf(0x0a, offset)) !== -1) { + if (newlineIdx > offset) { + const line = buffer.toString('utf-8', offset, newlineIdx); + yield line.endsWith('\r') ? line.slice(0, -1) : line; + } + offset = newlineIdx + 1; + } + + if (offset < buffer.length) { + const remainder = buffer.subarray(offset); + chunks.push(remainder); + totalLen = remainder.length; } } - if (pending && pending.length) { - const line = pending.toString('utf-8'); + if (totalLen > 0) { + const final = chunks.length === 1 ? chunks[0]! : Buffer.concat(chunks, totalLen); + const line = final.toString('utf-8'); if (line) yield line.endsWith('\r') ? line.slice(0, -1) : line; } } diff --git a/src/tui/App.tsx b/src/tui/App.tsx index 1e38dbb..9f8a4d2 100644 --- a/src/tui/App.tsx +++ b/src/tui/App.tsx @@ -32,7 +32,8 @@ import { LogsFilterPicker } from './components/LogsFilterPicker.js'; import { LogsTypeFilterPicker } from './components/LogsTypeFilterPicker.js'; import type { WizardStep } from './components/FormWizard.js'; import { Spinner } from './components/Spinner.js'; -import { OnboardingBox, type OnboardingConfig, WelcomeScreen, OnboardingNudge, OnboardingToast, type OnboardingStep } from './components/OnboardingBox.js'; +import { OnboardingBox, WelcomeScreen, OnboardingNudge, OnboardingToast, type OnboardingStep } from './components/OnboardingBox.js'; +import { ONBOARDING_GOALS, ONBOARDING_TASKS, ONBOARDING_AGENTS } from './onboarding-config.js'; import { ToastBanner, type Toast, type ToastType } from './components/ToastBanner.js'; import { HelpOverlay } from './components/HelpOverlay.js'; import { @@ -69,42 +70,6 @@ const MAX_TOASTS = 5; /** Statuses that allow R (run) action */ const RUNNABLE: Set = new Set(['todo', 'failed', 'cancelled']); -/* ── Onboarding configs for empty-state boxes ──── */ - -const ONBOARDING_GOALS: OnboardingConfig = { - title: 'Goals', - description: [ - 'Define what your team should achieve.', - 'The orchestrator breaks goals into tasks', - 'and assigns them to agents automatically.', - ], - hints: [{ key: 'N', label: 'new goal' }, { key: '/', label: 'commands' }], - nudge: 'Add more goals to keep your team focused.', -}; - -const ONBOARDING_TASKS: OnboardingConfig = { - title: 'Tasks', - description: [ - 'Units of work dispatched to agents.', - 'Create them manually or let goals', - 'generate them automatically.', - ], - hints: [{ key: 'N', label: 'new task' }, { key: 'W', label: 'start orchestrator' }], - nudge: 'Add more tasks to keep agents busy.', -}; - -// Exported so tests can assert the adapter list stays in sync with SUPPORTED_ADAPTERS. -export const ONBOARDING_AGENTS: OnboardingConfig = { - title: 'Agents', - description: [ - 'AI workers that execute your tasks.', - 'Each agent uses an adapter (claude,', - 'codex, opencode, cursor, pi, shell).', - ], - hints: [{ key: 'N', label: 'new agent' }, { key: 'W', label: 'start orchestrator' }], - nudge: 'Add more agents to increase parallelism.', -}; - /** History entry returned by onLoadHistory */ export interface HistoryEntry { timestamp: string; diff --git a/src/tui/onboarding-config.ts b/src/tui/onboarding-config.ts new file mode 100644 index 0000000..d477b8b --- /dev/null +++ b/src/tui/onboarding-config.ts @@ -0,0 +1,41 @@ +/** + * Empty-state onboarding tips for each top-level TUI tab. + * + * Kept in their own module so non-TUI consumers (regression tests, docs + * generators) can import them without pulling in the whole React app. + */ + +import type { OnboardingConfig } from './components/OnboardingBox.js'; + +export const ONBOARDING_GOALS: OnboardingConfig = { + title: 'Goals', + description: [ + 'Define what your team should achieve.', + 'The orchestrator breaks goals into tasks', + 'and assigns them to agents automatically.', + ], + hints: [{ key: 'N', label: 'new goal' }, { key: '/', label: 'commands' }], + nudge: 'Add more goals to keep your team focused.', +}; + +export const ONBOARDING_TASKS: OnboardingConfig = { + title: 'Tasks', + description: [ + 'Units of work dispatched to agents.', + 'Create them manually or let goals', + 'generate them automatically.', + ], + hints: [{ key: 'N', label: 'new task' }, { key: 'W', label: 'start orchestrator' }], + nudge: 'Add more tasks to keep agents busy.', +}; + +export const ONBOARDING_AGENTS: OnboardingConfig = { + title: 'Agents', + description: [ + 'AI workers that execute your tasks.', + 'Each agent uses an adapter (claude,', + 'codex, opencode, cursor, pi, shell).', + ], + hints: [{ key: 'N', label: 'new agent' }, { key: 'W', label: 'start orchestrator' }], + nudge: 'Add more agents to increase parallelism.', +}; diff --git a/test/integration/pi-tui.e2e.test.tsx b/test/integration/pi-tui.e2e.test.tsx index d7ed299..7838d53 100644 --- a/test/integration/pi-tui.e2e.test.tsx +++ b/test/integration/pi-tui.e2e.test.tsx @@ -22,41 +22,12 @@ import type { Task } from '../../src/domain/task.js'; import type { Agent } from '../../src/domain/agent.js'; import type { OrchestratorEvent } from '../../src/domain/events.js'; import { DEFAULT_STATE, type OrchestratorState } from '../../src/domain/state.js'; +import { makeTask, makeAgent } from '../unit/application/helpers.js'; const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); afterEach(() => { _resetAnimTick(); }); -function makeTask(overrides: Partial & { id: string; title: string }): Task { - return { - description: '', - status: 'todo', - priority: 3, - labels: [], - depends_on: [], - created_at: new Date().toISOString(), - updated_at: new Date().toISOString(), - attempts: 0, - max_attempts: 3, - ...overrides, - }; -} - -function makeAgent(overrides: Partial & { id: string; name: string }): Agent { - return { - adapter: 'pi', - config: { - approval_policy: 'auto', - max_turns: 50, - timeout_ms: 3_600_000, - stall_timeout_ms: 300_000, - }, - status: 'idle', - stats: { tasks_completed: 0, tasks_failed: 0, total_runs: 0, total_runtime_ms: 0 }, - ...overrides, - }; -} - describe('Pi agent — TUI lifecycle', () => { it('shows pi agent on Agents tab and walks todo → running → done with activity feed', async () => { const piAgent = makeAgent({ id: 'agt_pi', name: 'pi-bot', adapter: 'pi' }); diff --git a/test/unit/tui/onboarding-agents.test.ts b/test/unit/tui/onboarding-agents.test.ts index f8810ee..9b8b400 100644 --- a/test/unit/tui/onboarding-agents.test.ts +++ b/test/unit/tui/onboarding-agents.test.ts @@ -5,7 +5,7 @@ */ import { describe, it, expect } from 'vitest'; -import { ONBOARDING_AGENTS } from '../../../src/tui/App.js'; +import { ONBOARDING_AGENTS } from '../../../src/tui/onboarding-config.js'; import { SUPPORTED_ADAPTERS } from '../../../src/domain/model-tiers.js'; describe('ONBOARDING_AGENTS', () => { From 6fe17be4bf302e8f5d9de1d1fabc5585f512efeb Mon Sep 17 00:00:00 2001 From: oxgeneral Date: Tue, 19 May 2026 18:25:05 +0300 Subject: [PATCH 11/11] fix(pi): copy stderr tail on overflow to release oversized ArrayBuffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Buffer.subarray() returns a view sharing the parent ArrayBuffer. After a single oversized stderr chunk (e.g. a 64 KB stack trace from the Pi runtime), the post-overflow assignment buf = buf.subarray(buf.length - STDERR_TAIL_BYTES) would pin the entire 64 KB+ backing buffer alive even though only 4 KB of it is visible — until GC eventually frees it. On a chatty stderr this is a noticeable per-burst waste. Wrap the subarray in Buffer.from() so the bytes are copied into a fresh, exactly STDERR_TAIL_BYTES-sized allocation. The previous Buffer (and its backing ArrayBuffer) become unreachable immediately. Caught by `/simplify` efficiency review. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/infrastructure/adapters/pi.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/infrastructure/adapters/pi.ts b/src/infrastructure/adapters/pi.ts index 14ec5ff..803c9ef 100644 --- a/src/infrastructure/adapters/pi.ts +++ b/src/infrastructure/adapters/pi.ts @@ -453,7 +453,10 @@ function createStderrTailCapture(stderr: Readable | null | undefined): () => str const next = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf-8'); buf = buf.length === 0 ? next : Buffer.concat([buf, next], buf.length + next.length); if (buf.length > STDERR_TAIL_BYTES) { - buf = buf.subarray(buf.length - STDERR_TAIL_BYTES); + // Buffer.from materializes a fresh, exactly-sized copy. Plain subarray + // would keep a view into the larger backing ArrayBuffer (sized to the + // last chunk), wasting memory on every oversized burst until GC. + buf = Buffer.from(buf.subarray(buf.length - STDERR_TAIL_BYTES)); } }); stderr.on('error', () => {});