Skip to main content

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’s AgentSession 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

File Structure

Core Integration Flow

1. Running an Embedded Agent

The main entry point is runEmbeddedPiAgent() in pi-embedded-runner/run.ts:

2. Session Creation

Inside runEmbeddedAttempt() (called by runEmbeddedPiAgent()), the pi SDK is used:

3. Event Subscription

subscribeEmbeddedPiSession() subscribes to pi’s AgentSession events:
Events handled include:
  • message_start / message_end / message_update (streaming text/thinking)
  • tool_execution_start / tool_execution_update / tool_execution_end
  • turn_start / turn_end
  • agent_start / agent_end
  • auto_compaction_start / auto_compaction_end

4. Prompting

After setup, the session is prompted:
The SDK handles the full agent loop: sending to LLM, executing tool calls, streaming responses. Image injection is prompt-local: OpenClaw loads image refs from the current prompt and passes them via images for that turn only. It does not re-scan older history turns to re-inject image payloads.

Tool Architecture

Tool Pipeline

  1. Base Tools: pi’s codingTools (read, bash, edit, write)
  2. Custom Replacements: OpenClaw replaces bash with exec/process, customizes read/edit/write for sandbox
  3. OpenClaw Tools: messaging, browser, canvas, sessions, cron, gateway, etc.
  4. Channel Tools: Discord/Telegram/Slack/WhatsApp-specific action tools
  5. Policy Filtering: Tools filtered by profile, provider, agent, group, sandbox policies
  6. Schema Normalization: Schemas cleaned for Gemini/OpenAI quirks
  7. AbortSignal Wrapping: Tools wrapped to respect abort signals

Tool Definition Adapter

pi-agent-core’s AgentTool 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:
This ensures OpenClaw’s policy filtering, sandbox integration, and extended toolset remain consistent across providers.

System Prompt Construction

The system prompt is built in buildAgentSystemPrompt() (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’s SessionManager handles persistence:
OpenClaw wraps this with 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:
Profiles rotate on failures with cooldown tracking:

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_patch tool for Codex models
  • Thinking level downgrade handling

TUI Integration

OpenClaw also has a local TUI mode that uses pi-tui components directly:
This provides the interactive terminal experience similar to pi’s native mode.

Key Differences from Pi CLI

Future Considerations

Areas for potential rework:
  1. Tool signature alignment: Currently adapting between pi-agent-core and pi-coding-agent signatures
  2. Session manager wrapping: guardSessionManager adds safety but increases complexity
  3. Extension loading: Could use pi’s ResourceLoader more directly
  4. Streaming handler complexity: subscribeEmbeddedPiSession has grown large
  5. Provider quirks: Many provider-specific codepaths that pi could potentially handle

Tests

Pi integration coverage spans these suites:
  • src/agents/pi-*.test.ts
  • src/agents/pi-auth-json.test.ts
  • src/agents/pi-embedded-*.test.ts
  • src/agents/pi-embedded-helpers*.test.ts
  • src/agents/pi-embedded-runner*.test.ts
  • src/agents/pi-embedded-runner/**/*.test.ts
  • src/agents/pi-embedded-subscribe*.test.ts
  • src/agents/pi-tools*.test.ts
  • src/agents/pi-tool-definition-adapter*.test.ts
  • src/agents/pi-settings.test.ts
  • src/agents/pi-extensions/**/*.test.ts
Live/opt-in:
  • src/agents/pi-embedded-runner-extraparams.live.test.ts (enable OPENCLAW_LIVE_TEST=1)
For current run commands, see Pi Development Workflow.