从零构建 Coding Agent:Claude Code 系统要素

# 从零构建 Coding Agent:Claude Code 系统要素

> 仿照《计算机系统要素:从零开始构建现代计算机》(Nand to Tetris)的写作风格,
> 逐层拆解 Claude Code,最终用自己双手拼出一个可运行的 Coding Agent。

---

## 这套文档是什么

《计算机系统要素》用 12 章,从一个 NAND 门出发,搭建出能运行俄罗斯方块的完整计算机。
本系列做同样的事情——从一个最简单的命令行进程出发,一章一章地堆叠能力,
最终构建出一个能够读写文件、执行 Shell、与 LLM 对话、自主完成编程任务的 **Coding Agent**。

每章对应 Claude Code 代码库中的一个核心层次,提供:

| 栏目 | 说明 |
|------|------|
| **核心原理** | 该层为什么存在,它解决了什么问题 |
| **Claude Code 中的实现** | 对应源码的关键设计与数据结构 |
| **最小化产出物** | 用几十到几百行代码实现该层的可运行最简版本 |
| **验收命令** | 一行命令证明产出物实际可运行 |

把每章的产出物依次拼接,最终产物就是你亲手写的 Coding Agent。

---

## 阅读路线图

```
第 0 章  系统鸟瞰
         └─ 全局架构图 · 十六层抽象 · 数据流总览

第 1 章  进程与标准 I/O
         └─ 产出物:能读 stdin / 写 stdout 的最小 TS 进程

第 2 章  终端 UI 外壳(Ink/React)
         └─ 产出物:基于 Ink 的带光标输入框 REPL 外壳

第 3 章  CLI 命令路由
         └─ 产出物:支持 --help / --version / run 子命令的 CLI

第 4 章  工具抽象与执行引擎
         └─ 产出物:可注册 + 调用工具的最小工具运行时

第 5 章  LLM API 客户端
         └─ 产出物:流式调用 Claude API,打印思考过程

第 6 章  消息循环与对话管理
         └─ 产出物:带多轮历史的对话循环(无工具)

第 7 章  工具调用循环(Agentic Loop)
         └─ 产出物:LLM 可自主调用工具完成任务的 Agent 核心

第 8 章  权限与安全仲裁
         └─ 产出物:带白名单 / 用户确认的权限守卫层

第 9 章  上下文注入(System Prompt)
         └─ 产出物:自动感知项目、读取 CLAUDE.md 的上下文构建器

第 10 章  记忆系统与文件历史
          └─ 产出物:save_memory 工具 + --rewind 文件快照恢复机制

第 11 章  会话持久化与历史回放
          └─ 产出物:可 --resume 的会话存档 / 恢复机制

第 12 章  斜杠命令系统
          └─ 产出物:/help /clear /cost 等内置斜杠命令路由

第 13 章  多 Agent 与任务调度
          └─ 产出物:父 Agent 派生子 Agent 并聚合结果的调度器

第 14 章  插件与 MCP 集成
          └─ 产出物:加载外部 MCP Server 并暴露为工具的插件层

第 15 章  完整 Coding Agent 集成
          └─ 产出物:把前 14 章产出物串联,得到完整 Coding Agent

第 16 章  后台智能框架(forked Agent 模式)     ← 进阶选修
          └─ 产出物:主对话异步 fork 子 Agent,实现记忆提炼 + 文档自维护
```

---

## 各章产出物之间的依赖关系

```
chapters/01/src/state.ts          ← 地基:进程状态 + 信号处理
        ↑ import
chapters/02/src/app.tsx           ← UI 层:Ink 终端界面(import state.ts)
        ↑ import
chapters/03/src/main.ts           ← 路由层:CLI 参数解析(import state.ts + app.tsx)

chapters/04/src/tools.ts          ← 工具层:BashTool/ReadFileTool/WriteFileTool + callTool
        ↑ import
chapters/05/src/llm.ts            ← LLM 层:streamQuery + calculateCostUSD
        ↑ import
chapters/06/src/conversation.ts   ← 对话层:ConversationManager(import llm.ts)
        ↑ import
chapters/07/src/loop.ts           ← 循环层:agenticLoop(import tools.ts + llm.ts + conversation.ts)
        ↑ import
chapters/08/src/loop.ts           ← 权限层:带 canUseTool 的 agenticLoop
        ↑ import
chapters/09/src/loop.ts           ← 上下文层:带 System Prompt 注入的 agenticLoop
        ↑ import
chapters/10/src/loop.ts           ← 记忆层:带 MEMORY.md + 文件历史的 agenticLoop
        ↑ import
chapters/11/src/agent.ts          ← 持久化层:带 JSONL 会话存档的 Agent
        ↑ import
chapters/12/src/agent.ts          ← 命令层:带斜杠命令 + Skills 的 Agent
        ↑ import
chapters/13/src/agent.ts          ← 多 Agent 层:带 AgentTool 的 Agent
        ↑ import
chapters/14/src/agent.ts          ← MCP 层:带 MCP 工具的 Agent
        ↑ import
chapters/15/src/main.ts           ← 完整集成:直接复用第 14 章 Agent
        ↑ import
chapters/16/src/main.ts           ← 后台智能:带 forked Agent 框架的 Agent
```

