Skip to content

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.

Hoang Yell
Hoang Yell
13 min read
Tiếng Việt
Pi Agent in Practice: Setup, Custom Extensions & 5 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 /login or 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 (Enter vs Alt+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:

  1. Interactive Authentication with /login: Launch pi in any repository and invoke the login command:

    pi
    > /login

    Select your target service (Anthropic, OpenAI, GitHub Copilot…), paste your secret key, and Pi will store it encrypted in ~/.pi/agent/auth.json with strict 0600 permissions. Use /logout to clear sessions.

  2. 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..."
  3. 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 /model and press Ctrl+S to 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:

  1. Prompt Templates (*.md in ~/.pi/agent/templates/): Lightweight prompt aliases invoked via /templatename.
  2. Agent Skills (SKILL.md in ~/.pi/agent/skills/ or .agents/skills/): Progressive disclosure format (loads description into system prompt, full instructions on demand).
  3. TypeScript Extensions (*.ts in ~/.pi/agent/extensions/): Runtime hooks, custom /commands, or tool interception.
  4. 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

  1. Context Window Saturation Trap: During long pairing sessions, token consumption accumulates rapidly. Invoke /compact with explicit instructions (e.g. /compact "preserve architecture decisions and code snippets") to compress context safely.
  2. Bash-over-Edit Hallucination: AI models occasionally attempt sed or cat << 'EOF' via bash on large files, causing syntax corruption. Instruct the model or enforce --tools read,edit,write to prioritize precision editing.
  3. Trust Configuration vs Sandbox Confusion: Pi’s trust.json file 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 /model to 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. Press Ctrl+S to 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:

  1. 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 ya engine 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.
  2. 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.
  3. The Sandbox Illusion: Pi’s trust.json is 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:

  1. Install @earendil-works/pi-coding-agent and authenticate your primary LLM provider with /login.
  2. Author an extension file at ~/.pi/agent/extensions/status.ts that registers a /status command using ctx.ui.notify().
  3. Launch pi, prompt the agent to refactor a utility function in your project, and type /tree to 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.


If you are exploring agentic software engineering, study these complementary open-source architectures:

Related posts