@indie_maker_fox: Recommending a very worthwhile Pi Agent eBook https://dgzhuya.com/modules/ch01-overview… As everyone knows, I really like Pi agent, with its minimalist design and rich extensions. I also really like Craft agent…

X AI KOLs Timeline News

Summary

The author recommends the Pi Agent eBook and the Learn Claude Code tutorial, analyzing Pi Agent's minimalist design, four-layer architecture, and core principles, and mentions MkAgent, which they developed based on it.

Recommending a very worthwhile Pi Agent eBook https://dgzhuya.com/modules/ch01-overview… As everyone knows, I really like Pi agent, with its minimalist design and rich extensions. I also really like Craft agent and have recommended it many times, thanks to its excellent architecture and rich features. I've also built MkAgent based on them, which you can think of as a desktop version of Pi agent, or a Lite version of Craft agent. I'll release it in a few days once I'm free. For those who want to understand how agents work internally, I still recommend the Learn Claude Code tutorial I shared earlier. It's the most beginner-friendly material, with each chapter including only a small amount of Python code. For those who want to understand the internals of Pi agent, I recommend reading this eBook tutorial. It has 10 chapters, with source code analysis from the agent loop to context engineering, capturing the essence. To be honest, I've read a lot of Pi agent's code myself and wanted to write a tutorial, but I simply don't have much free time. I stumbled upon this book by chance and agree with its structure and explanations. The author's understanding surpasses mine in many ways, so I feel there's no need for me to write a Pi agent tutorial anymore. In short, I highly recommend these two tutorials. If you read them step by step and master the core basics, everything else will seem simple to implement. Nowadays, custom agent development has already become a core business within enterprises, and understanding agent internals can be considered the programming foundation for future programmers.
Original Article
View Cached Full Text

Cached at: 08/11/26, 03:40 AM

I’d like to recommend a highly worthwhile Pi Agent e-book: https://dgzhuya.com/modules/ch01-overview… As you all know, I really like Pi agent—minimalist design, rich extensibility. I also really like Craft agent and have recommended it multiple times—excellent architecture, rich features. I’ve also built MkAgent based on them, which you can think of as a desktop version of Pi agent, or a Lite version of Craft agent. I’ll publish it once I’m free in a few days. For those who want to understand the internal principles of agents, I still recommend the Learn Claude Code tutorial I shared before—the most beginner-friendly material, with each chapter containing only a small amount of Python code. For those who want to understand the internal principles of Pi agent, I recommend reading this e-book tutorial from today. It has 10 chapters, covering everything from the agent loop to context engineering with source code analysis—grasping the essence. Honestly, I’ve read quite a bit of Pi agent’s code myself and wanted to write a tutorial too, but I just don’t have much free time. I stumbled upon this book and found myself in strong agreement with its structure and explanations. The author’s understanding surpasses mine in many places, so I feel there’s no need for me to write a Pi agent tutorial anymore. In short, I highly recommend these 2 tutorials. Read through them progressively, and once you’ve mastered the core fundamentals, everything on top becomes simple to implement. Nowadays, customized agent development is already a core business within enterprises, and the internal principles of agents can be said to be the programming foundation for future programmers.


M01 · Chapter 1: Introduction — Why Pi-Agent Deserves Your Time

Source: https://www.dgzhuya.com/modules/ch01-overview

This article is the opening chapter of “Pi-Agent Project Principles Explained.” It doesn’t go into source code details but answers a more fundamental question: What is Pi? Why does it deserve your time? After reading this, you’ll have a clear overall understanding of Pi’s three identities—coding tool, learning material, development SDK.


1. Opening: Three Questions, One Answer

You might have clicked on this series for three different reasons:

  1. “I want a good coding Agent” — You’re tired of bloated tools and want something minimalist, transparent, and fast
  2. “I want to know how Agents actually work” — You’ve looked through some Agent framework source code, and it’s either too complex (tens of thousands of lines to start) or too simplistic (a while loop that dares to call itself an Agent)
  3. “I want to build my own Agent” — You have vertical scenario needs, requiring secondary development based on an SDK, and don’t want to reinvent the wheel from scratch

