Skip to content

pi-mono Deep Dive Series: From Zero to Understanding This Minimal Coding Agent's Complete Architecture

Aug 31, 20261 min
TL;DRThis 17-part series takes you from CLI user perspective through pi-mono's Agent Loop, Session Tree, Tool System, Extension System, TUI Architecture, Remote Session, Telemetry, Compaction, and Release process. Ideal for developers wanting to self-host agents, research agent architecture, or contribute to pi.

🌏 中文版

TL;DR

  • Project: pi-mono → renamed to earendil-works/pi, npm scope @earendil-works
  • Core: 7-package monorepo, "minimal core + infinite extensibility"
  • Positioning: Not a batteries-included agent, but primitives for developers to "build their own"
  • Series: 17 parts, from CLI usage → architecture overview → Agent Loop → Session/Compaction → Tools → Extensions → TUI → Remote/Telemetry/Release
  • Prerequisites: TypeScript basics, CLI familiarity, basic LLM concepts; no Rust, C++, or distributed systems experience needed

Who This Series Is For

Reader PersonaWhat You'll Get
Engineers wanting to self-host/customize coding agentsComplete architecture map, directly applicable design patterns
Researchers/students studying AI Agent architectureLayer-by-layer teardown of production-grade code with design rationale
Developers wanting to contribute to pi / build ExtensionsComplete Extension API mechanics, hook points, best practices
Curious how "minimalism" works in engineeringHow 4 tools support full coding workflow, why no MCP/Sub-agents

Not for: Users wanting "batteries-included, most features out of the box" → use Claude Code, Codex CLI, OpenCode, or oh-my-pi directly.


Project Overview: 7 Core Packages

