Pi 编程助手完整中文文档

本文档整理了 Pi (π) 编程助手的全部官方文档
版本:2025年3月
原文档位置:/home/pi/docs
总文档数:22个 Markdown 文件


目录

  1. 概述与简介
  2. 扩展系统 Extensions
  3. 技能系统 Skills
  4. SDK 开发包
  5. TUI 组件系统
  6. 模型配置
  7. 提供方配置
  8. 自定义提供方
  9. 键盘快捷键
  10. 主题系统
  11. 会话系统
  12. 树形导航
  13. 压缩与摘要
  14. 设置配置
  15. 提示词模板
  16. 包管理
  17. RPC 模式
  18. JSON 事件流
  19. 终端设置
  20. 开发指南
  21. 平台特定设置

1. 概述与简介

Pi 是一个强大的编程助手,支持通过扩展、技能、主题等方式进行深度定制。

核心特性

  • 自定义工具:通过 pi.registerTool() 注册 LLM 可调用的工具
  • 事件拦截:拦截或修改工具调用、注入上下文、自定义压缩
  • 用户交互:通过 ctx.ui 进行提示、确认、输入、通知
  • 自定义 UI 组件:通过 ctx.ui.custom() 创建复杂交互界面
  • 自定义命令:通过 pi.registerCommand() 注册 /mycommand 命令
  • 会话持久化:通过 pi.appendEntry() 存储跨重启的状态
  • 自定义渲染:控制 TUI 中工具调用/结果和消息的显示方式

