How to Integrate Pi-Web with External Systems: Complete HTTP API Guide
Pi-Web exposes a complete JSON-over-HTTP RPC interface through Next.js API routes, allowing any external service to create sessions, send commands, and receive real-time events without requiring a specialized SDK.
Pi-Web is a thin Next.js frontend that communicates with the local Pi-Coding-Agent SDK via standard HTTP endpoints. Because the architecture exposes all functionality as REST routes and Server-Sent Events (SSE) streams, you can integrate Pi-Web with CI/CD pipelines, custom orchestration tools, or third-party applications using any programming language capable of issuing HTTP requests.
Core Integration Architecture
Pi-Web functions as an RPC bridge between external clients and the underlying agent SDK. In lib/rpc-manager.ts, the AgentSessionWrapper class handles command routing, while lib/agent-client.ts provides a thin wrapper (sendAgentCommand) that the frontend uses to POST JSON payloads to the API layer. This design means external systems can bypass the UI entirely and communicate directly with the same endpoints, receiving structured responses and real-time event streams.
Key API Endpoints for Pi-Web Integration
Session Lifecycle Management
Create and control agent sessions through two primary routes defined in app/api/agent/new/route.ts and app/api/agent/[id]/route.ts:
- POST
/api/agent/new— Initializes a new session, optionally accepting acwd(working directory) and tool allow-list. Returns a uniquesessionIdrequired for subsequent requests. - POST
/api/agent/{sessionId}— The core command endpoint. Accepts JSON payloads withtypefields includingprompt,fork,steer,set_model, andnavigate_tree. The route forwards these toAgentSessionWrapper.send()inlib/rpc-manager.ts, which invokes corresponding SDK methods (inner.prompt,inner.fork, etc.).
Real-Time Event Streaming
Long-running operations communicate results via Server-Sent Events (SSE) at GET /api/agent/{sessionId}/events (implemented in app/api/agent/[id]/events/route.ts). External services open an EventSource connection to receive push notifications for agent_end, toolResult, and extension_ui_request events without polling.
Plugin Management API
The /api/plugins endpoint (defined in app/api/plugins/route.ts) exposes CRUD operations for Pi-Web extensions. Services can programmatically install, update, disable, or query skills and themes by sending JSON actions (install, remove, disable, enable), making it possible to provision specific capabilities during automated deployments.
Repository File Access
Read-only access to the underlying filesystem is available through app/api/files/[...path]/route.ts and /api/file-index. External linting tools or documentation generators can fetch source code directly via GET requests to /api/files/{path} without maintaining separate repository clones.
Step-by-Step Pi-Web Integration Workflow
- Initialize the session — POST to
/api/agent/newwith the target working directory. Persist the returnedsessionId. - Issue commands — Send JSON-RPC style payloads to
/api/agent/{sessionId}with the appropriatetypeand parameters. - Consume events — Establish an SSE connection to
/api/agent/{sessionId}/eventsto capture asynchronous results and UI requests. - Handle extensions — Respond to
extension_ui_requestevents by postingextension_ui_responsemessages back to the command endpoint, enabling headless automation of interactive workflows. - Provision capabilities — Use
/api/pluginsto install required skills before executing dependent prompts.
Code Examples for Pi-Web Integration
Node.js: Creating Sessions and Sending Prompts
The following snippet demonstrates session creation, command execution, and SSE consumption using standard fetch and EventSource:
import fetch from 'node-fetch';
// 1️⃣ Create a new session
const newRes = await fetch('http://localhost:30141/api/agent/new', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cwd: '/home/user/project' })
});
const { sessionId } = await newRes.json();
// 2️⃣ Send a prompt command
await fetch(`http://localhost:30141/api/agent/${sessionId}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: 'prompt',
message: 'Explain the MVC pattern.'
})
});
// 3️⃣ Listen for completion via SSE
const es = new EventSource(`http://localhost:30141/api/agent/${sessionId}/events`);
es.addEventListener('agent_end', e => {
console.log('Assistant finished:', JSON.parse(e.data));
es.close();
});
Relevant source: sendAgentCommand in lib/agent-client.ts; RPC routing in lib/rpc-manager.ts.
cURL: Programmatic Plugin Installation
Automate environment setup by installing skills directly via the plugins API:
curl -X POST http://localhost:30141/api/plugins \
-H "Content-Type: application/json" \
-d '{
"action": "install",
"source": "npm:my-pi-skill",
"scope": "project",
"cwd": "/home/user/project"
}'
The response returns the updated plugin manifest, confirming availability for subsequent agent prompts.
Relevant source: Plugin handlers in app/api/plugins/route.ts.
Python: Driving Pi-Web with SSE Streaming
This example uses the requests and sseclient libraries to fork a session and process streaming results:
import requests, sseclient
SID = "c2b34f9e-..." # Existing session ID
# 1️⃣ Fork the session to create a branch
fork_resp = requests.post(
f'http://localhost:30141/api/agent/{SID}',
json={'type': 'fork', 'entryId': 'root'}
).json()
new_sid = fork_resp['newSessionId']
# 2️⃣ Send a steered prompt
requests.post(
f'http://localhost:30141/api/agent/{new_sid}',
json={'type': 'steer', 'message': 'List all .ts files in the repo.'}
)
# 3️⃣ Consume the SSE event stream
stream = requests.get(
f'http://localhost:30141/api/agent/{new_sid}/events',
stream=True,
headers={'Accept': 'text/event-stream'}
)
client = sseclient.SSEClient(stream)
for event in client.events():
if event.event == 'agent_end':
print('Result:', event.data)
break
Relevant source: Command dispatch in lib/rpc-manager.ts (see AgentSessionWrapper.send switch cases for "fork" and "steer").
Advanced Integration: Extension UI Protocol
Pi-Web supports sophisticated automation through the Extension UI API. When extensions request user input (widgets, confirmations, or custom TUI components), they emit extension_ui_request events via the SSE stream. External systems can implement headless "extension runners" that intercept these requests in lib/rpc-manager.ts (specifically within AgentSessionWrapper.createExtensionUiContext()) and POST responses back to /api/agent/{sessionId} with type: "extension_ui_response".
Additionally, the global __piSessions registry and notifyRunningChange() broadcast mechanism in lib/rpc-manager.ts enable external monitoring dashboards to track live session activity and resource utilization without polling individual endpoints.
Summary
- Pi-Web integration relies entirely on standard HTTP routes and SSE streams—no proprietary SDK required.
- Session management flows through
/api/agent/newand/api/agent/{id}, handled internally byAgentSessionWrapper. - Real-time communication uses Server-Sent Events at
/api/agent/{id}/eventsfor asynchronous results. - Plugin automation is available via
/api/plugins, supporting CI/CD provisioning of skills and themes. - File system access exposes read-only repository contents through
/api/files/[...path]for external analysis tools.
Frequently Asked Questions
Can Pi-Web be integrated without using JavaScript?
Yes. Because Pi-Web exposes standard HTTP endpoints and SSE streams, any language capable of HTTP requests—including Python, Go, Ruby, or Bash—can integrate with the system. The API accepts and returns JSON, making it language-agnostic.
What real-time capabilities does Pi-Web offer for integrations?
Pi-Web provides Server-Sent Events (SSE) through /api/agent/{sessionId}/events, allowing external services to receive instantaneous notifications for agent_end, toolResult, and extension_ui_request events. This eliminates the need for polling and enables reactive automation workflows.
How do I automate plugin management in Pi-Web?
Use the POST /api/plugins endpoint with actions like install, remove, enable, or disable. You can specify package sources (e.g., npm:package-name) and scope (project or global), allowing automated provisioning of specific capabilities before executing agent prompts.
Is it possible to monitor active Pi-Web sessions externally?
Yes. The global __piSessions registry and notifyRunningChange() function in lib/rpc-manager.ts broadcast session state changes. External monitoring tools can subscribe to these broadcasts or poll session endpoints to build dashboards showing which sessions are active, idle, or processing commands.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →