diff --git a/README.md b/README.md index 5acc0f2..d3ff6eb 100644 --- a/README.md +++ b/README.md @@ -1,111 +1,145 @@ + +> [!NOTE] +> 本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。 +> [English](./README.en.md) · [原始项目](https://github.com/shareAI-lab/learn-claude-code) · [上游 README](https://github.com/shareAI-lab/learn-claude-code/blob/HEAD/README.md) +> 原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。 + +# Learn Claude Code -- 真正的 Agent Harness 工程 + [English](./README.md) | [中文](./README-zh.md) | [日本語](./README-ja.md) -shareAI-lab%2Flearn-claude-code | Trendshift +## Agency 来自模型,Agent 产品 = 模型 + Harness -# Learn Claude Code -- Harness Engineering for Real Agents +在讨论代码之前,先把一件事说清楚。 -## Agency Comes from the Model. An Agent Product = Model + Harness. +**Agency -- 感知、推理、行动的能力 -- 来自模型训练,不是来自外部代码的编排。** 但一个能干活的 agent 产品,需要模型和 harness 缺一不可。模型是驾驶者,harness 是载具。本仓库教你造载具。 -Before we write any code, one thing needs to be clear. +### Agency 从哪来 -**Agency -- the capacity to perceive, reason, and act -- comes from model training, not from external code orchestration.** But a working agent product needs both the model and the harness. The model is the driver. The harness is the vehicle. This repository teaches you how to build the vehicle. +Agent 的核心是一个神经网络 -- Transformer、RNN、一个被训练出来的函数 -- 经过数十亿次梯度更新,在行动序列数据上学会了感知环境、推理目标、采取行动。Agency 这个东西从来不是外面那层代码赋予的,而是模型在训练中学到的。 -### Where Agency Comes From +人类就是最好的例子。一个由数百万年进化训练出来的生物神经网络,通过感官感知世界,通过大脑推理,通过身体行动。当 DeepMind、OpenAI 或 Anthropic 说 "agent" 时,他们说的核心都是同一件事:**一个通过训练学会了行动的模型,加上让它能在特定环境中工作的基础设施。** -At the core of every agent is a neural network -- a Transformer, an RNN, a trained function -- shaped by billions of gradient updates on sequences of perception, reasoning, and action. Agency was never bestowed by the surrounding code. It was learned during training. +历史已经写好了铁证: -Humans are the original proof. A biological neural network, refined by millions of years of evolutionary pressure, perceives the world through senses, reasons through a brain, and acts through a body. When DeepMind, OpenAI, or Anthropic say "agent," they all mean the same core thing: **a model that learned to act through training, plus the infrastructure that lets it operate in a specific environment.** +- **2013 -- DeepMind DQN 玩 Atari。** 一个神经网络,只接收原始像素和游戏分数,学会了 7 款 Atari 2600 游戏 -- 超越所有先前算法,在其中 3 款上击败人类专家。到 2015 年,同一架构扩展到 [49 款游戏,达到职业人类测试员水平](https://www.nature.com/articles/nature14236),论文发表在 *Nature*。没有游戏专属规则。没有决策树。一个模型,从经验中学习。那个模型就是 agent。 -The historical record is unambiguous: +- **2019 -- OpenAI Five 征服 Dota 2。** 五个神经网络,在 10 个月内与自己对战了 [45,000 年的 Dota 2](https://openai.com/index/openai-five-defeats-dota-2-world-champions/),在旧金山直播赛上 2-0 击败了 **OG** -- TI8 世界冠军。随后的公开竞技场中,AI 在 42,729 场比赛中胜率 99.4%。没有脚本化的策略。没有元编程的团队协调逻辑。模型完全通过自我对弈学会了团队协作、战术和实时适应。 -- **2013 -- DeepMind DQN plays Atari.** A single neural network, receiving only raw pixels and game scores, learned 7 Atari 2600 games -- surpassing prior algorithms and beating human experts in 3 of them. By 2015, scaled to [49 games at professional tester level](https://www.nature.com/articles/nature14236), published in *Nature*. No game-specific rules. One model, learning from experience. +- **2019 -- DeepMind AlphaStar 制霸星际争霸 II。** AlphaStar 在闭门赛中 [10-1 击败职业选手](https://deepmind.google/blog/alphastar-mastering-the-real-time-strategy-game-starcraft-ii/),随后在欧洲服务器上达到[宗师段位](https://www.nature.com/articles/d41586-019-03298-6) -- 90,000 名玩家中的前 0.15%。一个信息不完全、实时决策、组合动作空间远超国际象棋和围棋的游戏。Agent 是什么?是模型。训练出来的。不是编出来的。 -- **2019 -- OpenAI Five conquers Dota 2.** Five neural networks played [45,000 years of Dota 2 against themselves](https://openai.com/index/openai-five-defeats-dota-2-world-champions/) over 10 months, then defeated **OG** -- the TI8 world champions -- 2-0 in a live match. In the public arena, the AI won 99.4% of 42,729 games. No scripted strategies. Models learned teamwork through self-play. +- **2019 -- 腾讯绝悟统治王者荣耀。** 腾讯 AI Lab 的 "绝悟" 于 2019 年 8 月 2 日世冠杯半决赛上[以 5v5 击败 KPL 职业选手](https://www.jiemian.com/article/3371171.html)。在 1v1 模式下,职业选手 [15 场只赢 1 场,最多坚持不到 8 分钟](https://developer.aliyun.com/article/851058)。训练强度:一天等于人类 440 年。到 2021 年,绝悟在全英雄池 BO5 上全面超越 KPL 职业选手水准。没有手工编写的英雄克制表。没有脚本化的阵容编排。一个从零开始通过自我对弈学习整个游戏的模型。 -- **2019 -- DeepMind AlphaStar masters StarCraft II.** AlphaStar [beat a professional player 10-1](https://deepmind.google/blog/alphastar-mastering-the-real-time-strategy-game-starcraft-ii/) in closed matches, then reached [Grandmaster rank](https://www.nature.com/articles/d41586-019-03298-6) on the European server -- top 0.15% of 90,000 players. An incomplete-information, real-time game with a combinatorial action space far exceeding chess or Go. +- **2024-2025 -- LLM Agent 重塑软件工程。** Claude、GPT、Gemini -- 在人类全部代码和推理上训练的大语言模型 -- 被部署为编程 agent。它们阅读代码库,编写实现,调试故障,团队协作。架构与之前每一个 agent 完全相同:一个训练好的模型,放入一个环境,给予感知和行动的工具。唯一的不同是它们学到的东西的规模和解决任务的通用性。 -- **2019 -- Tencent Jueyu dominates Honor of Kings.** Tencent AI Lab's "Jueyu" system [defeated KPL professional players in full 5v5](https://www.jiemian.com/article/3371171.html) at the World Champion Cup semifinal. In 1v1 mode, pros [won just 1 out of 15 matches, lasting under 8 minutes at best](https://developer.aliyun.com/article/851058). Training intensity: one day equaled 440 human years. A model that learned the entire game from scratch through self-play. +每一个里程碑都指向同一个事实:**Agency -- 那个感知、推理、行动的能力 -- 是训练出来的,不是编出来的。** 但每一个 agent 同时也需要一个环境才能工作:Atari 模拟器、Dota 2 客户端、星际争霸 II 引擎、IDE 和终端。模型提供智能,环境提供行动空间。两者合在一起才是一个完整的 agent。 -- **2024-2025 -- LLM agents reshape software engineering.** Claude, GPT, Gemini -- large language models trained on the full breadth of human code and reasoning -- are deployed as coding agents. They read codebases, write implementations, debug failures, and coordinate as teams. The architecture is identical to every previous agent: a trained model, placed in an environment, given tools for perception and action. +### Agent 不是什么 -Every milestone points to the same fact: **Agency -- the ability to perceive, reason, and act -- is trained, not coded.** But every agent also needs an environment to operate in: an Atari emulator, the Dota 2 client, the StarCraft II engine, an IDE and a terminal. The model supplies the intelligence. The environment supplies the action space. Together they form a complete agent. +"Agent" 这个词已经被一整个提示词水管工产业劫持了。 -### What an Agent Is NOT +拖拽式工作流构建器。无代码 "AI Agent" 平台。提示词链编排库。它们共享同一个幻觉:把 LLM API 调用用 if-else 分支、节点图、硬编码路由逻辑串在一起就算是 "构建 Agent" 了。 -The word "agent" has been hijacked by an entire prompt-plumbing industry. +不是的。它们做出来的东西是鲁布·戈德堡机械 -- 一个过度工程化的、脆弱的过程式规则流水线,LLM 被楔在里面当一个美化了的文本补全节点。那不是 Agent。那是一个有着宏大妄想的 shell 脚本。 -Drag-and-drop workflow builders. No-code "AI Agent" platforms. Prompt-chain orchestration libraries. They share a single delusion: that stringing LLM API calls together with if-else branches, node graphs, and hardcoded routing logic constitutes "building an agent." +**提示词水管工式 "Agent" 是不做模型的程序员的意淫。** 他们试图通过堆叠过程式逻辑来暴力模拟智能 -- 庞大的规则树、节点图、链式提示词瀑布流 -- 然后祈祷足够多的胶水代码能涌现出自主行为。不会的。你不可能通过工程手段编码出 agency。Agency 是学出来的,不是编出来的。 -It does not. What they produce are Rube Goldberg machines -- over-engineered, brittle, procedural rule pipelines with an LLM wedged in as a glorified text-completion node. That is not an agent. That is a shell script with grandiose pretensions. +那些系统从诞生之日起就已经死了:脆弱、不可扩展、根本不具备泛化能力。它们是 GOFAI(Good Old-Fashioned AI,经典符号 AI)的现代还魂 -- 几十年前就被学界抛弃的符号规则系统,现在喷了一层 LLM 的漆又登场了。换了个包装,同一条死路。 -You cannot brute-force intelligence by stacking procedural logic -- sprawling rule trees, node graphs, chained prompt waterfalls -- and praying that enough glue code will spontaneously produce autonomous behavior. It will not. You cannot engineer agency into existence. Agency is learned, not coded. +### 心智转换:从 "开发 Agent" 到开发 Harness -### The Mindshift: From "Building Agents" to Building Harnesses +当一个人说 "我在开发 Agent" 时,他只可能是两个意思之一: -When someone says "I am building an agent," they can only mean one of two things: +**1. 训练模型。** 通过强化学习、微调、RLHF 或其他基于梯度的方法调整权重。收集任务过程数据 -- 真实领域中感知、推理、行动的实际序列 -- 用它们来塑造模型的行为。这是 DeepMind、OpenAI、腾讯 AI Lab、Anthropic 在做的事。这是最本义的 Agent 开发。 -**1. Training a model.** Adjusting weights through reinforcement learning, fine-tuning, RLHF, or another gradient-based method. Collecting trajectory data -- real-world sequences of perception, reasoning, and action in a target domain -- and using it to shape the model's behavior. This is what DeepMind, OpenAI, Tencent AI Lab, and Anthropic do. +**2. 构建 Harness。** 编写代码,为模型提供一个可操作的环境。这是我们大多数人在做的事,也是本仓库的核心。 -**2. Building a harness.** Writing the code that gives a model an operational environment. This is what most of us do, and it is the core of this repository. - -A harness is everything an agent needs to work in a specific domain: +Harness 是 agent 在特定领域工作所需要的一切: ``` Harness = Tools + Knowledge + Observation + Action Interfaces + Permissions - Tools: file I/O, shell, network, database, browser - Knowledge: product docs, domain references, API specs, style guides - Observation: git diff, error logs, browser state, sensor data - Action: CLI commands, API calls, UI interactions - Permissions: sandbox isolation, approval workflows, trust boundaries + Tools: 文件读写、Shell、网络、数据库、浏览器 + Knowledge: 产品文档、领域资料、API 规范、风格指南 + Observation: git diff、错误日志、浏览器状态、传感器数据 + Action: CLI 命令、API 调用、UI 交互 + Permissions: 沙箱隔离、审批流程、信任边界 ``` -The model decides. The harness executes. The model reasons. The harness provides context. The model is the driver. The harness is the vehicle. +模型做决策。Harness 执行。模型做推理。Harness 提供上下文。模型是驾驶者。Harness 是载具。 -This repository teaches you to build the vehicle. A vehicle for coding. But the design patterns generalize to any domain. +**编程 agent 的 harness 是它的 IDE、终端和文件系统。** 农业 agent 的 harness 是传感器阵列、灌溉控制和气象数据。酒店 agent 的 harness 是预订系统、客户沟通渠道和设施管理 API。Agent -- 那个智能、那个决策者 -- 永远是模型。Harness 因领域而变。Agent 跨领域泛化。 -### What Harness Engineers Actually Do +这个仓库教你造载具。编程用的载具。但设计模式可以泛化到任何领域:庄园管理、农田运营、酒店运作、工厂制造、物流调度、医疗保健、教育培训、科学研究。只要有一个任务需要被感知、推理和执行 -- agent 就需要一个 harness。 -If you are reading this repository, you are most likely a harness engineer. Here is what the job actually entails: +### Harness 工程师到底在做什么 -- **Implement tools.** Give the agent hands. File read/write, shell execution, API calls, browser control, database queries. Each tool is one action the agent can take in its environment. Design them atomic, composable, and clearly described. +如果你在读这个仓库,你很可能是一名 harness 工程师 -- 这是一个强大的身份。以下是你真正的工作: -- **Curate knowledge.** Give the agent domain expertise. Product documentation, architecture decision records, style guides, compliance requirements. Load on demand, not upfront. +- **实现工具。** 给 agent 一双手。文件读写、Shell 执行、API 调用、浏览器控制、数据库查询。每个工具都是 agent 在环境中可以采取的一个行动。设计它们时要原子化、可组合、描述清晰。 -- **Manage context.** Give the agent clean memory. Subagent isolation prevents noise leakage. Context compaction prevents history from drowning the present. Task systems let goals persist beyond a single conversation. +- **策划知识。** 给 agent 领域专长。产品文档、架构决策记录、风格指南、合规要求。按需加载(s07),不要前置塞入。Agent 应该知道有什么可用,然后自己拉取所需。 -- **Control permissions.** Give the agent boundaries. Sandbox file access. Require approval for destructive operations. Enforce trust boundaries between the agent and external systems. +- **管理上下文。** 给 agent 干净的记忆。子 agent 隔离(s06)防止噪声泄露。上下文压缩(s08)防止历史淹没。任务系统(s12)让目标持久化到单次对话之外。 -- **Collect trajectory data.** Every action sequence the agent executes in your harness is training signal. Real deployment trajectories are the raw material for fine-tuning the next generation of agent models. +- **控制权限。** 给 agent 边界。沙箱化文件访问。对破坏性操作要求审批。在 agent 和外部系统之间实施信任边界。这是安全工程与 harness 工程的交汇点。 -You are not writing intelligence. You are building the world that intelligence inhabits. The quality of that world directly determines how effectively the intelligence can express itself. +- **收集任务过程数据。** Agent 在你的 harness 中执行的每一条行动序列都是训练信号。真实部署中的感知-推理-行动轨迹是微调下一代 agent 模型的原材料。你的 harness 不仅服务于 agent -- 它还可以帮助进化 agent。 -**Build the harness well. The model will do the rest.** +你不是在编写智能。你是在构建智能栖居的世界。这个世界的质量 -- agent 能看得多清楚、行动得多精准、可用知识有多丰富 -- 直接决定了智能能多有效地表达自己。 -### Why Claude Code +**造好 Harness。Agent 会完成剩下的。** -Because Claude Code is the most elegant, most complete agent harness implementation we have seen. Not because of any clever trick, but because of what it *does not* do: it does not try to be the agent. It does not impose rigid workflows. It does not substitute hand-crafted decision trees for the model's own judgment. It gives the model tools, knowledge, context management, and permission boundaries -- then gets out of the way. +### 为什么是 Claude Code -- Harness 工程的大师课 -Strip Claude Code down to its essence: +为什么这个仓库专门拆解 Claude Code? + +因为 Claude Code 是我们所见过的最优雅、最完整的 agent harness 实现。不是因为某个巧妙的技巧,而是因为它 *没做* 的事:它没有试图成为 agent 本身。它没有强加僵化的工作流。它没有用精心设计的决策树去替模型做判断。它给模型提供了工具、知识、上下文管理和权限边界 -- 然后让开了。 + +把 Claude Code 剥到本质来看: ``` -Claude Code = one agent loop - + tools (bash, read, write, edit, glob, grep, browser...) - + on-demand skill loading - + context compaction - + subagent spawning - + task system with dependency graphs - + async mailbox team coordination - + worktree-isolated parallel execution - + permission governance - + hooks extension system - + memory persistence - + MCP external capability routing +Claude Code = 一个 agent loop + + 工具 (bash, read, write, edit, glob, grep, browser...) + + 按需 skill 加载 + + 上下文压缩 + + 子 agent 派生 + + 带依赖图的任务系统 + + 异步邮箱的团队协调 + + worktree 隔离的并行执行 + + 权限治理 ``` -That is it. The agent itself? Claude. A model. Trained by Anthropic on the full breadth of human reasoning and code. The harness did not make Claude smart. Claude was already smart. The harness gave Claude hands, eyes, and a workspace. +就这些。这就是全部架构。每一个组件都是 harness 机制 -- 为 agent 构建的栖居世界的一部分。Agent 本身呢?是 Claude。一个模型。由 Anthropic 在人类推理和代码的全部广度上训练而成。Harness 没有让 Claude 变聪明。Claude 本来就聪明。Harness 给了 Claude 双手、双眼和一个工作空间。 -The takeaway is not "copy Claude Code." The takeaway is: **the best agent products come from engineers who understand that their job is the harness, not the intelligence.** +这就是 Claude Code 作为教学标本的意义:**它展示了当你信任模型、把工程精力集中在 harness 上时会发生什么。** 本仓库的课程(s01-s20)逐步拆解并重组 Claude Code 架构中的 harness 机制。学完之后,你理解的不只是 Claude Code 怎么工作,而是适用于任何领域、任何 agent 的 harness 工程通用原则。 + +启示不是 "复制 Claude Code"。启示是:**最好的 agent 产品,出自那些明白自己的工作是 harness 而非 intelligence 的工程师之手。** + +--- + +## 愿景:用真正的 Agent 铺满宇宙 + +这不只关乎编程 agent。 + +每一个人类从事复杂、多步骤、需要判断力的工作的领域,都是 agent 可以运作的领域 -- 只要有对的 harness。本仓库中的模式是通用的: + +``` +庄园管理 agent = 模型 + 物业传感器 + 维护工具 + 租户通信 +农业 agent = 模型 + 土壤/气象数据 + 灌溉控制 + 作物知识 +酒店运营 agent = 模型 + 预订系统 + 客户渠道 + 设施 API +医学研究 agent = 模型 + 文献检索 + 实验仪器 + 协议文档 +制造业 agent = 模型 + 产线传感器 + 质量控制 + 物流系统 +教育 agent = 模型 + 课程知识 + 学生进度 + 评估工具 +``` + +循环永远不变。工具在变。知识在变。权限在变。Agent = 模型(LLM) + 泛化的操作环境(Harness)。 + +每一个读这个仓库的 harness 工程师都在学习远超软件工程的模式。你在学习为一个智能的、自动化的未来构建基础设施。每一个部署在真实领域的好 harness,都是 agent 能够感知、推理、行动的又一个阵地。 + +先铺满工作室。然后是农田、医院、工厂。然后是城市。然后是星球。 + +**Bash is all you need. Real agents are all the universe needs.** --- @@ -124,13 +158,59 @@ The takeaway is not "copy Claude Code." The takeaway is: **the best agent produc loop back -----------------> messages[] - The model decides when to call tools and when to stop. - The code just executes what the model asks for. - This repo teaches you to build everything around this loop -- - the harness that makes the agent effective in a specific domain. + 这是最小循环。每个 AI Agent 都需要这个循环。 + 模型决定何时调用工具、何时停止。 + 代码只是执行模型的要求。 + 本仓库教你构建围绕这个循环的一切 -- + 让 agent 在特定领域高效工作的 harness。 ``` -## Core Pattern +**20 个递进式课程, 从简单循环到完整 Harness。** +**每个课程添加一个 harness 机制。每个机制有一句格言。** + +> **s01**   *"One loop & Bash is all you need"* — 一个工具 + 一个循环 = 一个 Agent +> +> **s02**   *"加一个工具, 只加一个 handler"* — 循环不用动, 新工具注册进 dispatch map 就行 +> +> **s03**   *"先划边界, 再给自由"* — 先判断操作能不能做,要不要问用户 +> +> **s04**   *"挂在循环上, 不写进循环里"* — 在工具前后留插口,不改主循环也能扩展 +> +> **s05**   *"没有计划的 agent 走哪算哪"* — 先列步骤再动手, 完成率翻倍 +> +> **s06**   *"大任务拆小, 每个小任务干净的上下文"* — 子 Agent 自己干活,只把结果带回来 +> +> **s07**   *"用到时再加载, 别全塞 prompt 里"* — 技能先列目录,用到时再展开 +> +> **s08**   *"上下文总会满, 要有办法腾地方"* — 四层压缩策略, 便宜的先跑贵的后跑 +> +> **s09**   *"记住该记的, 忘掉该忘的"* — 三个子系统: 筛选、提取、整理 +> +> **s10**   *"prompt 是组装出来的, 不是写死的"* — 分段 + 按需拼接 +> +> **s11**   *"错误不是终点, 是重试的起点"* — 出错时会重试、腾空间、换路子 +> +> **s12**   *"大目标拆成小任务, 排好序, 持久化"* — 文件持久化的任务图, 多 agent 协作的基础 +> +> **s13**   *"慢操作丢后台, agent 继续思考"* — 后台线程跑命令, 完成后注入通知 +> +> **s14**   *"定时触发, 不需要人推"* — 按时间自动触发任务 +> +> **s15**   *"一个搞不定, 组队来"* — 持久化队友 + 异步邮箱 +> +> **s16**   *"队友之间要有约定"* — 用固定的请求-回复格式沟通 +> +> **s17**   *"队友自己看板, 有活就认领"* — 不需要领导逐个分配, 自组织 +> +> **s18**   *"各干各的目录, 互不干扰"* — 任务管目标, worktree 管目录, 按 ID 绑定 +> +> **s19**   *"能力不够? 插上 MCP"* — 把外部工具接进同一个工具池 +> +> **s20**   *"机制很多,循环一个"* — 前面所有机制回到一个完整 harness + +--- + +## 核心模式 ```python def agent_loop(messages): @@ -157,214 +237,66 @@ def agent_loop(messages): messages.append({"role": "user", "content": results}) ``` -Every lesson layers one harness mechanism on top of this loop -- the loop itself never changes. The loop belongs to the agent. The mechanisms belong to the harness. +每个课程在这个循环之上叠加一个 harness 机制 -- 循环本身始终不变。循环属于 agent。机制属于 harness。 -The loop is constant. Tools, knowledge, and permissions change. Agent = Model (LLM) + a generalized operational environment (Harness). +## 版本说明 ---- +本仓库现在同时保留两条教程线: -## Version Status +- **新版主线:根目录 `s01-s20`** + 根目录下的 `s01_*` 到 `s20_*` 是新的主版本,也是当前推荐阅读路径。每章包含完整叙事 README、英文/日文译本、可运行的 `code.py`,以及必要的图示。 +- **旧版过渡:`docs/`、`agents/`、当前 `web/`** + 这些仍保留旧 12 章体系,暂时用于已有读者、旧链接和 Web 平台过渡。 -This repository currently contains two tutorial tracks: +新读者请从根目录 `s01_agent_loop/` 读到 `s20_comprehensive/`。如果你是从旧链接或当前 Web 平台进入,大概率看到的是旧 12 章版本。旧版章节号和新版不完全一致,不要混用章节号。 -- **Current track: root-level `s01-s20`** - The root-level `s01_*` ... `s20_*` folders are the new canonical version. Each chapter contains a full narrative README, translations, runnable `code.py`, and diagrams where needed. -- **Legacy transition track: `docs/`, `agents/`, and the current `web/` app** - These still preserve the older 12-lesson version. They are kept temporarily for existing readers, old links, and the web platform while the new 20-lesson track settles. +### 旧版到新版的对应关系 -If you are starting now, read the root-level `s01_agent_loop/` through `s20_comprehensive/` chapters. If you are following an older link or using the current web app, you are likely reading the legacy 12-lesson track. The legacy and current chapter numbers do not always match, so avoid mixing chapter numbers across tracks. - -### Legacy-to-Current Mapping - -| Legacy 12-lesson track | Current 20-lesson track | Topic | +| 旧 12 章版本 | 新 20 章版本 | 主题 | |---|---|---| -| old s01 | new s01 | Agent Loop | -| old s02 | new s02 | Tool Use | -| old s03 | new s05 | TodoWrite | -| old s04 | new s06 | Subagent | -| old s05 | new s07 | Skill Loading | -| old s06 | new s08 | Context Compact | -| old s07 | new s12 | Task System | -| old s08 | new s13 | Background Tasks | -| old s09 | new s15 | Agent Teams | -| old s10 | new s16 | Team Protocols | -| old s11 | new s17 | Autonomous Agents | -| old s12 | new s18 | Worktree Isolation | -| new only | s03, s04, s09, s10, s11, s14, s19, s20 | Permission, Hooks, Memory, System Prompt, Error Recovery, Cron, MCP, Comprehensive Agent | +| 旧 s01 | 新 s01 | Agent Loop | +| 旧 s02 | 新 s02 | Tool Use | +| 旧 s03 | 新 s05 | TodoWrite | +| 旧 s04 | 新 s06 | Subagent | +| 旧 s05 | 新 s07 | Skill Loading | +| 旧 s06 | 新 s08 | Context Compact | +| 旧 s07 | 新 s12 | Task System | +| 旧 s08 | 新 s13 | Background Tasks | +| 旧 s09 | 新 s15 | Agent Teams | +| 旧 s10 | 新 s16 | Team Protocols | +| 旧 s11 | 新 s17 | Autonomous Agents | +| 旧 s12 | 新 s18 | Worktree Isolation | +| 新版新增 | s03、s04、s09、s10、s11、s14、s19、s20 | Permission、Hooks、Memory、System Prompt、Error Recovery、Cron、MCP、Comprehensive Agent | ---- +## 范围说明 (重要) -## Scope +本仓库是一个 0->1 的 harness 工程学习项目 -- 构建围绕 agent 模型的工作环境。 +为保证学习路径清晰,仓库有意简化或省略了部分生产机制: -This repository is a 0-to-1 harness engineering learning project: it teaches how to build the working environment around an agent model. To keep the learning path clear, some production mechanisms are intentionally simplified or omitted: +- 完整事件 / Hook 总线 (例如 PreToolUse、SessionStart/End、ConfigChange)。 + s12 仅提供教学用途的最小 append-only 生命周期事件流。 +- 基于规则的权限治理与信任流程 +- 会话生命周期控制 (resume/fork) 与更完整的 worktree 生命周期控制 +- 完整 MCP 运行时细节 (transport/OAuth/资源订阅/轮询) -- Full event / hook bus behavior, such as `PreToolUse`, `SessionStart/End`, and `ConfigChange`. - The teaching code uses minimal lifecycle events where needed. -- Rule-based permission governance and full trust workflows. -- Session lifecycle controls such as resume/fork, plus more complete worktree lifecycle handling. -- Full MCP runtime details such as transport, OAuth, resource subscription, and polling. +仓库中的团队 JSONL 邮箱协议是教学实现,不是对任何特定生产内部实现的声明。 -The JSONL mailbox protocol in this repository is a teaching implementation, not a claim about any specific production internal implementation. +## 快速开始 ---- - -## 20 Progressive Lessons - -**Each lesson adds one harness mechanism. Each mechanism has a motto.** - -> **s01**   *"One loop & Bash is all you need"* — one tool + one loop = one agent -> -> **s02**   *"Adding a tool means adding one handler"* — the loop stays untouched; new tools register into the dispatch map -> -> **s03**   *"Set boundaries first, then grant freedom"* — check what can run, what must stop, and what needs approval -> -> **s04**   *"Hook around the loop, never rewrite the loop"* — add extension points without changing the main loop -> -> **s05**   *"An agent without a plan drifts"* — list the steps before starting; completion rate doubles -> -> **s06**   *"Big tasks split small, each subtask gets clean context"* — subagents do the side work and bring back only the result -> -> **s07**   *"Load knowledge on demand, not upfront"* — list skills first, expand them only when needed -> -> **s08**   *"Context always fills up -- have a way to make room"* — multi-layer compaction strategies buy you infinite sessions -> -> **s09**   *"Remember what matters, forget what doesn't"* — three subsystems: selection, extraction, consolidation -> -> **s10**   *"Prompts are assembled at runtime, not hardcoded"* — section-based concatenation, loaded on demand -> -> **s11**   *"Errors aren't the end, they're the start of a retry"* — retry, make room, or take another path when things fail -> -> **s12**   *"Big goals break into small tasks, ordered, persisted to disk"* — a file-backed task graph that lays the groundwork for multi-agent coordination -> -> **s13**   *"Slow ops go background, agent keeps thinking"* — background threads run commands; notifications inject on completion -> -> **s14**   *"Fire on schedule, no human kick needed"* — trigger tasks automatically by time -> -> **s15**   *"Too big for one agent -- delegate to teammates"* — persistent teammates + async mailboxes -> -> **s16**   *"Teammates need shared communication rules"* — use a fixed request-reply format for coordination -> -> **s17**   *"Teammates check the board, claim work themselves"* — no leader assigning one by one; self-organizing -> -> **s18**   *"Each works in its own directory, no interference"* — tasks own goals, worktrees own directories, bound by ID -> -> **s19**   *"Not enough capability? Plug in more via MCP"* — connect external tools into the same tool pool -> -> **s20**   *"Many mechanisms, one loop"* — all previous mechanisms return to one complete harness - ---- - -## Learning Path - -Main line: act → handle complex work → remember and recover → run long tasks → collaborate → extend and assemble. - -```mermaid -flowchart TD - %% Card styles - classDef stage1 fill:#E3F2FD,stroke:#1976D2,stroke-width:2px,color:#0D47A1,rx:12,ry:12,text-align:left - classDef stage2 fill:#E8F5E9,stroke:#388E3C,stroke-width:2px,color:#1B5E20,rx:12,ry:12,text-align:left - classDef stage3 fill:#FFF3E0,stroke:#F57C00,stroke-width:2px,color:#E65100,rx:12,ry:12,text-align:left - classDef stage4 fill:#FCE4EC,stroke:#C2185b,stroke-width:2px,color:#880E4F,rx:12,ry:12,text-align:left - classDef stage5 fill:#F3E5F5,stroke:#7B1FA2,stroke-width:2px,color:#4A148C,rx:12,ry:12,text-align:left - classDef stage6 fill:#E0F7FA,stroke:#0097A7,stroke-width:2px,color:#006064,rx:12,ry:12,text-align:left - - %% Group style - classDef groupBox fill:#F8F9FA,stroke:#CED4DA,stroke-width:2px,stroke-dasharray: 5 5,rx:15,ry:15,color:#495057 - - %% Layer 1: stages 1-3 - subgraph Phase1 ["🌱 Stages 1-3: Core capabilities (simple to complex)"] - direction LR - S1["1. Let the Agent act
━━━━━━━━━━━━━
s01 Agent Loop
└─ one loop + bash

s02 Tool Use
└─ one tool to many tools

s03 Permission
└─ decide what can run

s04 Hooks
└─ extension points around tools"]:::stage1 - - S2["2. Handle complex work
━━━━━━━━━━━━━
s05 TodoWrite
└─ plan first, then execute

s06 Subagent
└─ side work, result back

s08 Context Compact
└─ make room in long context"]:::stage2 - - S3["3. Remember and recover
━━━━━━━━━━━━━
s09 Memory
└─ remember what matters

s10 System Prompt
└─ assemble at runtime

s11 Error Recovery
└─ retry or change path"]:::stage3 - - S1 ==> S2 ==> S3 - end - - %% Layer 2: stages 4-6 - subgraph Phase2 ["🚀 Stages 4-6: Advanced capabilities (long-running, collaboration, integration)"] - direction LR - S4["4. Run long tasks
━━━━━━━━━━━━━
s12 Task System
└─ persist tasks and deps

s13 Background Tasks
└─ send slow work background

s14 Cron Scheduler
└─ trigger by time"]:::stage4 - - S5["5. Coordinate many Agents
━━━━━━━━━━━━━
s15 Agent Teams
└─ teammates + mailboxes

s16 Team Protocols
└─ fixed request-reply format

s17 Autonomous Agents
└─ claim work from the board

s18 Worktree Isolation
└─ separate directories"]:::stage5 - - S6["6. Extend and assemble
━━━━━━━━━━━━━
s07 Skill Loading
└─ expand skills on demand

s19 MCP Plugin
└─ external tools, one pool

s20 Comprehensive Agent
└─ all mechanisms, one loop"]:::stage6 - - S4 ==> S5 ==> S6 - end - - %% Connect the two layers - Phase1 ===> Phase2 - - class Phase1,Phase2 groupBox -``` - ---- - -## All Chapters - -| Chapter | Topic | Key Concepts | -|---|---|---| -| [s01](./s01_agent_loop/) | Agent Loop | `messages` / `while True` / `stop_reason` | -| [s02](./s02_tool_use/) | Tool Use | `TOOL_HANDLERS` / dispatch map / concurrency | -| [s03](./s03_permission/) | Permission System | `PermissionRule` / approval pipeline | -| [s04](./s04_hooks/) | Hook System | `PreToolUse` / `PostToolUse` / extension points | -| [s05](./s05_todo_write/) | TodoWrite | `TodoItem` / plan-then-execute | -| [s06](./s06_subagent/) | Subagent | `fresh messages[]` / context isolation | -| [s07](./s07_skill_loading/) | Skill Loading | `SkillManifest` / on-demand injection | -| [s08](./s08_context_compact/) | Context Compact | snipCompact / microCompact / toolResultBudget / autoCompact | -| [s09](./s09_memory/) | Memory System | selection / extraction / consolidation | -| [s10](./s10_system_prompt/) | System Prompt | runtime assembly / section concatenation | -| [s11](./s11_error_recovery/) | Error Recovery | token escalation / fallback model / retry strategies | -| [s12](./s12_task_system/) | Task System | `TaskRecord` / `blockedBy` / disk persistence | -| [s13](./s13_background_tasks/) | Background Tasks | threaded execution / notification queue | -| [s14](./s14_cron_scheduler/) | Cron Scheduler | durable scheduling / session-scoped triggers | -| [s15](./s15_agent_teams/) | Agent Teams | `MessageBus` / inbox / permission bubbling | -| [s16](./s16_team_protocols/) | Team Protocols | shutdown handshake / plan approval | -| [s17](./s17_autonomous_agents/) | Autonomous Agents | idle cycle / auto-claim / self-organization | -| [s18](./s18_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / task-directory binding | -| [s19](./s19_mcp_plugin/) | MCP Plugin | multi-transport / channel routing / tool pool assembly | -| [s20](./s20_comprehensive/) | Comprehensive Agent | all mechanisms around one loop | - ---- - -## How to Read - -Each chapter is a folder. Open one and you will find: - -``` -s08_context_compact/ - README.md # full narrative with inline code - README.en.md # English translation - README.ja.md # Japanese translation - code.py # standalone runnable implementation - images/ # SVG diagrams (where needed) -``` - -Read the `README.md` for the core idea and work through the code. Complex chapters have `
` folds for deep dives -- open them when you want to go deeper. Simple chapters have 0-1 diagrams, complex chapters have more. - -Read from s01 through s20 in order. Each chapter assumes you've read the previous ones and ends with a hook into the next. - ---- - -## Quick Start - -### Current 20-Lesson Track +### 新版 20 章主线 ```sh git clone https://github.com/shareAI-lab/learn-claude-code cd learn-claude-code pip install -r requirements.txt -cp .env.example .env # configure ANTHROPIC_API_KEY +cp .env.example .env # 编辑 .env 填入你的 ANTHROPIC_API_KEY -python s01_agent_loop/code.py # Start here -- one loop + bash -python s08_context_compact/code.py # Context compaction (complex) -python s20_comprehensive/code.py # Endpoint: all mechanisms in one loop +python s01_agent_loop/code.py # 起点 — 一个循环 + bash +python s08_context_compact/code.py # 上下文压缩(复杂章) +python s20_comprehensive/code.py # 终点章: 全部机制归到一个循环 ``` -### Legacy 12-Lesson Track +### 旧版 12 章过渡线 ```sh python agents/s01_agent_loop.py @@ -372,71 +304,140 @@ python agents/s12_worktree_task_isolation.py python agents/s_full.py ``` -### Web Platform +### Web 平台 -The current web app still renders the legacy `docs/` s01-s12 track. Use the root-level folders for the new s01-s20 track. +当前 Web 平台仍读取 `docs/` 中的旧 12 章内容。新版 20 章请直接阅读根目录 `s01-s20`。 ```sh cd web && npm install && npm run dev # http://localhost:3000 ``` ---- +## 学习路径 -## Project Structure +主线:能动手 → 能做复杂任务 → 能记住和恢复 → 能长期运行 → 能协作 → 能扩展并合体 + +```mermaid +flowchart TD + %% 统一定义卡片样式:加入 text-align:left 保证列表不会居中乱飘 + classDef stage1 fill:#E3F2FD,stroke:#1976D2,stroke-width:2px,color:#0D47A1,rx:12,ry:12,text-align:left + classDef stage2 fill:#E8F5E9,stroke:#388E3C,stroke-width:2px,color:#1B5E20,rx:12,ry:12,text-align:left + classDef stage3 fill:#FFF3E0,stroke:#F57C00,stroke-width:2px,color:#E65100,rx:12,ry:12,text-align:left + classDef stage4 fill:#FCE4EC,stroke:#C2185b,stroke-width:2px,color:#880E4F,rx:12,ry:12,text-align:left + classDef stage5 fill:#F3E5F5,stroke:#7B1FA2,stroke-width:2px,color:#4A148C,rx:12,ry:12,text-align:left + classDef stage6 fill:#E0F7FA,stroke:#0097A7,stroke-width:2px,color:#006064,rx:12,ry:12,text-align:left + + %% 背景框样式 + classDef groupBox fill:#F8F9FA,stroke:#CED4DA,stroke-width:2px,stroke-dasharray: 5 5,rx:15,ry:15,color:#495057 + + %% 第一层:1-3阶段 + subgraph Phase1 ["🌱 阶段 1-3:基础能力构建(从简单到复杂)"] + direction LR + S1["第一阶段:让 Agent 能动手
━━━━━━━━━━━━━
s01 Agent Loop
└─ 一个循环 + bash

s02 Tool Use
└─ 单个到多个工具

s03 Permission
└─ 判断能不能做

s04 Hooks
└─ 工具前后留扩展插口"]:::stage1 + + S2["第二阶段:做复杂任务
━━━━━━━━━━━━━
s05 TodoWrite
└─ 先列计划,再执行

s06 Subagent
└─ 子节点干活带回结果

s08 Context Compact
└─ 长下文腾空间"]:::stage2 + + S3["第三阶段:记住和恢复
━━━━━━━━━━━━━
s09 Memory
└─ 该记记,该忘忘

s10 System Prompt
└─ 运行时组装

s11 Error Recovery
└─ 重试换路子"]:::stage3 + + S1 ==> S2 ==> S3 + end + + %% 第二层:4-6阶段 + subgraph Phase2 ["🚀 阶段 4-6:高阶能力进化(长期、协作与融合)"] + direction LR + S4["第四阶段:让任务长期运行
━━━━━━━━━━━━━
s12 Task System
└─ 任务落盘记依赖

s13 Background Tasks
└─ 慢操作丢后台

s14 Cron Scheduler
└─ 按时自动触发"]:::stage4 + + S5["第五阶段:让多个 Agent 协作
━━━━━━━━━━━━━
s15 Agent Teams
└─ 队友 + 邮箱通信

s16 Team Protocols
└─ 固定收发格式

s17 Autonomous Agents
└─ 自己看板认领活

s18 Worktree Isolation
└─ 隔离目录"]:::stage5 + + S6["第六阶段:接外部能力合体
━━━━━━━━━━━━━
s07 Skill Loading
└─ 技能按需展开

s19 MCP Plugin
└─ 外部接进工具池

s20 Comprehensive Agent
└─ 全机制回单循环"]:::stage6 + + S4 ==> S5 ==> S6 + end + + %% 将两个模块连接起来,形成 Z 字形阅读流 + Phase1 ===> Phase2 + + %% 应用背景样式 + class Phase1,Phase2 groupBox +``` + +## 全部章节 + +| 章节 | 主题 | 关键概念 | +|---|---|---| +| [s01](./s01_agent_loop/) | Agent Loop | `messages` / `while True` / `stop_reason` | +| [s02](./s02_tool_use/) | Tool Use | `TOOL_HANDLERS` / dispatch map / 并发 | +| [s03](./s03_permission/) | Permission | `PermissionRule` / 审批管线 | +| [s04](./s04_hooks/) | Hooks | `PreToolUse` / `PostToolUse` / 扩展点 | +| [s05](./s05_todo_write/) | TodoWrite | `TodoItem` / 先计划后执行 | +| [s06](./s06_subagent/) | Subagent | `fresh messages[]` / 上下文隔离 | +| [s07](./s07_skill_loading/) | Skill Loading | `SkillManifest` / 按需注入 | +| [s08](./s08_context_compact/) | Context Compact | snip / micro / budget / auto 四层压缩 | +| [s09](./s09_memory/) | Memory | selection / extraction / consolidation | +| [s10](./s10_system_prompt/) | System Prompt | 运行时组装 / 分段拼接 | +| [s11](./s11_error_recovery/) | Error Recovery | token 升级 / fallback 模型 / 重试策略 | +| [s12](./s12_task_system/) | Task System | `TaskRecord` / `blockedBy` / 磁盘持久化 | +| [s13](./s13_background_tasks/) | Background Tasks | 线程执行 / 通知队列 | +| [s14](./s14_cron_scheduler/) | Cron Scheduler | 持久化调度 / 会话级触发 | +| [s15](./s15_agent_teams/) | Agent Teams | `MessageBus` / 收件箱 / 权限冒泡 | +| [s16](./s16_team_protocols/) | Team Protocols | 关机握手 / 计划审批 | +| [s17](./s17_autonomous_agents/) | Autonomous Agents | 空闲循环 / 自动认领 | +| [s18](./s18_worktree_isolation/) | Worktree Isolation | `WorktreeRecord` / 任务-目录绑定 | +| [s19](./s19_mcp_plugin/) | MCP Plugin | 多传输 / 通道路由 / 工具池组装 | +| [s20](./s20_comprehensive/) | Comprehensive Agent | 全部机制归到一个循环 | + +## 项目结构 ``` learn-claude-code/ - s01_agent_loop/ # one folder per chapter - README.md # Chinese source (complete narrative) - README.en.md # English translation - README.ja.md # Japanese translation - code.py # standalone runnable code - images/ # SVG diagrams + s01_agent_loop/ # 每章一个文件夹 + README.md # 中文源文档(完整叙事) + README.en.md # 英文译本 + README.ja.md # 日文译本 + code.py # 独立可运行代码 + images/ # SVG 流程图 s02_tool_use/ ... s19_mcp_plugin/ - s20_comprehensive/ # endpoint chapter - agents/ # legacy 12 runnable copies + s_full.py - skills/ # skill files used by s07 - docs/ # legacy 12-lesson docs, kept during transition - web/ # currently renders the legacy docs/ track + s20_comprehensive/ # 终点章 + agents/ # 旧 12 章可运行副本 + s_full.py + skills/ # s07 使用的 skill 文件 + docs/ # 旧 12 章文档,过渡期保留 + web/ # 当前仍基于 docs/ 旧版内容生成 tests/ ``` ---- +## 学完之后 -- 从理解到落地 -## What's Next +20 个课程走完, 你已经从内到外理解了 harness 工程的运作原理。两种方式把知识变成产品: -After 20 lessons, you understand harness engineering from the inside out. Two paths to turn that knowledge into product: - -### Kode Agent CLI -- Open-Source Coding Agent CLI +### Kode Agent CLI -- 开源 Coding Agent CLI > `npm i -g @shareai-lab/kode` -Skill and LSP support, Windows compatible, works with GLM / MiniMax / DeepSeek and other open models. Install and go. +支持 Skill & LSP, 适配 Windows, 可接 GLM / MiniMax / DeepSeek 等开放模型。装完即用。 GitHub: **[shareAI-lab/Kode-CLI](https://github.com/shareAI-lab/Kode-CLI)** -### Kode Agent SDK -- Embed Agent Capabilities in Your Application +### Kode Agent SDK -- 把 Agent 能力嵌入你的应用 -A standalone library with no per-user process overhead. Embed it in backends, browser extensions, embedded devices, or any runtime. +官方 Claude Code Agent SDK 底层与完整 CLI 进程通信 -- 每个并发用户 = 一个终端进程。Kode SDK 是独立库, 无 per-user 进程开销, 可嵌入后端、浏览器插件、嵌入式设备等任意运行时。 GitHub: **[shareAI-lab/kode-agent-sdk](https://github.com/shareAI-lab/kode-agent-sdk)** --- -## Sister Tutorial: From Passive Sessions to Always-On Assistants +## 姊妹教程: 从*被动临时会话*到*主动常驻助手* -The harness taught in this repository is the **use-and-discard** kind -- open a terminal, give the agent a task, close when done, next session starts fresh. Claude Code works this way. +本仓库教的 harness 属于 **用完即走** 型 -- 开终端、给 agent 任务、做完关掉, 下次重开是全新会话。Claude Code 就是这种模式。 -But [OpenClaw](https://github.com/openclaw/openclaw) proves another possibility: on the same agent core, two additional harness mechanisms turn an agent from "poke it and it moves" into "wakes itself every 30 seconds to look for work": +但 [OpenClaw](https://github.com/openclaw/openclaw) 证明了另一种可能: 在同样的 agent core 之上, 加两个 harness 机制就能让 agent 从 "踹一下动一下" 变成 "自己隔 30 秒醒一次找活干": -- **Heartbeat** -- every 30 seconds the harness sends the agent a message, letting it check for pending work. Nothing to do? Keep sleeping. Something appeared? Act immediately. -- **Cron** -- the agent can schedule its own future tasks, which fire automatically when the time arrives. +- **心跳 (Heartbeat)** -- 每 30 秒 harness 给 agent 发一条消息, 让它检查有没有事可做。没事就继续睡, 有事立刻行动。 +- **定时任务 (Cron)** -- agent 可以给自己安排未来要做的事, 到点自动执行。 -Add IM multi-channel routing (WhatsApp / Telegram / Slack / Discord and 13+ other platforms), persistent context memory, and a Soul personality system, and the agent transforms from a disposable tool into an always-on personal AI assistant. +再加上 IM 多通道路由 (WhatsApp/Telegram/Slack/Discord 等 13+ 平台)、不清空的上下文记忆、Soul 人格系统, agent 就从一个临时工具变成了始终在线的个人 AI 助手。 -**[claw0](https://github.com/shareAI-lab/claw0)** is our sister teaching repository, breaking down these harness mechanisms from scratch: +**[claw0](https://github.com/shareAI-lab/claw0)** 是我们的姊妹教学仓库, 从零拆解这些 harness 机制: ``` claw agent = agent core + heartbeat + cron + IM chat + memory + soul @@ -444,19 +445,17 @@ claw agent = agent core + heartbeat + cron + IM chat + memory + soul ``` learn-claude-code claw0 -(agent harness internals: (always-on harness: - loop, tools, planning, heartbeat, cron, IM channels, - teams, worktree isolation) memory, Soul personality) +(agent harness 内核: (主动式常驻 harness: + 循环、工具、规划、 心跳、定时任务、IM 通道、 + 团队、worktree 隔离) 记忆、Soul 人格) ``` -## License +## 许可证 MIT --- -**Agency comes from the model. The harness gives agency a place to land. Build the harness well, and the model will do the rest.** +**Agency 来自模型。Harness 让 agency 落地。造好 Harness,模型会完成剩下的。** **Bash is all you need. Real agents are all the universe needs.** - -**This is not "copy the source code." This is "grasp the key designs and build it yourself."**