Runoob Tutorial ArchiveEnglish

Pi Coding Agent Getting Started Tutorial

Pi Coding Agent Getting Started Tutorial

Pi is an AI coding agent that runs in the terminal, similar to tools like Claude Code and OpenAI Codex CLI.

Pi's official philosophy is: "There are many agent harnesses but this one is yours."

You give Pi a command, and it can read files, write files, and run commands in your project directory, looping calls to the large model until the task is completed.

The core philosophy is to use a minimal kernel with extremely strong extensibility, allowing you to customize the tool to fit your needs, rather than adapting to the tool.

Pi Agent Complete Tutorial:https://www.runoob.com/pi-agent/pi-agent-tutorial.html

pi 178394986 999

What Pi includes

Pi is not a standalone program, but a toolchain composed of four npm packages.

Ordinary users only need to install the top-level@earendil-works/pi-coding-agentto get a ready-to-use command-line Agent.

Who is it suitable for

Pi is particularly suitable for the following scenarios and people:

Note: Pi runs by default with your user permissions and has no built-in sandbox. Please read the "Security Notice" section of this document before using it on untrusted code repositories.


Core Design Philosophy: Primitives, Not Features

By understanding Pi's design philosophy, you will understand why it intentionally "does not include" many features that other Agents have.

Pi calls this concept Primitives, Not Features.

Features Not Built-in

The following features are not built into Pi; instead, you implement them on demand through extensions or external tools:

Features Not Built-in Alternatives to Pi
MCP protocol integration Write the tool as a CLI with a README, or install an MCP extension
Subagents Run multiple sessions with tmux, or write your own extension
Permission confirmation dialog Run in a container, or write your own confirmation process extension
Plan mode Write the plan to a file, or install an extension
Built-in to-do list Use a TODO.md file, or install an extension
Backend bash Use tmux for full observability

Why do this

Pi believes that the needs for these features vary greatly among different teams, and forcing them into the core would make the tool bloated and difficult to fit into actual workflows.

So its approach is: maintain a clean minimal core, and turn all "features" into installable, writable, and shareable extensions, skills, prompt templates, and themes.

You can even have Pi write these functions for you, and use them/reloadafter reloading.

This sentence is worth remembering:Adapt Pi to your workflows, not the other way around(Let Pi adapt to your workflows, not the other way around).


Architecture and core packages

Pi is composed of four distinct layers, where upper layers depend on lower layers.

The ones you usually usepiThe command is just the entry point provided by the top-level package.

Four core packages

Package name Function When it will be used alone
@earendil-works/pi-coding-agent Interactive coding Agent CLI, the entry point for direct user installation and use This is needed in most situations
@earendil-works/pi-agent-core Agent runtime, responsible for tool calling loop and state management When you want to build a non-coding Agent yourself
@earendil-works/pi-ai Unified multi-vendor LLM API (OpenAI, Anthropic, Google, etc.) When you only want to call multiple models through a unified interface
@earendil-works/pi-tui Terminal UI library supporting differential rendering When you want to write your own terminal application

Four running modes

Pi is not only for interactive running; it provides four modes to adapt to different scenarios:

Mode Description Typical scenarios
Interactive Complete terminal UI experience Daily coding, conversational development
Print / JSON pi -p "提问"One-time output;--mode jsonOutput event stream Script automation, pipeline processing
RPC JSON protocol communication via stdin/stdout Non-Node program integration
SDK Embed as a library in your application Integrate Agent capabilities into your own product

Installation

Pi offers multiple installation methods, covering macOS, Linux, and Windows.

The most common is global installation via npm, or using the official one-click script.

Method one: One-click script (recommended for beginners)

macOS and Linux users use curl:

curl -fsSL https://pi.dev/install.sh | sh

Windows users use PowerShell:



powershell -c "irm https://pi.dev/install.ps1 | iex"

Method two: Global npm installation

If you have already installed Node.js, you can install it globally using the package manager.

Note that--ignore-scriptsParameter: It will skip the dependency installation lifecycle scripts, which are not needed for normal Pi usage and add more security.

Original prompt (Chinese, left untranslated)



# npm 安装

npm install -g --ignore-scripts @earendil-works/pi-coding-agent



# pnpm 安装

pnpm add -g --ignore-scripts @earendil-works/pi-coding-agent



# bun 安装

bun add -g --ignore-scripts @earendil-works/pi-coding-agent

Verify installation

