图解 Pi AgentPi Agent, Illustratedv1.1.0
包Packages
演示Slides
v1.1.0Pi v1.1.0 源码分析Analysis of Pi v1.1.0 · 2026-10-07

图解 Pi AgentPi Agent,
Illustrated

基于 Pi v1.1.0 源码逐行核对的架构导读。总览页给出全局;全部 14 个包都有自己的深挖子页面——四个核心包 coding-agent、agent-core、pi-ai、tui,能力包 mcp、codemode、telemetry,运行时 chord、durable、env,远程会话三件套 protocol、client、server,以及私有的评测包 evals。共 125 张手绘架构图,每个结论都链接到 v1.1.0 标签中的具体代码行。An architecture walkthrough checked line by line against the Pi v1.1.0 source. This overview gives the big picture, and all 14 packages have their own deep-dive page — the four core packages coding-agent, agent-core, pi-ai and tui; the capabilities mcp, codemode and telemetry; the runtime chord, durable and env; the remote-session trio protocol, client and server; and the private evals package. 125 hand-laid diagrams, and every claim links to the exact lines at tag v1.1.0.

14
个 workspace 包workspace packages
177k
行 TypeScript 源码lines of TS source
185k
行测试代码lines of tests
42
个内置 LLM providerbuilt-in LLM providers
8
个内置工具built-in tools
41
种扩展事件extension events
33
种 RPC 命令RPC command types
125
张手绘架构图hand-laid diagrams
01Packages

14 个包The 14 packages#

一句话结论Takeaway从这里进入每个包的子页面。核心栈是 coding-agent → agent-core → pi-ai,外加 tui;其余包提供 MCP、代码沙箱、遥测、持久化运行时与远程会话。Enter each package's page from here. The core stack is coding-agent → agent-core → pi-ai, plus tui; the rest provide MCP, the code sandbox, telemetry, the durable runtime and remote sessions.