These three questions happen to correspond to Pi’s three identities. And the fact that these three identities all point to the same project is itself worth being curious about.

Before diving into the source code, let’s step back and look at Pi as a whole.


One-Sentence Definition

Pi is a minimalist, extensible terminal coding agent harness created by libGDX author Mario Zechner, written entirely in TypeScript, open-sourced under the MIT license.

Breaking it down:

  • “Coding agent” — It can read your codebase, write code, modify code, and run commands, like a pair-programming partner sitting next to you
  • “Terminal harness” — It lives in the terminal, with no GUI, no IDE plugins, writing output to the terminal scrollback buffer. This determines all of its subsequent design choices
  • “Minimalist” — Core has four built-in tools (read / write / edit / bash), a static system prompt template of ~90 words (English words, not tokens; typically 200–400 words at runtime after concatenating tools/skills/contextFiles), and ~12,000 lines of TUI code (the core tui.ts single file is ~1,700 lines). It deliberately does not build in MCP, sub-agents, plan mode, permission popups, or background bash
  • “Extensible” — Missing features on top of the minimalist core are supplemented through TypeScript extensions, skills, and Pi Packages

Key Numbers

MetricValueMeaning
GitHub Stars64,000+Ten months of growth; the community validated the demand
Built-in Tools4 core + 3 auxiliaryCore: read / write / edit / bash; Auxiliary: grep / find / ls
System PromptStatic template ~90 words (English words, 200–400 at runtime)Compared to Claude Code’s tens of thousands of characters
TUI Code Volume~12,000 linesCore tui.ts single file ~1,700 lines; the “restraint” brought by Mario’s game engine background
Supported Providers30+Source KnownProvider enum has 35 actual entries (including regional variants), ~27 independent brands; Anthropic, OpenAI, Google, Groq, Ollama, etc.
Core Package Count4pi-ai / pi-agent-core / pi-tui / pi-coding-agent
Operation Modes4Interactive / print-JSON / RPC / SDK

Note on numbers: Pi’s early marketing materials often mentioned “4 built-in tools,” “15+ providers,” and “~600 lines of TUI” — the first two refer to the 4 core tools (excluding the grep/find/ls auxiliary tools) and the well-known vendors listed in early versions; “600 lines of TUI” was the number from an early version, and v0.80.2 has actually grown to ~12,000 lines. This table presents actual numbers from the v0.80.2 source code to avoid confusion when readers compare against the source.

Four Core Packages, Each With Its Own Role

┌──────────────────────────────────────────┐
│ pi-coding-agent                          │ ← Complete CLI product + SDK
│ System prompt · Built-in tools · Session │
│ management · Extensions                  │
├──────────────────────────────────────────┤
│ pi-tui            │ pi-agent-core        │ ← Terminal UI + Agent engine
│ Diff rendering    │ AgentLoop · Tools    │
│ Component system  │ System · Event stream│
├───────────────────┴──────────────────────┤
│ pi-ai                                     │ ← Multi-provider LLM abstraction
│ Unified API · Context handoff · Streaming │
│ · Token tracking                          │
└───────────────────────────────────────────┘

Among these four layers, pi-ai / pi-agent-core / pi-coding-agent form a three-layer stack (each layer can be used independently), and pi-tui is an orthogonal UI library fully decoupled from the Agent system — you can use only pi-ai to call models, or use pi-agent-core to run an Agent Loop in your own application without ever touching the CLI. This is the core value of Pi as an SDK, which we’ll cover in detail in Section 5.

Pi-Agent Four-Layer Architecture

Caption: Layered dependency diagram of the four core packages. coding-agent is at the top (product + SDK), agent-core is in the middle (engine), pi-ai is at the bottom (model abstraction), and pi-tui is a parallel UI layer that doesn’t depend on any AI package. The bottom shows the four operation modes.

There’s also an experimental pi-orchestrator (new in v0.80.x) on the periphery, responsible for multi-Agent orchestration. It’s not on the core learning path.


3. Perspective 1: As a Coding Agent — A Great Everyday Tool

3.1 What Pi Is: Building Blocks, Not a Finished Vehicle