常见用例

  • 权限门控(rm -rfsudo 前确认)
  • Git 检查点(每回合 stash,分支上恢复)
  • 路径保护(阻止写入 .envnode_modules/
  • 自定义压缩(按您的方式总结对话)
  • 对话摘要
  • 交互式工具(问题、向导、自定义对话框)
  • 有状态工具(待办列表、连接池)
  • 外部集成(文件监视器、webhook、CI 触发器)

2. 扩展系统 Extensions

2.1 快速开始

扩展是 TypeScript 模块,用于扩展 Pi 的行为。

放置位置(用于 /reload 热重载):

  • ~/.pi/agent/extensions/(全局)
  • .pi/extensions/(项目本地)

快速测试:使用 -e 标志

pi -e ./my-extension.ts

2.2 创建扩展

创建 ~/.pi/agent/extensions/my-extension.ts

import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { Type } from "@sinclair/typebox";

export default function (pi: ExtensionAPI) {
  // 响应事件
  pi.on("session_start", async (_event, ctx) => {
    ctx.ui.notify("Extension loaded!", "info");
  });

  // 拦截危险命令
  pi.on("tool_call", async (event, ctx) => {
    if (event.toolName === "bash" && event.input.command?.includes("rm -rf")) {
      const ok = await ctx.ui.confirm("Dangerous!", "Allow rm -rf?");
      if (!ok) return { block: true, reason: "Blocked by user" };
    }
  });

  // 注册自定义工具
  pi.registerTool({
    name: "greet",
    label: "Greet",
    description: "Greet someone by name",
    parameters: Type.Object({
      name: Type.String({ description: "Name to greet" }),
    }),
    async execute(toolCallId, params, signal, onUpdate, ctx) {
      return {
        content: [{ type: "text", text: `Hello, ${params.name}!` }],
        details: {},
      };
    },
  });

  // 注册命令
  pi.registerCommand("hello", {
    description: "Say hello",
    handler: async (args, ctx) => {
      ctx.ui.notify(`Hello ${args || "world"}!`, "info");
    },
  });
}

2.3 扩展位置

位置 范围
~/.pi/agent/extensions/*.ts 全局(所有项目)
~/.pi/agent/extensions/*/index.ts 全局(子目录)
.pi/extensions/*.ts 项目本地
.pi/extensions/*/index.ts 项目本地(子目录)

通过 settings.json 添加额外路径:

{
  "packages": ["npm:@foo/bar@1.0.0", "git:github.com/user/repo@v1"],
  "extensions": ["/path/to/local/extension.ts"]
}

2.4 可用导入

用途
@mariozechner/pi-coding-agent 扩展类型、事件
@sinclair/typebox 工具参数 Schema
@mariozechner/pi-ai AI 工具类
@mariozechner/pi-tui TUI 组件

2.5 生命周期事件

主要事件:

  • session_directory - CLI 启动时的会话目录解析
  • session_start - 初始会话加载
  • session_before_switch / session_switch - 切换会话
  • session_before_fork / session_fork - 分支会话
  • session_before_compact / session_compact - 压缩会话
  • session_before_tree / session_tree - 树导航
  • session_shutdown - 退出
  • before_agent_start - 用户提交提示后,代理循环前
  • agent_start / agent_end - 代理开始/结束
  • turn_start / turn_end - 回合开始/结束
  • tool_call - 工具执行前(可阻止)
  • tool_result - 工具执行后(可修改)

2.6 ExtensionContext 方法

ctx.ui - UI 交互
  • notify(message, type) - 通知(info/success/warning/error)
  • confirm(title, message) - 确认对话框
  • input(title, placeholder) - 输入对话框
  • select(title, options) - 选择对话框
  • editor(title, prefill) - 编辑器对话框
  • custom(component, options) - 自定义组件
  • setStatus(key, text) - 设置状态栏
  • setWidget(key, lines, options) - 设置小部件
会话管理
  • ctx.sessionManager - 会话管理器(只读)
  • ctx.getContextUsage() - 获取当前上下文使用量
  • ctx.compact(options) - 触发压缩
  • ctx.getSystemPrompt() - 获取当前系统提示

2.7 自定义工具

pi.registerTool({
  name: "my_tool",
  label: "My Tool",
  description: "What this tool does",
  parameters: Type.Object({
    action: StringEnum(["list", "add"] as const),
    text: Type.Optional(Type.String()),
  }),
  async execute(toolCallId, params, signal, onUpdate, ctx) {
    onUpdate?.({ content: [{ type: "text", text: "Working..." }] });
    return {
      content: [{ type: "text", text: "Done" }],
      details: { result: "..." },
    };
  },
});

2.8 输出截断

import { truncateHead, truncateTail, formatSize, DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES } from "@mariozechner/pi-coding-agent";

const truncation = truncateHead(output, {
  maxLines: DEFAULT_MAX_LINES,  // 2000
  maxBytes: DEFAULT_MAX_BYTES,  // 50KB
});

3. 技能系统 Skills

3.1 概述

技能是自包含的能力包,代理按需加载。

3.2 技能位置

  • 全局: ~/.pi/agent/skills/~/.agents/skills/
  • 项目: .pi/skills/.agents/skills/
  • : skills/ 目录或 package.json 中的 pi.skills
  • CLI: --skill <path>

3.3 技能命令

/skill:brave-search           # 加载并执行技能
/skill:pdf-tools extract      # 带参数加载技能

启用:settings.json 中设置 "enableSkillCommands": true

3.4 技能结构

my-skill/
├── SKILL.md              # 必需
├── scripts/              # 辅助脚本
├── references/           # 详细文档
└── assets/               # 资源文件

3.5 SKILL.md Frontmatter

字段 必需 描述
name 最多 64 字符,小写 a-z、0-9、连字符
description 最多 1024 字符
license 许可证
compatibility 环境要求

4. SDK 开发包

4.1 快速开始

import { AuthStorage, createAgentSession, ModelRegistry, SessionManager } from "@mariozechner/pi-coding-agent";

const authStorage = AuthStorage.create();
const modelRegistry = new ModelRegistry(authStorage);

const { session } = await createAgentSession({
  sessionManager: SessionManager.inMemory(),
  authStorage,
  modelRegistry,
});

session.subscribe((event) => {
  if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
    process.stdout.write(event.assistantMessageEvent.delta);
  }
});

await session.prompt("Hello!");

4.2 AgentSession 主要方法

  • prompt(text, options) - 发送提示
  • steer(text) - 中断式队列
  • followUp(text) - 等待完成后队列
  • subscribe(listener) - 订阅事件
  • setModel(model) - 切换模型
  • setThinkingLevel(level) - 设置思考级别
  • newSession(options) - 新建会话
  • fork(entryId) - 分支会话
  • navigateTree(targetId, options) - 树导航
  • compact(instructions) - 压缩上下文

4.3 运行模式

InteractiveMode
import { InteractiveMode } from "@mariozechner/pi-coding-agent";
const mode = new InteractiveMode(session, { initialMessage: "Hello" });
await mode.run();
runPrintMode
import { runPrintMode } from "@mariozechner/pi-coding-agent";
await runPrintMode(session, { mode: "text", initialMessage: "Hello" });
runRpcMode
import { runRpcMode } from "@mariozechner/pi-coding-agent";
await runRpcMode(session);

5. TUI 组件系统

5.1 组件接口