核心栈Core stack
能力包Capabilities
持久化与运行时Durable runtime
远程会话Remote sessions
工具链Tooling
第一版中按包划分的章节已迁移到对应子页面(旧链接 index.html#loop 等会自动跳转):First-edition sections that belong to one package now live on that package's page (old links such as index.html#loop redirect automatically):

如何阅读这些图How to read the diagrams

Run modespi-coding-agentExtensionspi-agent-corepi-aipi-tuiInfra
  • 颜色 = 代码所在的层 / 包,所有页面、图、表与幻灯片一致。Colour = the layer / package the code lives in, identical across every page, diagram, table and slide.
  • 圆角容器 = 包或层;卡片 = 类、函数或组件;深色胶囊 = 起止点;红色 = 错误路径。Rounded containers = packages or layers; cards = classes, functions or components; dark pill = start / end; red = error path.
  • 实线箭头 = 调用 / 依赖;虚线 = 事件、异步返回或 devDependency;流动的虚线标出主路径;圆形数字 = 执行顺序。Solid arrow = call / dependency; dashed = event, async return or devDependency; animated dashes mark the main path; numbered circles = execution order.
  • 每张图都带图例。鼠标悬停某个组件会高亮它的连线;点击图可放大、滚轮缩放、拖动平移。Every diagram carries its own legend. Hover a component to highlight its connections; click to enlarge, wheel to zoom, drag to pan.
02pi-coding-agent

包依赖图Package dependency graph#

一句话结论Takeaway14 个 npm workspace 包,pi-coding-agent 位于顶端;运行时栈只有四层,其余包互相解耦。14 npm workspace packages with pi-coding-agent on top; the runtime stack is only four packages deep and everything else is decoupled.

内部依赖:实线 = dependencies,虚线 = devDependenciesInternal deps: solid = dependencies, dashed = devDependencies
← 左右滑动查看,点击放大 →← swipe to scroll, tap to enlarge →
Package dependency graph运行时栈RUNTIME STACK独立库STANDALONE无内部依赖no internal deps持久化与远程会话DURABLE & REMOTE SESSIONSpi-coding-agentAgentSession · 8 工具AgentSession · toolspi-agent-coreAgent · runLoop()pi-ai42 provider · 10 种 API42 providers · 10 APIspi-telemetry遥测契约telemetry contractspi-tui差分渲染differential renderpi-mcpMCP 客户端MCP clientpi-codemode沙箱 JS 执行sandboxed JSpi-server实验性服务端experimental serverpi-client远程会话客户端remote clientpi-protocolCBOR 帧协议CBOR protocolpi-durable持久化运行时durable runtimepi-env经 SSH 远程执行remote exec · SSHpi-evals评测工具eval harnesschord应用组合运行时:services · 复制状态 · RPC · pluginsapplication composition runtime — services · replicated state · RPC · pluginspi-durable → pi-ai5 个包都依赖 chordall 5 depend on chorddevdevDependencies(仅测试):pi-server · pi-client · pi-protocoldevDependencies (tests only): pi-server · pi-client · pi-protocoldependency(运行时依赖)dependencydevDependency(开发依赖)devDependency四层运行时栈the 4-deep runtime stackpi-coding-agentpi-agent-corepi-aipi-tui其他包other packages

要点Key points

  • pi-coding-agent 直接依赖 pi-agent-core、pi-ai、pi-tui、pi-mcp、pi-codemode 和 chord。pi-coding-agent depends on pi-agent-core, pi-ai, pi-tui, pi-mcp, pi-codemode and chord.
  • pi-ai 唯一的内部依赖是 pi-telemetry;pi-tui、pi-mcp、pi-codemode、chord 没有任何内部依赖,可以独立使用。pi-ai's only internal dependency is pi-telemetry; pi-tui, pi-mcp, pi-codemode and chord have none and can be used standalone.
  • Durable 与远程会话是一组独立的包:pi-durable、pi-env、pi-protocol、pi-client、pi-server,都构建在 chord 之上。Durable and remote sessions form a separate cluster — pi-durable, pi-env, pi-protocol, pi-client, pi-server — all built on chord.
  • 虚线是 devDependencies:pi-coding-agent 只在测试中使用 client / protocol / server;pi-evals 依赖 coding-agent 与 ai。Dashed edges are devDependencies: pi-coding-agent only uses client / protocol / server in tests; pi-evals depends on coding-agent and ai.

工作原理How it works

  1. 根 package.json 用 npm workspaces 管理 packages/*。The root package.json manages packages/* with npm workspaces.
  2. npm run build 按拓扑顺序依次构建:chord → tui → telemetry → codemode → mcp → ai → durable → env → agent → protocol → client → server → coding-agent。npm run build builds in topological order: chord → tui → telemetry → codemode → mcp → ai → durable → env → agent → protocol → client → server → coding-agent.
  3. 图中的边直接取自每个包 package.json 里的 @earendil-works/* 依赖。Edges are read from each package's @earendil-works/* entries in package.json.

关键文件Key files · v1.1.0

文件File符号Symbol作用Role
package.jsonL15scripts.buildworkspace 与构建顺序workspaces and build order
packages/coding-agent/package.jsonL49dependencies顶层 CLI 的依赖top-level CLI dependencies
packages/agent/package.jsonL25dependenciesagent core 只依赖 pi-aiagent core depends only on pi-ai
packages/ai/package.jsonL69dependenciesLLM 层与 vendor SDKLLM layer and vendor SDKs
03pi-coding-agent

分层架构Layered architecture#

一句话结论Takeaway请求自上而下穿过四层:运行模式 → AgentSession → Agent 循环 → pi-ai 统一事件流。A request passes down four layers: run mode → AgentSession → the Agent loop → pi-ai's normalized event stream.

自上而下的四层运行时栈The four-layer runtime stack, top to bottom
← 左右滑动查看,点击放大 →← swipe to scroll, tap to enlarge →
Layered architecture运行模式RUN MODES共享同一个运行时all share one runtimepi-coding-agent会话编排session orchestrationAgentSessionprompt() · steer() · followUp() · compact() · bindExtensions()pi-agent-coreAgentSession 注入的钩子hooks set by AgentSessionpi-aipi-tui仅 interactiveinteractive onlyJSONL宿主应用 / IDEHost app / IDEpipe脚本 / CIScripts / CITTY开发者DeveloperrunRpcMode()33 种 JSONL 命令 · 事件33 JSONL commands · eventsrunPrintMode()text · json,一次性text · json, one-shotInteractiveMode编辑器 · 聊天视图 · /命令editor · chat view · /commandsAgentSessionRuntime持有当前会话 · newSession() · switchSession() · fork() 时整体替换owns the current session · replaced wholesale on newSession() · switchSession() · fork()SessionManager只追加的 JSONL 树append-only JSONL treeExtensionRunner41 种事件 · register*41 events · register*8 个内置工具8 built-in toolsread · bash · edit · write …compaction摘要 + 保留尾部summary + kept tailModelRuntime实现 pi-ai 的 Modelsimplements pi-ai ModelsResourceLoader扩展 · skills · promptsextensions · skills · promptsAgent状态 · 两个消息队列state · two message queuesrunLoop()内层 + 外层循环inner + outer looptransformContextconvertToLlmprepareNextTurnprepareRequestbeforeToolCallafterToolCallfinishTurnModelsgetModel · checkAuthproviders/*42 个内置 provider42 built-in providersapi/*.lazy.ts10 种对话 API · 懒加载10 chat APIs · lazyAssistantMessageEventStreamstart · text_* · thinking_* · toolcall_* · done · errorTuiMainScreen主屏 · 保留 scrollbackmain buffer · scrollbackTuiAltScreen备用屏 · 全屏alt screen · fullscreenComponentrender(width) → string[]ProcessTerminalStdinBuffer → 按键StdinBuffer → keysEditorMarkdownSelectListLoaderImageScrollView内置组件,还有 Input、Stack …built-ins, plus Input, Stack …prompt ↓ · 事件 ↑prompt ↓ · events ↑agent.prompt()注入installsstreamFn = modelRuntime.streamSimple()事件流回到循环events back to the loop12345

要点Key points

  • pi-ai:把 42 个内置 provider 归一为一套流式事件协议 AssistantMessageEventStream。pi-ai normalizes 42 built-in providers into one streaming protocol, AssistantMessageEventStream.
  • pi-agent-core:与具体产品无关的工具调用循环,所有策略通过 AgentLoopConfig 钩子注入。pi-agent-core is a product-agnostic tool-calling loop; all policy is injected through AgentLoopConfig hooks.
  • pi-coding-agent:AgentSession 组装会话、8 个内置工具、扩展、压缩、设置与模型解析。pi-coding-agent: AgentSession wires in sessions, 8 built-in tools, extensions, compaction, settings and model resolution.
  • 运行模式:interactive、print(text / json)和 rpc 共享同一个 AgentSessionRuntime;只有 interactive 使用 pi-tui。Run modes: interactive, print (text / json) and rpc share one AgentSessionRuntime; only interactive uses pi-tui.

工作原理How it works

  1. 模式层调用 AgentSessionRuntime,它持有当前 AgentSession,并在 new / switch / fork 时整体替换会话。Modes call AgentSessionRuntime, which owns the current AgentSession and replaces it wholesale on new / switch / fork.
  2. AgentSession 把自己的逻辑挂到 Agent 的钩子上:prepareNextTurn、prepareRequest、finishTurn、beforeToolCall 等。AgentSession attaches its logic to the Agent hooks: prepareNextTurn, prepareRequest, finishTurn, beforeToolCall and more.
  3. sdk.ts 把 streamFn 设为 modelRuntime.streamSimple(),由 Models 注册表找到 provider 和对应的 API 实现。sdk.ts sets streamFn to modelRuntime.streamSimple(); the Models registry resolves the provider and its API implementation.

关键文件Key files · v1.1.0

文件File符号Symbol作用Role
packages/coding-agent/src/core/agent-session.tsL378AgentSession核心编排对象(约 4.4k 行)the core orchestrator (~4.4k lines)
packages/coding-agent/src/core/agent-session-runtime.tsL74AgentSessionRuntime会话生命周期与替换session lifecycle and replacement
packages/coding-agent/src/core/sdk.tsL420streamFn把 Agent 接到 ModelRuntimeconnects Agent to ModelRuntime
packages/agent/src/agent.tsL188Agent状态、队列与钩子state, queues and hooks
packages/ai/src/models.tsL250Modelsprovider / model 注册表provider / model registry
04pi-coding-agent

一次提示的完整时序One prompt, end to end#

一句话结论Takeaway一次用户输入会经过扩展拦截、两次 LLM 请求和一次工具执行;每条消息在 message_end 时写入会话文件。One user prompt passes extension interception, two LLM requests and a tool run; every message is persisted to the session file on message_end.

Interactive 模式下的一次提示(含一次 bash 工具调用)One prompt in interactive mode, with one bash tool call
← 左右滑动查看,点击放大 →← swipe to scroll, tap to enlarge →
One prompt, end to end运行模式run modepi-coding-agentpi-agent-corepi-aiInteractiveModeAgentSessionExtensionRunnerSessionManager工具 · bashTool · bashAgent · runLoopstreamFn · pi-ai1 · 预处理1 · Preprocess2 · 请求 12 · Request 13 · 工具调用3 · Tool call4 · 请求 24 · Request 2prompt(text)input · 可改写或接管input · may rewrite / handle展开 skill 与模板expand skills · templatesbefore_agent_startagent.prompt() → runAgentLoop()message_end(user)appendMessage()context · 每次请求前context · before every requeststreamFn(model, ctx)text_delta …message_update重绘(批处理)re-render (batched)done(toolUse)message_end(assistant)appendMessage()tool_call · 可阻止tool_call · may blockexecute(…)onUpdate … 结果onUpdate … resulttool_result · 可改写tool_result · may rewritemessage_end(toolResult)appendMessage()streamFn(含结果)streamFn(+ result)done(stop)message_end · turn_end · agent_endappendMessage()idle · 等待输入idle · ready for input每个 message_end 都追加到会话 JSONLevery message_end is appended to the session JSONL1234567891011121314151617181920212223242526调用call事件 / 返回event / return1顺序编号,颜色 = 发起方order · colour = caller

要点Key points

  • AgentSession.prompt() 的顺序:扩展命令 → input 事件 → 展开 skill 与 prompt template → 若正在流式输出则排队为 steer / follow-up → 预检压缩 → before_agent_start → agent.prompt()。AgentSession.prompt() order: extension commands → input event → expand skills and prompt templates → queue as steer / follow-up if streaming → pre-prompt compaction check → before_agent_start → agent.prompt().
  • pi-ai 的流事件(text_delta、toolcall_delta 等)在 agent 层变成 message_update。pi-ai stream events (text_delta, toolcall_delta, …) become message_update agent events.
  • transformContext 在 coding agent 中调用 emitContext(),扩展可以在每次请求前改写消息。In the coding agent transformContext calls emitContext(), so extensions can rewrite messages before every request.

工作原理How it works

  1. Interactive 模式订阅会话事件,每个 delta 都触发一次(批处理后的)重绘。Interactive mode subscribes to session events; each delta triggers a (batched) re-render.
  2. AgentSession 在每个 message_end 时调用 sessionManager.appendMessage(),会话文件随每条完成的消息增量写入。AgentSession calls sessionManager.appendMessage() on every message_end, so the session file grows with each completed message.
  3. 工具结果追加到上下文后,循环自动发起下一次请求,直到模型以 stop 结束。After tool results join the context the loop issues the next request automatically, until the model ends with stop.

关键文件Key files · v1.1.0

文件File符号Symbol作用Role
packages/coding-agent/src/core/agent-session.tsL1968AgentSession.prompt()提示预处理流水线prompt preprocessing pipeline
packages/coding-agent/src/core/agent-session.tsL1162appendMessagemessage_end 时持久化persists on message_end
packages/coding-agent/src/core/sdk.tsL439emitContexttransformContext → 扩展transformContext → extensions
packages/ai/src/types.tsL788AssistantMessageEvent12 种流事件the 12 stream event types
05pi-coding-agent

核心类型Key types#

一句话结论TakeawayAgentSessionRuntime 持有 AgentSession,后者组合 Agent、SessionManager、ExtensionRunner 和 ModelRuntime。AgentSessionRuntime owns an AgentSession, which composes Agent, SessionManager, ExtensionRunner and ModelRuntime.

主要类与接口及其组合关系Main classes and interfaces and how they compose
← 左右滑动查看,点击放大 →← swipe to scroll, tap to enlarge →
Key typesAgentSessionRuntime+session: AgentSession+services+newSession()+switchSession()+fork()+importFromJsonl()+dispose()SessionManager−byId · leafId+appendMessage()+appendCompaction()+getBranch() · getTree()+branch() · branchWithSummary()+buildSessionContext()+createBranchedSession()AgentSession+agent: Agent+sessionManager+settingsManager−_extensionRunner · _modelRuntime+prompt(text, options)+steer() · followUp()+setModel() · cycleModel()+compact() · navigateTree()+bindExtensions() · reload()+executeBash() · subscribe()ExtensionRunner+bindCore(actions)+setUIContext(ui, mode)+emit(event)+emitToolCall() · emitToolResult()Agent+state: AgentState+streamFunction: StreamFn+toolExecution+convertToLlm · transformContext+beforeToolCall · afterToolCall+prepareRequest · prepareNextTurn+finishTurn+prompt() · continue()+steer() · followUp()+abort() · waitForIdle()«interface»AgentTool+name · label · parameters+executionMode?+prepareArguments?(args)+execute(toolCallId, params, …)ModelRuntime+streamSimple(model, ctx)+getAuth() · checkAuth()+registerProvider(id, config)+resolveModel()«interface» pi-aiModels+getProviders() · getModel()+getAvailable() · refresh()+streamSimple()«interface»Provider+id · name · auth+getModels()+stream() · streamSimple()sessionagentsessionManager创建并 bindCore()creates · bindCore()_modelRuntimestate.tools *implementsgetProviders() *字段与方法均为节选members are a selection组合(持有)composition (owns)聚合 / 引用aggregation / reference实现接口implements调用 / 依赖calls / uses

要点Key points

  • Agent 的钩子都是公开字段(beforeToolCall、prepareRequest、finishTurn …),由上层直接赋值或包装。Agent hooks are public fields (beforeToolCall, prepareRequest, finishTurn, …) that the layer above assigns or wraps.
  • ModelRuntime 实现 pi-ai 的 Models 接口,并允许扩展通过 registerProvider 注册 provider。ModelRuntime implements pi-ai's Models interface and lets extensions register providers via registerProvider.
  • ExtensionRunner 在 AgentSession 内部创建,bindCore() 把会话动作暴露给扩展。ExtensionRunner is created inside AgentSession; bindCore() exposes session actions to extensions.

工作原理How it works

  1. Agent 维护 steering 与 follow-up 两个队列(PendingMessageQueue),转化为循环的 getSteeringMessages / getFollowUpMessages。Agent keeps two queues (PendingMessageQueue) for steering and follow-up and exposes them to the loop as getSteeringMessages / getFollowUpMessages.
  2. AgentSessionRuntime.fork() / switchSession() 先发出 session_before_* 扩展事件,再拆除当前会话并创建新会话。AgentSessionRuntime.fork() / switchSession() emit session_before_* extension events, then tear down the current session and create a new one.

关键文件Key files · v1.1.0

文件File符号Symbol作用Role
packages/agent/src/agent.tsL188Agent队列、状态与订阅queues, state, subscription
packages/coding-agent/src/core/agent-session-runtime.tsL262fork()会话替换session replacement
packages/coding-agent/src/core/session-manager.tsL987SessionManagerJSONL 树存储JSONL tree store
packages/coding-agent/src/core/extensions/runner.tsL357ExtensionRunner事件分发event dispatch
packages/coding-agent/src/core/model-runtime.tsL172ModelRuntimeimplements Modelsimplements Models
06Repository

仓库统计Repository stats#

一句话结论Takeaway约 177k 行源码、185k 行测试;coding-agent 一个包就占了 48% 的源码,测试代码量与源码相当。About 177k lines of source and 185k of tests; coding-agent alone is 48% of the source, and test code roughly matches source code.

统计自标签 v1.1.0(abe508e):只计 .ts(不含 .d.ts),排除 node_modules 与 dist;src = src/ 下,test = test*/ 下或 *.test.*。Counted at tag v1.1.0 (abe508e): .ts only (no .d.ts), node_modules and dist excluded; src = under src/, test = under test*/ or *.test.*.

源码行数src LOC测试行数test LOC
包Package源文件src files源码行src LOC测试文件test files测试行test LOC全部 .tsall .ts
coding-agent29885,81633171,137735
ai19626,79717343,028379
durable6720,4049029,837159
tui4619,4095119,96797
chord298,817309,72659
mcp183,24361,52025
agent62,51974,05816
env62,073689713
server161,95861,05423
codemode101,83741,11415
evals51,446782923
client81,135479913
telemetry693522438
protocol8869356712
合计Total719177,258720184,7761,577