Skip to content
Series
17 posts

pi-mono Deep Dive

A close reading of the pi-mono source: how it implements the agent loop, tool calls, approvals, and session management — one of the reference implementations in the mature-coding-agent-design comparison.

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

This 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.

pi-mono Deep Dive 1: pi from a CLI User's Perspective — Install, Modes, Session, Model Switch & Message Interjection

Treat pi as a black box first: 4 run modes, session tree persistence, mid-conversation model switching, Enter vs Alt+Enter message interjection, /tree branch navigation. Builds intuition for the architecture parts that follow.

pi-mono Deep Dive 2: Monorepo Architecture & Core Abstractions — How 7 Packages Divide Work & Why Dependencies Flow One Way

From user-visible features into architecture: 7 npm packages with clear boundaries, one-way dependency flow, why pi-tui/pi-telemetry have zero deps, how pi-ai encapsulates provider details, lockstep versioning avoiding diamond deps. Builds an 'outside-in' mental model.

pi-mono Deep Dive 3: pi-ai — Unifying 15+ LLM Providers, From Lazy Loading to Auto-Generated Model Catalog

pi-ai is pi-mono's anti-corruption layer: upper layers only see Message/Tool/Context/streamFunction; 15+ providers implement details underneath. This post dissects: unified interface design, Provider Factory Registry, Lazy Loading for tree-shaking, Model Catalog auto-generation, OAuth/API Key unification, Credential Sync, Thinking/Reasoning parameter standardization.

pi-mono Deep Dive 4: Agent Loop — Double-Loop & Event Flow, From Steering to Follow-up Complete Timeline

Heart of pi-agent-core: agentLoop() → runLoop() double while(true). Inner loop handles tool calls + steering messages; Outer loop handles follow-up + prepareNextTurn (compaction, model switch). Enter = steering (inject after current tool), Alt+Enter = follow-up (inject after agent stops). streamAssistantResponse() partial message updates, tool call parsing, parallel/sequential execution, before/after hooks.

pi-mono Deep Dive 5: Session Tree — Append-only JSONL, Branching Without History Mutation, Compaction Logic Full Analysis

SessionManager core: JSONL append-only storage, id/parentId tree formation, branch() moves leaf pointer without mutating history, buildSessionContext() handles compaction entries, createBranchedSession() forks to new file. Complete Entry types: message, thinking_level_change, model_change, compaction, branch_summary, custom, custom_message, label, session_info. Migration v1→v2→v3 details.

pi-mono Deep Dive 6: Tool System — 8 Core Tools, Factory Pattern, Parallel/Sequential Execution, Before/After Hooks Interception

Complete analysis of pi-coding-agent's 8 core tools: ToolDefinition (for LLM) vs AgentTool (execution logic), createToolDefinition/createTool Factory, executionMode determines parallel/sequential, beforeToolCall/afterToolCall interception chain, withFileMutationQueue serializes file writes, truncateHead/Line/Tail output truncation, read/write/edit/bash/grep/find/ls/powershell implementation details.

pi-mono Deep Dive 7: Extension System — Hooks, Custom Tools, UI Components, Lifecycle Complete Mechanism

Complete Extension system analysis: Extension interface definition, onLoad/onUnload lifecycle, four major Hooks (onAgentStart/onBeforeToolCall/onAfterToolCall/onTurnEnd), five extension points (tools/commands/keybindings/ui/settings), ExtensionRunner load order and dependency resolution, ExtensionAPI capabilities, Dynamic Border, Widget, Dialog, Selector UI components, Extension inter-communication, hot reload mechanism, official example Extensions.

pi-mono Deep Dive 8: TUI Architecture — Differential Rendering, Component Tree, Layout Engine, CSI 2026 Synchronized Output

