文章目录
一、Pi 架构概览
Pi 是一个 TypeScript 单体仓库(Monorepo),包含四个核心包:
packages/
ai/ # LLM 提供商抽象(pi-ai)
agent/ # Agent 循环和消息类型(pi-agent-core)
tui/ # 终端 UI 组件库(pi-tui)
coding-agent/ # CLI 和交互模式(pi-coding-agent)
每个包各司其职,形成清晰的分层架构:
| 包 | 职责 | 暴露的核心能力 |
|---|---|---|
pi-ai |
模型提供商抽象 | 多提供商统一流式 API、模型注册表、Auth 管理 |
pi-agent-core |
Agent 核心循环 | 消息管理、工具执行、回合循环、压缩逻辑 |
pi-tui |
终端 UI 框架 | 保留模式渲染、组件系统、主题系统、键盘输入 |
pi-coding-agent |
编码代理主程序 | CLI、交互模式、扩展系统、会话管理 |
1.1 四种运行模式
Pi 提供四种集成方式,满足不同场景需求:
| 模式 | 适用场景 | 特点 |
|---|---|---|
| Interactive | 终端直接使用 | 完整 TUI 交互,最常用 |
| 一次性查询 | 非交互,输出文本后退出 | |
| RPC | 子进程集成 | JSONL 协议,双向通信 |
| SDK | Node.js 应用嵌入 | 直接 API 调用,最高灵活性 |
建议:对于 Node.js/TypeScript 用户,优先使用 SDK 直接嵌入,而非子进程方式(RPC/JSON)。
二、SDK 编程接口
2.1 快速开始
包名:@earendil-works/pi-coding-agent
import {
AuthStorage,
createAgentSession,
ModelRegistry,
SessionManager
} from "@earendil-works/pi-coding-agent";
// 初始化核心组件
const authStorage = AuthStorage.create();
const modelRegistry = ModelRegistry.create(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("What files are in the current directory?");
2.2 AgentSession 接口
AgentSession 是 SDK 的核心接口,提供完整的会话控制能力:
interface AgentSession {
// 发送消息
prompt(text: string, options?: PromptOptions): Promise<void>;
steer(text: string): Promise<void>;
followUp(text: string): Promise<void>;
// 事件订阅
subscribe(listener: (event: AgentSessionEvent) => void): () => void;
// 会话信息
sessionFile: string | undefined;
sessionId: string;
// 模型控制
setModel(model: Model): Promise<void>;
setThinkingLevel(level: ThinkingLevel): void;
cycleModel(): Promise<ModelCycleResult | undefined>;
cycleThinkingLevel(): ThinkingLevel | undefined;
// 状态访问
agent: Agent;
model: Model | undefined;
thinkingLevel: ThinkingLevel;
messages: AgentMessage[];
isStreaming: boolean;
// 树导航
navigateTree(targetId: string, options?: {
summarize?: boolean;
customInstructions?: string;
replaceInstructions?: boolean;
label?: string;
}): Promise<{
editorText?: string; cancelled: boolean }>;
// 压缩
compact(customInstructions?: string): Promise<CompactionResult>;
abortCompaction(): void;
// 控制
abort(): Promise<


2114

被折叠的 条评论
为什么被折叠?