Let me first clarify Pi’s position in one sentence: Pi is not another Cursor or Claude Code — it’s a box of building blocks that lets you assemble your own CodingAgent the way you want.

An analogy. Cursor is like a fully assembled car — seats, air conditioning, and navigation are all installed; you sit in and drive. Claude Code is also a fully assembled car, just with a racing engine and upgraded suspension. Pi is different — it gives you the engine, chassis, steering column, and electrical system, plus a guarantee that “we’ve verified this combination works.” It comes with a default configuration you can drive immediately (just press enter after pi), but its core value is: you can take this kit apart, reassemble it, add parts, reskin it, and build a car completely customized to your workflow.

This positioning is the source of all of Pi’s design decisions. Once you understand it, the following all make sense:

  • Why is the system prompt only ~1,000 tokens? Because “what to say” should be decided by you, not predetermined by the framework
  • Why only 4 built-in tools (read / write / edit / bash)? Because more built-in tools = more immutable constraints
  • Why no MCP / plan mode / sub-agents / todos? Because these are all “features on a finished vehicle” — Pi leaves them to you. Whatever mode you want, you build it with extensions

Community observer Pasquale articulated this distinction most sharply:

“Tools like Claude Code and Codex CLI optimize for ‘getting your first success as quickly as possible in a polished environment’… Pi shifts the priority to ‘ownership of the tool.’ It doesn’t give you a plan mode; it gives you the building blocks needed to construct a plan mode that behaves exactly as you wish.

This isn’t to say Pi “doesn’t work out of the box” — it absolutely does. Press enter after pi, and you’re talking to a capable coding Agent. But Pi’s “usability” isn’t essentially the result of adding features; it’s the result of doing subtraction and then leaving all the power of addition to you. A community observer called it “the world’s most steerable harness” — steerable not because it responds fast, but because you have veto power and modification rights over every one of its actions.

Suitability assessment: If you live in the terminal, are familiar with tmux and containers, and get irritated by every feature you can’t turn off — Pi is your tool. If you want zero-configuration out-of-the-box usability and a minimal setup to get running — choose Cursor or Claude Code. This isn’t a question of better or worse; it’s a question of fit with your working style.

3.2 Five Customization Levers: Everything Pi Doesn’t Have, You Can Build Yourself

Section 3.1 mentioned that Pi has no MCP, no plan mode, no sub-agents, no loop mode, no todos — you might ask: what if I want these “standard commercial Agent features”?

The answer is in Section 3.1’s phrase: “it doesn’t give you a plan mode; it gives you the building blocks needed to construct a plan mode.” Pi gives you five levers to shape it into whatever form you want — the first four are for your own use, and the fifth is for sharing your results with others. These five levers themselves are Pi’s true capability: a minimalist core + powerful levers, giving you “an Agent that can grow into any shape” rather than “an Agent whose shape was decided by its author.”

Extensions — the most underestimated and the most powerful lever

Extensions are TypeScript files that Pi auto-loads and supports hot reloading. Modify an extension file, and a running session takes effect immediately without restarting. This seems like a small thing, but it’s actually a killer feature — it spawned a unique play style: letting the coding Agent modify its own capabilities. Mario emphasized this specifically in his talks.

Extensions can touch deep things: tools, slash commands, keyboard shortcuts, event hooks, the entire TUI component tree — in other words, Pi doesn’t keep secrets; it exposes its innards to you.

The key point: all the “features Pi doesn’t have” listed in Section 3.1 can be implemented with extensions. The Pi repo includes 50+ official extension examples, and community observer Rushi analyzed:

“Those built-in capabilities you’d probably assume are default behavior — sub-agents, plan mode, permission gates, sandboxing, MCP integration, custom editors — can all be implemented as extensions and are provided as examples in the repo.”

Translating that into plain language: commercial Agents weld these features into the product; Pi unbolts them and turns them into optional modules. Want MCP? Install an MCP extension. Want sub-agents? There’s a ready-made extension that derives a new Pi instance. Want a loop mode (letting the Agent iterate on its own until the task is complete)? Write an extension that intercepts the turn_end event and triggers the next turn — Chapter 11 of this tutorial will walk you through writing one from scratch.

