20  SDK

20.1 Overview

The Pi SDK provides a programmatic API for embedding Pi’s agent capabilities into your own applications. It exposes the core agent loop, tool execution, session management, and event system without requiring the TUI.

20.2 Installation

npm install @earendil-works/pi-coding-agent

20.3 Quick Start

import { createAgentSession } from "@earendil-works/pi-coding-agent";

async function main() {
  const session = await createAgentSession({
    model: "claude-sonnet-4-20250514",
    provider: "anthropic",
    apiKey: process.env.ANTHROPIC_API_KEY!,
    cwd: "/path/to/project",
  });

  // Listen for events
  session.on("assistant_message", (event) => {
    console.log("Assistant:", event.content);
  });

  session.on("tool_call", (event) => {
    console.log(`Tool: ${event.toolName}`, event.input);
  });

  session.on("tool_result", (event) => {
    console.log(`Result:`, event.output);
  });

  // Send a prompt
  await session.prompt("Summarize this codebase");

  // Wait for completion
  await session.waitForIdle();

  // Clean up
  await session.shutdown();
}

main();

20.4 Core Concepts

20.4.1 createAgentSession

Creates and returns an AgentSession instance:

const session = await createAgentSession({
  model: "claude-sonnet-4-20250514",
  provider: "anthropic",
  apiKey: process.env.ANTHROPIC_API_KEY,
  cwd: process.cwd(),
  tools: ["read", "write", "edit", "bash"],
  systemPrompt: "You are a helpful coding assistant.",
  thinkingLevel: "medium",
});

20.4.2 AgentSession

The AgentSession is the main interface for interacting with the agent:

interface AgentSession {
  // Prompting
  prompt(content: string | ContentBlock[]): Promise<void>;
  sendUserMessage(content: string): Promise<void>;
  
  // State
  isIdle(): boolean;
  abort(): void;
  waitForIdle(): Promise<void>;
  
  // Configuration
  setModel(model: string): void;
  getModel(): string;
  setThinkingLevel(level: string): void;
  getThinkingLevel(): string;
  setActiveTools(tools: string[]): void;
  getActiveTools(): string[];
  
  // Events
  on(event: string, handler: (event: any) => void | Promise<void>): void;
  off(event: string, handler: (event: any) => void | Promise<void>): void;
  
  // Session management
  getSessionPath(): string | null;
  getSessionId(): string | null;
  shutdown(): Promise<void>;
}

20.4.3 Runtime

The Runtime provides shared infrastructure across sessions:

import { createRuntime } from "@earendil-works/pi-coding-agent";

const runtime = await createRuntime({
  configDir: "~/.pi/agent",
  sessionDir: "~/.pi/agent/sessions",
});

// Create multiple sessions sharing the same runtime
const session1 = await createAgentSession({ runtime, model: "claude-sonnet-4" });
const session2 = await createAgentSession({ runtime, model: "gpt-5" });

20.5 Prompting

20.5.1 Basic Prompt

await session.prompt("Explain this function");

20.5.2 Multi-Modal Prompt

await session.prompt([
  { type: "text", text: "What's in this image?" },
  { type: "image", source: { type: "base64", data: base64Data } },
]);

20.5.3 Streaming Responses

session.on("assistant_message", (event) => {
  if (event.delta) {
    process.stdout.write(event.delta);
  }
});

session.on("assistant_message_done", (event) => {
  console.log("\n--- Done ---");
  console.log("Tokens used:", event.usage);
});

await session.prompt("Write a poem about code");
await session.waitForIdle();

20.6 Agent State

// Check if agent is working
if (!session.isIdle()) {
  console.log("Agent is busy...");
  await session.waitForIdle();
}

// Abort current work
session.abort();

// Check active tools
console.log("Active tools:", session.getActiveTools());

// Change model mid-session
session.setModel("gpt-5");

20.7 Events

The SDK emits events for all agent activity:

20.7.1 Message Events

session.on("user_message", (event) => {
  console.log("User:", event.content);
});

session.on("assistant_message", (event) => {
  console.log("Assistant:", event.content);
});

session.on("assistant_message_delta", (event) => {
  // Streaming delta
  process.stdout.write(event.delta);
});

20.7.2 Tool Events

session.on("tool_call", (event) => {
  console.log(`Calling ${event.toolName}:`, event.input);
});