After installation, check the version number to confirm success:



pi --version

For example:



$ pi --version

0.80.6

Uninstall

The uninstallation method depends on how you originally installed it:

Original prompt (Chinese, left untranslated)



# installed via curl or npm

npm uninstall -g @earendil-works/pi-coding-agent



# pnpm 装的

pnpm remove -g @earendil-works/pi-coding-agent



# bun 装的

bun uninstall -g @earendil-works/pi-coding-agent

Note: Uninstalling Pi will not delete your configuration. Settings, credentials, session records, and installed Pi packages are retained in~/.pi/agent/the directory and need to be manually cleaned up.


Configure Model Provider

Pi itself does not include large models; it requires you to provide access credentials for at least one model provider (Provider).

There are two configuration methods: subscription login or API Key.

Method one: Subscription login (easiest)

If you already have a Claude Pro/Max, ChatGPT Plus/Pro, or GitHub Copilot subscription, you can log in directly to reuse it.

After starting Pi, run/login, and then select the provider:

Original prompt (Chinese, left untranslated)



# 启动 pi

pi



# Execute login command in pi

/login

There are three optional subscription providers:

Vendor Requirements Description
Claude Pro / Max Anthropic subscription Third-party tool usage is billed by Token and does not count against the subscription quota
ChatGPT Plus / Pro (Codex) OpenAI subscription OpenAI officially recognized Codex for OSS
GitHub Copilot Copilot subscription If the model is not supported, you need to enable the corresponding model in VS Code first

Credentials will be stored after logging in~/.pi/agent/auth.jsonFor logout, use/logoutMethod two: API Key (most flexible)

Method two: API Key (most flexible)

Passing the API Key via environment variables is the most universal method. For example, using Anthropic's Key:

Original prompt (Chinese, left untranslated)



# Start after setting environment variables

export ANTHROPIC_API_KEY=sk-ant-...

pi

You can also run it in Pi/loginand select the API Key type provider to persist the Key inauth.json.

Environment variables for common providers

Pi supports over 15 providers, and the most common ones are listed below:

Provider Environment variable key names in auth.json
Anthropic ANTHROPIC_API_KEY anthropic
OpenAI OPENAI_API_KEY openai
Google Gemini GEMINI_API_KEY google
DeepSeek DEEPSEEK_API_KEY deepseek
Groq GROQ_API_KEY groq
Mistral MISTRAL_API_KEY mistral
xAI XAI_API_KEY xai
OpenRouter OPENROUTER_API_KEY openrouter
Hugging Face HF_TOKEN huggingface

Hint:auth.jsonCredentials in the configuration take precedence over environment variables. If configured in both places, theauth.jsontakes precedence.

Structure of auth.json

If you want to manage credentials manually, you can directly edit~/.pi/agent/auth.jsonThis file will be created with 0600 permissions (read and write only by the current user):

{

  "anthropic": { "type": "api_key", "key": "sk-ant-..." },

  "openai": { "type": "api_key", "key": "sk-..." },

  "google": { "type": "api_key", "key": "..." }

}

The Key field also supports three advanced syntaxes for convenience in retrieving values from password managers or environment variables:

Syntax Meaning Example
"!命令" Starts with an exclamation mark, executes the command, and uses stdout as the Key "!op read 'op://vault/item/cred'"
"$变量名" Retrieves the value of an environment variable "$MY_ANTHROPIC_KEY"
Pure literal Use directly as Key "sk-ant-..."

Cloud platform provider

If you are using a model service on the cloud, Pi also supports Azure OpenAI, Amazon Bedrock, Google Vertex AI, Cloudflare, etc.

These usually require additional configuration of endpoints, regions, or deployment names. For example, Azure OpenAI:

Original prompt (Chinese, left untranslated)



# Environment variables required for Azure OpenAI

export AZURE_OPENAI_API_KEY=...

export AZURE_OPENAI_BASE_URL=https://your-resource.ai.azure.com



# Optional: API version and deployment name mapping

export AZURE_OPENAI_API_VERSION=2024-02-01

export AZURE_OPENAI_DEPLOYMENT_NAME_MAP=gpt-4o=my-gpt4o

Configure DeepSeek provider

Pi supports custom providers through models.json, configuration file address:

First, obtain an API Key from the DeepSeek Open Platform:https://platform.deepseek.com/api_keys.