Complete pi-tui core analysis: Virtual DOM Diff for flicker-free rendering, Component lifecycle, Layout Engine (Flex-like), CSI 2026 Synchronized Output avoiding partial frame tearing, Keybindings Manager, Alt Screen, Bracketed Paste, Kitty/iTerm2 Image Protocol, built-in components (Markdown, Editor, Selector, Diff, Border, Loader, etc.).

pi-mono Deep Dive 9: Model Catalog, Provider Factory, OAuth & Credential Sync — From Auto-Generation to Cross-Device Sync

pi-ai Model Catalog auto-generation flow, Provider Factory registration with Lazy Loading, OAuth 2.0 + PKCE flow implementation, Credential Store (Keychain/Libsecret/Credential Manager/Encrypted File Fallback), Credential Sync cross-device sync mechanism, Model Scope Diagnostics, ModelResolver parsing logic, CredentialSynchronizationOperation state machine.

pi-mono Deep Dive 10: Remote Session — Client/Server, JSON-RPC 2.0, WebSocket, Reconnection

pi-protocol JSON-RPC 2.0 Definition, pi-client Connection Management & Exponential Backoff Reconnection, pi-server Session Registry, WebSocket Transport, Heartbeat Mechanism, Session Snapshot, Remote Session Handle, RPC Mode Architecture, Streaming Event Transport, Remote Steering/Follow-up Message Interjection.

pi-mono Deep Dive 11: Telemetry — Vendor-neutral Contracts, Schema Definition, Conformance Tests

pi-telemetry Core: TelemetrySchema Defines Span/Event/Attribute, defineTelemetrySchema Creates TypedSpanStarter, InMemoryTelemetryContext/NOOP_TELEMETRY_CONTEXT Zero-overhead Implementations, Conformance Tests Verify Adapter Correctness, AI/Harness Telemetry Schema Complete Definitions, Attribute Type System, Why Not Use OpenTelemetry Directly.

pi-mono Deep Dive 12: Compaction Deep Dive — Strategy, Token Estimation, Branch Summary, Structured Compaction

Complete Compaction Mechanism: shouldCompact Trigger Conditions (Token Ratio, Message Count), estimateTokens Calculation (Char/Word Approximation), findCutPoint Finding Cut Point (Retain Recent N Turns), generateSummary Generating Summary (LLM Call), prepareCompaction Preparing Context, Branch Summary Generation, Structured Compaction (Extension Custom via fromHook), CompactionEntry Details, fromHook Mechanism, Compaction Settings.

pi-mono Deep Dive 13: Agent Harness, Skills, System Prompt Assembly — Building Agent Behavior from Scratch

AgentHarness Core Class, System Prompt Dynamic Assembly Flow, Skills Loading & Formatting, Prompt Templates System, How Harness Decides Tool Availability, Result Handling, Telemetry Schema Registration, Default Harness Construction, Extension Harness Extension.

pi-mono Deep Dive 14: Testing, Quality Gates, Supply-chain Hardening — Faux Provider, Browser Smoke, Biome, tsgo, Shrinkwrap, Trusted Publishing

Testing strategy: Faux Provider (no API key e2e), Vitest unit, Browser Smoke (real browser), Biome lint/format, tsgo type check, Pinned Deps, Shrinkwrap, Install Lock, npm Trusted Publishing, CI pipeline.

pi-mono Deep Dive 15: Containerization, Sandbox, Permission Model — Gondolin, Docker, OpenShell, Security Boundaries

Why Pi has no built-in permission system, Gondolin Extension (micro-VM), Docker mode, OpenShell policy-controlled sandbox, permission model philosophy, three containerization patterns, security boundary comparison, micro-VM vs container vs process isolation.

pi-mono Deep Dive 16: Release Pipeline — Lockstep Versioning, Binary Build, Trusted Publishing From Code to npm

Full release flow: Lockstep versioning (all packages same version), CHANGELOG, local smoke, release script, Bun+Node binary build, npm-shrinkwrap, GitHub Actions OIDC trusted publishing, R2 release marker, pi.dev/api/latest-version, announcement verification.