Even more powerful — if the official extensions don’t satisfy you, you can write one completely tailored to your needs. Mario described an example: someone wrote read, write, edit, and bash in five minutes, operating remote machines over SSH — completely replacing the built-in tools. If you want to add a permission approval popup to Pi (since it’s YOLO by default), about 50 lines of extension code suffice. If you want to fork a completely different UI (like running the Agent in a browser and redrawing the interface with React), that’s doable too. Pi’s capability grows linearly with your willingness to customize it.

Skills — on-demand capability packs

Skills are capability packs that package “instructions + tools,” using progressive disclosure — they only enter the context when invoked, not occupying a single token otherwise. This solves a core contradiction: you want a rich capability library, but you don’t want to pay the context tax for capabilities you don’t use in every session.

The relationship between skills and extensions can be understood this way: extensions give the Agent new capabilities (new tools, new commands, new modes); skills give the Agent new knowledge (“what to do when encountering task X”). The two can stack — an extension can register skills, and a skill can call tools provided by an extension.

Prompt Templates — reusable workflows

Reusable markdown templates for repetitive tasks, with parameter support. For example, if you do code review every day, you can write a template that codifies the “read diff, check style, give feedback” instructions. Load it with a single slash command when needed.

Themes — TUI skins with live reload

Graphical themes for the TUI. Switch them mid-session, taking effect immediately. This is the lightest of the levers, but important for long-term users — if you’re going to look at a tool all day, it needs to be easy on your eyes.

Pi Packages — package and distribute the four things above

Extensions, skills, templates, and themes can all be packaged into a Pi Package, installed from npm or git:

pi install npm:@foo/pi-tools
# Or directly from a git repo
pi install git:github.com/user/repo

This model is highly similar to the package managers developers use every day — this familiarity is one of the reasons it was quickly adopted. You write an extension, publish it to npm, and any Pi user worldwide can install it with one command. This expands the scope of “build it yourself” from “use it yourself” to “community sharing.”

Note: The specific syntax for extensions, skills, templates, themes, and Pi Packages will be covered in detail in later chapters of this tutorial. This section is just to establish the mindset that “Pi is malleable, and you can build whatever’s missing yourself.”

3.3 The Daily Benefits It Brings: The Default Configuration Is Already Great

Having covered “Pi is building blocks,” let’s return to the most practical question: after assembling this box of Pi building blocks with the default configuration, how does the experience compare as an everyday coding tool? The answer: surprisingly good.

Pi ranks second on the TerminalBench benchmark (an Agent evaluation with ~82 computer-use and programming tasks), trailing only Terminus when using Claude Opus 4.5 — despite having no MCP support, no sub-agents, no plan mode, no background bash, and no built-in todos. This result shows: the minimalist orientation didn’t sacrifice capability, and those “features on a finished vehicle” aren’t necessities for a capable Agent.

Here are a few benefits you can enjoy immediately with the default configuration:

Context cleanliness that’s the envy of others. This is Pi’s hardest-core differentiator. The system prompt + tool definitions total less than 1,000 tokens, compared to Claude Code’s tens of thousands of tokens. The context window is an Agent’s scarcest resource — the less fixed instructions occupy, the more space remains for your code and project context. Pi doesn’t secretly inject anything behind your back; all prompt source code is publicly visible, and you can even replace the entire system prompt with a SYSTEM.md file.

Transparent to the bone. You can see every message the model receives, the complete input/output of every tool call, complete cross-session cost tracking, and HTML/JSON export of sessions. Anyone who’s used other coding Agents has probably experienced: the Agent made a strange decision, you want to know why, but you can’t see what it “saw.” There’s no such black box in Pi.

Model freedom (30+ providers). Pi supports 35 KnownProviders (Anthropic, OpenAI, Google, Azure, Bedrock, Mistral, Groq, Cerebras, xAI, Hugging Face, Kimi, MiniMax, OpenRouter, Ollama, DeepSeek, Zhipu, Xiaomi, Together, Fireworks, etc., ~27 independent brands after deduplication). More importantly, you can switch models mid-session with /model or Ctrl+L. For example, use Claude for complex reasoning, then switch to MiniMax for simple text processing to save money. pi-ai handles cross-provider context handoff at the lower level (thought trajectory conversion, signature blob replay, etc.), which is lossy in nature but far better than “switching equals starting over.”