{

  "providers": {

    "deepseek": {

      "baseUrl": "https://api.deepseek.com",

      "api": "openai-completions",

      "apiKey": "$DEEPSEEK_API_KEY",

      "models": [

        {

          "id": "deepseek-v4-pro",

          "name": "DeepSeek V4 Pro",

          "contextWindow": 1000000,

          "maxTokens": 384000,

          "input": ["text"],

          "reasoning": true,

          "cost": {

            "input": 1.74,

            "output": 3.48,

            "cacheRead": 0.145,

            "cacheWrite": 0

          },

          "compat": {

            "requiresReasoningContentOnAssistantMessages": true,

            "thinkingFormat": "deepseek",

            "reasoningEffortMap": {

              "minimal": "high",

              "low": "high",

              "medium": "high",

              "high": "high",

              "xhigh": "max"

            }

          }

        },

        {

          "id": "deepseek-v4-flash",

          "name": "DeepSeek V4 Flash",

          "contextWindow": 1000000,

          "maxTokens": 384000,

          "input": ["text"],

          "reasoning": true,

          "cost": {

            "input": 0.14,

            "output": 0.28,

            "cacheRead": 0.028,

            "cacheWrite": 0

          },

          "compat": {

            "requiresReasoningContentOnAssistantMessages": true,

            "thinkingFormat": "deepseek",

            "reasoningEffortMap": {

              "minimal": "high",

              "low": "high",

              "medium": "high",

              "high": "high",

              "xhigh": "max"

            }

          }

        }

      ]

    }

  }

}

Set the environment variable:

Linux / Mac users:

Original prompt (Chinese, left untranslated)



export DEEPSEEK_API_KEY="<你的 DeepSeek API Key>"

Windows users:

Original prompt (Chinese, left untranslated)



$env:DEEPSEEK_API_KEY="<你的 DeepSeek API Key>"

Enter the project directory and execute the pi command:



cd /path/to/my-project

pi

Enter /model to open the model switcher, select deepseek, and then select DeepSeek-V4-Pro or DeepSeek-V4-Flash.

For more configuration options, please refer to:https://github.com/earendil-works/pi/blob/main/packages/coding-agent/docs/models.md.

Credential parsing order

When Pi needs a credential from a supplier, it searches in the following order sequentially, and uses it when found:

Priority Source
1 (highest) Command line--api-keyParameters
2 auth.jsonentries (API Key or OAuth token)
3 Environment variables
4 models.jsonKey for custom providers

First run

After configuring the credentials, enter your project directory and runpiStart.

Original prompt (Chinese, left untranslated)



# Change to project directory

cd /path/to/project



# 启动 pi

pi

After starting, just enter a sentence and press Enter, for example, asking it to analyze this repository:



Summarize this repository and tell me how to run its checks.

Pi will automatically read files, run commands, and then provide a summary and checking methods.

Project Trust Prompt

If there are project-level resources such as.piconfiguration, extensions, skills, etc., in the current directory or parent directory, Pi will first ask you whether to trust this project during interactive startup.

This is to prevent a repository from silently loading its extensions or modifying settings without your knowledge.

Note: Trust decisions are saved in~/.pi/agent/trust.jsonNon-interactive modes (-p,--mode json) will not pop up windows and will default to the handling in the global settings.defaultProjectTrustHow does Agent work?

For every message you send, Pi starts an agent loop. Understanding this loop is understanding how Pi works.

The core is the middle turn loop: the model may call a tool in each round, Pi executes the tool and feeds the result back into the context, and then lets the model continue until the model stops calling tools and provides a final reply.

Four built-in tools


Four built-in tools

Pi defaults to providing the model with four tools, covering the core coding capabilities of reading, writing, and executing.

Tool Function Default enabled
read Read file content Yes
write Create or overwrite file Yes
edit Apply local patch modification to files Yes
bash Run shell commands Yes
grep Search file content No (requires enabling via tool options)
find Find files based on conditions No (requires enabling via tool options)
ls List directory contents No (must be enabled via tool options)

Control available tools

You can precisely control which tools the model can use via command-line arguments.

This is useful when you need to restrict Agent capabilities, for example, only allowing it to review code without making changes:

Original prompt (Chinese, left untranslated)



# Read-only mode: only allows reading and searching class tools

pi --tools read,grep,find,ls -p "审查这段代码"



# Disable a certain tool, keep the rest

pi --exclude-tools ask_question



# Disable all built-in tools, only keep tools provided by extensions

