Agent 管理层 — agent.tsAgent Management Layer — agent.ts

pi-agent-core · 543 行 · Agent 引擎的"整车组装"pi-agent-core · 543 lines · The "full vehicle assembly" of the Agent engine

上一章读的 agent-loop.ts 是引擎——它只管跑循环。但一辆车不能只有引擎:谁来记住之前的对话?谁来管启动和停止?用户在 Agent 跑的时候发了新消息怎么办?外面怎么知道 Agent 跑到哪了?这些都是 agent.ts 的活——它是把引擎装进车里的那层"管理壳"。 The agent-loop.ts we read in the last chapter is the engine — it only runs the loop. But a car can't be just an engine: who remembers previous conversations? Who manages start and stop? What happens when the user sends a new message while the Agent is running? How does the outside world know the Agent's progress? These are all agent.ts's jobs — the "management shell" that puts the engine into a car.

这一章同样分为上下两篇:This chapter also has two parts:

上篇Part A 源码精读Source Code Deep Read

左边是 agent.ts 的完整原始代码,右边是逐段中文解读。543 行代码被拆成 9 个功能区块:配置合并、消息历史、启动入口、上下文注入、中途插话、事件通知、生命周期管理等。

Left column: the full original code of agent.ts. Right column: section-by-section explanations. 543 lines broken into 9 functional blocks: config merging, message history, entry point, context injection, mid-run message insertion, event notifications, lifecycle management, and more.

适合第一遍精读,搞懂管理层的每个机制。

Best for your first close reading — understand every mechanism in the management layer.

开始阅读 →Start Reading →
下篇Part B 中文翻译版Module Overview

用中文伪代码重述 agent.ts 的 9 个区块,加上 types.ts 里最关键的类型合同。梳理管理层和引擎层之间"谁调谁、数据怎么流"的完整关系。

Restates agent.ts's 9 blocks in pseudocode, plus the key type contracts from types.ts. Maps out the complete relationship between the management layer and engine layer — who calls whom, and how data flows.

已优化排版,支持直接 Ctrl+P 打印 / 保存 PDF。读完上篇后用它建立完整画面,和第 1 章放在一起就是引擎层速查手册。

Print-optimized layout (Ctrl+P / Save as PDF). Use it after Part A for the complete picture — together with Chapter 1, it becomes a quick reference for the entire engine layer.

开始阅读 →Start Reading →
推荐顺序:先读上篇(源码精读),再读下篇(中文翻译版)。
时间有限?直接从下篇入手,它能让你快速了解管理层的 9 个区块和整体结构。
Recommended order: Read Part A (Source Code Deep Read) first, then Part B (Module Overview).
Short on time? Start with Part B — it gives you a quick overview of the management layer's 9 blocks and overall structure.