Tree-shaped sessions: fork when you go down the wrong path. Pi stores sessions as a tree structure (DAG, directed acyclic graph), not a linear log. /tree lets you jump to any historical message and fork a new branch from there to continue exploring. All branches live in the same file. Especially useful for debugging — you can try three different fixes from the same starting point without worrying about “not being able to go back.”

YOLO mode and the security philosophy. Pi is YOLO by default — the Agent executes actions directly without approval popups. Mario’s argument: approval-based security measures cause user fatigue (“popup fatigue”) and ultimately either get disabled entirely or degenerate into “security theater” where users mechanically click approve without looking. He recommends containerization as the security boundary. If you do need an approval flow, about 50 lines of extension code can implement it yourself — the framework provides all the hooks.

3.4 Getting Started in One Minute

curl -fsSL https://pi.dev/install.sh | sh
# Or
npm install -g --ignore-scripts @earendil-works/pi-coding-agent

Then run pi in any project directory. Set an ANTHROPIC_API_KEY environment variable, or use /login for authentication, and you’re ready to go.

3.5 Not Relying on Environment Variables: Defining Third-Party Models with models.json

The official tutorial defaults to setting ANTHROPIC_API_KEY, but in real projects you’ll most likely want to use domestic providers like Zhipu, DeepSeek, Kimi, Qwen, etc. These can’t possibly be handled with a single environment variable — you need to tell Pi: where the base URL is, which API protocol to use, what the model ID is called, and how large the context window is.

