为什么读 Agent 源码Why Read Agent Source Code
从"通用助手"到"AI 员工",Agent 好像正在接管世界。大模型的魔力我们可以通过聊天直观感知,那 Agent 的魔力从哪里来,比大模型多了什么?弄清楚这个问题最好的方法是去看 Agent 源码。
From "general assistants" to "AI employees," Agents seem to be taking over the world. We can intuitively feel the magic of large language models through chatting — but where does the Agent's magic come from? What does it add beyond the LLM itself? The best way to answer that question is to read Agent source code.
PiMono 是 OpenClaw 的内核引擎。核心只有 5 个文件、2002 行代码,但体现了所有 Agent 的通用模式 —— 代码量最少,模式最完整,理解 Agent 核心性价比最高的一次阅读。
PiMono is the kernel engine of OpenClaw. Its core is just 5 files and 2,002 lines of code, yet it embodies all universal Agent patterns — the least code, the most complete patterns, and the highest return-on-investment reading for understanding how Agents work.
这份笔记来自非技术背景的自学者。阅读方法:先看架构全景图建立整体感 → 每章上篇是左源码右中文讲解,逐行过一遍 → 下篇是提炼后的中文模块概览,梳理全貌 → 打印下篇反复看,直到变成直觉。所有术语即时解释,从前往后读就好。
These notes are from a self-taught learner with a non-technical background. Reading approach: start with the architecture overview to build the big picture → each chapter's Part A has source code on the left and explanations on the right, going line by line → Part B is a distilled module overview → print Part B and review until it becomes intuition. All terms are explained inline — just read from start to finish.
架构全景Architecture Overview
蓝色模块是本系列精读的部分,点击可跳转Blue modules are covered in this series — click to navigate
章节目录Table of Contents
1核心循环 — agent-loop.tsCore Loop — agent-loop.ts
引擎层Engine LayerAgent 的心脏,695 行。问 AI → AI 说要用工具 → 执行工具 → 结果告诉 AI → 再问。上篇:左源码右中文讲解;下篇:中文模块概览。
The Agent's heart, 695 lines. Ask AI → AI requests tools → execute tools → feed results back → ask again. Part A: source code with line-by-line explanations; Part B: module overview.
2管理层 — agent.tsManagement Layer — agent.ts
引擎层Engine Layer引擎只管跑循环,这个文件是「整车」—— 记住对话历史、管理启停、运行中插入新消息、向外通报进度。同样上下两篇。
The engine only runs the loop. This file is the "whole car" — remembering conversation history, managing start/stop, injecting messages mid-run, and reporting progress. Also in two parts.
3AI 适配层 — 一套代码对接 27 家供应商AI Adapter Layer — One Codebase for 27 Providers
LLM 层LLM LayerAgent 怎么和 AI 模型通信?27 家供应商(Anthropic、OpenAI、Google……)只用 9 套代码全部搞定。架构图 + 完整调用链路。
How does the Agent communicate with AI models? 27 providers (Anthropic, OpenAI, Google...) handled with just 9 code modules. Architecture diagrams + complete call chains.
精读版本:基于 2025 年 5 月的 PiMono 源码
说明:本资料的注释和解读均为学习笔记,帮助理解 Agent 架构的通用设计模式。标注了通用模式的概念在大多数 Agent 框架中通用,标注了Pi 特有的是 PiMono 的特定实现。 Source Repository: github.com/badlogic/pi-mono
Version Studied: Based on PiMono source code from May 2025
Note: All annotations and interpretations are study notes to help understand universal Agent architecture patterns. Concepts tagged Universal Pattern are common across most Agent frameworks; those tagged Pi-Specific are particular to PiMono's implementation.