ππ Agent
Based on pi source · 21 interactive chapters

Deep Dive
Pi Agent

|
These 21 chapters take you from the core agent loop to the full engineering picture — based on real source analysis.

SOURCE CODE WALKTHROUGH

Core Agent Loop

Every AI Agent is essentially a loop. pi's core lives in packages/agent/src/agent.ts (577 lines) and agent-loop.ts (792 lines). Click each step to see the corresponding source and implementation details.

Tool results feed back, loop continues
1

User Input

Call Agent.prompt(), push the user message into messages[]

// packages/agent/src/agent.ts
const agent = new Agent({ model, tools, systemPrompt })
const sub = agent.subscribe((e) => render(e))
await agent.prompt("Fix the bug in auth.ts")
// ↑ user message pushed into state.messages
WHY DEEP DIVE

From 30 Lines to 920 Files

A teaching Agent's core loop is just ~30 lines, but how much engineering does production pi stack on top of the same loop?

Teaching~30 lines TypeScript
// A complete Agent core
const agent = new Agent()
while (true) {
r = await provider.stream(msgs)
if (r.stop !== "tool_use") break
msgs.push(await runTool(r.tool))
}
Synchronous API calls
Single provider
No session persistence
No compaction
Crash = data loss
No extensions
Production piSame loop + 21 layers of engineering
Ch09
Lazy Stream + Retry
lazyStream async-loads SDKs, RetryPolicy exponential backoff
Ch06
Provider Abstraction
Models route to ~40 providers, header priority chain
Ch08
7+ OAuth Flows
Anthropic/Copilot/Codex/OpenRouter/xAI/Kimi …
Ch04
Durable Session Tree
JSONL append-only, in-place branching without copying files
Ch03
Auto + Branch Compaction
findCutPoint, file tracking, branch summarization
Ch13
Extension System
~40 lifecycle events, jiti + VIRTUAL_MODULES
Ch16
6,046-line TUI
steer/follow-up queues, dialogs, hot-reload themes
Ch21
Supply-Chain Hardening
lockstep releases, shrinkwrap allowlist, --ignore-scripts
ARCHITECTURE LAYERS

Five Architecture Layers

pi's ~920 TypeScript files organized into five architecture layers. Click to expand and see core files, design patterns, and corresponding chapters.

L1
Engine Core
5 chapters in depth
L2
Unified LLM API
4 chapters in depth
L3
Coding-Agent & Extensibility
6 chapters in depth
L4
Surfaces & UI
3 chapters in depth
L5
Backend & Engineering
3 chapters in depth
DISTINCTIVE DESIGN

8 Distinctive Design Choices in pi

pi's unusual engineering tradeoffs: minimal core + self-extension, Result types, durable session tree, lazy SDKs, supply-chain hardening — each maps to a specific chapter.

KEY SOURCE FILES

Key Source Files

Understanding these key files gives you a grasp of the entire system. File size reflects engineering complexity.

LEARNING PATH

21 Chapters of Source Deep Dive

Each chapter focuses on a core subsystem with source analysis + architecture visualization + runnable demos. Filter by layer, or follow the sequence.

Ch01

Agent Loop

Heart of the conversation loop

Every Agent is a loop: stream model → execute tool → feed back

~50KBNeeds API Key
Ch02

AgentHarness & Durable Session

Above the loop: orchestration & durability

Result<T,E> never throws — turn snapshot vs harness config

~76KBDirectly runnable
Ch03

Compaction & Branch Summarization

Infinite work in a finite window

Context always fills up — the cut-point decides what survives

~60KBDirectly runnable
Ch04

Session JSONL Tree

A session is a durable tree, not a log

Branch in place — never copy a file

~53KBDirectly runnable
Ch05

Built-in Tools

Four default tools; the rest is extension territory

Operations interfaces behind every tool; mutations serialized

~40KBDirectly runnable
Ch06

Models & Provider Abstraction

One stream interface, 40 providers

Models route to their Provider; header merge has a priority chain

~60KBDirectly runnable
Ch07

Wire Protocols & Lazy SDKs

Each API speaks its own dialect

lazyStream wraps async auth+SDK loading behind a synchronous stream

~160KBDirectly runnable
Ch08

Auth & OAuth

Provider-owned credentials & OAuth flows

Stored credential beats env; failed refresh never silently falls back

~85KBDirectly runnable
Ch09

Streaming, Partial JSON & Retries

Tolerant streams & constrained sampling

Errors are events, never thrown: stopReason 'error'/'aborted'

~50KBDirectly runnable
Ch10

CLI Modes & Dispatch

From bin entry to interactive/print/rpc/json modes

main.ts dispatches the Mode; project trust gates before the prompt

~62KBDirectly runnable
Ch11

AgentSession Orchestration

The harness pi actually uses

Event subscription + session persistence + model management in one

111KBNeeds API Key
Ch12

System Prompt, Skills & Context Files

The system prompt is an assembly pipeline

AGENTS.md walks up from cwd; skills follow agentskills.io

~62KBDirectly runnable
Ch13

The Extension System

Self-extensibility: one loader powers built-ins & users

~40 lifecycle events; jiti + VIRTUAL_MODULES for the Bun binary

~135KBDirectly runnable
Ch14

Model Runtime, Provider Composition

Builtin catalog + extension providers

composeModelProvider merges extension providers with built-ins

~60KBDirectly runnable
Ch15

Pi Packages & Model Catalog

pi install/update/list over npm: & git:

min-release-age=2, exact pins, --ignore-scripts; never edit models.generated.ts

~115KBDirectly runnable
Ch16

Interactive TUI

Six thousand lines to make the loop feel instant

Enter→steer, Alt+Enter→follow-up; dialogs, themes, footer telemetry

205KBDirectly runnable
Ch17

The pi-tui Engine

Differential rendering with zero dependencies

Synchronized output for atomic frames; paste markers survive as atomic graphemes

~190KBDirectly runnable
Ch18

Settings, Trust, Telemetry & Output Guard

Project trust gate & TUI output integrity

output-guard owns stdout so the model never corrupts the TUI

~80KBDirectly runnable
Ch19

RPC Mode & pi-server

Beyond the terminal: JSONL RPC & a supervisor daemon

One pi --mode rpc child per instance; length-delimited IPC over a Unix socket

~66KBDirectly runnable
Ch20

SQL Session Backend

JSONL tree, but queryable

WAL + busy_timeout + FULL sync for concurrent agent processes

~50KBDirectly runnable
Ch21

Evals & Supply-Chain Hardening

Behavioral evals & a hardened monorepo

Lockstep versioning; never edit models.generated.ts; lgtm gates

~30KB+Needs API Key