> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch15-piagent-runtime-core/15.1-what-is-piagent.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 15.1 What is Pi Agent

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~350,000 tokens, Output \~28,000 tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In the previous chapters, we learned how Gateway receives messages, routes them to the correct session, and how the channel layer handles inbound and outbound messages. But where does the actual "AI conversation" happen? The answer is the **Pi Agent runtime**. Pi Agent is the core engine in OpenClaw responsible for interacting with large language models (LLMs)—it constructs conversation context, sends requests to model providers, handles streaming responses, executes tool calls, and returns final results to Gateway.

> **Sidebar**: Pi Agent is OpenClaw's AI inference runtime, derived from the `pi-agent-core` library developed by Mario Zechner. It implements the RPC calling pattern for LLMs, managing conversation context, tool calls, and response streaming. It can be compared to an "AI conversation engine"—just as the JavaScript engine in a browser executes code, Pi Agent executes each round of AI conversation.

## 15.1.1 pi-mono Dependency Analysis

OpenClaw's Agent runtime is built on four external packages, all pinned to the same version (`package.json:349-352`):

```json
"@mariozechner/pi-agent-core":   "0.57.1",
"@mariozechner/pi-ai":           "0.57.1",
"@mariozechner/pi-coding-agent": "0.57.1",
"@mariozechner/pi-tui":          "0.57.1"
```

| Package                       | Role                    | Responsibility                                                                              |
| ----------------------------- | ----------------------- | ------------------------------------------------------------------------------------------- |
| `@mariozechner/pi-agent-core` | Core Engine             | Provides LLM conversation loop, message formatting, tool call protocol, session persistence |
| `pi-ai`                       | LLM abstraction         | Per-provider API adaptation and streaming protocol (Anthropic, OpenAI, Google, etc.)        |
| `pi-coding-agent`             | Higher-level facilities | `SessionManager` / `AuthStorage` / `ModelRegistry` and similar                              |
| `pi-tui`                      | Terminal UI             | Terminal components (used by the TUI, Chapter 41)                                           |

> **Note all four carry the `@mariozechner/` scope** — npm also has unscoped packages by the same names, which are different things. **Versions are pinned exactly rather than with `^0.57.1`**: pi evolves quickly and even patch releases can change behavior, so OpenClaw upgrades explicitly rather than tracking automatically.

The official statement of the division of labor (`docs/pi.md`) is clear: LLM abstraction and the streaming protocol belong to pi-ai, the agent loop and tool execution to pi-agent-core, and `SessionManager` / `AuthStorage` / `ModelRegistry` to pi-coding-agent — while **session management, tool wiring, model discovery, and credential rotation are all taken over by OpenClaw itself**. It reads no configuration from `~/.pi`, and session JSONL lives under `~/.openclaw/agents/<agentId>/sessions/`.

The dependency relationship is hierarchical:

```
OpenClaw Agent Code (src/agents/)
    ├── @mariozechner/pi-agent-core     ← agent loop engine
    │   └── @mariozechner/pi-ai         ← LLM API adapter layer
    ├── @mariozechner/pi-coding-agent   ← SessionManager and other facilities
    └── @mariozechner/pi-tui            ← terminal UI components
```

`pi-agent-core` defines the core abstractions of the Agent runtime:

* **Session**—a persistent container for conversation history, stored as JSONL files
* **Tool**—external capabilities that Agent can invoke, defined using JSON Schema
* **Provider**—a unified interface for LLM APIs, supporting both streaming and non-streaming calls
* **Extension**—hooks to inject custom logic at specific stages of the conversation loop

OpenClaw does not directly use the high-level APIs of these packages. Instead, it deeply integrates them through an **embedded mode**, building its own runtime wrapper layer in the `src/agents/` directory.

## 15.1.2 RPC Mode vs Embedded Mode

Pi Agent supports two operating modes:

### RPC Mode (External Process)

In RPC mode, Pi Agent runs as an independent child process. Gateway communicates with it through standard input/output (stdin/stdout) or HTTP:

```
Gateway Process                 Pi Agent Child Process
    │                               │
    │── RPC Request (JSON) ────────→│
    │                               │── Call LLM API
    │                               │← Streaming Response
    │←── RPC Response (JSON) ──────│
```

The advantage of this mode is process isolation—if Agent crashes, it won't affect Gateway. However, the disadvantage is the overhead of inter-process communication, and the inability to directly share in-memory state.

### Embedded Mode (Same Process)

In embedded mode, Pi Agent code runs directly within the Gateway process. This is OpenClaw's current default mode:

```
Gateway Process
    │
    ├── WebSocket Server
    ├── HTTP Server
    ├── Channel Adapters
    └── Pi Agent Runtime (Embedded)
        ├── Conversation Loop
        ├── Tool Execution
        └── LLM API Calls
```

Advantages of embedded mode:

* **Zero serialization overhead**—function calls instead of JSON-RPC
* **Shared state**—can directly access Gateway's configuration, session storage, and event system
* **Lower latency**—no inter-process communication needed
* **Simplified deployment**—single process, single binary

In OpenClaw's source code, the `isCliProvider` function determines whether a provider needs to run as an independent CLI process (RPC mode):

