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/CONTRIBUTING.md b/CONTRIBUTING.md index 0803e8b..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 1694 should pass +# 4. Run tests — all 1954 should pass npm test # 5. Type-check diff --git a/readme.md b/readme.md index ab9cafe..9e07677 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.

@@ -15,7 +15,7 @@ Website  npm  MIT License  - Tests + Tests


@@ -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 @@ -621,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 # 1954 tests via Vitest npm run typecheck # Strict TypeScript ``` @@ -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..803c9ef --- /dev/null +++ b/src/infrastructure/adapters/pi.ts @@ -0,0 +1,512 @@ +/** + * 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 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'; + +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'], + }); + + // 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({ + id: `orch-${Date.now()}`, + type: 'prompt', + message: params.prompt, + }) + '\n'); + // 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); + 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, + 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; + let exitError: Error | null = null; + + const exitPromise = new Promise((resolve) => { + proc.on('close', (code) => { exitCode = code; resolve(); }); + proc.on('error', (err) => { exitError = err; resolve(); }); + }); + + let streamError: Error | null = null; + try { + if (proc.stdout) { + 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 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 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; +} + +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); + + 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): ParsedPiEvent | null { + const tokens = extractPiTokensFromMessage(parsed); + return tokens ? { tokens } : 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; +} + +// 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 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 }); +} + +/** + * 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. + * + * 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 () => ''; + let buf: Buffer = Buffer.alloc(0); + stderr.on('data', (chunk: Buffer | string) => { + 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) { + // 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', () => {}); + 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: 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 { + const chunks: Buffer[] = []; + let totalLen = 0; + + for await (const chunk of stream) { + 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 = 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 (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 4788d27..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,41 +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.', -}; - -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.', - ], - 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/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/integration/pi-adapter.e2e.test.ts b/test/integration/pi-adapter.e2e.test.ts new file mode 100644 index 0000000..fb5ca75 --- /dev/null +++ b/test/integration/pi-adapter.e2e.test.ts @@ -0,0 +1,252 @@ +/** + * 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'])); + + // 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'); + 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); + }); +}); diff --git a/test/integration/pi-tui.e2e.test.tsx b/test/integration/pi-tui.e2e.test.tsx new file mode 100644 index 0000000..7838d53 --- /dev/null +++ b/test/integration/pi-tui.e2e.test.tsx @@ -0,0 +1,144 @@ +/** + * 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'; +import { makeTask, makeAgent } from '../unit/application/helpers.js'; + +const delay = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +afterEach(() => { _resetAnimTick(); }); + +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 + }); +}); 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/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..43d1f96 --- /dev/null +++ b/test/unit/infrastructure/pi-adapter.test.ts @@ -0,0 +1,398 @@ +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'; +import type { ChildProcess } from 'node:child_process'; + +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 {}; + }), + }; +}); + +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(); + proc.pid = 8888; + proc.kill = vi.fn(); + return proc; +} + +function createMockProcessManager(proc: MockProcess): IProcessManager { + return { + isAlive: vi.fn(() => true), + kill: vi.fn(), + killWithGrace: vi.fn(async () => {}), + spawn: vi.fn(() => ({ process: proc as unknown as ChildProcess, 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('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); + const endSpy = vi.spyOn(proc.stdin, 'end'); + + adapter.execute(makeParams({ prompt: 'do work' })); + + expect(endSpy).not.toHaveBeenCalled(); + }); + + 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 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); + 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); + }); + + 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', () => { + 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'); + }); + }); +}); diff --git a/test/unit/tui/onboarding-agents.test.ts b/test/unit/tui/onboarding-agents.test.ts new file mode 100644 index 0000000..9b8b400 --- /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/onboarding-config.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); + }); +}); 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')!;