Pi’s solution is a local JSON configuration file: ~/.pi/agent/models.json (on Windows: C:\Users\<you>\.pi\agent\models.json). The file is auto-read at startup by ModelRegistry.create() (https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/core/model-registry.ts#L367), requiring no command-line arguments.

A real example:

{
  "providers": {
    "zhipu": {
      "baseUrl": "https://open.bigmodel.cn/api/paas/v4",
      "api": "openai-completions",
      "apiKey": "",
      "models": [
        { "id": "glm-4.5-air", "name": "GLM-4.5-Air" },
        { "id": "glm-4-flash", "name": "GLM-4-Flash" }
      ]
    },
    "deepseek": {
      "baseUrl": "https://api.deepseek.com",
      "api": "openai-completions",
      "apiKey": "",
      "models": [
        { "id": "deepseek-v4-flash", "name": "DeepSeek V4 Flash" },
        {
          "id": "deepseek-v4-pro",
          "name": "DeepSeek V4 Pro",
          "contextWindow": 1000000,
          "maxTokens": 384000
        }
      ]
    }
  }
}

Let’s break down a few key fields:

  • providers — The top level is a provider dictionary; the key names (zhipu/deepseek) are names you choose yourself, displayed as the model’s provider field
  • api — Choose the protocol. The most common are openai-completions (OpenAI-compatible interface, supported by almost all domestic vendors), anthropic-messages, and openai-responses. This field determines which request format Pi uses to call the API
  • baseUrl — The provider’s API endpoint
  • apiKey — Stored in plaintext. Be sure to add .pi/ to .gitignore, otherwise a single git add . will leak it
  • models — The model list under this provider. id is the real model name passed when calling the API; name is the friendly name displayed in the TUI
  • contextWindow/maxTokens — Optional; tells Pi the model’s window and maximum output length, affecting context compaction strategy

How to use it after configuration? Three ways:

  1. Temporary switching: Press /model or Ctrl+L during a session, list all loaded models (including the ones you just configured), and fuzzy-search to select one
  2. Set as default: Edit ~/.pi/agent/settings.json, add "defaultProvider": "deepseek" and "defaultModel": "deepseek-v4-pro", and Pi will use it directly on startup
  3. Command-line listing: pi models (or pi models deepseek for fuzzy filtering) — on error, parse errors from models.json are printed at the top of the terminal for easy troubleshooting

models.json also supports two advanced usages (not covered in this tutorial): use modelOverrides to patch a specific model of a built-in provider (e.g., change baseUrl to point to a self-deployed gateway); use the compat field to handle compatibility issues with non-standard interfaces (e.g., some gateways require the special max_tokens field name). The full schema definition is at model-registry.ts:158-218 (https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/core/model-registry.ts#L158-L218).


4. Perspective 2: As Learning Material — A Textbook on Agent Design

The second identity: Pi is an excellent textbook for learning “how to build a production-grade Agent.”

4.1 Why Pi? — Because It’s Small Enough

Many Agent frameworks have tens of thousands of lines of code, and just figuring out the startup flow means reading dozens of files. Pi’s core loop is only a few hundred lines, but its design quality is anything but “crude” — it ranks second on the TerminalBench benchmark (using Claude Opus 4.5), behind only Terminus, despite lacking MCP, sub-agents, plan mode, and other features.

This means you can actually “read through” all the core code of a high-quality Agent within a limited amount of time. That’s impossible for Claude Code, and impossible for LangChain.

4.2 What This Tutorial Covers

This tutorial (illustrated edition) has currently published 10 chapters. The first 6 chapters build core understanding, and the last 4 move into advanced engineering topics:

ChapterTopicCore QuestionDifficulty
Chapter 1Opening overviewWhat is Pi? Why is it worth learning?Beginner
Chapter 2Project structure & layered architectureHow do the four packages divide work? Why this layering?Beginner
Chapter 3Agent LoopHow to make the LLM think and act repeatedly?★ Core
Chapter 4Model invocationHow to call 30+ models with one set of code?★ Core
Chapter 5Tool systemHow are tools defined, validated, and executed?★ Core
Chapter 6Message systemHow is conversation history represented and passed?★ Core
Chapter 7Event-driven architectureWhy do we need events?Advanced
Chapter 8Context engineeringHow to fit infinite conversation into a limited window?Advanced
Chapter 9Context compactionWhat to do when the conversation gets too long?Advanced
Chapter 10Session managementHow are sessions stored, resumed, and forked?Advanced

Future plans: Advanced topics such as Chapter 11 Extension System, Chapter 12 Testing Patterns, and Chapter 13 Design Essence Summary are not yet covered in this tutorial. Interested readers can refer to the source code and documentation in the pi official repository (https://github.com/earendil-works/pi).

Reading suggestions: We recommend reading the first 6 chapters in order — they form the foundation for understanding Pi-Agent’s operating mechanics. From Chapter 7 onward, feel free to skip around; each chapter is relatively self-contained.

Every chapter answers questions at three levels: what it is (concept), how to do it (source code analysis), and why it’s done this way (design trade-offs).

4.3 Pi’s “Subtraction Philosophy”: The Real Education Is in the Trade-offs

Looking at a framework that “does everything,” you can only learn “what they did.” Looking at a framework that deliberately does nothing, you can learn “what you actually need to build an Agent.”

The “What we didn’t build” section on Pi’s official website is an inverted manifesto. Competitors list features; Pi lists what it chose to omit. Behind every omission is a clear engineering rationale:

What Pi Doesn’t DoWhy NotAlternative
MCP supportMCP servers (e.g., Playwright MCP) inject 13,700+ tokens of tool descriptions at session startCLI tools with READMEs, read by the Agent on demand
Sub-agentsAdds complexity, reduces observabilitytmux multi-instance, or dedicated extensions
Permission popupsCause “popup fatigue,” degenerating into security theaterContainerization isolation, or build an approval flow with extensions
Plan modeWriting a plan to a markdown file is more persistent and reusableWrite a plan.md file
Background bashtmux already solves this problemUse tmux
Built-in todosTODO.md files are more flexibleUse markdown files or custom extensions

These trade-offs are key to understanding Pi’s design philosophy and are the most valuable thinking material when learning Agent design.


5. Perspective 3: As an SDK — Building Your Own Agent

The third identity: Pi is a set of independently reusable SDKs that let you build your own Agent applications on top of it.

5.1 SDK Stack: Three-Layer Architecture + One Orthogonal UI Library

Looking back at the four-layer architecture diagram in Section 2, you’ll notice pi-tui is drawn alongside pi-agent-core — it’s not on the stack chain but is a “side dependency” that coding-agent uses only in interactive mode. So from an SDK reuse perspective, Pi is actually a three-layer stack (pi-ai → pi-agent-core → pi-coding-agent), plus an orthogonal terminal UI library (pi-tui). Each of the three stack layers can be used independently, and the UI library can also be used independently — but it solves a different class of problems unrelated to Agents.

Layer 1: pi-ai — Just Calling Models

// Entry point is in the compat submodule (not the main entry)
import { getModel, stream } from '@earendil-works/pi-ai/compat';
import type { Context } from '@earendil-works/pi-ai';

const model = getModel('anthropic', 'claude-sonnet-4-5');

// Context is an interface (not a class), constructed with an object literal
const context: Context = {
  systemPrompt: 'You are helpful.',
  messages: [{ role: 'user', content: 'Hello!' }],
};

// stream() returns an event stream; complete() directly awaits to get the final AssistantMessage
const eventStream = stream(model, context);
for await (const event of eventStream) {
  if (event.type === 'text_delta') process.stdout.write(event.delta);
}

pi-ai doesn’t depend on any Agent concepts. You can use it in any project that needs to call LLMs — chatbots, document analysis, code review tools, even applications completely unrelated to Agents. It supports 30+ providers, streaming output, cross-provider context handoff, token cost tracking, and browser-side execution.

Layer 2: pi-agent-core — Just Running the Loop

// Teaching illustration (simplified); the real API is the Agent class at agent.ts:166
// The Agent class constructor only accepts AgentOptions (convertToLlm/streamFn/beforeToolCall, etc.)
// model/tools/systemPrompt are passed in via AgentSessionConfig when calling prompt()
import { Agent } from '@earendil-works/pi-agent-core';
// Note: defineTool is in the coding-agent package, not agent-core
// import { defineTool } from '@earendil-works/pi-coding-agent';

const agent = new Agent({
  /* AgentOptions: hooks, streamFn, convertToLlm, etc. */
});

// Real entry point: agent.prompt() internally calls the private runWithLifecycle()
// To get the event stream, subscribe via subscribe(listener); event types are the AgentEvent union type in types.ts

pi-agent-core depends on pi-ai but not on pi-coding-agent or pi-tui. You can use it to build any type of Agent — not limited to coding scenarios. Data analysis Agents, customer service Agents, automated testing Agents — any scenario needing the “model thinks → calls tools → sees results → thinks again” loop can use it.

Layer 3: pi-coding-agent — Complete CLI + SDK

This is the top of the stack, assembling the two layers below into a complete coding Agent product. It also exposes SDK interfaces, letting you embed the Agent in your own application in “headless” mode:

import { createAgentSession } from '@earendil-works/pi-coding-agent';
import { getModel } from '@earendil-works/pi-ai/compat';

const session = await createAgentSession({
  cwd: '/path/to/project',
  model: getModel('anthropic', 'claude-sonnet-4-5'),
  // Model object, not {id, api}
});

// subscribe accepts a listener function; event types are the AgentSessionEvent union type
session.subscribe((event) => {
  if (event.type === 'turn_end') {
    console.log('Agent finished a turn of thinking');
  }
});

await session.prompt('Read the codebase and explain the architecture.');

Side library: pi-tui — a terminal UI library unrelated to Agents

pi-tui deserves its own mention because it has a special property: it’s completely independent of Pi’s Agent system. Its package.json (https://github.com/earendil-works/pi/blob/main/packages/tui/package.json) only depends on two packages — get-east-asian-width and marked (markdown parsing) — and its source code has zero import statements from @earendil-works/pi-* sibling packages. On the contrary, coding-agent depends on it unidirectionally (e.g., list-models.ts:6 (https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/cli/list-models.ts#L6) imports fuzzyFilter from pi-tui).

pi-tui is the work of Mario, who’s back in his element (libGDX game engine author). ~12,000 lines of code implementing:

  • Diff rendering — Each frame only redraws changed cells, basically flicker-free
  • Retained-mode UI — A declarative component system similar to React, not the imperative style of ncurses
  • Built-in components — Input boxes with autocomplete, markdown renderer, syntax highlighting, fuzzy search

What is it useful for? Nothing to do with Agents — any Node.js program needing a terminal interactive interface can use it: CLI tools, interactive dashboards, TUI games, custom REPLs. If you’ve ever felt that blessed/ink is either too heavy or too abstract, pi-tui is a minimalist alternative worth reading the source of.

Why does it exist in Pi? Because Pi chose the “terminal harness” form factor (see Section 2), it had to solve terminal rendering itself. Rather than using any existing TUI library, Mario rewrote one following game engine principles. This “byproduct” turned out to be the part of Pi most easily extracted and reused on its own — it doesn’t care whether you’re calling LLMs or doing something else entirely.

5.2 Extension System: Letting the Agent Modify Its Own Capabilities

Pi’s extension system has hot reload capability — when the Agent modifies an extension file, the change takes effect immediately without restarting the session. This enables a powerful pattern: you can have the coding Agent modify and enhance its own capabilities.

Extensions can implement:

  • Custom tools — Define new tools with TypeBox schema parameter validation
  • UI components — Embed custom interfaces in the terminal
  • Slash commands — Register new / commands
  • Event listeners — Insert logic at points like tool calls, turn end, etc.
  • Themes — Customize the TUI appearance
  • Prompt templates — Reusable prompt snippets

These five customization levers (extensions, skills, prompt templates, themes, Pi Packages) essentially provide a smooth upgrade path from “using Pi” to “transforming Pi.”

5.3 Four Operation Modes

ModeUse CaseExample
Interactive modeThe classic TUI for daily codingpi
print/JSON modeScripts and CI/CD pipelinespi -p "explain this code"
RPC modeExchange JSON over stdin/stdoutIntegrate into non-Node.js programs
SDK modeEmbed into your own applicationcreateAgentSession()

This multi-mode design means Pi can seamlessly evolve from “a tool at the developer’s fingertips” to “a provider of Agent capabilities in production systems” — you don’t need to switch frameworks when your project grows.

5.4 Already in Use by Open Source Projects

Projects like OpenClaw are already using Pi’s SDK in production, running every Agent instance on Pi. Pi Packages can be distributed via npm or git, and an ecosystem is forming.


6. Pi’s Opposite: Two Contrasting Philosophies

The best way to understand Pi is to look at its opposite.

Claude Code represents the “all-inclusive” route: built-in plan mode, sub-agents, MCP, permission pop

Similar Articles

@indie_maker_fox: If you haven't tried Pi or Craft agent yet, I suggest you give it a try now. You'll immediately understand what I meant last month when I said that. I've said before: In the future, programmers will no longer mainly 'take requirements', but 'make agents'. Agents are used to distill your abilities: just make your requirements clear...

X AI KOLs Timeline

The author recommends developers to try Pi agent and Craft agent, believing that the focus of programming will shift from taking requirements to building agents, and shares his new product Echo, which is a secondary development based on Pi agent.

@alin_zone: A must-read whitepaper for friends who want to learn about Pi Agent! Recently, Pi Agent has been very popular, and while searching for materials online, I found an excellent tutorial. It contains 10 chapters, with source code analysis from Agent Loop to context engineering, very comprehensive. The website link is in the comments section.

X AI KOLs Timeline

Shared a popular whitepaper tutorial on Pi Agent, containing 10 chapters with source code analysis from Agent Loop to context engineering.

@9hills: After several weeks of exploration and various attempts, the configuration of pi agent is basically stable. I posted a list before without explanation, which wasn't very friendly. This time I'm posting a full version with comments. Warning: If you need an out-of-box Coding Agent, don't use Pi; Claude Code/Codex is more suitable…

X AI KOLs Timeline

The author shares the stable configuration of pi agent (full version with comments), and warns that if you need an out-of-box Coding Agent, Claude Code/Codex is more suitable.