Pi Agent in Practice: Setup, Custom Extensions & 5 Best Practices
Master Pi Agent from scratch: complete CLI setup, multi-provider LLM routing, custom TypeScript extensions, and 5 battle-tested best practices.

Most developers working with AI coding agents quietly settle for a frustrating compromise: living inside someone else’s opinionated cage. Want the agent to ask permission before executing an arbitrary bash command? Wait for the vendor to release an update. Want to switch mid-session from Claude to a local Qwen model to conserve API budget? Locked down.
Pi Agent (pi-coding-agent) was built to demolish that artificial boundary. Uncompromising, lean, and unopinionated, Pi hands the steering wheel directly back to you.
Architectural Context: If you want a deep dive into the 7-package monorepo architecture and its underlying design philosophy, read our foundational analysis Pi Mono Explained: Anti-Framework for AI Coding Agents. This guide is a dedicated, hands-on operational handbook focusing on global setup, local model configuration, authoring custom extensions, and battle-tested pairing practices.
TL;DR
Quick Answer Box (Google Search Featured Snippet):
- How to setup and run Pi Agent effectively? Install the CLI globally via npm (
npm i -g --ignore-scripts @earendil-works/pi-coding-agent), authenticate via/loginor point to local inference via~/.pi/agent/models.json, and harness its 7 core primitives (read,write,edit,bash,grep,find,ls). To customize workflows without forking, leverage the progressive customization ladder ranging from Prompt Templates and Agent Skills to full TypeScript Extensions.- Core Philosophy: Anti-framework design that decouples the fast terminal interface (TUI) from the stateful execution loop (
pi-agent-core) and the multi-provider LLM gateway (pi-ai).- Killer Features: Native session branching (
/tree,/fork,/clone), 4 automation execution modes (interactive,-p,json,rpc), and keyboard steering (EntervsAlt+Enter).- Official Repositories: earendil-works/pi and badlogic/pi-mono.
Beginner Map
Think of mainstream coding assistants like Cursor or Claude Code as factory-sealed cars with the hood welded shut: you can drive them anywhere, but you cannot swap the transmission. Pi Agent is an exposed racing chassis: you choose the engine, bolt on custom safety brakes, and tune the instrument cluster to your exact habits.
Part 1: Foundations
The deepest pain point of pre-packaged AI coding tools is powerlessness. When an agent blindly overwrites half your codebase without checking, or when you need to hook into an internal enterprise tool, you are left writing paragraphs of pleading system prompts hoping the model complies.
Pi Agent solves this operational bottleneck by adhering to Primitives First. Rather than guessing how you write software, Pi ships with composable primitives and gives you absolute control:
| Technical Concept | Pocket Definition (3-6 words) | Role in Pi Agent Architecture |
|---|---|---|
| CLI / TUI | Terminal user interface | High-speed, flicker-free differential text rendering. |
| pi-agent-core | Stateful loop orchestrator | Manages events, tool execution, and mid-flight steering. |
| pi-ai | Unified LLM gateway | Interacts with 20+ AI providers via a single API call. |
| Session Tree | Branched conversation history | Stores sessions as a JSONL tree for non-linear exploration. |
| TypeScript Extension | Userland plugin module | Injects custom runtime logic without forking upstream core. |
The secret to Pi’s longevity is that you own the execution loop (agent loop). Want an interactive confirmation popup before writing to disk? Write an extension. Want to bind a Model Context Protocol (MCP) server? Drop in an extension. Everything runs on standard TypeScript without hidden magic.
Part 2: Investigation: Complete Setup Walkthrough
Getting Pi Agent operational on your development machine takes under 3 minutes across 3 verified steps.
Step 1: Global CLI Installation
Official packages are distributed under the @earendil-works scope (requires Node.js 22.19 or higher):
# Install the CLI globally from npm
npm install -g --ignore-scripts @earendil-works/pi-coding-agent
# Or install via the official one-liner script
curl -fsSL https://pi.dev/install.sh | bash
# Verify successful installation
pi --version
Step 2: Credential Management & Local Inference
Pi supports flexible authentication tiers:
-
Interactive Authentication with
/login: Launchpiin any repository and invoke the login command:pi > /loginSelect your target service (Anthropic, OpenAI, GitHub Copilot…), paste your secret key, and Pi will store it encrypted in
~/.pi/agent/auth.jsonwith strict0600permissions. Use/logoutto clear sessions. -
Environment Variables: Ideal for automated CI/CD (continuous integration) pipelines:
export ANTHROPIC_API_KEY="sk-ant-api03-..." export OPENAI_API_KEY="sk-proj-..." export GEMINI_API_KEY="AIzaSy..." -
Configuring Local LLMs via
~/.pi/agent/models.json: For complete offline privacy, point Pi directly to your local Ollama or vLLM inference server:{ "providers": { "ollama": { "baseUrl": "http://localhost:11434/v1", "api": "openai-completions", "apiKey": "ollama", "models": [ { "id": "qwen2.5-coder:32b" } ] } } }Open
pi, run/modeland pressCtrl+Sto persist it as your default model.
Step 3: Operating the 7 Core Primitives & Sandboxing
Unlike outdated guides referencing only 4 tools, Pi Agent mounts 7 built-in surgical tools:
read: Reads file contents with exact line-range slices.write: Creates new files or overwrites existing buffers cleanly.edit: Replaces unique text blocks using exact match strings, avoiding accidental deletions.bash: Runs shell commands with configurable execution timeouts.grep: Lightning-fast regex search across codebase contents.find: Scans file paths by glob patterns.ls: Lists directory tree entries.
You can restrict tools via the --tools allowlist to enforce read-only safety:
# Restrict agent to inspection tools only, preventing file writes or command execution
pi --tools read,grep,find,ls --print "Review the architectural boundaries in this repo"
Part 3: Diagnosis: Customization Ladder & Extension Architecture
Before writing complex code, understand Pi’s 4-Tier Customization Ladder:
- Prompt Templates (
*.mdin~/.pi/agent/templates/): Lightweight prompt aliases invoked via/templatename. - Agent Skills (
SKILL.mdin~/.pi/agent/skills/or.agents/skills/): Progressive disclosure format (loads description into system prompt, full instructions on demand). - TypeScript Extensions (
*.tsin~/.pi/agent/extensions/): Runtime hooks, custom/commands, or tool interception. - Custom Providers (
models.json): Custom endpoint routing or local GGUF execution via/llama.
Building a Safe Command Extension in 20 Lines
Create ~/.pi/agent/extensions/guardrails.ts:
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
export default function (pi: ExtensionAPI) {
// Register a custom command in the TUI
pi.registerCommand("status", {
description: "Print current session security status",
handler: async (_args, ctx) => {
ctx.ui.notify("Guardrail active: Command interception enabled.", "info");
},
});
// Intercept bash tool execution before dispatch
pi.on("tool_call", async (event, _ctx) => {
if (event.toolName === "bash") {
const command = String(event.params.command || "").trim();
const forbidden = [/rm\s+-rf\s+[\/~]/, /git\s+push\s+.*--force/, /mkfs/];
for (const pattern of forbidden) {
if (pattern.test(command)) {
throw new Error(`Blocked by Guardrail: "${command}" violates workspace security rules.`);
}
}
}
});
}
Load your extension via pi --extension ./guardrails.ts or place it in ~/.pi/agent/extensions/. After editing, type /reload in the terminal to hot-reload changes instantly.
4 Automation Execution Modes
Never treat Pi as merely an interactive chat window:
- Interactive Mode (
pi): Full TUI with keyboard controls and diff rendering. - Print Mode (
pi -p "summarize diff" < <(git diff)): Single-turn execution printing directly to stdout, ideal for shell script piping. - JSON Event Stream (
pi --mode json "task" > events.jsonl): Emits structured JSONL telemetry for CI/CD audit pipelines. - RPC Mode (
pi --mode rpc): Stdin/stdout JSONL stream transforming Pi into a background daemon for custom GUI or web clients.
3 Production Traps to Avoid
- Context Window Saturation Trap: During long pairing sessions, token consumption accumulates rapidly. Invoke
/compactwith explicit instructions (e.g./compact "preserve architecture decisions and code snippets") to compress context safely. - Bash-over-Edit Hallucination: AI models occasionally attempt
sedorcat << 'EOF'via bash on large files, causing syntax corruption. Instruct the model or enforce--tools read,edit,writeto prioritize precision editing. - Trust Configuration vs Sandbox Confusion: Pi’s
trust.jsonfile only manages command execution approval; it is not a process sandbox. For true multi-tenant or untrusted code safety, always execute Pi within Docker or lightweight containerization boundaries.
Part 4: Resolution: 5 Battle-Tested Best Practices
To unlock maximum engineering leverage with Pi Agent, adopt these 5 field-tested protocols:
1. Master the Session Quadrant: /tree, /fork, /clone, and /resume
/tree: Navigate between conversation branches within the same session file without losing alternate paths./fork: Spawn a clean, separate session starting from a specific prior user prompt./clone: Duplicate the active working branch into a new session./resume: Open the interactive session picker to search, rename, or prune historical runs.
2. Multi-Model Handoff Strategy
Leverage pi-ai to split costs and maximize analytical depth:
- Start with a frontier reasoning model (such as Claude 3.7 Sonnet) for the architectural breakdown.
- Switch via
/modelto a rapid, low-cost coding model (such as Qwen 2.5 Coder 32B or GPT-4o-mini) to churn out implementation code and unit tests. PressCtrl+Sto persist default model selections.
3. Harness Prompt Caching and Session Affinity
Pi propagates the x-session-id header when routing through compatible inference gateways. Keeping continuous work within the same session tree allows inference providers to hit KV-cache prefixes, reducing response latency and significantly lowering input token expenses.
4. Precision Keyboard Steering
Enter: Steer (interject immediately after the currently running tool finishes).Alt + Enter: Follow-up (queue instructions after the entire agent task concludes).Esc: Abort execution and return the entire prompt buffer back to the editor for instant revision.Ctrl + T: Cycle reasoning depth on the fly (/thinking off/low/medium/high/max).
5. Scope Context with @ Symbols and AGENTS.md
Pass targeted file references using @path/to/file rather than asking the agent to search the whole project. Maintain an AGENTS.md file in your repository root to establish architecture standards, testing checklists, and style guidelines that Pi loads automatically.
When Should You NOT Install Pi Agent? (A Homelab Reality Check)
A frequent question among engineers is: “Should I immediately install Pi Agent on my daily workstation or personal server as my primary tool?”
The pragmatic answer is: It depends on your hardware budget and existing agent topology. Here are 3 scenarios where installing Pi may not be the optimal move:
- Role Redundancy with Existing Host Agents: If your machine already runs a dedicated, full-cycle autonomous host agent with broad operating-system permissions (such as our custom
yaengine built on Google Antigravity CLI and OpenCode minion fleets, detailed in Zero-Dollar AI Agent Farming: Turning a Broken-Screen Laptop into a 24/7 Autonomous Engineering Server), installing Pi Agent alongside it introduces unnecessary functional overlap. - Hardware Bottlenecks for Local Inference: Pi shines when paired with local GGUF models or Ollama. However, on machines with 8GB RAM and zero discrete GPU hardware, loading 7B-8B parameter weights exhausts memory budgets and triggers aggressive OS swapping. In constrained environments, leveraging lightweight cloud-native host agents remains far more responsive.
- The Sandbox Illusion: Pi’s
trust.jsonis strictly an interactive terminal confirmation filter; it provides zero kernel-level isolation or process sandboxing. If you plan to let an agent run unvetted scripts autonomously, wrap Pi inside Docker or Linux mount namespaces (bwrap) rather than trusting userland CLI flags alone.
Decision Matrix: When to Choose Pi Agent
| Evaluation Criteria | Cursor / Claude Code | Pi Agent (pi-coding-agent) |
|---|---|---|
| Out-of-the-box Polish | High, graphical desktop interface | Minimalist terminal CLI / TUI |
| Custom Extensibility | Constrained to vendor-approved APIs | 100% open via TypeScript extensions, Skills & Templates |
| Provider Portability | Locked to fixed model catalogs | 20+ cloud providers plus local Ollama/vLLM & GGUF |
| History Management | Linear scrollback lists | Non-linear session tree (/tree, /fork, /clone, /resume) |
| Automation Modes | Manual GUI interactions | 4 modes: TUI, Print (-p), JSON Stream, RPC Daemon |
Final Take
The most powerful coding agent is not the one with the most built-in bells and whistles; it is the one that gives you complete sovereignty over how it reasons and executes.
Pi Agent does not try to be everything for everyone. It was crafted for engineers who demand total visibility into tool execution, insist on zero proprietary lock-in, and want to build their own autonomous workflows from first principles.
Student First Assignment
Take 20 minutes to complete your first operational loop with Pi Agent:
- Install
@earendil-works/pi-coding-agentand authenticate your primary LLM provider with/login. - Author an extension file at
~/.pi/agent/extensions/status.tsthat registers a/statuscommand usingctx.ui.notify(). - Launch
pi, prompt the agent to refactor a utility function in your project, and type/treeto observe the generated session branches.
Frequently Asked Questions (FAQ)
1. When should I use a Prompt Template versus a Skill or an Extension?
Use Prompt Templates (*.md) when you simply need to reuse fixed prompt snippets (like a code-review template). Use Agent Skills (SKILL.md) when equipping the agent with domain-specific knowledge, reference docs, and helper scripts. Reserve TypeScript Extensions for runtime interception, adding custom tools, or modifying core behavior.
2. What is the primary purpose of --mode rpc?
RPC mode runs Pi as a headless background daemon, communicating over stdin/stdout via JSON Lines. This provides a robust interface for embedding Pi into custom IDE extensions, desktop interfaces, or private automation frameworks without re-implementing agent orchestration.
3. Can I run Pi Agent completely offline with local GGUF models?
Yes. You can leverage the built-in llama.cpp router via /llama or configure local Ollama/vLLM servers inside models.json. The agent operates entirely on local hardware without transmitting any telemetry or code to external servers.
4. Should I install Pi Agent directly on my primary workstation or homelab server?
Install it if you want to explore Mario Zechner’s minimalist terminal diff engine, navigate non-linear session trees (/tree), or embed CLI script pipes into custom automation. If you already maintain an autonomous host agent infrastructure (such as the zero-cost homelab engineering setup documented in Zero-Dollar AI Agent Farming: Turning a Broken-Screen Laptop into a 24/7 Autonomous Engineering Server), adding Pi creates role redundancy without expanding your core automation capabilities.
Related AI Agent Architectures in Our Ecosystem
If you are exploring agentic software engineering, study these complementary open-source architectures:
- Zero-Dollar AI Agent Farming: Turning a Broken-Screen Laptop into a 24/7 Autonomous Engineering Server: Complete architectural blueprint of our custom
yaautonomous host agent running on Google Antigravity CLI, Bubblewrap namespace isolation, and zero-cost OpenCode minion fleets. - Pi Mono: Deconstructing the World’s Leanest AI Coding Agent Architecture: Deep dive into the raw 1,200 lines of minimalist TypeScript that serve as the foundation of Mario Zechner’s Pi Agent.
- Understand Anything: Codebase Knowledge Graphs: Deterministic Tree-sitter AST parsing coupled with multi-agent semantic explanations for complex 200k-line codebases.
- Taste Skill: Giving AI Coding Agents Good Taste: Enforce modern design aesthetics, Linear/Apple minimalism, and typography constraints on autonomous agents.
Related posts
- AI & Agents
Pi Mono Explained: The Anti-Framework for AI Coding Agents
Pi Mono is a radically extensible AI agent monorepo that refuses to dictate your workflow, stack, or agent framework of choice.
19 min readRead → - AI & Agents
Orca IDE: What It Is, Parallel Worktrees & AI Agent Setup Guide
What is Orca? Explore the open-source AI agent IDE (stablyai/orca) to orchestrate parallel coding agents in isolated Git worktrees with mobile steering.
10 min readRead → - AI & Agents
Context Hub: The Curated Doc Layer Every Coding Agent Needs
Context Hub (`chub`) gives AI coding agents current, versioned API docs on demand -- so they code from facts, not 18-month-old training weights.
14 min readRead → - AI & Agents
Vercel Skills Explained: The Open Agent Package Manager
How Vercel's npx skills creates a universal package manager for 79+ AI agents: architecture, symlink pipelines, skills-lock determinism, and security edges.
11 min readRead →