diff --git a/apps/marketing/src/content/docs/commands/code-review.md b/apps/marketing/src/content/docs/commands/code-review.md index ab8941f..70ca8de 100644 --- a/apps/marketing/src/content/docs/commands/code-review.md +++ b/apps/marketing/src/content/docs/commands/code-review.md @@ -83,8 +83,9 @@ Plannotator supports multiple AI providers. Providers are auto-detected based on - **Claude** — Requires the `claude` CLI ([Claude Code](https://docs.anthropic.com/en/docs/claude-code)) - **Codex** — Requires the `codex` CLI ([OpenAI Codex](https://github.com/openai/codex)) +- **Pi** — Requires the `pi` CLI ([Pi](https://github.com/mariozechner/pi-coding-agent)) -Both providers can be available simultaneously. Plannotator does not manage API keys — you must be authenticated with each CLI independently (`claude` uses `~/.claude/` credentials, `codex` uses `OPENAI_API_KEY`). +All providers can be available simultaneously. Plannotator does not manage API keys — you must be authenticated with each CLI independently (`claude` uses `~/.claude/` credentials, `codex` uses `OPENAI_API_KEY`, `pi` uses its own local configuration). ### Choosing a provider diff --git a/apps/marketing/src/content/docs/getting-started/installation.md b/apps/marketing/src/content/docs/getting-started/installation.md index c984e95..28eb4f2 100644 --- a/apps/marketing/src/content/docs/getting-started/installation.md +++ b/apps/marketing/src/content/docs/getting-started/installation.md @@ -1,6 +1,6 @@ --- title: "Installation" -description: "How to install Plannotator for Claude Code, OpenCode, and other agent hosts." +description: "How to install Plannotator for Claude Code, OpenCode, Pi, and other agent hosts." sidebar: order: 1 section: "Getting Started" @@ -109,3 +109,21 @@ Install the binary, then use it directly: !plannotator review # Code review for current changes !plannotator annotate file.md # Annotate a markdown file ``` + +## Pi + +Install the Pi extension: + +```bash +pi install npm:@plannotator/pi-extension +``` + +Or try it without installing: + +```bash +pi -e npm:@plannotator/pi-extension +``` + +Start plan mode with `pi --plan`, or toggle mid-session with `/plannotator` or `Ctrl+Alt+P`. The extension provides file-based plan review, code review (`/plannotator-review`), markdown annotation (`/plannotator-annotate`), bash safety gating during planning, and progress tracking during execution. + +See [Plannotator Meets Pi](/blog/plannotator-meets-pi) for the full walkthrough. diff --git a/apps/marketing/src/content/docs/guides/ai-features.md b/apps/marketing/src/content/docs/guides/ai-features.md index 026dbba..e2ce2d7 100644 --- a/apps/marketing/src/content/docs/guides/ai-features.md +++ b/apps/marketing/src/content/docs/guides/ai-features.md @@ -33,6 +33,12 @@ Requires the `codex` CLI installed and authenticated. The AI operates in a sandb - GPT-5.2 Codex - GPT-5.2 +### Pi (via RPC subprocess) + +Requires the `pi` CLI installed and configured. Plannotator spawns `pi --mode rpc` and communicates over JSONL/stdio. Models are discovered dynamically from your Pi installation — whatever models you've configured in Pi are available here. + +No API keys are managed by Plannotator — Pi uses its own local configuration. + ## Configuration Provider and model selection is available in **Settings > AI**. These persist via cookies across sessions. @@ -47,6 +53,8 @@ A session is created lazily on your first question. Until then, no resources are **Codex sessions** inject the review context as a system prompt prefix. The AI has Codex's built-in capabilities plus the diff. Codex sessions are always standalone — fork support is not available. +**Pi sessions** inject the review context as a system prompt prefix, similar to Codex. Pi uses its full default toolset (read, bash, edit, write). Pi sessions are always standalone — fork and resume are not available. + **Diff context handling:** Large diffs are truncated at roughly 40k characters to stay within context limits. However, when you select specific lines and ask a question, the selected code is always sent alongside the question regardless of truncation. ## Permission requests @@ -55,20 +63,22 @@ When using Claude, the AI may request permission to use tools like Read, Glob, G Codex sessions run in a sandboxed read-only mode, so permission requests do not apply. +Pi does not expose a permission approval gate over RPC, so tool execution is handled entirely by Pi's own runtime. + ## Reasoning effort Codex supports a reasoning effort setting with four levels: **Low**, **Medium**, **High**, and **Max**. This is available in the config bar at the bottom of the AI sidebar. Higher effort means slower but more thorough responses. -This setting only applies to Codex — Claude does not expose a reasoning effort control. +This setting only applies to Codex — Claude and Pi do not expose a reasoning effort control. ## Available settings | Setting | Description | Provider | |---------|-------------|----------| -| Provider | Claude or Codex | Both | -| Model | Model selection per provider | Both | +| Provider | Claude, Codex, or Pi | All | +| Model | Model selection per provider | All | | Reasoning effort | Low / Medium / High / Max | Codex only | | Default tools | Read, Glob, Grep, WebSearch | Claude only | | Sandbox mode | Read-only | Codex only | | Permission mode | Default | Claude only | -| Max turns | 99 | Both | +| Max turns | 99 | Claude, Codex | diff --git a/bun.lock b/bun.lock index a70c3f3..addfc76 100644 --- a/bun.lock +++ b/bun.lock @@ -139,14 +139,6 @@ "packages/ai": { "name": "@plannotator/ai", "version": "0.0.1", - "peerDependencies": { - "@anthropic-ai/claude-agent-sdk": ">=0.1.0", - "@openai/codex-sdk": ">=0.100.0", - }, - "optionalPeers": [ - "@anthropic-ai/claude-agent-sdk", - "@openai/codex-sdk", - ], }, "packages/editor": { "name": "@plannotator/editor", diff --git a/packages/ai/ai.test.ts b/packages/ai/ai.test.ts index 9e68ae8..ff7fbfe 100644 --- a/packages/ai/ai.test.ts +++ b/packages/ai/ai.test.ts @@ -904,3 +904,153 @@ describe("Multi-provider endpoints", () => { expect(data.sessionId).toBeDefined(); }); }); + +// --------------------------------------------------------------------------- +// buildEffectivePrompt +// --------------------------------------------------------------------------- + +import { buildEffectivePrompt } from "./context.ts"; + +describe("buildEffectivePrompt", () => { + test("prepends preamble on first query", () => { + const result = buildEffectivePrompt("What is this?", "System context here", false); + expect(result).toBe("System context here\n\n---\n\nUser question: What is this?"); + }); + + test("returns bare prompt on subsequent queries", () => { + const result = buildEffectivePrompt("What is this?", "System context here", true); + expect(result).toBe("What is this?"); + }); + + test("returns bare prompt when preamble is null", () => { + const result = buildEffectivePrompt("What is this?", null, false); + expect(result).toBe("What is this?"); + }); +}); + +// --------------------------------------------------------------------------- +// mapPiEvent +// --------------------------------------------------------------------------- + +import { mapPiEvent } from "./providers/pi-sdk.ts"; + +describe("mapPiEvent", () => { + const SESSION_ID = "pi-session-123"; + + test("text_delta from message_update", () => { + const result = mapPiEvent({ + type: "message_update", + assistantMessageEvent: { type: "text_delta", delta: "Hello", contentIndex: 0, partial: {} }, + }, SESSION_ID); + expect(result).toEqual([{ type: "text_delta", delta: "Hello" }]); + }); + + test("toolcall_end from message_update", () => { + const result = mapPiEvent({ + type: "message_update", + assistantMessageEvent: { + type: "toolcall_end", + contentIndex: 0, + toolCall: { type: "toolCall", id: "tc_1", name: "read", arguments: { path: "/foo" } }, + partial: {}, + }, + }, SESSION_ID); + expect(result).toEqual([{ + type: "tool_use", + toolName: "read", + toolInput: { path: "/foo" }, + toolUseId: "tc_1", + }]); + }); + + test("tool_execution_end maps to tool_result", () => { + const result = mapPiEvent({ + type: "tool_execution_end", + toolCallId: "tc_1", + toolName: "read", + result: "file contents", + isError: false, + }, SESSION_ID); + expect(result).toEqual([{ + type: "tool_result", + toolUseId: "tc_1", + result: "file contents", + }]); + }); + + test("tool_execution_end with error maps to tool_result with [Error] prefix", () => { + const result = mapPiEvent({ + type: "tool_execution_end", + toolCallId: "tc_1", + toolName: "read", + result: "not found", + isError: true, + }, SESSION_ID); + expect(result).toEqual([{ + type: "tool_result", + toolUseId: "tc_1", + result: "[Error] not found", + }]); + }); + + test("agent_end maps to result", () => { + const result = mapPiEvent({ + type: "agent_end", + messages: [], + }, SESSION_ID); + expect(result).toEqual([{ + type: "result", + sessionId: SESSION_ID, + success: true, + }]); + }); + + test("process_exited maps to error", () => { + const result = mapPiEvent({ type: "process_exited" }, SESSION_ID); + expect(result).toEqual([{ + type: "error", + error: "Pi process exited unexpectedly.", + code: "pi_process_exit", + }]); + }); + + test("ignored events return empty", () => { + expect(mapPiEvent({ type: "agent_start" }, SESSION_ID)).toEqual([]); + expect(mapPiEvent({ type: "turn_start" }, SESSION_ID)).toEqual([]); + expect(mapPiEvent({ type: "turn_end", message: {}, toolResults: [] }, SESSION_ID)).toEqual([]); + expect(mapPiEvent({ type: "message_start", message: {} }, SESSION_ID)).toEqual([]); + expect(mapPiEvent({ type: "message_end", message: {} }, SESSION_ID)).toEqual([]); + expect(mapPiEvent({ type: "tool_execution_start", toolCallId: "x", toolName: "y", args: {} }, SESSION_ID)).toEqual([]); + }); + + test("message_update with thinking events returns empty", () => { + const result = mapPiEvent({ + type: "message_update", + assistantMessageEvent: { type: "thinking_delta", delta: "hmm", contentIndex: 0, partial: {} }, + }, SESSION_ID); + expect(result).toEqual([]); + }); + + test("message_update with done returns empty", () => { + const result = mapPiEvent({ + type: "message_update", + assistantMessageEvent: { type: "done", reason: "stop", message: {} }, + }, SESSION_ID); + expect(result).toEqual([]); + }); + + test("tool_execution_end with object result stringifies it", () => { + const result = mapPiEvent({ + type: "tool_execution_end", + toolCallId: "tc_2", + toolName: "ls", + result: { files: ["a.ts", "b.ts"] }, + isError: false, + }, SESSION_ID); + expect(result).toEqual([{ + type: "tool_result", + toolUseId: "tc_2", + result: JSON.stringify({ files: ["a.ts", "b.ts"] }), + }]); + }); +}); diff --git a/packages/ai/base-session.ts b/packages/ai/base-session.ts new file mode 100644 index 0000000..2e072cc --- /dev/null +++ b/packages/ai/base-session.ts @@ -0,0 +1,94 @@ +/** + * Shared session base class — extracts the common lifecycle, abort, and + * ID-resolution logic that every AIProvider session needs. + * + * Concrete providers extend this and implement query(). + */ + +import type { AIMessage, AISession } from "./types.ts"; + +export abstract class BaseSession implements AISession { + readonly parentSessionId: string | null; + onIdResolved?: (oldId: string, newId: string) => void; + + protected _placeholderId: string; + protected _resolvedId: string | null = null; + protected _isActive = false; + protected _currentAbort: AbortController | null = null; + protected _queryGen = 0; + protected _firstQuerySent = false; + + constructor(opts: { parentSessionId: string | null; initialId?: string }) { + this.parentSessionId = opts.parentSessionId; + this._placeholderId = opts.initialId ?? crypto.randomUUID(); + } + + get id(): string { + return this._resolvedId ?? this._placeholderId; + } + + get isActive(): boolean { + return this._isActive; + } + + // --------------------------------------------------------------------------- + // Query lifecycle helpers — call from concrete query() implementations + // --------------------------------------------------------------------------- + + /** Error message returned when a query is already active. */ + static readonly BUSY_ERROR: AIMessage = { + type: "error", + error: + "A query is already in progress. Abort the current query before sending a new one.", + code: "session_busy", + }; + + /** + * Call at the start of query(). Returns the generation number and abort + * signal, or null if the session is busy. + */ + protected startQuery(): { gen: number; signal: AbortSignal } | null { + if (this._isActive) return null; + + const gen = ++this._queryGen; + this._isActive = true; + this._currentAbort = new AbortController(); + return { gen, signal: this._currentAbort.signal }; + } + + /** + * Call in the finally block of query(). Only clears state if the + * generation matches (prevents a stale finally from clobbering a newer query). + */ + protected endQuery(gen: number): void { + if (this._queryGen === gen) { + this._isActive = false; + this._currentAbort = null; + } + } + + /** + * Call when the provider resolves the real session ID from the backend. + * Fires the onIdResolved callback so the SessionManager can remap its key. + */ + protected resolveId(newId: string): void { + if (this._resolvedId) return; // Already resolved + const oldId = this._placeholderId; + this._resolvedId = newId; + this.onIdResolved?.(oldId, newId); + } + + /** + * Abort the current in-flight query. Subclasses should call super.abort() + * after any provider-specific cleanup. + */ + abort(): void { + if (this._currentAbort) { + this._currentAbort.abort(); + this._isActive = false; + this._currentAbort = null; + } + } + + abstract query(prompt: string): AsyncIterable; +} diff --git a/packages/ai/context.ts b/packages/ai/context.ts index 13671d7..173cbae 100644 --- a/packages/ai/context.ts +++ b/packages/ai/context.ts @@ -101,6 +101,22 @@ export function buildForkPreamble(ctx: AIContext): string { return lines.join("\n"); } +/** + * Build the effective prompt for a query, prepending a preamble on the first + * message. Used by providers that inject context via the prompt itself (Codex, + * Pi) rather than a separate system-prompt channel (Claude). + */ +export function buildEffectivePrompt( + userPrompt: string, + preamble: string | null, + firstQuerySent: boolean, +): string { + if (!firstQuerySent && preamble) { + return `${preamble}\n\n---\n\nUser question: ${userPrompt}`; + } + return userPrompt; +} + // --------------------------------------------------------------------------- // Internals // --------------------------------------------------------------------------- diff --git a/packages/ai/index.ts b/packages/ai/index.ts index 34acfa1..8b845ea 100644 --- a/packages/ai/index.ts +++ b/packages/ai/index.ts @@ -73,6 +73,7 @@ export type { CreateSessionOptions, ClaudeAgentSDKConfig, CodexSDKConfig, + PiSDKConfig, } from "./types.ts"; // Provider registry @@ -83,7 +84,10 @@ export { } from "./provider.ts"; // Context builders -export { buildSystemPrompt, buildForkPreamble } from "./context.ts"; +export { buildSystemPrompt, buildForkPreamble, buildEffectivePrompt } from "./context.ts"; + +// Base session +export { BaseSession } from "./base-session.ts"; // Session manager export { SessionManager } from "./session-manager.ts"; diff --git a/packages/ai/package.json b/packages/ai/package.json index 1f603af..3303bf4 100644 --- a/packages/ai/package.json +++ b/packages/ai/package.json @@ -11,6 +11,7 @@ "./session-manager": "./session-manager.ts", "./endpoints": "./endpoints.ts", "./providers/claude-agent-sdk": "./providers/claude-agent-sdk.ts", - "./providers/codex-sdk": "./providers/codex-sdk.ts" + "./providers/codex-sdk": "./providers/codex-sdk.ts", + "./providers/pi-sdk": "./providers/pi-sdk.ts" } } diff --git a/packages/ai/providers/claude-agent-sdk.ts b/packages/ai/providers/claude-agent-sdk.ts index 47c57e9..a62732a 100644 --- a/packages/ai/providers/claude-agent-sdk.ts +++ b/packages/ai/providers/claude-agent-sdk.ts @@ -11,7 +11,8 @@ * to keep inline chat safe and cost-bounded. */ -import { buildSystemPrompt, buildForkPreamble } from "../context.ts"; +import { buildSystemPrompt, buildForkPreamble, buildEffectivePrompt } from "../context.ts"; +import { BaseSession } from "../base-session.ts"; import type { AIProvider, AIProviderCapabilities, @@ -170,54 +171,32 @@ interface SessionConfig { settingSources?: string[]; } -class ClaudeAgentSDKSession implements AISession { - readonly parentSessionId: string | null; - onIdResolved?: (oldId: string, newId: string) => void; - +class ClaudeAgentSDKSession extends BaseSession { private config: SessionConfig; - private _isActive = false; - private _placeholderId: string; - private _resolvedId: string | null = null; - private _currentAbort: AbortController | null = null; - private _firstQuerySent = false; - /** Monotonic counter — each query() call gets a unique generation. */ - private _queryGen = 0; /** Active Query object — needed to send control responses (permission decisions) */ private _activeQuery: { streamInput: (iter: AsyncIterable) => Promise } | null = null; constructor(config: SessionConfig) { + super({ + parentSessionId: config.parentSessionId, + initialId: config.resumeSessionId, + }); this.config = config; - this.parentSessionId = config.parentSessionId; - this._placeholderId = config.resumeSessionId ?? crypto.randomUUID(); - } - - get id(): string { - return this._resolvedId ?? this._placeholderId; - } - - get isActive(): boolean { - return this._isActive; } async *query(prompt: string): AsyncIterable { - // Reject if a query is already in-flight — let the caller decide to queue or abort - if (this._isActive) { - yield { - type: "error", - error: "A query is already in progress. Abort the current query before sending a new one.", - code: "session_busy", - }; - return; - } - - const gen = ++this._queryGen; - this._isActive = true; - this._currentAbort = new AbortController(); + const started = this.startQuery(); + if (!started) { yield BaseSession.BUSY_ERROR; return; } + const { gen } = started; try { const queryFn = await getSDKQuery(); - const queryPrompt = this.buildQueryPrompt(prompt); + const queryPrompt = buildEffectivePrompt( + prompt, + this.config.forkPreamble ?? null, + this._firstQuerySent, + ); const options = this.buildQueryOptions(); const stream = queryFn({ prompt: queryPrompt, options }); @@ -235,9 +214,7 @@ class ClaudeAgentSDKSession implements AISession { typeof message.session_id === "string" && message.session_id ) { - const oldId = this._placeholderId; - this._resolvedId = message.session_id; - this.onIdResolved?.(oldId, this._resolvedId); + this.resolveId(message.session_id); } for (const msg of mapped) { @@ -251,23 +228,14 @@ class ClaudeAgentSDKSession implements AISession { code: "provider_error", }; } finally { - // Only clear state if this is still the active query generation. - // Prevents a stale finally block from clobbering a newer query. - if (this._queryGen === gen) { - this._isActive = false; - this._currentAbort = null; - this._activeQuery = null; - } + this.endQuery(gen); + this._activeQuery = null; } } abort(): void { - if (this._currentAbort) { - this._currentAbort.abort(); - this._isActive = false; - this._currentAbort = null; - this._activeQuery = null; - } + this._activeQuery = null; + super.abort(); } respondToPermission(requestId: string, allow: boolean, message?: string): void { @@ -286,13 +254,6 @@ class ClaudeAgentSDKSession implements AISession { // Internal // ------------------------------------------------------------------------- - private buildQueryPrompt(userPrompt: string): string { - if (this.config.forkPreamble && !this._firstQuerySent) { - return `${this.config.forkPreamble}\n\n---\n\nUser question: ${userPrompt}`; - } - return userPrompt; - } - private buildQueryOptions(): ClaudeSDKQueryOptions { const opts: ClaudeSDKQueryOptions = { model: this.config.model, diff --git a/packages/ai/providers/codex-sdk.ts b/packages/ai/providers/codex-sdk.ts index cfc7b82..1745c26 100644 --- a/packages/ai/providers/codex-sdk.ts +++ b/packages/ai/providers/codex-sdk.ts @@ -10,7 +10,8 @@ * Sessions default to read-only sandbox mode for safety in inline chat. */ -import { buildSystemPrompt } from "../context.ts"; +import { buildSystemPrompt, buildEffectivePrompt } from "../context.ts"; +import { BaseSession } from "../base-session.ts"; import type { AIProvider, AIProviderCapabilities, @@ -126,17 +127,8 @@ interface SessionConfig { reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh"; } -class CodexSDKSession implements AISession { - readonly parentSessionId: string | null; - onIdResolved?: (oldId: string, newId: string) => void; - +class CodexSDKSession extends BaseSession { private config: SessionConfig; - private _isActive = false; - private _placeholderId: string; - private _resolvedId: string | null = null; - private _currentAbort: AbortController | null = null; - private _firstQuerySent = false; - private _queryGen = 0; // biome-ignore lint/suspicious/noExplicitAny: SDK types not available at compile time private _codexInstance: any = null; // biome-ignore lint/suspicious/noExplicitAny: SDK types not available at compile time @@ -145,36 +137,22 @@ class CodexSDKSession implements AISession { private _itemTextOffsets = new Map(); constructor(config: SessionConfig) { + super({ + parentSessionId: config.parentSessionId, + initialId: config.resumeThreadId, + }); this.config = config; - this.parentSessionId = config.parentSessionId; - this._placeholderId = config.resumeThreadId ?? crypto.randomUUID(); // If resuming, treat the thread ID as already resolved if (config.resumeThreadId) { this._resolvedId = config.resumeThreadId; } } - get id(): string { - return this._resolvedId ?? this._placeholderId; - } - - get isActive(): boolean { - return this._isActive; - } - async *query(prompt: string): AsyncIterable { - if (this._isActive) { - yield { - type: "error", - error: "A query is already in progress. Abort the current query before sending a new one.", - code: "session_busy", - }; - return; - } + const started = this.startQuery(); + if (!started) { yield BaseSession.BUSY_ERROR; return; } + const { gen, signal } = started; - const gen = ++this._queryGen; - this._isActive = true; - this._currentAbort = new AbortController(); this._itemTextOffsets.clear(); try { @@ -206,9 +184,13 @@ class CodexSDKSession implements AISession { } } - const effectivePrompt = this.buildQueryPrompt(prompt); + const effectivePrompt = buildEffectivePrompt( + prompt, + this.config.systemPrompt, + this._firstQuerySent, + ); const streamed = await this._thread.runStreamed(effectivePrompt, { - signal: this._currentAbort.signal, + signal, }); this._firstQuerySent = true; @@ -221,9 +203,7 @@ class CodexSDKSession implements AISession { event.type === "thread.started" && typeof event.thread_id === "string" ) { - const oldId = this._placeholderId; - this._resolvedId = event.thread_id; - this.onIdResolved?.(oldId, this._resolvedId); + this.resolveId(event.thread_id); } if (event.type === "turn.failed") { @@ -251,32 +231,10 @@ class CodexSDKSession implements AISession { code: "provider_error", }; } finally { - if (this._queryGen === gen) { - this._isActive = false; - this._currentAbort = null; - } - } - } - - abort(): void { - if (this._currentAbort) { - this._currentAbort.abort(); - this._isActive = false; - this._currentAbort = null; + this.endQuery(gen); } } - // ------------------------------------------------------------------------- - // Internal - // ------------------------------------------------------------------------- - - private buildQueryPrompt(userPrompt: string): string { - // On first query, prepend system prompt - if (!this._firstQuerySent && this.config.systemPrompt) { - return `${this.config.systemPrompt}\n\n---\n\nUser question: ${userPrompt}`; - } - return userPrompt; - } } // --------------------------------------------------------------------------- diff --git a/packages/ai/providers/pi-sdk.ts b/packages/ai/providers/pi-sdk.ts new file mode 100644 index 0000000..ae9e227 --- /dev/null +++ b/packages/ai/providers/pi-sdk.ts @@ -0,0 +1,540 @@ +/** + * Pi SDK provider — bridges Plannotator's AI layer with Pi's coding agent. + * + * Spawns `pi --mode rpc` as a subprocess and communicates via JSONL over + * stdio. No Pi SDK is imported — this is a thin protocol adapter. + * + * One subprocess per session. The user must have the `pi` CLI installed. + */ + +import { BaseSession } from "../base-session.ts"; +import { buildEffectivePrompt, buildSystemPrompt } from "../context.ts"; +import type { + AIMessage, + AIProvider, + AIProviderCapabilities, + CreateSessionOptions, + PiSDKConfig, +} from "../types.ts"; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +const PROVIDER_NAME = "pi-sdk"; + +// --------------------------------------------------------------------------- +// JSONL subprocess wrapper +// --------------------------------------------------------------------------- + +type EventListener = (event: Record) => void; + +class PiProcess { + private proc: ReturnType | null = null; + private listeners: EventListener[] = []; + private pendingRequests = new Map< + string, + { + resolve: (data: Record) => void; + reject: (err: Error) => void; + } + >(); + private nextId = 0; + private buffer = ""; + private _alive = false; + + async spawn(piPath: string, cwd: string): Promise { + this.proc = Bun.spawn([piPath, "--mode", "rpc"], { + cwd, + stdin: "pipe", + stdout: "pipe", + stderr: "pipe", + }); + this._alive = true; + + this.readStream(); + + this.proc.exited.then(() => { + this._alive = false; + for (const [, pending] of this.pendingRequests) { + pending.reject(new Error("Pi process exited unexpectedly")); + } + this.pendingRequests.clear(); + // Signal active query listeners so the drain loop exits with an error + for (const listener of this.listeners) { + listener({ type: "process_exited" }); + } + }); + } + + private async readStream(): Promise { + if (!this.proc?.stdout) return; + const reader = this.proc.stdout.getReader(); + const decoder = new TextDecoder(); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + this.buffer += decoder.decode(value, { stream: true }); + const lines = this.buffer.split("\n"); + this.buffer = lines.pop() ?? ""; + + for (const line of lines) { + const trimmed = line.replace(/\r$/, ""); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed); + this.routeMessage(parsed); + } catch { + // Ignore malformed lines + } + } + } + } catch { + // Stream closed + } + } + + private routeMessage(msg: Record): void { + // Response to a command we sent + if (msg.type === "response" && typeof msg.id === "string") { + const pending = this.pendingRequests.get(msg.id); + if (pending) { + this.pendingRequests.delete(msg.id); + if (msg.success === false) { + pending.reject(new Error((msg.error as string) ?? "RPC error")); + } else { + pending.resolve((msg.data as Record) ?? {}); + } + return; + } + } + + // Agent event — forward to listeners + for (const listener of this.listeners) { + listener(msg); + } + } + + /** Send a command without waiting for a response. */ + send(command: Record): void { + if (!this.proc?.stdin) return; + // Bun.spawn stdin is a FileSink with .write(), not a WritableStream + this.proc.stdin.write(`${JSON.stringify(command)}\n`); + this.proc.stdin.flush(); + } + + /** Send a command and wait for the correlated response. */ + sendAndWait( + command: Record, + ): Promise> { + const id = `req_${++this.nextId}`; + return new Promise((resolve, reject) => { + this.pendingRequests.set(id, { resolve, reject }); + this.send({ ...command, id }); + }); + } + + /** Register a listener for agent events (non-response messages). */ + onEvent(listener: EventListener): () => void { + this.listeners.push(listener); + return () => { + const idx = this.listeners.indexOf(listener); + if (idx >= 0) this.listeners.splice(idx, 1); + }; + } + + get alive(): boolean { + return this._alive; + } + + kill(): void { + this._alive = false; + if (this.proc) { + this.proc.kill(); + this.proc = null; + } + this.listeners.length = 0; + for (const [, pending] of this.pendingRequests) { + pending.reject(new Error("Process killed")); + } + this.pendingRequests.clear(); + } +} + +// --------------------------------------------------------------------------- +// Provider +// --------------------------------------------------------------------------- + +export class PiSDKProvider implements AIProvider { + readonly name = PROVIDER_NAME; + readonly capabilities: AIProviderCapabilities = { + fork: false, + resume: false, + streaming: true, + tools: true, + }; + models?: Array<{ id: string; label: string; default?: boolean }>; + + private config: PiSDKConfig; + private sessions = new Map(); + + constructor(config: PiSDKConfig) { + this.config = config; + } + + async createSession(options: CreateSessionOptions): Promise { + const session = new PiSDKSession({ + systemPrompt: buildSystemPrompt(options.context), + cwd: options.cwd ?? this.config.cwd ?? process.cwd(), + parentSessionId: null, + piExecutablePath: this.config.piExecutablePath ?? "pi", + model: options.model ?? this.config.model, + }); + this.sessions.set(session.id, session); + return session; + } + + async forkSession(): Promise { + throw new Error( + "Pi does not support session forking. " + + "The endpoint layer should fall back to createSession().", + ); + } + + async resumeSession(): Promise { + throw new Error("Pi does not support session resuming."); + } + + dispose(): void { + for (const session of this.sessions.values()) { + session.killProcess(); + } + this.sessions.clear(); + } + + /** Fetch available models from Pi. Call before registering the provider. */ + async fetchModels(): Promise { + const piPath = this.config.piExecutablePath ?? "pi"; + + let proc: PiProcess | undefined; + + try { + proc = new PiProcess(); + await proc.spawn(piPath, this.config.cwd ?? process.cwd()); + + const data = await Promise.race([ + proc.sendAndWait({ type: "get_available_models" }), + new Promise((_, reject) => + setTimeout(() => reject(new Error("Timeout")), 10_000), + ), + ]); + + const rawModels = ( + data as { + models?: Array<{ provider: string; id: string; name?: string }>; + } + ).models; + if (rawModels && rawModels.length > 0) { + this.models = rawModels.map((m, i) => ({ + id: `${m.provider}/${m.id}`, + label: m.name ?? m.id, + ...(i === 0 && { default: true }), + })); + } + } catch { + // Pi not configured or no models available + } finally { + proc?.kill(); + } + } +} + +// --------------------------------------------------------------------------- +// Session +// --------------------------------------------------------------------------- + +interface SessionConfig { + systemPrompt: string; + cwd: string; + parentSessionId: string | null; + piExecutablePath: string; + /** Model in "provider/modelId" format, e.g. "anthropic/claude-haiku-4-5". */ + model?: string; +} + +class PiSDKSession extends BaseSession { + private config: SessionConfig; + private process: PiProcess | null = null; + + constructor(config: SessionConfig) { + super({ parentSessionId: config.parentSessionId }); + this.config = config; + } + + async *query(prompt: string): AsyncIterable { + const started = this.startQuery(); + if (!started) { + yield BaseSession.BUSY_ERROR; + return; + } + const { gen } = started; + + try { + // Lazy-spawn subprocess + if (!this.process || !this.process.alive) { + this.process = new PiProcess(); + await this.process.spawn(this.config.piExecutablePath, this.config.cwd); + + // Set model if specified (format: "provider/modelId") + if (this.config.model) { + const [provider, ...rest] = this.config.model.split("/"); + const modelId = rest.join("/"); + if (provider && modelId) { + try { + await this.process.sendAndWait({ + type: "set_model", + provider, + modelId, + }); + } catch { + // Continue with Pi's default model + } + } + } + + // Get session ID + try { + const state = await this.process.sendAndWait({ type: "get_state" }); + if (typeof state.sessionId === "string") { + this.resolveId(state.sessionId); + } + } catch { + // Continue with placeholder ID + } + + // If subprocess died during startup, surface the error immediately + if (!this.process.alive) { + yield { + type: "error", + error: + "Pi process exited during startup. Check that Pi is configured correctly (API keys, models).", + code: "pi_startup_error", + }; + return; + } + } + + // Build effective prompt (prepend system prompt on first query) + const effectivePrompt = buildEffectivePrompt( + prompt, + this.config.systemPrompt, + this._firstQuerySent, + ); + + // Set up async queue to bridge callback events → async iterable + const queue: AIMessage[] = []; + let resolve: (() => void) | null = null; + let done = false; + + const push = (msg: AIMessage) => { + queue.push(msg); + resolve?.(); + }; + + const finish = () => { + done = true; + resolve?.(); + }; + + const unsubscribe = this.process.onEvent((event) => { + const mapped = mapPiEvent(event, this.id); + for (const msg of mapped) { + push(msg); + if ( + msg.type === "result" || + (msg.type === "error" && + (event.type === "agent_end" || event.type === "process_exited")) + ) { + finish(); + } + } + }); + + // Send prompt — use sendAndWait to catch RPC-level rejections + // (e.g. expired credentials, invalid session) + try { + await this.process.sendAndWait({ + type: "prompt", + message: effectivePrompt, + }); + } catch (err) { + unsubscribe(); + yield { + type: "error", + error: `Pi rejected prompt: ${err instanceof Error ? err.message : String(err)}`, + code: "pi_prompt_rejected", + }; + return; + } + this._firstQuerySent = true; + + // Drain queue + try { + while (!done || queue.length > 0) { + if (queue.length > 0) { + yield queue.shift()!; + } else { + await new Promise((r) => { + resolve = r; + }); + resolve = null; + } + } + } finally { + unsubscribe(); + } + } catch (err) { + yield { + type: "error", + error: err instanceof Error ? err.message : String(err), + code: "provider_error", + }; + } finally { + this.endQuery(gen); + } + } + + abort(): void { + if (this.process?.alive) { + this.process.send({ type: "abort" }); + } + super.abort(); + } + + /** Kill the subprocess. Called by the provider on dispose. */ + killProcess(): void { + this.process?.kill(); + this.process = null; + } +} + +// --------------------------------------------------------------------------- +// Event mapping +// --------------------------------------------------------------------------- + +/** + * Map a Pi AgentEvent (received as JSONL) to AIMessage[]. + * + * Pi event hierarchy: + * agent_start > turn_start > message_start > message_update* > message_end + * > tool_execution_start > tool_execution_end > turn_end > agent_end + * + * We extract: + * - text_delta from message_update.assistantMessageEvent + * - tool_use from toolcall_end + * - tool_result from tool_execution_end + * - result from agent_end + */ +export function mapPiEvent( + event: Record, + sessionId: string, +): AIMessage[] { + const eventType = event.type as string; + + switch (eventType) { + case "message_update": { + const ame = event.assistantMessageEvent as + | Record + | undefined; + if (!ame) return []; + + const subType = ame.type as string; + + switch (subType) { + case "text_delta": + return [{ type: "text_delta", delta: ame.delta as string }]; + + case "toolcall_end": { + const tc = ame.toolCall as Record; + if (!tc) return []; + return [ + { + type: "tool_use", + toolName: tc.name as string, + toolInput: (tc.arguments as Record) ?? {}, + toolUseId: tc.id as string, + }, + ]; + } + + case "error": { + const partial = ame.error as Record | undefined; + const errorMessage = + (partial?.errorMessage as string) ?? "Stream error"; + return [ + { type: "error", error: errorMessage, code: "pi_stream_error" }, + ]; + } + + default: + return []; + } + } + + case "tool_execution_end": { + const result = event.result; + const isError = event.isError as boolean; + const resultStr = + result == null + ? "" + : typeof result === "string" + ? result + : JSON.stringify(result); + + return [ + { + type: "tool_result", + toolUseId: event.toolCallId as string, + result: isError + ? `[Error] ${resultStr || "Tool execution failed"}` + : resultStr, + }, + ]; + } + + case "agent_end": + return [ + { + type: "result", + sessionId, + success: true, + }, + ]; + + case "process_exited": + return [ + { + type: "error", + error: "Pi process exited unexpectedly.", + code: "pi_process_exit", + }, + ]; + + default: + return []; + } +} + +// --------------------------------------------------------------------------- +// Factory registration +// --------------------------------------------------------------------------- + +import { registerProviderFactory } from "../provider.ts"; + +registerProviderFactory( + PROVIDER_NAME, + async (config) => new PiSDKProvider(config as PiSDKConfig), +); diff --git a/packages/ai/types.ts b/packages/ai/types.ts index 3601667..304d13a 100644 --- a/packages/ai/types.ts +++ b/packages/ai/types.ts @@ -349,3 +349,13 @@ export interface CodexSDKConfig extends AIProviderConfig { */ codexExecutablePath?: string; } + +export interface PiSDKConfig extends AIProviderConfig { + type: "pi-sdk"; + /** + * Explicit path to the pi CLI binary. + * Required when running inside a compiled binary where PATH resolution + * doesn't work the same way (e.g., bun build --compile). + */ + piExecutablePath?: string; +} diff --git a/packages/server/review.ts b/packages/server/review.ts index 395a54b..84166db 100644 --- a/packages/server/review.ts +++ b/packages/server/review.ts @@ -135,6 +135,25 @@ export async function startReviewServer( // Codex SDK not available } + // Try Pi + try { + const { PiSDKProvider } = await import("@plannotator/ai/providers/pi-sdk"); + const piPath = Bun.which("pi"); + if (piPath) { + const provider = await createProvider({ + type: "pi-sdk", + cwd: process.cwd(), + piExecutablePath: piPath, + }); + if (provider instanceof PiSDKProvider) { + await provider.fetchModels(); + } + aiRegistry.register(provider); + } + } catch { + // Pi not available + } + // Create endpoints if any provider registered if (aiRegistry.size > 0) { aiEndpoints = createAIEndpoints({ diff --git a/packages/ui/components/ProviderIcons.tsx b/packages/ui/components/ProviderIcons.tsx index 107078a..f878c90 100644 --- a/packages/ui/components/ProviderIcons.tsx +++ b/packages/ui/components/ProviderIcons.tsx @@ -13,6 +13,14 @@ export const CodexIcon: React.FC<{ className?: string }> = ({ className = 'w-4 h ); +/** Pi icon — extracted from apps/marketing/public/assets/icon-pi.svg */ +export const PiIcon: React.FC<{ className?: string }> = ({ className = 'w-4 h-4' }) => ( + + + + +); + /** Generic fallback icon for unknown providers */ const GenericProviderIcon: React.FC<{ className?: string }> = ({ className = 'w-4 h-4' }) => ( @@ -24,6 +32,7 @@ const GenericProviderIcon: React.FC<{ className?: string }> = ({ className = 'w- export const PROVIDER_META: Record }> = { 'claude-agent-sdk': { label: 'Claude', icon: ClaudeIcon }, 'codex-sdk': { label: 'Codex', icon: CodexIcon }, + 'pi-sdk': { label: 'Pi', icon: PiIcon }, }; /** Get provider metadata, with fallback for unknown providers. */