pi --no-builtin-tools -e ./my-extension.ts



# Completely disable tools, pure dialogue

pi --no-tools -p "解释一下这个概念"

Reminder: Pi runs in your current working directory and can modify your files. It is recommended to use it with version control like git for easy rollback.


Give instructions to the project using AGENTS.md

AGENTS.md is Pi's project instruction file, telling the model what rules the project has, how to run it, and what to pay attention to.

Its function is similar to Claude Code's CLAUDE.md—and Pi supports both file names.

Write an AGENTS.md

Create in the project root directoryAGENTS.mdand write the rules you want the model to follow:

Original prompt (Chinese, left untranslated)



# Project instructions



- 改完代码后运行 `npm run check`。

- 不要在本地跑生产环境的数据库迁移。

- 回答尽量简洁。

Where does Pi load instructions from

Pi loads instruction files from multiple locations at startup, from largest to smallest scope:

Location Scope of effect Description
~/.pi/agent/AGENTS.md Global General instructions that apply to all your projects
Of the parent directoryAGENTS.md Project-level Search upwards from the current directory
Of the current directoryAGENTS.md Project-level Most specific and highest priority instructions

Filename can be usedAGENTS.mdorCLAUDE.mdPi will recognize both.

Modify system prompt

AGENTS.md is an instruction appended outside the default system prompt. If you want more thorough control, you can replace the entire system prompt.

Placing it in the project.pi/SYSTEM.mdwill replace the default system prompt; placing.pi/APPEND_SYSTEM.mdis appended (corresponding globally~/.pi/agent/to the same named file below).

Note: After modifying the instruction file, remember to run/reloadreload in Pi, or restart Pi, for the new instructions to take effect.


Common operations in interactive mode

Interactive mode is the most frequently used form of Pi; mastering a few key operations allows for efficient use.

Reference file: @

Enter in the editor@A fuzzy search for project files will pop up, and the file content will be sent to the model as context after selection.

You can also include files directly when starting from the command line:

Original prompt (Chinese, left untranslated)



# Include a file at startup

pi @README.md "总结一下这个文件"



# Review multiple files together

pi @src/app.ts @src/app.test.ts "一起审查这两个文件"

Run the shell command: !

In the editor, start typing the command with!Typing a command starting with , will run it directly and send the output to the model:

Original prompt (Chinese, left untranslated)



# Run command, output will enter model context

!npm run lint



# Two exclamation marks: run but do not add output to model context

!!npm run build

Switch model and thinking intensity

Pi supports switching models and thinking intensity mid-process to adapt to the complexity of different tasks.

Operation Shortcut / Command Description
Open model selector /modelor Ctrl+L Select one from all available models
Toggle thinking intensity Shift+Tab Cycle between off / minimal / low / medium / high / xhigh / max
Cyclic model collection Ctrl+P / Shift+Ctrl+P Quickly switch between several pre-selected models

You can also specify the model and thinking intensity at startup:

Original prompt (Chinese, left untranslated)



# Specify vendor and model

pi --provider openai --model gpt-4o "帮我重构"



# Using Vendor/Model format

pi --model openai/gpt-4o "帮我重构"



# Abbreviation for Name: Thinking Intensity

pi --model sonnet:high "解决这个复杂问题"



# Limit models that can be cycled in Ctrl+P

pi --models "claude-*,gpt-4o"

Input and editing techniques

Operation Method Description
Multi-line input Shift+Enter (Ctrl+Enter in Windows Terminal) Line break in a message
Path completion Tab Complete file path
Paste image Ctrl+V (Alt+V in Windows) Also supports dragging images into the terminal
Copy reply Ctrl+X Copy the last assistant message
External editor Ctrl+G Open $VISUAL / $EDITOR for long text

Interject while running

While the Agent is working, you don't have to wait; you can insert messages at any time.

Key Behavior Applicable Scenarios
Enter Redirect message: delivered immediately after the current tool finishes, interrupting remaining tools Detect deviation in direction and correct it in time
Alt+Enter Subsequent messages: delivered after the Agent finishes running completely Want to add a new requirement
Escape Stop the current work and restore queued messages to the editor Want to pause and reorganize

Tip: In Windows Terminal, Alt+Enter defaults to full-screen toggle; the keys for navigation and subsequent messages can be changed in settingssteeringModeandfollowUpModecan be changed.


Quick reference for common slash commands

Type in the editor/Command completion will pop up. Below are the most commonly used slash commands.

