Pi Agent 包源码逐行解读 — agent-loop.ts & agent.ts

Pi Agent 包源码逐行解读 本文对 packages/agent/src/ 下的 agent-loop.ts(~700 行)和 agent.ts(~540 行)做逐行级的代码解读,涵盖每个函数的设计意图、类型系统、控制流和错误处理策略。 目录 文件概览 agent-loop.ts 逐行解读 类型与导入 agentLoop / agentLoopContinue — 公开入口 runAgentLoop / runAgentLoopContinue — 异步底层 runLoop — 核心双层循环 streamAssistantResponse — LLM 流式调用 executeToolCalls — 工具调度 executeToolCallsSequential / Parallel — 串行与并行 prepareToolCall — 前置管道 executePreparedToolCall — 工具执行 finalizeExecutedToolCall — 后处理 辅助函数 agent.ts 逐行解读 类型与导入 MutableAgentState 与 createMutableAgentState PendingMessageQueue Agent 类 — 构造器 subscribe — 事件订阅 prompt — 发起对话 continue — 继续对话 steer / followUp — 消息队列 abort / waitForIdle / reset — 生命周期控制 私有方法:runPromptMessages / runContinuation runWithLifecycle — 并发控制 handleRunFailure — 失败处理 finishRun — 运行终结 processEvents — 事件归约 createContextSnapshot / createLoopConfig — 适配层 设计模式总结 文件概览 packages/agent/src/ ├── agent-loop.ts # 无状态循环引擎(~700 行,纯函数) ├── agent.ts # 有状态封装层(~540 行,Agent 类) ├── types.ts # 类型定义(~400 行) ├── proxy.ts # HTTP 代理(~320 行) ├── index.ts # 导出入口(~8 行) ├── agent-learn.ts # 学习相关 ├── agent-loop-learn.ts └── README.md 核心分界线: ...

May 29, 2026 · 26 min · 5422 words

Pi-Architecture: Agent

Pi Agent 包架构 packages/agent/src/ 实现了 Pi 框架中的 Agent 运行时,用于构建工具增强型 LLM 对话代理(Tool-Augmented LLM Agent)。 整个包由五个模块组成: 文件 职责 行数 types.ts 类型定义层 ~400 agent-loop.ts 无状态循环引擎 ~700 agent.ts 有状态封装层 ~540 proxy.ts 代理流式函数 ~320 index.ts 导出入口 8 架构总览 graph TD App[外部应用] subgraph "Agent 包" Index[index.ts导出入口] subgraph "类型系统" Types[types.tsAgentMessage / AgentEventAgentLoopConfig / AgentTool] end subgraph "管理层 agent.ts" Agent[Agent 类状态管理 / 队列 / 并发 / 事件] Queue[PendingMessageQueuesteering / follow-up 队列] State[MutableAgentState状态归约] end subgraph "引擎层 agent-loop.ts" Engine[LoopEnginerunAgentLoop / runLoop] LLMCall[streamAssistantResponseLLM 调用] ToolExec[executeToolCalls工具执行] end subgraph "HTTP 代理 proxy.ts" Proxy[streamProxy代理流式函数] end end subgraph "LLM 核心库 @earendil-works/pi-ai" AI[streamSimple / ModelMessage / Tool] end App --> Agent Agent --> Engine Agent --> Queue Agent --> State Engine --> LLMCall Engine --> ToolExec LLMCall --> AI Proxy -- 替代 streamFn --> Agent Agent -.-> Types Engine -.-> Types 分层设计 无状态引擎 vs 有状态封装 Agent 包的核心设计思想是将引擎逻辑与状态管理分离: ...

May 29, 2026 · 13 min · 2577 words