Pi Agents cover
Book In development

Pi Agents

A practical book about writing agents that run on Pi: prompt templates, skills, extensions, settings, MCP, and the SDK and RPC surfaces — worked from the least powerful mechanism that solves the problem.

Most people write agents by writing prompts. That works right up until the moment it does not: the prompt gets longer, the instructions start to contradict each other, and the same task works on Tuesday and fails on Thursday for reasons nobody can name.

Pi takes a different position. The agent is not a conversation you happen to be having; it is a program, with a documented set of places to attach. There is a mechanism for persistent instructions. A mechanism for reusable prompts. A mechanism for bundled instructions and files. A mechanism for executable tools and event handlers that runs inside the agent’s own process. Each one is more powerful than the last, and each one costs more than the last — in review surface, in trust, and in the damage a mistake can do.

This book is about choosing correctly on that ladder, and then building well on the rung you chose.

What is the least powerful Pi mechanism that solves this problem?

What the book builds

Four parts, thirty-six chapters. Part I is deliberately slow: it explains what Pi actually does, because an extension author who does not know how context is assembled writes an extension that fights the system and cannot tell whether the bug is theirs or Pi’s. Part II takes the building blocks in order of power. Part III handles what happens when the conversation outgrows the window and you need to steer it, inspect it, or recover it. Part IV removes the human from the terminal entirely.

Part I: The Agent Loop. What Pi is and what you are writing against. The loop that every extension attaches to, installation and a first task, models and thinking level, the context window as a budget rather than a container, where sessions live, the built-in tools, where configuration comes from and in what order it wins, the project .pi directory and the trust decision in front of it, the shell Pi actually invokes, and how to write a task the agent can finish.

Part II: The Four Building Blocks. How you change Pi. Chapter 11 is the decision chapter, and everything after it assumes you have made the decision. Then prompt templates and their argument substitution; skills and their description-based routing; skills that carry scripts, references and assets; your first extension; the lifecycle and the event contracts; tools in depth including exposure and nested calls; changing what the model knows; where state goes and why the four storage choices are not interchangeable; slash commands and terminal UI; MCP; and shipping the result as a package.

Part III: Long Sessions and Control. What happens when the conversation gets big. Compaction and what a summary does and does not preserve; branching and forking over a tree rather than a list; steering, queueing and aborting work in flight; the message types the whole system is built from; the session file format on disk; context files and the difference between them and project configuration; failures, retries and recovery; debugging; and the terminal interface itself.

Part IV: Pi as a Program. When there is no human at the terminal. Headless operation through print, JSON and RPC modes; the JSONL event stream and how to reconstruct state from it; the TypeScript SDK creating sessions in process; driving a live Pi over RPC; and a capstone that gathers trust, permissions, tool annotations and isolation into one answer to the question the reader should have been asking since chapter 1: what makes an agent worth building at all?

The decision the book is really about

Pi’s quickstart tells you to start with the least powerful mechanism that meets your need, and then gives the ladder:

AGENTS.md        persistent instructions for a folder
prompt template  reuse a prompt from the / menu
skill            task-specific instructions plus supporting files
extension        executable tools, commands, or event handlers
terminal UI      a custom component in the terminal
custom provider  an unsupported model service
package          install or distribute several resources at once

Chapter 11 turns that into a procedure, and the rest of the book assumes you have climbed it deliberately. The reason is not elegance. A prompt template is one file that a reviewer can read in a diff. An extension is TypeScript running inside the agent’s process with the operating-system permissions of the user who launched it, able to inspect prompts, tool calls, files, credentials and session history. Both are legitimate. They are not the same commitment, and the difference is invisible until it matters.

What kind of claims this book makes

Three kinds, kept apart in the prose.

Documented is what Pi’s documentation or its exported type declarations state. The book asserts these plainly and names the doc topic. Observed is behaviour that was run and recorded, with the version noted. Proposed is a pattern that belongs to this book and not to Pi — a reasonable way to structure an extension, a shape for a skill directory — and it is always signalled as such.

This separation is the book’s method. Most agent writing goes wrong not because a technique was wrong but because a pattern that happened to work got described as though the framework guaranteed it. Where the book recommends something Pi does not require, it says so.

Who this is for

You can use the agent already and you want it to do one specific thing reliably. You are comfortable enough with TypeScript to read an event declaration. You would rather understand the mechanism than copy a snippet, and you want to know which parts of what you built depend on a documented contract and which parts are your own judgement.

No prior Pi experience is assumed. Parts I and III are readable without TypeScript. Part II assumes you can read an async factory and a schema object.

How to read it

If you are here to build one thing, read chapter 11 first and let it send you to the chapter you need. If you are writing extensions, read Part I in order — it is the part that stops your bugs being ambiguous. If you are embedding Pi in a pipeline, go straight to Part IV, but skim Part III, because the session format is what you will be debugging at two in the morning.

Contents

Chapters

01

The Loop You Are Writing For