Command Function
/login//logout Manage OAuth or API Key credentials
/model Switch models
/scoped-models Configure which models participate in the Ctrl+P loop
/settings Adjust reasoning intensity, topic, message delivery method, etc.
/resume Select one from the history to continue
/new Start a new session
/name <名称> Give the current session a display name
/session View session files, ID, message count, Token usage, and cost
/tree Jump to any node in the session tree and continue from there
/fork Branch a new session from a historical message
/clone Copy the current branch as a new session
/compact [提示] Manually compress context with custom instructions
/copy Copy the last assistant message to the clipboard
/export [文件] Export the session as HTML or JSONL
/import <文件> Import and restore a session from a JSONL file
/share Upload as a private GitHub Gist to generate a shareable HTML link
/reload Reload shortcuts, extensions, skills, prompts, themes, and context files
/trust Save the trust decisions of the current project
/hotkeys Show all shortcuts
/changelog View version update history
/quit Exit Pi

Session management: Tree history

Pi's sessions are not a straight line, but a tree.

This means that even if you branch at any historical node, you will not lose the original branch; all branches exist in the same session file.

Where are the sessions located

Sessions are automatically saved to~/.pi/agent/sessions/Grouped by working directory.

Recover or browse history sessions from the command line:

Original prompt (Chinese, left untranslated)



# Continue last session

pi -c



# Browse and select a historical session

pi -r



# Give the session a name for easy future lookup

pi --name "my task"



# Open the specified session file or ID

pi --session <path|id>



# Temporary session, not saved

pi --no-session

Navigate in the session tree

Use/treeYou can open the session tree view and jump to any historical node to continue.

Continuing from here will create a new branch, and the original branch will remain unchanged.

Branching and cloning

Command Behavior Difference
/fork Branching a new session from an earlier user message Restarting from a point in the history
/clone Copying the current active branch into a new session Creating a copy based on the current latest state

Context compression

When the conversation gets long and approaches the model's context limit, Pi will automatically compress earlier messages into a summary.

You can also actively use/compactto trigger, and you can also include a custom instruction telling it what key points to retain during compression:

Original prompt (Chinese, left untranslated)



# Manually compress in pi, and require keeping recent changes

/compact 重点保留最近的改动和错误处理

Export and Share

Export the conversation as HTML for easy archiving or display:

Original prompt (Chinese, left untranslated)



# Export to HTML file

/export my-session.html



# Upload as private GitHub Gist, get share link

/share


Non-interactive Mode and Integration

Pi can not only engage in interactive conversations, but it can also be used as a command-line tool, event stream, RPC service, and SDK library.

One-shot Questioning: print mode

Use-pExit after Pi answers, suitable for script invocation:

Original prompt (Chinese, left untranslated)



# Ask directly

pi -p "总结一下这个代码库"



# Pipe content to Pi

cat README.md | pi -p "总结这段文字"



# Ask a question with an image

pi -p @screenshot.png "这张图里是什么?"

Event Stream: JSON Mode

--mode jsonOutputs all events as JSON lines, convenient for program parsing:

Original prompt (Chinese, left untranslated)



# Output JSON event stream

pi --mode json -p "列出 src 下所有 .ts 文件"

Process Integration: RPC Mode

--mode rpcUses JSON protocol via stdin/stdout, suitable for non-Node programs (e.g., Python, Go) to drive Pi.

Export Existing Session

Exports an existing session file directly to HTML without starting a new session:

Original prompt (Chinese, left untranslated)



# Export conversation file to HTML

pi --export session.jsonl output.html

SDK Mode

If you want to embed Pi's capabilities in your Node application, you can introduce it as a library using the SDK mode.

This is a tighter integration method than RPC. See the SDK chapter in the official documentation:https://pi.dev/docs/latest/sdk.


Extensions

Extensions are the core of Pi's extensibility. It is a TypeScript module that can subscribe to lifecycle events, register custom tools, and add commands and shortcuts.

Extensions are loaded via jiti, so you can write TypeScript directly without compilation.

Where to place extensions