interface Component {
  render(width: number): string[];
  handleInput?(data: string): void;
  wantsKeyRelease?: boolean;
  invalidate(): void;
}

5.2 内置组件

import { Text, Box, Container, Spacer, Markdown } from "@mariozechner/pi-tui";

5.3 键盘输入

import { matchesKey, Key } from "@mariozechner/pi-tui";

handleInput(data: string) {
  if (matchesKey(data, Key.up)) { /* ... */ }
  else if (matchesKey(data, Key.ctrl("c"))) { /* ... */ }
}

6. 模型配置 (models.md)

6.1 最小示例

{
  "providers": {
    "ollama": {
      "baseUrl": "http://localhost:11434/v1",
      "api": "openai-completions",
      "apiKey": "ollama",
      "models": [{ "id": "llama3.1:8b" }]
    }
  }
}

6.2 支持的 API

  • openai-completions - OpenAI Chat Completions
  • openai-responses - OpenAI Responses API
  • anthropic-messages - Anthropic Messages API
  • google-generative-ai - Google Generative AI

6.3 模型配置字段

字段 必需 默认 描述
id 模型标识符
name id 显示名称
api 提供方 API 类型
reasoning false 支持扩展思考
input ["text"] 输入类型
contextWindow 128000 上下文窗口
maxTokens 16384 最大输出 token

7. 提供方配置 (providers.md)

7.1 订阅提供方

在交互模式中使用 /login

  • Claude Pro/Max
  • ChatGPT Plus/Pro (Codex)
  • GitHub Copilot
  • Google Gemini CLI
  • Google Antigravity

使用 /logout 清除凭证。

7.2 API 密钥环境变量

提供方 环境变量
Anthropic ANTHROPIC_API_KEY
OpenAI OPENAI_API_KEY
Google GEMINI_API_KEY
Groq GROQ_API_KEY
xAI XAI_API_KEY
OpenRouter OPENROUTER_API_KEY

8. 自定义提供方 (custom-provider.md)

8.1 覆盖现有提供方

pi.registerProvider("anthropic", {
  baseUrl: "https://proxy.example.com"
});

8.2 注册新提供方

pi.registerProvider("my-llm", {
  baseUrl: "https://api.my-llm.com/v1",
  apiKey: "MY_LLM_API_KEY",
  api: "openai-completions",
  models: [{
    id: "my-llm-large",
    name: "My LLM Large",
    reasoning: true,
    input: ["text", "image"],
    cost: { input: 3.0, output: 15.0, cacheRead: 0.3, cacheWrite: 3.75 },
    contextWindow: 200000,
    maxTokens: 16384
  }]
});

8.3 OAuth 支持

pi.registerProvider("corporate-ai", {
  baseUrl: "https://ai.corp.com/v1",
  api: "openai-responses",
  models: [...],
  oauth: {
    name: "Corporate AI (SSO)",
    async login(callbacks) {
      callbacks.onAuth({ url: "https://sso.corp.com/authorize?..." });
      const code = await callbacks.onPrompt({ message: "Enter SSO code:" });
      const tokens = await exchangeCodeForTokens(code);
      return { refresh: tokens.refreshToken, access: tokens.accessToken, expires: Date.now() + tokens.expiresIn * 1000 };
    },
    async refreshToken(credentials) { /* ... */ },
    getApiKey(credentials) { return credentials.access; }
  }
});

9. 键盘快捷键 (keybindings.md)

9.1 按键格式

modifier+key,修饰符:ctrlshiftalt(可组合)

9.2 主要快捷键

操作 默认
cursorUp / cursorDown up / down
cursorLeft / cursorRight left / right
cursorWordLeft / cursorWordRight alt+left / alt+right
deleteCharBackward backspace
deleteCharForward delete
deleteWordBackward ctrl+w
submit enter
newLine shift+enter
interrupt escape
exit ctrl+d
selectModel ctrl+l
cycleModelForward ctrl+p
expandTools ctrl+o

9.3 自定义配置

创建 ~/.pi/agent/keybindings.json

{
  "cursorUp": ["up", "ctrl+p"],
  "cursorDown": ["down", "ctrl+n"]
}

10. 主题系统 (themes.md)

