Pi Integration Architecture
This document describes how OpenClaw integrates with pi-coding-agent and its sibling packages (pi-ai, pi-agent-core, pi-tui) to power its AI agent capabilities.
Overview
OpenClaw uses the pi SDK to embed an AI coding agent into its messaging gateway architecture. Instead of spawning pi as a subprocess or using RPC mode, OpenClaw directly imports and instantiates pi’sAgentSession via createAgentSession(). This embedded approach provides:
- Full control over session lifecycle and event handling
- Custom tool injection (messaging, sandbox, channel-specific actions)
- System prompt customization per channel/context
- Session persistence with branching/compaction support
- Multi-account auth profile rotation with failover
- Provider-agnostic model switching
Package Dependencies
| Package | Purpose |
|---|---|
pi-ai | Core LLM abstractions: Model, streamSimple, message types, provider APIs |
pi-agent-core | Agent loop, tool execution, AgentMessage types |
pi-coding-agent | High-level SDK: createAgentSession, SessionManager, AuthStorage, ModelRegistry, built-in tools |
pi-tui | Terminal UI components (used in OpenClaw’s local TUI mode) |
File Structure
Core Integration Flow
1. Running an Embedded Agent
The main entry point isrunEmbeddedPiAgent() in pi-embedded-runner/run.ts:
2. Session Creation
InsiderunEmbeddedAttempt() (called by runEmbeddedPiAgent()), the pi SDK is used:
3. Event Subscription
subscribeEmbeddedPiSession() subscribes to pi’s AgentSession events:
message_start/message_end/message_update(streaming text/thinking)tool_execution_start/tool_execution_update/tool_execution_endturn_start/turn_endagent_start/agent_endauto_compaction_start/auto_compaction_end
4. Prompting
After setup, the session is prompted:images for that turn only. It does not re-scan older history turns
to re-inject image payloads.
Tool Architecture
Tool Pipeline
- Base Tools: pi’s
codingTools(read, bash, edit, write) - Custom Replacements: OpenClaw replaces bash with
exec/process, customizes read/edit/write for sandbox - OpenClaw Tools: messaging, browser, canvas, sessions, cron, gateway, etc.
- Channel Tools: Discord/Telegram/Slack/WhatsApp-specific action tools
- Policy Filtering: Tools filtered by profile, provider, agent, group, sandbox policies
- Schema Normalization: Schemas cleaned for Gemini/OpenAI quirks
- AbortSignal Wrapping: Tools wrapped to respect abort signals
Tool Definition Adapter
pi-agent-core’sAgentTool has a different execute signature than pi-coding-agent’s ToolDefinition. The adapter in pi-tool-definition-adapter.ts bridges this:
Tool Split Strategy
splitSdkTools() passes all tools via customTools:
System Prompt Construction
The system prompt is built inbuildAgentSystemPrompt() (system-prompt.ts). It assembles a full prompt with sections including Tooling, Tool Call Style, Safety guardrails, OpenClaw CLI reference, Skills, Docs, Workspace, Sandbox, Messaging, Reply Tags, Voice, Silent Replies, Heartbeats, Runtime metadata, plus Memory and Reactions when enabled, and optional context files and extra system prompt content. Sections are trimmed for minimal prompt mode used by subagents.
The prompt is applied after session creation via applySystemPromptOverrideToSession():
Session Management
Session Files
Sessions are JSONL files with tree structure (id/parentId linking). Pi’sSessionManager handles persistence:
guardSessionManager() for tool result safety.
Session Caching
session-manager-cache.ts caches SessionManager instances to avoid repeated file parsing:
History Limiting
limitHistoryTurns() trims conversation history based on channel type (DM vs group).
Compaction
Auto-compaction triggers on context overflow.compactEmbeddedPiSessionDirect() handles manual compaction:
Authentication & Model Resolution
Auth Profiles
OpenClaw maintains an auth profile store with multiple API keys per provider:Model Resolution
Failover
FailoverError triggers model fallback when configured:
Pi Extensions
OpenClaw loads custom pi extensions for specialized behavior:Compaction Safeguard
src/agents/pi-extensions/compaction-safeguard.ts adds guardrails to compaction, including adaptive token budgeting plus tool failure and file operation summaries:
Context Pruning
src/agents/pi-extensions/context-pruning.ts implements cache-TTL based context pruning:
Streaming & Block Replies
Block Chunking
EmbeddedBlockChunker manages streaming text into discrete reply blocks:
Thinking/Final Tag Stripping
Streaming output is processed to strip<think>/<thinking> blocks and extract <final> content:
Reply Directives
Reply directives like[[media:url]], [[voice]], [[reply:id]] are parsed and extracted:
Error Handling
Error Classification
pi-embedded-helpers.ts classifies errors for appropriate handling:
Thinking Level Fallback
If a thinking level is unsupported, it falls back:Sandbox Integration
When sandbox mode is enabled, tools and paths are constrained:Provider-Specific Handling
Anthropic
- Refusal magic string scrubbing
- Turn validation for consecutive roles
- Claude Code parameter compatibility
Google/Gemini
- Turn ordering fixes (
applyGoogleTurnOrderingFix) - Tool schema sanitization (
sanitizeToolsForGoogle) - Session history sanitization (
sanitizeSessionHistory)
OpenAI
apply_patchtool for Codex models- Thinking level downgrade handling
TUI Integration
OpenClaw also has a local TUI mode that uses pi-tui components directly:Key Differences from Pi CLI
| Aspect | Pi CLI | OpenClaw Embedded |
|---|---|---|
| Invocation | pi command / RPC | SDK via createAgentSession() |
| Tools | Default coding tools | Custom OpenClaw tool suite |
| System prompt | AGENTS.md + prompts | Dynamic per-channel/context |
| Session storage | ~/.pi/agent/sessions/ | ~/.openclaw/agents/<agentId>/sessions/ (or $OPENCLAW_STATE_DIR/agents/<agentId>/sessions/) |
| Auth | Single credential | Multi-profile with rotation |
| Extensions | Loaded from disk | Programmatic + disk paths |
| Event handling | TUI rendering | Callback-based (onBlockReply, etc.) |
Future Considerations
Areas for potential rework:- Tool signature alignment: Currently adapting between pi-agent-core and pi-coding-agent signatures
- Session manager wrapping:
guardSessionManageradds safety but increases complexity - Extension loading: Could use pi’s
ResourceLoadermore directly - Streaming handler complexity:
subscribeEmbeddedPiSessionhas grown large - Provider quirks: Many provider-specific codepaths that pi could potentially handle
Tests
Pi integration coverage spans these suites:src/agents/pi-*.test.tssrc/agents/pi-auth-json.test.tssrc/agents/pi-embedded-*.test.tssrc/agents/pi-embedded-helpers*.test.tssrc/agents/pi-embedded-runner*.test.tssrc/agents/pi-embedded-runner/**/*.test.tssrc/agents/pi-embedded-subscribe*.test.tssrc/agents/pi-tools*.test.tssrc/agents/pi-tool-definition-adapter*.test.tssrc/agents/pi-settings.test.tssrc/agents/pi-extensions/**/*.test.ts
src/agents/pi-embedded-runner-extraparams.live.test.ts(enableOPENCLAW_LIVE_TEST=1)