```typescript
// src/agents/model-selection.ts
export function isCliProvider(provider: string, cfg?: OpenClawConfig): boolean {
  // Determines if provider needs CLI running mode (e.g., claude-cli or codex)
  const normalized = normalizeProviderId(provider);
  if (normalized === "claude-cli") {
    return true;
  }
  if (normalized === "codex-cli") {
    return true;
  }
  const backends = cfg?.agents?.defaults?.cliBackends ?? {};
  return Object.keys(backends).some((key) => normalizeProviderId(key) === normalized);
}
```

Most providers (Anthropic, OpenAI, Google, etc.) use embedded mode, with only a few special providers (like Claude CLI, Codex) using RPC mode.

## 15.1.3 Agent Entry File Hierarchy

OpenClaw's Agent entry files adopt a **layered structure**, from high-level to low-level:

```
src/agents/pi-embedded.ts           ← Public API exports (types + function re-exports)
    └── pi-embedded-runner.ts       ← Module aggregation layer (re-exports all submodules)
        ├── run.ts                  ← Core run function runEmbeddedPiAgent()
        ├── runs.ts                 ← Active run management (register/query/abort)
        ├── lanes.ts                ← Lane resolution
        ├── model.ts                ← Model resolution
        ├── compact.ts              ← Session compaction
        ├── system-prompt.ts        ← System prompt override
        ├── tool-split.ts           ← Tool splitting
        └── types.ts                ← Type definitions
```

**Layer 1: `pi-embedded.ts`**—a pure re-export file providing a stable public API:

```typescript
// src/agents/pi-embedded.ts
export type {
  EmbeddedPiAgentMeta,
  EmbeddedPiCompactResult,
  EmbeddedPiRunMeta,
  EmbeddedPiRunResult,
} from "./pi-embedded-runner.js";
export {
  abortEmbeddedPiRun,
  compactEmbeddedPiSession,
  isEmbeddedPiRunActive,
  isEmbeddedPiRunStreaming,
  queueEmbeddedPiMessage,
  resolveEmbeddedSessionLane,
  runEmbeddedPiAgent,
  waitForEmbeddedPiRunEnd,
} from "./pi-embedded-runner.js";
```

**Layer 2: `pi-embedded-runner.ts`**—aggregation layer, unifying implementations scattered across subdirectories:

```typescript
// src/agents/pi-embedded-runner.ts
export { runEmbeddedPiAgent } from "./pi-embedded-runner/run.js";
export {
  abortEmbeddedPiRun,
  isEmbeddedPiRunActive,
  isEmbeddedPiRunStreaming,
  queueEmbeddedPiMessage,
  waitForEmbeddedPiRunEnd,
} from "./pi-embedded-runner/runs.js";
export { resolveEmbeddedSessionLane } from "./pi-embedded-runner/lanes.js";
// ...
```

**Layer 3: `pi-embedded-runner/` subdirectory**—where actual implementations reside. The most critical is `run.ts`, which contains the `runEmbeddedPiAgent` function—the entry point of the entire Agent loop.

### Core Type Definitions

Agent run inputs and outputs are defined by the following types:

```typescript
// src/agents/pi-embedded-runner/types.ts
export type EmbeddedPiRunResult = {
  payloads?: Array<{
    text?: string;         // Reply text
    mediaUrl?: string;     // Media URL
    isError?: boolean;     // Whether error message
  }>;
  meta: EmbeddedPiRunMeta; // Run metadata
  didSendViaMessagingTool?: boolean; // Whether sent directly via messaging tool
};

export type EmbeddedPiRunMeta = {
  durationMs: number;           // Run duration (milliseconds)
  agentMeta?: EmbeddedPiAgentMeta; // Agent metadata
  aborted?: boolean;            // Whether aborted
  systemPromptReport?: SessionSystemPromptReport; // System prompt report
  error?: {                     // Error information
    kind: "context_overflow" | "compaction_failure" | "role_ordering" | "image_size";
    message: string;
  };
};

export type EmbeddedPiAgentMeta = {
  sessionId: string;    // Session ID
  provider: string;     // Provider (e.g., "anthropic")
  model: string;        // Model ID (e.g., "claude-sonnet-4-20250514")
  usage?: {             // Token usage statistics
    input?: number;
    output?: number;
    cacheRead?: number;
    cacheWrite?: number;
    total?: number;
  };
};
```

These types embody OpenClaw's complete modeling of Agent run results—not only containing reply text, but also execution duration, token usage, whether aborted, whether errored, and other metadata, providing necessary data for upper-layer usage statistics and error recovery.

***

## Summary of This Section

1. **Pi Agent** is OpenClaw's AI conversation engine, built on **four** pi-mono packages under `@mariozechner/` (`pi-agent-core` / `pi-ai` / `pi-coding-agent` / `pi-tui`, pinned at `0.57.1`); **session management, tool wiring, model discovery, and credential rotation are owned by OpenClaw**.
2. Agent execution supports **RPC mode** (independent child process) and **embedded mode** (same process), with OpenClaw defaulting to embedded mode for zero serialization overhead and shared state advantages.
3. Agent entry code adopts a **three-layer structure**: public API export layer → module aggregation layer → subdirectory implementation layer, with the core function being `runEmbeddedPiAgent()`.
4. The `EmbeddedPiRunResult` type completely models all outputs of Agent execution, including reply content, metadata, error information, and usage statistics.