10.1 主题位置

  • 内置: dark, light
  • 全局: ~/.pi/agent/themes/*.json
  • 项目: .pi/themes/*.json

10.2 创建主题

{
  "$schema": "https://raw.githubusercontent.com/badlogic/pi-mono/main/packages/coding-agent/src/modes/interactive/theme/theme-schema.json",
  "name": "my-theme",
  "vars": {
    "primary": "#00aaff",
    "secondary": 242
  },
  "colors": {
    "accent": "primary",
    "text": "",
    "success": "#00ff00",
    "error": "#ff0000",
    "warning": "#ffff00"
  }
}

10.3 颜色令牌(共51个)

  • 核心 UI: accent, border, success, error, warning, text, …
  • 背景: selectedBg, userMessageBg, toolPendingBg, …
  • Markdown: mdHeading, mdLink, mdCode, …
  • 语法高亮: syntaxComment, syntaxKeyword, syntaxFunction, …
  • 思考级别: thinkingOff, thinkingMinimal, thinkingLow, …

11. 会话系统 (session.md)

11.1 会话文件格式

会话存储为 JSONL(JSON Lines)文件:

~/.pi/agent/sessions/--<path>--/<timestamp>_<uuid>.jsonl

11.2 消息类型

  • UserMessage - 用户消息
  • AssistantMessage - 助手消息
  • ToolResultMessage - 工具结果
  • BashExecutionMessage - Bash 执行
  • CustomMessage - 扩展自定义消息
  • BranchSummaryMessage - 分支摘要
  • CompactionSummaryMessage - 压缩摘要

11.3 SessionManager API

// 静态创建方法
SessionManager.create(cwd, sessionDir?)           // 新会话
SessionManager.open(path)                         // 打开现有会话
SessionManager.continueRecent(cwd)                // 继续最近会话
SessionManager.inMemory(cwd?)                     // 内存会话

// 实例方法
appendMessage(message)                            // 添加消息
appendCompaction(summary, firstKeptEntryId, tokensBefore)
branch(entryId)                                   // 分支
getBranch(fromId?)                                // 获取分支
getTree()                                         // 获取树结构
buildSessionContext()                             // 构建 LLM 上下文

12. 树形导航 (tree.md)

12.1 /tree 命令

提供基于树的会话历史导航。

12.2 与 /fork 的区别

特性 /fork /tree
视图 用户消息平面列表 完整树结构
操作 提取到新会话文件 在同一会话中更改叶子
摘要 从不 可选

12.3 控件

操作
↑/↓ 导航
←/→ 向上/向下翻页
Ctrl+←/→ 折叠/展开
Enter 选择节点
Escape 取消
Ctrl+U 仅用户消息
Ctrl+O 显示所有

12.4 事件

  • session_before_tree - 可以取消或提供自定义摘要
  • session_tree - 导航完成

13. 压缩与摘要 (compaction.md)

13.1 概述

机制 触发 目的
压缩 上下文超过阈值或 /compact 总结旧消息以释放上下文
分支摘要 /tree 导航 切换分支时保留上下文

13.2 压缩触发

自动压缩在以下情况触发:

contextTokens > contextWindow - reserveTokens

默认:reserveTokens = 16384

13.3 设置

{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000
  }
}

13.4 摘要格式

## Goal
[用户试图完成的目标]

## Constraints & Preferences
- [用户提到的要求]

## Progress
### Done
- [x] [已完成任务]

### In Progress
- [ ] [当前工作]

## Key Decisions
- **[决策]**: [理由]

## Next Steps
1. [接下来应该做什么]

## Critical Context
- [继续所需的数据]

<read-files>
path/to/file1.ts
</read-files>

<modified-files>
path/to/changed.ts
</modified-files>

14. 设置配置 (settings.md)

14.1 设置位置

位置 范围
~/.pi/agent/settings.json 全局
.pi/settings.json 项目(覆盖全局)

14.2 主要设置

模型与思考
  • defaultProvider - 默认提供方
  • defaultModel - 默认模型
  • defaultThinkingLevel - 默认思考级别
  • hideThinkingBlock - 隐藏思考块
  • thinkingBudgets - 自定义思考 token 预算
UI 与显示
  • theme - 主题名称
  • quietStartup - 隐藏启动标题
  • doubleEscapeAction - 双 Esc 动作
  • editorPaddingX - 编辑器水平内边距
  • showHardwareCursor - 显示终端光标
压缩
{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000
  }
}
重试
{
  "retry": {
    "enabled": true,
    "maxRetries": 3,
    "baseDelayMs": 2000,
    "maxDelayMs": 60000
  }
}
资源
  • packages - npm/git 包
  • extensions - 本地扩展路径
  • skills - 本地技能路径
  • prompts - 本地提示词模板路径
  • themes - 本地主题路径

15. 提示词模板 (prompt-templates.md)

15.1 位置

  • 全局: ~/.pi/agent/prompts/*.md
  • 项目: .pi/prompts/*.md

15.2 格式

---
description: Review staged git changes
---
Review the staged changes (`git diff --cached`). Focus on:
- Bugs and logic errors
- Security issues

15.3 使用

/review                           # 展开 review.md
/component Button                 # 带参数展开

15.4 参数

  • $1, $2, … - 位置参数
  • $@$ARGUMENTS - 所有参数连接
  • ${@:N} - 从第 N 个位置开始的参数

16. 包管理 (packages.md)

16.1 安装与管理

pi install npm:@foo/bar@1.0.0
pi install git:github.com/user/repo@v1
pi install /absolute/path/to/package
pi remove npm:@foo/bar
pi list
pi update

使用 -l 写入项目设置。

16.2 包源

npm:

npm:@scope/pkg@1.2.3
npm:pkg

git:

git:github.com/user/repo@v1
https://github.com/user/repo@v1
ssh://git@github.com/user/repo@v1

16.3 创建包

package.json 中添加 pi 清单:

{
  "name": "my-package",
  "keywords": ["pi-package"],
  "pi": {
    "extensions": ["./extensions"],
    "skills": ["./skills"],
    "prompts": ["./prompts"],
    "themes": ["./themes"]
  }
}

17. RPC 模式 (rpc.md)

17.1 启动 RPC 模式

pi --mode rpc [options]

17.2 主要命令

提示
{"type": "prompt", "message": "Hello!"}
{"type": "steer", "message": "Stop and do this"}
{"type": "follow_up", "message": "After you're done..."}
状态
{"type": "get_state"}
{"type": "get_messages"}
模型
{"type": "set_model", "provider": "anthropic", "modelId": "claude-sonnet-4"}
{"type": "cycle_model"}
{"type": "get_available_models"}
会话
{"type": "new_session"}
{"type": "switch_session", "sessionPath": "/path/to/session.jsonl"}
{"type": "fork", "entryId": "abc123"}

17.3 事件

  • agent_start / agent_end
  • turn_start / turn_end
  • message_start / message_update / message_end
  • tool_execution_start / tool_execution_update / tool_execution_end

18. JSON 事件流 (json.md)

pi --mode json "Your prompt"

输出所有会话事件为 JSON 行到 stdout。


19. 终端设置 (terminal-setup.md)

19.1 Kitty, iTerm2

开箱即用。

19.2 Ghostty

keybind = alt+backspace=text:\x1b\x7f

19.3 WezTerm

local wezterm = require 'wezterm'
local config = wezterm.config_builder()
config.enable_kitty_keyboard = true
return config

19.4 VS Code

{
  "key": "shift+enter",
  "command": "workbench.action.terminal.sendSequence",
  "args": { "text": "\u001b[13;2u" },
  "when": "terminalFocus"
}

19.5 Windows Terminal

{
  "actions": [
    { "command": { "action": "sendInput", "input": "\u001b[13;2u" }, "keys": "shift+enter" }
  ]
}

20. 开发指南 (development.md)

20.1 设置

git clone https://github.com/badlogic/pi-mono
cd pi-mono
npm install
npm run build

20.2 运行测试

./test.sh                         # 运行非 LLM 测试
npm test                          # 运行所有测试
npm test -- test/specific.test.ts # 运行特定测试

20.3 项目结构

packages/
  ai/           # LLM 提供方抽象
  agent/        # 代理循环和消息类型
  tui/          # 终端 UI 组件
  coding-agent/ # CLI 和交互模式

21. 平台特定设置

21.1 Termux (Android)

pkg update && pkg upgrade
pkg install nodejs termux-api git
npm install -g @mariozechner/pi-coding-agent
mkdir -p ~/.pi/agent
pi

限制:无图像剪贴板,无原生二进制文件。

21.2 tmux

添加到 ~/.tmux.conf

set -g extended-keys on
set -g extended-keys-format csi-u

然后完全重启 tmux:

tmux kill-server
tmux

21.3 Windows

Pi 需要 bash shell。检查位置:

  1. 自定义路径来自 settings.json
  2. Git Bash
  3. bash.exe 在 PATH 中(Cygwin、MSYS2、WSL)

自定义 Shell 路径:

{
  "shellPath": "C:\\cygwin64\\bin\\bash.exe"
}

21.4 Shell 别名

启用 shell 别名:

{
  "shellCommandPrefix": "shopt -s expand_aliases\neval \"$(grep '^alias ' ~/.zshrc)\""
}

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