每章的**可复用模块**(`tools.ts`、`llm.ts`、`conversation.ts`、`loop.ts` 等)与**验收入口**(`main.ts`)分离,后续章节直接 import 前章模块,不重复定义逻辑。

---

## 技术栈说明

| 技术 | 用途 |
|------|------|
| TypeScript (tsx) | 全部产出物的实现语言 |
| Node.js 18+ | 运行时 |
| Ink 5 + React 18 | 终端 UI(第 2 章起) |
| @anthropic-ai/sdk | Claude API 客户端(第 5 章起) |
| Commander.js | CLI 命令路由(第 3 章起) |
| zod | Schema 校验(工具入参,第 4 章起) |

运行任何章节产出物只需:

```bash
cd chapters/<N>/
npm install
npx tsx src/main.ts
```

---

## 与 Claude Code 源码的对应关系

| 本系列章节 | Claude Code 对应源码路径 |
|-----------|------------------------|
| 第 1 章 | `src/main.tsx`、`src/bootstrap/state.ts` |
| 第 2 章 | `src/ink.ts`、`src/replLauncher.tsx`、`src/components/` |
| 第 3 章 | `src/main.tsx`(Commander 部分)、`src/cli/` |
| 第 4 章 | `src/Tool.ts`、`src/tools.ts`、`src/tools/` |
| 第 5 章 | `src/services/api/claude.ts`、`src/query/` |
| 第 6 章 | `src/history.ts`、`src/assistant/sessionHistory.ts` |
| 第 7 章 | `src/QueryEngine.ts`、`src/query.ts` |
| 第 8 章 | `src/types/permissions.ts`、`src/utils/permissions/` |
| 第 9 章 | `src/context.ts`、`src/context/`、`src/setup.ts` |
| 第 10 章 | `src/memdir/`、`src/utils/fileHistory.ts` |
| 第 11 章 | `src/history.ts`、`src/projectOnboardingState.ts` |
| 第 12 章 | `src/commands.ts`、`src/commands/` |
| 第 13 章 | `src/Task.ts`、`src/tasks/`、`src/coordinator/` |
| 第 14 章 | `src/plugins/`、`src/services/`(MCP 部分) |
| 第 15 章 | 全部集成 |
| 第 16 章 | `src/utils/forkedAgent.ts`、`src/services/MagicDocs/`、`src/services/awaySummary.ts`、`src/services/PromptSuggestion/speculation.ts` |

---

## 章节目录

### 正文

- [第 0 章:系统鸟瞰](00-system-overview)
- [第 1 章:进程与标准 I/O](01-process-and-io)
- [第 2 章:终端 UI 外壳](02-terminal-ui)
- [第 3 章:CLI 命令路由](03-cli-routing)
- [第 4 章:工具抽象与执行引擎](04-tool-engine)
- [第 5 章:LLM API 客户端](05-llm-client)
- [第 6 章:消息循环与对话管理](06-conversation)
- [第 7 章:工具调用循环(Agentic Loop)](07-agentic-loop)
- [第 8 章:权限与安全仲裁](08-permissions)
- [第 9 章:上下文注入](09-context-injection)
- [第 10 章:记忆系统与文件历史](10-memory-system)
- [第 11 章:会话持久化与历史回放](11-session-persistence)
- [第 12 章:斜杠命令系统](12-slash-commands)
- [第 13 章:多 Agent 与任务调度](13-multi-agent)
- [第 14 章:插件与 MCP 集成](14-plugins-mcp)
- [第 15 章:完整 Coding Agent 集成](15-full-integration)
- [第 16 章:后台智能框架](16-background-agent)

### 附录

- [附录 I:基础设施](appendix-I-infrastructure)
- [附录 II:后台智能](appendix-II-background-intelligence)
- [附录 III:安全](appendix-III-security)
- [附录 IV:自动化](appendix-IV-automation)
- [附录 V:工作区](appendix-V-workspace)
- [附录 VI:用户体验](appendix-VI-ux)
- [附录 VII:测试](appendix-VII-testing)

### 写作笔记

- [章节大纲(写作前的整体规划)](CHAPTERS-OUTLINE)