Embed Pi into Node/Bun applications, or access other languages and clients through RPC subprocesses.
1. Choose SDK or RPC?
SDK
- process boundaries
- same process
- Control method
- Directly call the TypeScript method and subscribe to events
- most suitable
- Node.js/Bun host who wants full API
RPC
- process boundaries
- child process
- Control method
- JSONL commands, responses, events on stdin/stdout
- most suitable
- Other languages, process isolation required, IDE, custom client
| interface | process boundaries | Control method | most suitable |
|---|---|---|---|
| SDK | same process | Directly call the TypeScript method and subscribe to events | Node.js/Bun host who wants full API |
| RPC | child process | JSONL commands, responses, events on stdin/stdout | Other languages, process isolation required, IDE, custom client |
- Node/TS but want child process isolation: use exported
RpcClient; - Just the final text or one-off event: print / JSON schema is enough (see 03 Usage tips)。
02
Part One: TypeScript SDK
@earendil-works/pi-coding-agent You can embed Pi into the Node.js or Bun process to directly access the agents, sessions, tools, models and resources used by command line applications.
npm install @earendil-works/pi-coding-agent
2. Minimal example (official SDK documentation)
import { createAgentSession } from "@earendil-works/pi-coding-agent";
const { session } = await createAgentSession();
try {
await session.prompt("What files are in the current directory?");
console.log(session.getLastAssistantText());
} finally {
session.dispose();
}
Used by default Working directory, discovered resources, saved settings, and configured credentials;prompt() resolve after the run ends.
2.1 Streaming output (official examples/sdk/01-minimal.ts)
import { createAgentSession } from "@earendil-works/pi-coding-agent";
const { session } = await createAgentSession();
try {
session.subscribe((event) => {
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
process.stdout.write(event.assistantMessageEvent.delta);
}
});
await session.prompt("What files are in the current directory?");
console.log();
} finally {
session.dispose();
}
Subscribe first and then prompt, otherwise quickly completed events may be missed.
subscribe()Return the unsubscribe function.
3. Session life cycle
createAgentSession()Create aAgentSession: owns a conversation, its model and tools, queued messages, compressed state, and extended runtime;- Read status:
session.messages、session.model、session.thinkingLevel、session.systemPrompt(read only),session.getActiveToolNames(); session.dispose(): Abort activity work, invalidate extended context, remove listeners.Be sure to call when finished.cwdDetermines project resource discovery, context files, session groupings, and built-in tool paths; andprocess.cwd()If not, please pass it in explicitly.
3.1 Session storage:SessionManager(Official 11-sessions.ts)
import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent";
// Memory session (not dropped to disk)
const { session: inMemory } = await createAgentSession({
sessionManager: SessionManager.inMemory(),
});
// new persistent session
const { session: newSession } = await createAgentSession({
sessionManager: SessionManager.create(process.cwd()),
});
// Continue the most recent conversation (create a new one if none exists)
const { session: continued, modelFallbackMessage } = await createAgentSession({
sessionManager: SessionManager.continueRecent(process.cwd()),
});
// List and open specified sessions
const sessions = await SessionManager.list(process.cwd());
if (sessions.length > 0) {
const { session: opened } = await createAgentSession({
sessionManager: SessionManager.open(sessions[0].path),
});
}
Key points:SessionManager to the final model context authoritative. To restore external history, construct a session with a manager containing these entries;direct assignment session.agent.state.messages Persistence context will not be replaced。
3.2 Replace active session:AgentSessionRuntime
AgentSessionRuntime provide newSession()、switchSession()、fork()、importFromJsonl(), each action replaces the activity AgentSession And rebuild the service for the target directory. After replacement, the old subscription belongs to the old session,Must rebind. see 13-session-runtime.ts。
4. Prompt, Steering and Follow-up
prompt()Will process extended commands and expand file-based prompt templates; for accepted runs, resolve after the run (including automatic retries) ends;- session Streaming output Called when
prompt()Must specify whether to steer or follow-up, otherwise Reject directly; steer()/followUp():return"queued"(queued) or"handled"(consumed by extension);abort(): Stop and wait for idle;waitForIdle(): Just wait without stopping.
5. Configure session
The default factory will create ModelRuntime, file-based SettingsManager, lasting SessionManager、DefaultResourceLoader and default tools. Each boundary is replaceable:
modelRuntime、model、thinkingLevel、scopedModels- function
- Model access and selection
settingsManager- function
- Merged settings or memory configuration
sessionManager- function
- Persistent or in-memory history
resourceLoader- function
- extensions, skills, templates, themes, context files
tools、noTools、excludeTools、customTools- function
- Activate toolset
cwd- function
- working directory
| Options | function |
|---|---|
modelRuntime、model、thinkingLevel、scopedModels | Model access and selection |
settingsManager | Merged settings or memory configuration |
sessionManager | Persistent or in-memory history |
resourceLoader | extensions, skills, templates, themes, context files |
tools、noTools、excludeTools、customTools | Activate toolset |
cwd | working directory |
5.1 Specified model (official 02-custom-model.ts)
import { createAgentSession, ModelRuntime } from "@earendil-works/pi-coding-agent";
const modelRuntime = await ModelRuntime.create();
const opus = modelRuntime.getModel("anthropic", "claude-opus-4-5"); // press provider/id Find
const available = await modelRuntime.getAvailable(); // Models with available credentials
if (available.length > 0) {
const { session } = await createAgentSession({
model: available[0],
thinkingLevel: "medium",
modelRuntime,
});
// ...
session.dispose();
}
5.2 Select tools (official 05-tools.ts)
import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent";
// read-only mode
const { session } = await createAgentSession({
tools: ["read", "grep", "find", "ls"],
sessionManager: SessionManager.inMemory(),
});
// Customize cwd
const customCwd = "/path/to/project";
const { session: s2 } = await createAgentSession({
cwd: customCwd,
tools: ["read", "bash", "edit", "write"],
sessionManager: SessionManager.inMemory(customCwd),
});
Custom tools extend the system’s pi.registerTool() Register (see next section).
5.3 Loading extensions (official 06-extensions.ts)
import {
createAgentSession,
DefaultResourceLoader,
getAgentDir,
SessionManager,
} from "@earendil-works/pi-coding-agent";
const resourceLoader = new DefaultResourceLoader({
cwd: process.cwd(),
agentDir: getAgentDir(),
additionalExtensionPaths: ["./my-logging-extension.ts", "./my-safety-extension.ts"],
extensionFactories: [
(pi) => {
pi.on("agent_start", () => {
console.log("[Inline Extension] Agent starting");
});
},
],
});
await resourceLoader.reload();
const { session } = await createAgentSession({
resourceLoader,
sessionManager: SessionManager.inMemory(),
});
remember
await resourceLoader.reload(). inline extension factory (extensionFactories) and file extension use the sameExtensionAPI。
5.4 Customized system prompts (official 03-custom-prompt.ts)
// Method 1: Whole replacement
const loader1 = new DefaultResourceLoader({
cwd,
agentDir,
systemPromptOverride: () => `You are a helpful assistant that speaks like a pirate.
Always end responses with "Arrr!"`,
// avoid additional ~/.pi/agent or <cwd>/.pi in APPEND_SYSTEM.md
appendSystemPromptOverride: () => [],
});
// Method 2: Append after the default prompt
const loader2 = new DefaultResourceLoader({
cwd,
agentDir,
appendSystemPromptOverride: (base) => [
...base,
"## Additional Instructions\n- Always be concise\n- Use bullet points when listing things",
],
});
5.5 Skills and context files (official 04-skills.ts、07-context-files.ts ideas)
DefaultResourceLoader Also supports skillsOverride(Filtering/adding skills),agentsFilesOverride(Append or replace AGENTS.md content) and provide loader.getSkills()、loader.getAgentsFiles() Check out the findings:
const loader = new DefaultResourceLoader({
cwd: process.cwd(),
agentDir: getAgentDir(),
agentsFilesOverride: (current) => ({
agentsFiles: [
...current.agentsFiles,
{ path: "/virtual/AGENTS.md", content: "# Project Guidelines\n- Use TypeScript strict mode" },
],
}),
});
await loader.reload();
Enable Codemode / MCP in 5.6 SDK (official 14-codemode-mcp.ts)
The CLI will codemode、tool_search, MCP as Built-in extensions loading,SDK sessions will not, need to be added manually:
import {
createAgentSession,
createCodemodeExtension,
createMcpExtension,
createToolSearchExtension,
DefaultResourceLoader,
getAgentDir,
SessionManager,
SettingsManager,
} from "@earendil-works/pi-coding-agent";
const cwd = process.cwd();
const resourceLoader = new DefaultResourceLoader({
cwd,
agentDir: getAgentDir(),
extensionFactories: [
createCodemodeExtension({ mode: "on" }),
createToolSearchExtension(),
createMcpExtension(), // Read mcp.json in the agent directory and trusted projects like CLI
],
});
await resourceLoader.reload();
const settingsManager = SettingsManager.create(cwd);
settingsManager.applyOverrides({ defaultTools: ["+codemode", "+tool_search"] });
const { session } = await createAgentSession({
resourceLoader,
settingsManager,
sessionManager: SessionManager.inMemory(),
});
try {
await session.bindExtensions({}); // trigger session_start,Background connection MCP server
console.log("Active tools:", session.getActiveToolNames().join(", "));
await session.prompt("Use codemode to count the TypeScript files in src/ and list the three largest.");
} finally {
session.dispose();
}
5.7 SDK Example List
01-minimal
- Purpose
- Create, prompt, observe, release
02-custom-model
- Purpose
- Choosing models and thinking levels
03-custom-prompt
- Purpose
- Replace or append system prompts
04-skills
- Purpose
- Discover, filter, and add skills
05-tools
- Purpose
- Select built-in tools and their working directories
06-extensions
- Purpose
- File extensions and inline extensions
07-context-files
- Purpose
- Add or replace project directives
08-prompt-templates
- Purpose
- Add file prompt template
09-api-keys-and-oauth
- Purpose
- Credentials and model storage
10-settings
- Purpose
- File or memory settings
11-sessions
- Purpose
- Session persistence and recovery
12-full-control
- Purpose
- Replacing the default discovery and status services
13-session-runtime
- Purpose
- Safely replace active sessions
14-codemode-mcp
- Purpose
- codemode, tool_search and MCP
| Example | Purpose |
|---|---|
| 01-minimal | Create, prompt, observe, release |
| 02-custom-model | Choosing models and thinking levels |
| 03-custom-prompt | Replace or append system prompts |
| 04-skills | Discover, filter, and add skills |
| 05-tools | Select built-in tools and their working directories |
| 06-extensions | File extensions and inline extensions |
| 07-context-files | Add or replace project directives |
| 08-prompt-templates | Add file prompt template |
| 09-api-keys-and-oauth | Credentials and model storage |
| 10-settings | File or memory settings |
| 11-sessions | Session persistence and recovery |
| 12-full-control | Replacing the default discovery and status services |
| 13-session-runtime | Safely replace active sessions |
| 14-codemode-mcp | codemode, tool_search and MCP |
07
Part 2: RPC Pattern
6. Startup and protocol recording
pi --mode rpc --no-session
Ordinary CLI options (`--provider`、`--model`、`--name`、`--session-dir` etc.) are still valid. Four types of records:
stdin
- record
- Command
- Purpose
- Let Pi prompt, query status, change configuration, and manage sessions
stdout
- record
response- Purpose
- Report whether a command is successful and return data
stdout
- record
- Session event
- Purpose
- Streaming output runs, messages, tools, queues, compression, retries
Two-way
- record
- Extension UI records
- Purpose
- Forward extended interactions (dialog boxes, notifications)
| direction | record | Purpose |
|---|---|---|
| stdin | Command | Let Pi prompt, query status, change configuration, and manage sessions |
| stdout | response | Report whether a command is successful and return data |
| stdout | Session event | Streaming output runs, messages, tools, queues, compression, retries |
| Two-way | Extension UI records | Forward extended interactions (dialog boxes, notifications) |
6.1 Correlation between commands and responses
Each command can take optional strings id, the response will be brought back unchanged. Command processing is asynchronous,Associate by id, not by order:
{"id":"req-1","type":"get_state"}
{"id":"req-1","type":"response","command":"get_state","success":true,"data":{"...":"..."}}
6.2 Operation life cycle
{"id":"req-2","type":"prompt","message":"Review this repository"}
{"id":"req-2","type":"response","command":"prompt","success":true,"data":{"disposition":"started"}}
- successful
promptresponse Only means accepted/queued/processed, does not mean that the model work is completed; disposition:"started"、"queued"、"handled"(handled will not run, don’t waitagent_settled);- Prompt must be sent again during streaming
"streamingBehavior": "steer"or"followUp", otherwise an error will be reported; - wait
agent_settledOnly then can you confirm that Pi will no longer continue automatically.
6.3 Quick check of commonly used commands
Prompt
- command
prompt、steer、follow_up、abort、clear_queue、new_session
Status
- command
get_state、get_messages
model
- command
set_model、cycle_model、get_available_models
think
- command
set_thinking_level、cycle_thinking_level、get_available_thinking_levels
queue mode
- command
set_steering_mode、set_follow_up_mode
Compression
- command
compact、set_auto_compaction
Try again
- command
set_auto_retry、abort_retry
Bash
- command
bash(The output ends withbash_execution_updateStreaming return),abort_bash
session
- command
get_session_stats、export_html、switch_session、fork、clone、get_fork_messages、get_entries、get_tree、get_last_assistant_text、set_session_name
discover
- command
get_commands(Extended commands, templates, skills)
| Category | command |
|---|---|
| Prompt | prompt、steer、follow_up、abort、clear_queue、new_session |
| Status | get_state、get_messages |
| model | set_model、cycle_model、get_available_models |
| think | set_thinking_level、cycle_thinking_level、get_available_thinking_levels |
| queue mode | set_steering_mode、set_follow_up_mode |
| Compression | compact、set_auto_compaction |
| Try again | set_auto_retry、abort_retry |
| Bash | bash(The output ends with bash_execution_update Streaming return),abort_bash |
| session | get_session_stats、export_html、switch_session、fork、clone、get_fork_messages、get_entries、get_tree、get_last_assistant_text、set_session_name |
| discover | get_commands(Extended commands, templates, skills) |
Example:
{"type": "set_model", "provider": "anthropic", "modelId": "claude-sonnet-4-20250514"}
{"type": "compact", "customInstructions": "Focus on code changes"}
{"id": "req-1", "type": "bash", "command": "ls -la"}
{"type": "prompt", "message": "New instruction", "streamingBehavior": "steer"}
6.4 Errors
{"id":"req-3","type":"response","command":"set_model","success":false,"error":"Model not found: invalid/model"}
{"type":"response","command":"parse","success":false,"error":"Failed to parse command: Unexpected token..."}
Provider failures and aborts occur in the event stream,No Send a second response to the same request. The client also needs to handle child process startup failures, unexpected exits, stderr diagnostics, and self-timeouts;Don’t parse stderr as protocol data。
6.5 Framing and closing
- Strict JSONL: Each record has a JSON object + LF; only split by LF, and the leading CR can be removed;
- Don't use Node.js
readline(It will be divided by U+2028/U+2029 by mistake); - Continuously read stdout and observe backpressure when writing to stdin;
- Close child process stdin That is, an orderly shutdown is requested.
6.6 Python minimal client (official example)
import json
import subprocess
process = subprocess.Popen(
["pi", "--mode", "rpc", "--no-session"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
)
assert process.stdin is not None
assert process.stdout is not None
command = {"id": "prompt-1", "type": "prompt", "message": "Hello"}
process.stdin.write(json.dumps(command).encode("utf-8") + b"\n")
process.stdin.flush()
while line := process.stdout.readline():
record = json.loads(line)
if record.get("type") == "message_update":
update = record["assistantMessageEvent"]
if update["type"] == "text_delta":
print(update["delta"], end="", flush=True)
elif record.get("type") == "agent_settled":
print()
break
process.stdin.close()
process.wait()
(binary pipe's readline() Just press \n Split so it's safe here. )
6.7 TypeScript:RpcClient(Official examples/rpc-client.ts)
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { RpcClient } from "@earendil-works/pi-coding-agent";
const exampleDirectory = dirname(fileURLToPath(import.meta.url));
const prompt = process.argv.slice(2).join(" ") || "Explain this repository in one paragraph.";
const client = new RpcClient({
cliPath: join(exampleDirectory, "../dist/cli.js"),
args: ["--no-session"],
});
const unsubscribe = client.onEvent((event) => {
if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
process.stdout.write(event.assistantMessageEvent.delta);
} else if (event.type === "tool_execution_start") {
process.stderr.write(`\n[tool: ${event.toolName}]\n`);
}
});
try {
await client.start();
await client.promptAndWait(prompt);
process.stdout.write("\n");
} finally {
unsubscribe();
await client.stop();
}
cliPathNeed to point to the runnable Pi CLI (the warehouse example points to the builtdist/cli.js;Please point to the installed one in your projectpientrance);promptAndWait()internal Install the listener first and then send the prompt, to avoid race conditions; please subscribe first when calling separately, and only call it during operation.waitForIdle()。
7. RPC extended UI subprotocol
extension call ctx.ui , in RPC mode:
- Conversation(
select、confirm、input、editor): Pi is emitted on stdoutextension_ui_requestand blocks until the client replies on stdin with the sameidofextension_ui_response; - fire-and-forget category(
notify、setStatus、setWidget、setTitle、set_editor_text): The client can display or ignore it.
{"type":"extension_ui_request","id":"uuid-1","method":"select","title":"Allow dangerous command?","options":["Allow","Block"],"timeout":10000}
{"type":"extension_ui_response","id":"uuid-1","value":"Allow"}
{"type":"extension_ui_request","id":"uuid-2","method":"confirm","title":"Clear session?","message":"All messages will be lost.","timeout":5000}
{"type":"extension_ui_response","id":"uuid-2","confirmed":true}
{"type":"extension_ui_response","id":"uuid-3","cancelled":true}
In RPC mode ctx.mode for "rpc"、ctx.hasUI for true;custom() Return undefined, many TUI-specific methods are no-ops. Example:examples/rpc-extension-ui.ts + examples/extensions/rpc-demo.ts。
8. Change brand: Fork Pi
The source code can be forked at package.json Modify the CLI name and configuration directory in:
{
"piConfig": {
"name": "my-agent",
"configDir": ".my-agent"
}
}
Modify the top layer again bin Field sets the executable file name. This affects banners, configuration paths, and derived environment variable names.
9. Small exercises
- SDK minimal program: Create a new Node project and install it
@earendil-works/pi-coding-agent, run the code in Section 2.1; change toSessionManager.inMemory()and only giveread、lsTools. - Event Dashboard:Subscribe to events and print each
tool_execution_starttool name andtool_execution_endofdurationMs, output a summary table after the run is completed. - inline expansion:Pass
extensionFactoriesRegister acurrent_timeTool that lets the model answer "what time is it now?" - Session continuation: use
SessionManager.continueRecent()Implement a CLI script that "asks for progress once a day" and can remember the context when run twice in a row. - Python RPC: Extended Section 6.6 Client: First
get_statePrint the model and thenprompt, receivedtool_execution_startwhen printing the tool name, and finallyget_session_statsPrinting costs. - Extended UI bridge:load
permission-gate.ts, processed with RPC clientextension_ui_requestofselect, pop up a confirmation in your program (command lineinput()That’s it). - Thinking questions: A VS Code plug-in integrates Pi. Which one should you choose, SDK or RPC? Give reasons (process isolation, crash recovery, multilingualism, etc.).
10. Official sources
- SDK:https://pi.dev/docs/latest/sdk
- CLI Integration:https://pi.dev/docs/latest/cli-integration
- RPC Mode:https://pi.dev/docs/latest/rpc
- RPC Commands:https://pi.dev/docs/latest/rpc-commands
- RPC Extension UI:https://pi.dev/docs/latest/rpc-extension-ui
- JSON Event Stream:https://pi.dev/docs/latest/json
- Session File Format:https://pi.dev/docs/latest/session-format
- SDK example:https://github.com/earendil-works/pi/tree/main/packages/coding-agent/examples/sdk
- RPC client example:https://github.com/earendil-works/pi/blob/main/packages/coding-agent/examples/rpc-client.ts
rpc-types.ts:https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/modes/rpc/rpc-types.ts