Location Scope
~/.pi/agent/extensions/*.ts Global, applies to all projects
.pi/extensions/*.ts Project level, applies only to the current project

It can also be in subdirectory form (扩展名/index.ts), or a complete package withpackage.json.

A minimal extension example

The following extension demonstrates three things: startup notification, intercepting dangerous commands, and registering a custom tool and a command.

Original prompt (Chinese, left untranslated)



// File path: ~/.pi/agent/extensions/my-extension.ts

import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";

import { Type } from "typebox";



// Export a default factory function that accepts ExtensionAPI

export default function (pi: ExtensionAPI) {



  // 1. Listen to the session_start event: show a notification when the session starts

  pi.on("session_start", async (_event, ctx) => {

    ctx.ui.notify("扩展已加载!", "info");

  });



  // 2. Listen for tool_call event: intercept dangerous bash commands

  pi.on("tool_call", async (event, ctx) => {

    if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {

      // Show confirmation box, block execution if user rejects

      const ok = await ctx.ui.confirm("危险操作!", "允许执行 rm -rf 吗?");

      if (!ok) return { block: true, reason: "被用户阻止" };

    }

  });



  // 3. Register a custom tool that the model can call

  pi.registerTool({

    name: "greet",

    label: "打招呼",

    description: "按名字向某人打招呼",

    parameters: Type.Object({

      name: Type.String({ description: "要打招呼的名字" }),

    }),

    async execute(toolCallId, params, signal, onUpdate, ctx) {

      return {

        content: [{ type: "text", text: `你好,${params.name}!` }],

        details: {},

      };

    },

  });



  // 4. Register a slash command /hello

  pi.registerCommand("hello", {

    description: "打个招呼",

    handler: async (args, ctx) => {

      ctx.ui.notify(`你好 ${args || "world"}!`, "info");

    },

  });

}

Use after writing-eTemporary loading and testing of parameters:

Original prompt (Chinese, left untranslated)



# Temporarily load an extension for testing

pi -e ./my-extension.ts

What the extension can do

The extension's capabilities are far more than what is listed above; it can intervene in almost every stage of the Pi workflow:

Capabilities Corresponding method Typical use cases
Register custom tools pi.registerTool() Let the model call your business interfaces
Register commands pi.registerCommand() Add your own slash commands
Register shortcuts pi.registerShortcut() Bind custom shortcuts
Intercept tool calls tool_callEvents Permission confirmation, command rewriting
Modify context contextEvents Filter history, inject RAG content
Inject messages pi.sendMessage() Dynamically supplement context
Register providers pi.registerProvider() Connect to private model gateway
Custom UI ctx.uiSeries Dialog box, status bar, components

Tip: The Pi repository has over 50 example extensions covering sub-Agents, planning mode, permission gates, SSH execution, sandbox, etc., and is the best reference for learning extension development.


Skills

Skills are another type of reusable capability package; the difference from extensions is that skills are mainly instructions and scripts for the model, loaded as needed.

Pi implements the Agent Skills standard, so it can also use skills from tools like Claude Code and OpenAI Codex directly.

How Skills work

Skills adopt the principle of progressive disclosure.

At startup, Pi only puts the name and description of each skill into the system prompt; the model only usesreadthe full skill description when the task matches the tool.

This allows for many skills without filling up the context from the start.

Where are the skills located?

Location Scope of action
~/.pi/agent/skills/ Global
~/.agents/skills/ Global (shared across tools)
.pi/skills/ Project-level (requires project trust)
.agents/skills/ Project-level (cross-tool sharing)

Skill structure

A skill is a directory containingSKILL.mdOrganize the remaining files as you wish:

Original prompt (Chinese, left untranslated)



my-skill/

├── SKILL.md              # 必需:前置信息 + 指令

├── scripts/              # 辅助脚本

│   └── process.sh

├── references/           # 按需加载的详细文档

│   └── api-reference.md

└── assets/

    └── template.json

How to write SKILL.md

The top of SKILL.md is frontmatter, and the rest is the instruction body for the model:

Original prompt (Chinese, left untranslated)



---

name: my-skill

description: 这个技能做什么、什么时候用。要写具体。

---



# My Skill



## Setup



Run once before first use:

```bash

cd /path/to/skill && npm install

Usage

./scripts/process.sh <input>

Original prompt (Chinese, left untranslated)



# The two most important fields in the preamble:



| 字段 | 是否必填 | 说明 |

| --- | --- | --- |

| `name` | 必填 | 最多 64 字符,只能用小写字母、数字、连字符 |

| `description` | 必填 | 最多 1024 字符,决定模型何时加载这个技能,要写得具体 |



> <p>提醒:<code>description</code> 写得好不好,直接决定模型会不会在正确时机用上这个技能。写「处理 PDF 文件,提取文本和表格、填表单、合并多个 PDF」远好过写「帮助处理 PDF」。</p>



### Manual Skill Invocation



The model may not automatically load skills. You can force load and execute using `/skill:name`:



Load and execute skill

/skill:brave-search

Load skill with parameters

/skill:pdf-tools extract

Original prompt (Chinese, left untranslated)



---



## Pi 包管理



扩展、技能、提示模板、主题都可以打包成 Pi 包,通过 npm 或 git 分享安装。



Pi 内置了一套包管理命令,让你像装插件一样扩展能力。



### Installation and Uninstallation



Install a package from npm

pi install npm:@foo/pi-tools

Install from git repository

pi install git:github.com/badlogic/pi-doom

Local project installation (add -l)

pi install npm:@foo/pi-tools -l

Uninstall

pi remove npm:@foo/pi-tools

Original prompt (Chinese, left untranslated)



### 更新与查看



| 命令 | 功能 |

| --- | --- |

| `pi list` | 列出已安装的包 |

| `pi update` | 只更新 Pi 自身 |

| `pi update --all` | 更新 Pi 和所有包 |

| `pi update --extensions` | 只更新包,不动 Pi 本体 |

| `pi update --extension <源>` | 更新指定的某个包 |

| `pi config` | 启用或禁用包里的各项资源 |



---



## Safety Notice



安全是使用 Pi 前必须了解的部分。Pi 的安全模型和很多 Agent 工具不同,需要你主动配合。



### No built-in sandbox



Pi 不包含内置沙箱,它以启动它的用户身份运行,拥有该用户的全部权限。



内置工具可以读写文件、运行 shell 命令;扩展是 TypeScript 模块,权限和 Pi 进程一样。



这是有意为之:Pi 要在本机源码上工作、调用项目工具链、融入开发环境,一个不完整的进程内沙箱会让人误以为是安全边界,实际却仍依赖宿主的 shell、文件系统和凭证。



> <p>重要:真正的隔离必须来自操作系统或容器/虚拟化边界,而不是 Pi 内部。</p>



### 项目信任



项目信任决定 Pi 是否加载项目级的设置、资源、扩展和包。



当一个目录里存在 `.pi/settings.json`、`.pi/extensions`、`.pi/skills`、`.pi/SYSTEM.md` 等内容时,Pi 会要求先信任才能加载。



| 信任级别 | 行为 | 设置方式 |

| --- | --- | --- |

| `ask`(默认) | 交互式询问;非交互模式忽略项目资源 | settings.json 的 `defaultProjectTrust` |

| `always` | 始终信任项目资源 | 同上,或用 `-a` / `--approve` |

| `never` | 从不信任,忽略项目资源 | 同上,或用 `-na` / `--no-approve` |



信任决策保存在 `~/.pi/agent/trust.json`,按目录路径记录,最近的父目录决策优先。



> <p>注意:项目信任只是「输入加载守卫」,它防止仓库静默改你的设置或扩展,但<span class="marked">不能让不可信的代码、提示或模型输出变得安全</span>。仓库文件、注释、文档里的提示注入是本地 Agent 固有的风险,Pi 无法可靠阻止。</p>



### Handling untrusted or unattended tasks



对于不受信任的仓库、需要密切监控的生成代码、或无人值守的自动化,官方建议把 Pi 放进隔离环境里跑。



Recommended approach:



- 把整个 `pi` 进程放进容器、虚拟机或远程沙箱

- 只挂载 Agent 应该访问的工作区路径

- 除非必要,不要挂载宿主的 `~/.pi/agent`(里面有你的凭证和会话)

- 只传最少必要的 API Key,或用短期凭证

- 任务不需要联网时,限制网络访问

- 把结果复制回可信系统前,先审查 diff 和输出



> <p>提醒:如果你把宿主工作区以读写方式挂载进容器,容器内的写入仍会改到宿主文件。要更强地防范误写,用只读挂载,或把文件复制进出沙箱。</p>



---



## Resources and Community



### Official Resources



- GitHub 仓库:[github.com/earendil-works/pi](https://github.com/earendil-works/pi)

- 官网:[pi.dev](https://pi.dev/)

- 官方文档:[pi.dev/docs/latest](https://pi.dev/docs/latest)

- npm 包:[@earendil-works/pi-coding-agent](https://www.npmjs.com/package/@earendil-works/pi-coding-agent)