Before you write an extension, know the loop it attaches to: how a submitted message becomes a model request, how a tool call becomes a result, and when the run is over.

02

Install, First Session, First Task

Get Pi running and give it something real to do: installation, the working folder, authentication, a first task, and what to do when the result is not what you wanted.

03

Models and Thinking Level

Which model the agent runs on, how hard it thinks, how credentials are resolved, and why a model choice can explain a behaviour you attributed to your code.

04

The Context Window Is a Budget

What Pi sends to the model each turn, the arithmetic that triggers compaction, and how to tune reserveTokens and keepRecentTokens for your model.

05

Sessions and Where They Live

Session files are append-only JSONL trees keyed by id and parentId; here is how to read one, resume it, fork it, and control where it is stored.

06

The Built-In Tools

The eight built-in Pi tools, what defaultTools actually selects, how tool results reach the transcript, and when to add codemode.

07

Settings and Where Configuration Comes From

Pi merges the agent-directory and project .pi settings files: scalars override, resource lists combine, and environment variables and CLI flags are documented per setting rather than as higher layers.

10

Writing a Task Pi Can Finish

Pi does not ask before tool calls, so the task statement has to carry the scope, the acceptance check, and the files; here is a shape that works.

11

Four Ways to Change Pi

A decision procedure for choosing between context files, prompt templates, skills, and extensions, with four worked cases and one running example for the rest of this part.

12

Prompt Templates

Prompt templates turn a Markdown file into a slash command with shell-style argument substitution; here is the frontmatter, the substitution table, and where templates load from.

13

Skills

Pi advertises each skill by name and description and loads its full instructions on demand; here is how to write the description that makes routing work.

14

Skills That Carry Files

SKILL.md can reference scripts, references and assets by relative path; here is the layout, the path convention, and how to distribute the whole directory as a package.

15

Your First Extension

An extension is a TypeScript module with a default factory receiving ExtensionAPI; here is the smallest working tool, how it loads, and the lifecycle rules for the factory.

16

Events and the Extension Lifecycle

Pi dispatches named events to handlers in registration order; here is the run lifecycle, what each event may return, and a force-push guard built on tool_call.

17

Tools in Depth

A tool declares a name, description, schema and execute(); this chapter covers exposure, annotations, structured output, terminate, and nested calls.

18

Changing What Pi Knows

Four surfaces change the model's input - SYSTEM.md, APPEND_SYSTEM.md, before_agent_start sections, and the context event - each with a different lifetime and cost.

19

Extension State and Persistence

Where an extension puts its state so it survives reload, resume, and fork, and why the answer is almost always a session entry rather than a module variable.

20

Slash Commands and Custom UI

How an extension adds a / command and renders its own screen, and the mode rules that decide whether that screen exists at all.

21

MCP Servers

Connecting Model Context Protocol servers over stdio and HTTP, controlling how their tools reach the model, and what a permission gate can and cannot see of them.

22

Packages: Shipping an Agent

How a Pi package carries an extension, its skills, prompts and themes as one installable unit, and which dependencies must never be bundled.

23

Compaction

How Pi decides when the context window is full, what it replaces with a summary, what survives untouched, and where an extension can take the summarization over.

24

Branching and Forking

Three ways to go back — /tree, /fork and /clone — and how to choose when a wrong turn stays in the session or becomes separate work.

25

Steering, Queuing, and Changing Direction

What happens when you type while Pi is working — steering enters after the current turn, follow-ups wait for the run to finish, and Escape returns the queue.

26

Message Types

The eight roles AgentMessage covers, the content blocks they share, and which fields are authoritative — including the one timestamp type that catches everyone.

27

The Session File Format

One JSON object per line, a tree of entries, and the three-pass walk that turns a stored session into exactly the messages a model request contains.

28

Context Files and Project Instructions

Which files on disk become instructions the model receives on every request, which tier wins, and why context files load even when you decline project trust.

29

Failures, Retries, and Recovery

Three different responses to a failed request — repeat it, repair the context and retry once, or stop — and the settings and events that tell them apart.

30

Debugging Pi

What Pi records when something goes wrong — pi-debug.log, /bug, /session, /hotkeys — and how extension lifecycle rules explain most failures before you read a single log line.

31

The Terminal Interface

The terminal UI as a layered system — keybindings, themes, the pi-tui component model, and the protocol layers your terminal must actually report.

32

Headless Pi

Running Pi with no person attached — print and JSON modes, how the mode is chosen, what survives without a terminal, and what each mode costs and gives you.

33

The JSON Event Stream

The wire reference for Pi's JSONL events — strict LF framing, the event vocabulary, and the reconstruction rule that turns deltas back into authoritative messages.

34

SDK Sessions

Embedding Pi in a Node.js or Bun process — createAgentSession, the injected boundaries, session replacement, and the rules that keep an in-process agent well behaved.

35

RPC

Driving a live Pi subprocess over JSONL — four record families, correlated commands, an extension UI subprotocol, and the shutdown contract.