pi-mono (earendil-works/pi)
├── packages/ai              # pi-ai: Unified multi-provider LLM API
├── packages/agent           # pi-agent-core: Agent Runtime + Loop + Harness
├── packages/coding-agent    # pi-coding-agent: CLI Entry + Session + SDK
├── packages/tui             # pi-tui: Terminal UI Library (Differential Rendering)
├── packages/telemetry       # pi-telemetry: Vendor-neutral Telemetry Contracts
├── packages/client          # pi-client: Remote Session Client
├── packages/server          # pi-server: Remote Session Server
├── packages/protocol        # pi-protocol: JSON-RPC/WebSocket Protocol
└── packages/session-backends/*  # Session Storage Backends

Package Dependencies (Simplified)

pi-tui (zero deps)
    ↑
pi-telemetry (zero deps)
    ↑
pi-ai ─────────────────────→ 15+ providers (OpenAI, Anthropic, Google, Azure, Bedrock, Mistral, Groq, Cerebras, xAI, HF, Ollama, OpenRouter...)
    ↑
pi-agent-core ←────────────── pi-telemetry, pi-ai
    ↑
pi-coding-agent ←──────────── pi-agent-core, pi-ai, pi-tui, pi-telemetry
    ↑                    ↑
pi-client ──────────────→ pi-protocol ←────────── pi-server
    ↑
session-backends/sqlite-node

Key Design Decisions at a Glance

DecisionContentRationale
LanguageTypeScript (ESM, Node ≥ 22.19)Type safety, rich ecosystem, shared types across frontend/backend
Monorepo Toolnpm workspaces + hand-written build orderFull control, zero config deps, auditable supply chain
VersioningLockstep versioning (all packages same version)Avoids diamond deps, single version publish
Dependency LockingExact versions + npm-shrinkwrap.json + min-release-age=2Supply-chain hardening, reproducible builds
TestingVitest (unit) + Faux Provider (e2e no API keys) + Browser smokeFast CI, no external deps, runnable locally
Code QualityBiome (lint/format) + tsgo (type check) + pinned deps checkSingle toolchain, blazing fast, no compromise
ReleaseLocal smoke → release:patch/minor → CI trusted publishing → R2 markerZero manual intervention, npm OIDC, verifiable on publish

Core Abstraction Layers (Outside-In)

┌─────────────────────────────────────────────────────────────┐
│ User Interface Layer                                         │
│  ├── CLI (Interactive / Print / JSON / RPC / SDK)           │
│  ├── TUI Components (Markdown, Editor, Selector, Diff...)   │
│  └── Extension UI (Widgets, Dialogs, Custom Renderers)      │
├─────────────────────────────────────────────────────────────┤
│ Application Logic Layer                                      │
│  ├── Session Manager (Tree, Branching, Compaction, Fork)    │
│  ├── Model Registry / Resolver / Runtime (15+ providers)    │
│  ├── Extension Runtime (Hooks, Tools, Commands, Keys, UI)   │
│  └── Settings / Trust / Package Manager                     │
├─────────────────────────────────────────────────────────────┤
│ Agent Core Layer                                             │
│  ├── Agent Loop (Double While: Inner tool calls, Outer follow-up) │
│  ├── Harness (System Prompt, Skills, Compaction, Branch Summary) │
│  ├── Tool Execution (Parallel/Sequential, Before/After Hooks)    │
│  └── Telemetry (Schema-defined, Vendor-neutral)                │
├─────────────────────────────────────────────────────────────┤
│ LLM Integration Layer                                        │
│  ├── Unified API (Messages, Tools, Streaming, Thinking)     │
│  ├── Provider Factories (Lazy-loaded, Tree-shakable)        │
│  ├── Model Catalog (Auto-generated, Versioned)              │
│  └── Auth (API Key, OAuth, Credential Store, Sync)          │
├─────────────────────────────────────────────────────────────┤
│ Infrastructure Layer                                         │
│  ├── TUI Engine (Virtual DOM Diff, CSI 2026, Kitty Images)  │
│  ├── Session Storage (JSONL, Append-only, Tree Index)       │
│  ├── Protocol (JSON-RPC 2.0, WebSocket, Reconnection)       │
│  └── Telemetry Contracts (Schema, Conformance Tests)        │
└─────────────────────────────────────────────────────────────┘

Series Reading Map (17 Parts)

OrderTitleFocus QuestionStatusEst. Length
0Series Overview & Project Tour (this post)What is this project? How to read the series?✅ Published—
1pi from a CLI User's PerspectiveHow to install/use? 4 modes? How sessions persist?🔄 Writing~2500 words
2Monorepo Architecture & Core AbstractionsHow do 7 packages divide work? Why one-way deps?⏳ Planned~3000 words
3pi-ai: Unified Multi-Provider LLM API15+ providers under one interface? Lazy loading? Unified streaming?⏳ Planned~3500 words
4Agent Loop: Double-Loop & Event FlowWhy double while? Steering vs Follow-up? Interrupt handling?⏳ Planned~4000 words
5Session Tree: Append-only, Branching, CompactionTree storage? Branching without history mutation? Compaction triggers?⏳ Planned~3500 words
6Tool System: Definition, Execution, Parallel/Sequential, HooksTool definition shape? Before/After hook interception?⏳ Planned~3000 words
7Extension System: Hooks, Custom Tools, UI Components, LifecycleWhat can extensions do? How loaded? How access TUI?⏳ Planned~4000 words
8TUI Architecture: Differential Rendering, Component Tree, Layout EngineFlicker-free how? Virtual DOM Diff? What is CSI 2026?⏳ Planned~3500 words
9Model Catalog, Provider Factory, OAuth & Credential SyncModel data generation? Provider lazy loading? OAuth flow?⏳ Planned~3000 words
10Remote Session: Client/Server, Protocol, RPC, WebSocketRemote session sync? JSON-RPC definition? Reconnection?⏳ Planned~3000 words
11Telemetry: Vendor-neutral Contracts, Schema, ConformanceWhy not OpenTelemetry? Schema definition? Conformance tests?⏳ Planned~2500 words
12Compaction Deep Dive: Strategy, Token Estimation, Branch Summary, Structured CompactionToken estimation? Cut point finding? Extension customization?⏳ Planned~3500 words
13Agent Harness, Skills, System Prompt AssemblySystem prompt composition? Skills loading? Prompt templates?⏳ Planned~2500 words
14Testing, Quality Gates, Supply-chain HardeningFaux provider? Browser smoke? Pinned deps? Shrinkwrap?⏳ Planned~3000 words
15Containerization, Sandbox, Permission ModelGondolin? Docker? OpenShell? Why no built-in permission?⏳ Planned~2500 words
16Release Process, Lockstep Versioning, Binary Build, Trusted PublishingSingle version publish? Binary build? npm OIDC flow?⏳ Planned~3000 words

Suggested Reading Orders

Beginner/User perspective: 0 → 1 → 2 → 3 → 4 → 5 → 6 → 7
Architect/Contributor perspective: 0 → 2 → 4 → 5 → 6 → 7 → 8 → 3 → 9 → 10 → 11 → 12 → 13 → 14 → 15 → 16
Topic-driven: Each part notes `Prerequisite: read order X first`, jump as needed

Cliff Handling: Bridging Cognitive Jumps

PositionCognitive JumpBridge Strategy
1→2From "how to use" to "why architected this way"Part 1 ends with "Architecture Preview", Part 2 opens by revisiting user pain points
3→4From LLM API to Agent LoopPart 3 ends showing streamFunction signature, Part 4 continues with how runLoop calls it
5→6From Session to ToolPart 5 mentions toolResult entering session, Part 6 starts from executeToolCalls
7→8From Extension API to TUI internalsPart 7 shows ExtensionUIDialogOptions, Part 8 dissects DialogComponent implementation
10→11From network protocol to TelemetryPart 10 ends mentioning telemetry binding, Part 11 explains why custom Schema
12→13From Compaction details to Harness assemblyPart 12 ends "Harness decides when to trigger", Part 13 continues with shouldCompact, prepareCompaction

TopicOn-Site Guide
LLM Basics, Token, Context WindowLLM Glossary
RAG / Embedding / Vector SearchComplete Guide to RAG System Patterns
AI Agent Architecture PatternsComplete Guide to AI Agent Architecture
MCP ProtocolMCP Protocol Complete Introduction
Cloudflare Workers / D1 / VectorizeCloudflare Workers Complete Introduction
TypeScript / ESM / tsgoTypeScript 7 Native Compiler
Differential Rendering / Virtual DOMLooplane TUI Architecture

How to Follow Along Hands-On

Each part ends with actionable steps:

# Example: Part 1 ending
# 1. Install and run
npm install -g @earendil-works/pi-coding-agent
pi --help

# 2. Run local model via Ollama
ollama pull qwen3:1.7b
pi -p "Say hello world in traditional Chinese" --model ollama:qwen3:1.7b

# 3. Inspect session file
cat ~/.pi/agent/sessions/--your-cwd--/latest.jsonl

Recommended setup:

  • Node.js ≥ 22.19
  • pi CLI installed (or ./pi-test.sh from source)
  • A Git repo project directory (for session, tools, git integration testing)
  • Optional: Ollama / API Keys (Anthropic, OpenAI, etc.)

References


Next Up

Part 1: pi from a CLI User's Perspective

Install, run, switch modes, persist sessions, view tree, export HTML, interject messages. Turn the "black box" into a "glass box" to build intuition for the architecture parts that follow.