session.on("tool_result", (event) => {
  console.log(`Result:`, event.output);
});

20.7.3 Session Events

session.on("session_start", () => {
  console.log("Session started");
});

session.on("session_end", () => {
  console.log("Session ended");
});

session.on("compaction", (event) => {
  console.log("Context compacted. Freed tokens:", event.freedTokens);
});

20.7.4 Model Events

session.on("model_start", (event) => {
  console.log(`API call to ${event.model}`);
});

session.on("model_end", (event) => {
  console.log(`Tokens: ${event.usage.input} in / ${event.usage.output} out`);
  console.log(`Cost: $${event.cost.toFixed(4)}`);
});

20.7.5 Error Events

session.on("error", (event) => {
  console.error("Error:", event.message);
  if (event.retryable) {
    console.log("Will retry...");
  }
});

20.8 Options Reference

20.8.1 createAgentSession Options

Option Type Default Description
model string Required Model ID or pattern
provider string Auto-detected Provider name
apiKey string From env/auth API key
cwd string process.cwd() Working directory
tools string[] ["read", "write", "edit", "bash"] Active tools
systemPrompt string Default Pi prompt Custom system prompt
appendSystemPrompt string undefined Text appended to system prompt
thinkingLevel string "medium" Thinking level
contextFiles boolean true Load AGENTS.md files
sessionPath string Auto-generated Session file path
runtime Runtime Created automatically Shared runtime
extensions string[] [] Extension paths
skills string[] [] Skill paths
verbose boolean false Verbose logging

20.8.2 createRuntime Options

Option Type Default Description
configDir string ~/.pi/agent Pi config directory
sessionDir string ~/.pi/agent/sessions Session storage
modelsFile string models.json in config Custom models file
authFile string auth.json in config Auth file

20.9 Complete Example

import { createAgentSession, createRuntime } from "@earendil-works/pi-coding-agent";
import { writeFileSync } from "node:fs";

async function automatedReview() {
  const runtime = await createRuntime({
    configDir: "~/.pi/agent",
  });

  const session = await createAgentSession({
    runtime,
    model: "claude-sonnet-4-20250514",
    provider: "anthropic",
    apiKey: process.env.ANTHROPIC_API_KEY,
    cwd: process.cwd(),
    tools: ["read", "bash"],
    thinkingLevel: "high",
    systemPrompt: "You are a security-focused code reviewer.",
  });

  let findings: string[] = [];

  session.on("assistant_message", (event) => {
    findings.push(event.content);
  });

  session.on("tool_call", (event) => {
    console.log(`[tool] ${event.toolName}: ${JSON.stringify(event.input).slice(0, 100)}`);
  });

  session.on("model_end", (event) => {
    console.log(`[usage] Input: ${event.usage.input}, Output: ${event.usage.output}, Cost: $${event.cost.toFixed(4)}`);
  });

  await session.prompt(`
    Review the codebase for security vulnerabilities.
    Focus on:
    1. SQL injection
    2. XSS
    3. Authentication bypass
    4. Sensitive data exposure
    
    Run git diff main to see recent changes.
    Provide a structured report.
  `);

  await session.waitForIdle();
  await session.shutdown();

  // Save report
  writeFileSync("security-report.md", findings.join("\n\n"));
  console.log("\nReport saved to security-report.md");
}

automatedReview().catch(console.error);

20.10 Run Modes

The SDK can run in different modes:

20.10.1 Interactive

const session = await createAgentSession({
  model: "claude-sonnet-4",
  // ... defaults to interactive if TUI is available
});

20.10.2 Headless (Server/CI)

const session = await createAgentSession({
  model: "claude-sonnet-4",
  // No TUI; events only
});

20.10.3 JSON Output

const session = await createAgentSession({
  model: "claude-sonnet-4",
  mode: "json",
});

session.on("event", (event) => {
  console.log(JSON.stringify(event));
});

20.11 Exports

The SDK exports:

Export Description
createAgentSession Create an agent session
createRuntime Create a shared runtime
AgentSession Session interface type
Runtime Runtime interface type
ExtensionAPI Extension API type
ExtensionContext Extension context type
ContentBlock Content block type
ToolDefinition Tool definition type
SessionEntry Session entry type
Tip

The SDK is the foundation that Pi itself is built on. The TUI, JSON mode, and RPC mode are all thin wrappers around the SDK’s AgentSession.