diff --git a/.gitignore b/.gitignore
index ce87dce25..4f8618a6b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -232,3 +232,14 @@ test_providers.py
# Internal analysis artifacts (not learning material)
analysis/
analysis_progress.md
+
+# Local scratch repo copies (not part of the course; contain .venv/node_modules)
+/learn-claude-code/
+/learn-pi-agent/
+
+# Local Claude Code config & skills (keep local, not published)
+.claude/
+
+# Local SVG style notes (not published)
+/docs/svg-style-guide.md
+.runtime/
diff --git a/s01_agent_loop/README.en.md b/s01_agent_loop/README.en.md
deleted file mode 100644
index 92f761798..000000000
--- a/s01_agent_loop/README.en.md
+++ /dev/null
@@ -1,207 +0,0 @@
-# s01: The Agent Loop — One Loop Is All You Need
-
-[中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)
-
-`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20
-> *"One loop & Bash is all you need"* — One tool + one loop = one Agent.
->
-> **Harness Layer**: The Loop — the first bridge between the model and the real world.
-
----
-
-## The Problem
-
-You ask the model: "List the files in my directory and run XXX.py."
-
-The model can output a bash command, but once it's done outputting, it stops — it won't execute the command on its own, and it won't keep reasoning based on the result.
-
-You could run it manually, paste the output back into the chat, and let it continue. Next command comes out, you run it again, paste it back.
-
-Every round-trip, you're the middle layer. Automating that is what this chapter is about.
-
----
-
-## The Solution
-
-
-
-A `while True` loop: keep going when the model calls a tool, stop when it doesn't. The entire process hinges on two signals:
-
-| Signal | Meaning | Loop Action |
-|--------|---------|-------------|
-| `stop_reason == "tool_use"` | Model raises hand: "I need a tool" | Execute → feed result back → continue |
-| `stop_reason != "tool_use"` | Model says: "I'm done" | Exit loop |
-
----
-
-## How It Works
-
-Let's translate this process into code. Step by step:
-
-**Step 1**: Start with the user's question as the first message.
-
-```python
-messages = [{"role": "user", "content": query}]
-```
-
-**Step 2**: Send the messages and tool definitions to the LLM.
-
-```python
-response = client.messages.create(
- model=MODEL, system=SYSTEM, messages=messages,
- tools=TOOLS, max_tokens=8000,
-)
-```
-
-**Step 3**: Append the model's response and check whether it called a tool. No tool call → done.
-
-```python
-messages.append({"role": "assistant", "content": response.content})
-if response.stop_reason != "tool_use":
- return
-```
-
-**Step 4**: Execute the tool the model requested and collect the results.
-
-```python
-results = []
-for block in response.content:
- if block.type == "tool_use":
- output = run_bash(block.input["command"])
- results.append({
- "type": "tool_result",
- "tool_use_id": block.id,
- "content": output,
- })
-```
-
-**Step 5**: Append the tool results as a new message and go back to Step 2.
-
-```python
-messages.append({"role": "user", "content": results})
-```
-
-Assembled into a complete function:
-
-```python
-def agent_loop(messages):
- while True:
- response = client.messages.create(
- model=MODEL, system=SYSTEM, messages=messages,
- tools=TOOLS, max_tokens=8000,
- )
- messages.append({"role": "assistant", "content": response.content})
-
- if response.stop_reason != "tool_use":
- return
-
- results = []
- for block in response.content:
- if block.type == "tool_use":
- output = run_bash(block.input["command"])
- results.append({
- "type": "tool_result",
- "tool_use_id": block.id,
- "content": output,
- })
- messages.append({"role": "user", "content": results})
-```
-
-Under 30 lines — that's the minimal runnable agent harness kernel. It's not intelligence itself, but the smallest runtime framework that lets the model keep acting. The model decides (whether to call a tool, which one), the harness executes (if called, run it, feed the result back). The next 18 chapters all add mechanisms on top of this loop. The loop itself never changes.
-
----
-
-## Try It
-
-> **Teaching demo notice**: The code executes shell commands generated by the model. Run it in a temporary test directory to avoid affecting your project files. s03 covers the real permission system.
-
-**Setup** (first run):
-
-```sh
-pip install -r requirements.txt
-cp .env.example .env
-# Edit .env, fill in ANTHROPIC_API_KEY and MODEL_ID
-```
-
-**Run**:
-
-```sh
-python s01_agent_loop/code.py
-```
-
-Try these prompts:
-
-1. `Create a file called hello.py that prints "Hello, World!"`
-2. `List all Python files in this directory`
-3. `What is the current git branch?`
-
-What to watch for: When does the model call a tool (loop continues), and when does it not (loop ends)?
-
----
-
-## What's Next
-
-Right now the model only has bash — reading files requires `cat`, writing files requires `echo ... >`, finding files requires `find`. Ugly and error-prone.
-
-→ s02 Tool Use: What happens when we give it 5 proper tools? Will the model call multiple tools at once? Will parallel tool executions step on each other?
-
-
-Dive into CC Source Code
-
-> The following is based on a review of CC source code `src/query.ts` (1729 lines). The core differences are twofold: CC doesn't rely on the `stop_reason` field to decide whether to continue the loop — instead it checks whether the content contains `tool_use` blocks (because `stop_reason` is unreliable in streaming responses); CC has more exit paths and recovery strategies for production-grade protection.
-
-**The 30-line `while True` from the teaching version IS the core of CC's 1729 lines.** Everything below is a protection mechanism layered on top of that core.
-
-
-1. Loop Structure Differences
-
-The teaching version checks `response.stop_reason`. CC doesn't use it as the sole signal for loop continuation — in streaming responses, `stop_reason` may not have updated yet even though `tool_use` blocks are already present. CC uses a `needsFollowUp` flag: during streaming message reception (`query.ts:830-834`), it's set to `true` whenever a `tool_use` block is detected. `QueryEngine.ts` captures the real `stop_reason` from `message_delta` for other logic, but the query loop itself relies on `needsFollowUp`.
-
-```typescript
-// query.ts:554-558
-// stop_reason === 'tool_use' is unreliable.
-// Set during streaming whenever a tool_use block arrives.
-let needsFollowUp = false
-```
-
-
-
-
-2. State Object — 10 Fields (Teaching Version Only Uses messages)
-
-| # | Field | Purpose | Chapter |
-|---|-------|---------|---------|
-| 1 | `messages` | Message array for the current iteration | s01 |
-| 2 | `toolUseContext` | Tool, signal, and permission context | s02 |
-| 3 | `autoCompactTracking` | Compaction state tracking | s08 |
-| 4 | `maxOutputTokensRecoveryCount` | Token recovery attempt count (max 3) | s11 |
-| 5 | `hasAttemptedReactiveCompact` | Whether reactive compaction was attempted this round | s08 |
-| 6 | `maxOutputTokensOverride` | 8K→64K upgrade override | s11 |
-| 7 | `pendingToolUseSummary` | Background Haiku-generated tool use summary | s08 |
-| 8 | `stopHookActive` | Whether the stop hook produced a blocking error | s04 |
-| 9 | `turnCount` | Turn count (for maxTurns check) | s01 |
-| 10 | `transition` | Last continue reason | s11 |
-
-> Note: `taskBudgetRemaining` (`query.ts:291`) is a loop-local variable, not on State. The source comment explicitly says "Loop-local (not on State)".
-
-
-
-
-3. Multiple Exit and Continue Paths
-
-The teaching version has only 1 exit path (model doesn't call a tool → done). The production version has multiple exit and continue paths, covering blocking limit, prompt too long, model error, abort, hook stop, max turns, token budget continuation, reactive compact retry, and more. Each scenario has a corresponding recovery or exit strategy.
-
-
-
-
-4. Streaming Tool Execution and QueryEngine
-
-CC's `StreamingToolExecutor` (`query.ts:561`) allows tools to begin parallel execution while the model is still generating (concurrency-safe tools run in parallel, others run exclusively). `QueryEngine.ts` adds additional protections for cost overruns, structured output validation failures, and more. The teaching version doesn't implement these — the goal is conceptual clarity, not peak performance.
-
-
-
-**In one sentence**: The core of query.ts's 1729 lines is a 30-line `while True`. All the complex fields and exit paths are protection mechanisms. Understand the core loop first, and everything that follows unfolds naturally.
-
-
-
-
diff --git a/s01_agent_loop/README.ja.md b/s01_agent_loop/README.ja.md
index 636af477c..b074e50ea 100644
--- a/s01_agent_loop/README.ja.md
+++ b/s01_agent_loop/README.ja.md
@@ -1,6 +1,6 @@
# s01: Agent Loop — ループ一つで十分
-[中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)
+[中文](README.zh.md) · [English](README.md) · [日本語](README.ja.md)
`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20
> *"One loop & Bash is all you need"* — ツール一つ + ループ一つ = 一つの Agent。
@@ -13,7 +13,7 @@
モデルにこう頼んだとする:「ディレクトリ内のファイル一覧を取得して、XXX.py を実行して」。
-モデルは bash コマンドを出力できるが、出力が終わると止まってしまう — 自分で実行することも、結果を見て推論を続けることもない。
+モデルは bash コマンドを出力できるが、出力が終わると止まってしまう。自分で実行することも、結果を見て推論を続けることもない。
手動で実行し、出力をチャットに貼り付ければ、モデルは続きを生成できる。次のコマンドが出たら、また実行して貼り付ける。
@@ -23,14 +23,14 @@
## ソリューション
-
+
一つの `while True` ループ — モデルがツールを呼べば続き、呼ばなければ停止。全体でたった 2 つのシグナル:
| シグナル | 意味 | ループの動作 |
|----------|------|-------------|
-| `stop_reason == "tool_use"` | モデルが「ツールが必要」と挙手 | 実行 → 結果を戻す → 続行 |
-| `stop_reason != "tool_use"` | モデルが「完了」と宣言 | ループ終了 |
+| `stop_reason == "tool_use"` | モデルがツール呼び出しを要求 | 実行 → 結果を戻す → 続行 |
+| `stop_reason != "tool_use"` | モデルがツール呼び出しなしで生成終了 | ループ終了 |
---
@@ -107,7 +107,7 @@ def agent_loop(messages):
messages.append({"role": "user", "content": results})
```
-30 行未満 — これが最小実行可能な agent harness のカーネルだ。これは知能そのものではなく、モデルが継続的に行動できるための最小ランタイムフレームワーク。モデルが決定し(ツールを呼ぶか、どれを呼ぶか)、harness が実行する(呼ばれたら実行し、結果を戻す)。次の 18 章はすべてこのループの上に仕組みを積み重ねていく。ループ自体は永遠に変わらない。
+30 行未満、これが最小実行可能な agent harness のカーネルだ。これは知能そのものではなく、モデルが継続的に行動できるための最小ランタイムフレームワーク。モデルが決定し(ツールを呼ぶか、どれを呼ぶか)、harness が実行する(呼ばれたら実行し、結果を戻す)。次の 18 章はすべてこのループの上に仕組みを積み重ねていく。ループ自体は永遠に変わらない。
---
@@ -146,16 +146,16 @@ python s01_agent_loop/code.py
→ s02 Tool Use:5 つの本格的なツールを与えたらどうなる? モデルは複数のツールを同時に呼び出すか? 並列実行で競合は起きないか?
-CC ソースコードを深掘り
+Claude Code ソースコードを深掘り
-> 以下は CC ソースコード `src/query.ts`(1729 行)の検証に基づく。核心的な違いは二つ:CC はループ継続の判断に `stop_reason` フィールドを頼らず、コンテンツに `tool_use` ブロックが含まれるかをチェックする(ストリーミングレスポンスでは `stop_reason` が信頼できないため)。CC には本番環境向けのより多くの終了パスとリカバリ戦略がある。
+> 以下は Claude Code ソースコード `src/query.ts`(1729 行)の検証に基づく。核心的な違いは二つ:Claude Code はループ継続の判断に `stop_reason` フィールドを頼らず、コンテンツに `tool_use` ブロックが含まれるかをチェックする(ストリーミングレスポンスでは `stop_reason` が信頼できないため)。Claude Code には本番環境向けのより多くの終了パスとリカバリ戦略がある。
-**教育版の 30 行 `while True` が CC の 1729 行の核心。** 以下の各項目は、すべてその核心の上に積み重ねられた保護機構である。
+以下の各項目は、すべて教育版のループの上に積み重ねられた保護機構である。
一、ループ構造の違い
-教育版は `response.stop_reason` をチェックする。CC はこれをループ継続の唯一の根拠として使わない — ストリーミングレスポンスでは、`stop_reason` がまだ更新されていなくても、コンテンツに既に `tool_use` ブロックが含まれている可能性がある。CC は `needsFollowUp` フラグを使用する:ストリーミングメッセージの受信時(`query.ts:830-834`)に、`tool_use` ブロックが検出されると `true` に設定される。`QueryEngine.ts` は `message_delta` から実際の `stop_reason` を取得して他の処理に利用するが、query loop 自体は `needsFollowUp` に依存する。
+教育版は `response.stop_reason` をチェックする。Claude Code はこれをループ継続の唯一の根拠として使わない — ストリーミングレスポンスでは、`stop_reason` がまだ更新されていなくても、コンテンツに既に `tool_use` ブロックが含まれている可能性がある。Claude Code は `needsFollowUp` フラグを使用する:ストリーミングメッセージの受信時(`query.ts:830-834`)に、`tool_use` ブロックが検出されると `true` に設定される。`QueryEngine.ts` は `message_delta` から実際の `stop_reason` を取得して他の処理に利用するが、query loop 自体は `needsFollowUp` に依存する。
```typescript
// query.ts:554-558
@@ -196,11 +196,11 @@ let needsFollowUp = false
四、ストリーミングツール実行と QueryEngine
-CC の `StreamingToolExecutor`(`query.ts:561`)は、モデルがまだ生成中にツールの実行を開始できる(concurrency-safe なツールは並列、それ以外は排他実行)。`QueryEngine.ts` はさらに、コスト超過や構造化出力の検証失敗などの保護を追加する。教育版はこれらを実装しない — 目標は概念の明確さであり、極限のパフォーマンスではない。
+Claude Code の `StreamingToolExecutor`(`query.ts:561`)は、モデルがまだ生成中にツールの実行を開始できる(concurrency-safe なツールは並列、それ以外は排他実行)。`QueryEngine.ts` はさらに、コスト超過や構造化出力の検証失敗などの保護を追加する。教育版はこれらを実装しない — 目標は概念の明確さであり、極限のパフォーマンスではない。
-**一言で**: query.ts の 1729 行の核心は 30 行の `while True`。複雑なフィールドや終了パスはすべて保護機構だ。まず核心のループを理解すれば、その後のすべては自然に理解できる。
+複雑なフィールドや終了パスはすべて保護機構であり、核心のループを理解していれば読み解きやすい。
diff --git a/s01_agent_loop/README.md b/s01_agent_loop/README.md
index 3b109715a..83e819180 100644
--- a/s01_agent_loop/README.md
+++ b/s01_agent_loop/README.md
@@ -1,50 +1,50 @@
-# s01: Agent Loop — 一个循环就够了
+# s01: The Agent Loop — One Loop Is All You Need
-[中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)
+[中文](README.zh.md) · [English](README.md) · [日本語](README.ja.md)
`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20
-> *"One loop & Bash is all you need"* — 一个工具 + 一个循环 = 一个 Agent。
+> *"One loop & Bash is all you need"* — One tool + one loop = one Agent.
>
-> **Harness 层**: 循环 — 模型与真实世界的第一道连接。
+> **Harness Layer**: The Loop — the first bridge between the model and the real world.
---
-## 问题
+## The Problem
-你提出了一个问题给大模型:“帮我读取下我的目录下有哪些文件,并且执行XXX.py”。
+You ask the model: "List the files in my directory and run XXX.py."
-模型能输出一条 bash 命令,但输出完了就停了,它不会自己跑,也不会看到结果后继续推理。
+The model can output a bash command, but once it's done outputting, it stops. It won't execute the command on its own, and it won't keep reasoning based on the result.
-你可以手动跑一遍,把输出粘贴回对话框,让它接着干。下一个命令出来,你再跑一遍、再贴回去。
+You could run it manually, paste the output back into the chat, and let it continue. Next command comes out, you run it again, paste it back.
-每一个来回,你都在做中间层。而把它自动化,就是这一章要做的事。
+Every round-trip, you're the middle layer. Automating that is what this chapter is about.
---
-## 解决方案
+## The Solution

-一个 `while True` 循环,模型调用工具就继续,不调用就停。整个过程只有两个信号:
+A `while True` loop: keep going when the model calls a tool, stop when it doesn't. The entire process hinges on two signals:
-| 信号 | 含义 | 循环动作 |
-|------|------|---------|
-| `stop_reason == "tool_use"` | 模型举手说"我要用工具" | 执行 → 结果喂回去 → 继续 |
-| `stop_reason != "tool_use"` | 模型说"我做完了" | 退出循环 |
+| Signal | Meaning | Loop Action |
+|--------|---------|-------------|
+| `stop_reason == "tool_use"` | Model requests a tool call | Execute → feed result back → continue |
+| `stop_reason != "tool_use"` | Model returns without a tool call | Exit loop |
---
-## 工作原理
+## How It Works
-将这个过程翻译成代码。分步来看:
+Let's translate this process into code. Step by step:
-**第 1 步**:把用户的问题作为第一条消息。
+**Step 1**: Start with the user's question as the first message.
```python
messages = [{"role": "user", "content": query}]
```
-**第 2 步**:将消息和工具定义一起发给 LLM。
+**Step 2**: Send the messages and tool definitions to the LLM.
```python
response = client.messages.create(
@@ -53,7 +53,7 @@ response = client.messages.create(
)
```
-**第 3 步**:追加模型回答,检查它是否调了工具。没调 → 结束。
+**Step 3**: Append the model's response and check whether it called a tool. No tool call → done.
```python
messages.append({"role": "assistant", "content": response.content})
@@ -61,7 +61,7 @@ if response.stop_reason != "tool_use":
return
```
-**第 4 步**:执行模型要求的工具,收集结果。
+**Step 4**: Execute the tool the model requested and collect the results.
```python
results = []
@@ -75,13 +75,13 @@ for block in response.content:
})
```
-**第 5 步**:把工具结果作为新消息追加,回到第 2 步。
+**Step 5**: Append the tool results as a new message and go back to Step 2.
```python
messages.append({"role": "user", "content": results})
```
-组装为一个完整函数:
+Assembled into a complete function:
```python
def agent_loop(messages):
@@ -107,55 +107,55 @@ def agent_loop(messages):
messages.append({"role": "user", "content": results})
```
-不到 30 行,这就是最小可运行的 agent harness 内核。它不是智能本身,而是让模型能持续行动的最小运行框架,模型负责决策(要不要调工具、调哪个),harness 负责执行(调了就跑、结果喂回去)。后面 18 个章节都在这个循环上叠加机制,循环本身始终不变。
+Under 30 lines — that's the minimal runnable agent harness kernel. It's not intelligence itself, but the smallest runtime framework that lets the model keep acting. The model decides (whether to call a tool, which one), the harness executes (if called, run it, feed the result back). The next 18 chapters all add mechanisms on top of this loop. The loop itself never changes.
---
-## 试一下
+## Try It
-> **教学 demo 提示**:代码会执行模型生成的 shell 命令。建议在一个临时测试目录中运行,避免影响你的项目文件。s03 会讲真正的权限系统。
+> **Teaching demo notice**: The code executes shell commands generated by the model. Run it in a temporary test directory to avoid affecting your project files. s03 covers the real permission system.
-**准备**(首次运行):
+**Setup** (first run):
```sh
pip install -r requirements.txt
cp .env.example .env
-# 编辑 .env,填入 ANTHROPIC_API_KEY 和 MODEL_ID
+# Edit .env, fill in ANTHROPIC_API_KEY and MODEL_ID
```
-**运行**:
+**Run**:
```sh
python s01_agent_loop/code.py
```
-试试这些 prompt:
+Try these prompts:
1. `Create a file called hello.py that prints "Hello, World!"`
2. `List all Python files in this directory`
3. `What is the current git branch?`
-观察重点:模型什么时候调用工具(循环继续),什么时候不调用(循环结束)?
+What to watch for: When does the model call a tool (loop continues), and when does it not (loop ends)?
---
-## 接下来
+## What's Next
-现在模型手里只有 bash 一个工具,读文件要 `cat`,写文件要 `echo ... >`,找个文件要 `find`,又丑又容易出错。
+Right now the model only has bash: reading files requires `cat`, writing files requires `echo ... >`, finding files requires `find`. Ugly and error-prone.
-s02 Tool Use → 给它 5 个真正的工具,会发生什么?模型会不会一次调用多个工具?几个工具同时跑会不会互相踩?
+→ s02 Tool Use: What happens when we give it 5 proper tools? Will the model call multiple tools at once? Will parallel tool executions step on each other?
-深入 CC 源码
+Dive into Claude Code Source Code
-> 以下内容基于 CC 源码 `src/query.ts`(1729 行)的核查。核心差异就两个:CC 不看 `stop_reason` 字段而是检查内容里有没有 tool_use 块(因为流式响应中 stop_reason 不可靠);CC 有更多的退出路径和恢复策略做生产级保护。
+> The following is based on a review of Claude Code source code `src/query.ts` (1729 lines). The core differences are twofold: Claude Code doesn't rely on the `stop_reason` field to decide whether to continue the loop — instead it checks whether the content contains `tool_use` blocks (because `stop_reason` is unreliable in streaming responses); Claude Code has more exit paths and recovery strategies for production-grade protection.
-**教学版的 30 行 `while True` 就是 CC 1729 行的核心。** 下面每一项都是在这个核心上叠加的保护机制。
+Everything below is a protection mechanism layered on top of the teaching version's loop.
-一、循环结构差异
+1. Loop Structure Differences
-教学版检查 `response.stop_reason`。CC 不把它作为循环继续的唯一依据——流式响应中 `stop_reason` 可能还没更新但内容里已经有 `tool_use` 块了。CC 用 `needsFollowUp` 标志:接收到流式消息时(`query.ts:830-834`),只要检测到 `tool_use` 块就设为 `true`;`QueryEngine.ts` 会从 `message_delta` 捕获真实 `stop_reason` 用于其他逻辑,但 query loop 本身靠 `needsFollowUp` 决定是否继续。
+The teaching version checks `response.stop_reason`. Claude Code doesn't use it as the sole signal for loop continuation — in streaming responses, `stop_reason` may not have updated yet even though `tool_use` blocks are already present. Claude Code uses a `needsFollowUp` flag: during streaming message reception (`query.ts:830-834`), it's set to `true` whenever a `tool_use` block is detected. `QueryEngine.ts` captures the real `stop_reason` from `message_delta` for other logic, but the query loop itself relies on `needsFollowUp`.
```typescript
// query.ts:554-558
@@ -167,41 +167,41 @@ let needsFollowUp = false
-二、State 对象 10 字段(教学版只用 messages)
-
-| # | 字段 | 用途 | 对应章节 |
-|---|------|------|---------|
-| 1 | `messages` | 当前迭代的消息数组 | s01 |
-| 2 | `toolUseContext` | 工具、信号、权限上下文 | s02 |
-| 3 | `autoCompactTracking` | 压缩状态追踪 | s08 |
-| 4 | `maxOutputTokensRecoveryCount` | token 恢复尝试次数(上限 3) | s11 |
-| 5 | `hasAttemptedReactiveCompact` | 本轮是否已尝试响应式压缩 | s08 |
-| 6 | `maxOutputTokensOverride` | 8K→64K 的升级覆盖 | s11 |
-| 7 | `pendingToolUseSummary` | 后台 Haiku 生成的 tool use 摘要 | s08 |
-| 8 | `stopHookActive` | 停止钩子是否产生阻塞错误 | s04 |
-| 9 | `turnCount` | 轮次计数(maxTurns 检查) | s01 |
-| 10 | `transition` | 上一次继续原因 | s11 |
-
-> 注:`taskBudgetRemaining`(`query.ts:291`)是 loop-local 局部变量,不在 State 上。源码注释明确写了 "Loop-local (not on State)"。
+2. State Object — 10 Fields (Teaching Version Only Uses messages)
+
+| # | Field | Purpose | Chapter |
+|---|-------|---------|---------|
+| 1 | `messages` | Message array for the current iteration | s01 |
+| 2 | `toolUseContext` | Tool, signal, and permission context | s02 |
+| 3 | `autoCompactTracking` | Compaction state tracking | s08 |
+| 4 | `maxOutputTokensRecoveryCount` | Token recovery attempt count (max 3) | s11 |
+| 5 | `hasAttemptedReactiveCompact` | Whether reactive compaction was attempted this round | s08 |
+| 6 | `maxOutputTokensOverride` | 8K→64K upgrade override | s11 |
+| 7 | `pendingToolUseSummary` | Background Haiku-generated tool use summary | s08 |
+| 8 | `stopHookActive` | Whether the stop hook produced a blocking error | s04 |
+| 9 | `turnCount` | Turn count (for maxTurns check) | s01 |
+| 10 | `transition` | Last continue reason | s11 |
+
+> Note: `taskBudgetRemaining` (`query.ts:291`) is a loop-local variable, not on State. The source comment explicitly says "Loop-local (not on State)".
-三、多条退出和继续路径
+3. Multiple Exit and Continue Paths
-教学版只有 1 条退出路径(模型不调工具就结束)。生产版有多条退出和继续路径,覆盖 blocking limit、prompt too long、model error、abort、hook stop、max turns、token budget continuation、reactive compact retry 等场景。每种场景都有对应的恢复或退出策略。
+The teaching version has only 1 exit path (model doesn't call a tool → done). The production version has multiple exit and continue paths, covering blocking limit, prompt too long, model error, abort, hook stop, max turns, token budget continuation, reactive compact retry, and more. Each scenario has a corresponding recovery or exit strategy.
-四、流式工具执行和 QueryEngine
+4. Streaming Tool Execution and QueryEngine
-CC 的 `StreamingToolExecutor`(`query.ts:561`)让工具在模型还在生成时就开始并行执行(根据工具是否 concurrency-safe 决定并发或独占)。`QueryEngine.ts` 额外加了费用超限、结构化输出验证失败等保护。教学版不实现这些——目标是概念清晰,不是性能极致。
+Claude Code's `StreamingToolExecutor` (`query.ts:561`) allows tools to begin parallel execution while the model is still generating (concurrency-safe tools run in parallel, others run exclusively). `QueryEngine.ts` adds additional protections for cost overruns, structured output validation failures, and more. The teaching version doesn't implement these — the goal is conceptual clarity, not peak performance.
-**一句话**:1729 行的 query.ts 核心就是 30 行 `while True`。所有复杂字段和退出路径都是保护机制。先理解核心循环,后面的一切自然展开。
+All the complex fields and exit paths are protection mechanisms. Understanding the core loop makes the rest easier to follow.
-
+
diff --git a/s01_agent_loop/README.zh.md b/s01_agent_loop/README.zh.md
new file mode 100644
index 000000000..12776730c
--- /dev/null
+++ b/s01_agent_loop/README.zh.md
@@ -0,0 +1,207 @@
+# s01: Agent Loop — 一个循环就够了
+
+[中文](README.zh.md) · [English](README.md) · [日本語](README.ja.md)
+
+`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20
+> *"One loop & Bash is all you need"* — 一个工具 + 一个循环 = 一个 Agent。
+>
+> **Harness 层**: 循环 — 模型与真实世界的第一道连接。
+
+---
+
+## 问题
+
+你提出了一个问题给大模型:“帮我读取下我的目录下有哪些文件,并且执行XXX.py”。
+
+模型能输出一条 bash 命令,但输出完了就停了,它不会自己跑,也不会看到结果后继续推理。
+
+你可以手动跑一遍,把输出粘贴回对话框,让它接着干。下一个命令出来,你再跑一遍、再贴回去。
+
+每一个来回,你都在做中间层。而把它自动化,就是这一章要做的事。
+
+---
+
+## 解决方案
+
+
+
+一个 `while True` 循环,模型调用工具就继续,不调用就停。整个过程只有两个信号:
+
+| 信号 | 含义 | 循环动作 |
+|------|------|---------|
+| `stop_reason == "tool_use"` | 模型请求调用工具 | 执行 → 结果喂回去 → 继续 |
+| `stop_reason != "tool_use"` | 模型未请求工具,生成结束 | 退出循环 |
+
+---
+
+## 工作原理
+
+将这个过程翻译成代码。分步来看:
+
+**第 1 步**:把用户的问题作为第一条消息。
+
+```python
+messages = [{"role": "user", "content": query}]
+```
+
+**第 2 步**:将消息和工具定义一起发给 LLM。
+
+```python
+response = client.messages.create(
+ model=MODEL, system=SYSTEM, messages=messages,
+ tools=TOOLS, max_tokens=8000,
+)
+```
+
+**第 3 步**:追加模型回答,检查它是否调了工具。没调 → 结束。
+
+```python
+messages.append({"role": "assistant", "content": response.content})
+if response.stop_reason != "tool_use":
+ return
+```
+
+**第 4 步**:执行模型要求的工具,收集结果。
+
+```python
+results = []
+for block in response.content:
+ if block.type == "tool_use":
+ output = run_bash(block.input["command"])
+ results.append({
+ "type": "tool_result",
+ "tool_use_id": block.id,
+ "content": output,
+ })
+```
+
+**第 5 步**:把工具结果作为新消息追加,回到第 2 步。
+
+```python
+messages.append({"role": "user", "content": results})
+```
+
+组装为一个完整函数:
+
+```python
+def agent_loop(messages):
+ while True:
+ response = client.messages.create(
+ model=MODEL, system=SYSTEM, messages=messages,
+ tools=TOOLS, max_tokens=8000,
+ )
+ messages.append({"role": "assistant", "content": response.content})
+
+ if response.stop_reason != "tool_use":
+ return
+
+ results = []
+ for block in response.content:
+ if block.type == "tool_use":
+ output = run_bash(block.input["command"])
+ results.append({
+ "type": "tool_result",
+ "tool_use_id": block.id,
+ "content": output,
+ })
+ messages.append({"role": "user", "content": results})
+```
+
+不到 30 行,这就是最小可运行的 agent harness 内核。它不是智能本身,而是让模型能持续行动的最小运行框架,模型负责决策(要不要调工具、调哪个),harness 负责执行(调了就跑、结果喂回去)。后面 18 个章节都在这个循环上叠加机制,循环本身始终不变。
+
+---
+
+## 试一下
+
+> **教学 demo 提示**:代码会执行模型生成的 shell 命令。建议在一个临时测试目录中运行,避免影响你的项目文件。s03 会讲真正的权限系统。
+
+**准备**(首次运行):
+
+```sh
+pip install -r requirements.txt
+cp .env.example .env
+# 编辑 .env,填入 ANTHROPIC_API_KEY 和 MODEL_ID
+```
+
+**运行**:
+
+```sh
+python s01_agent_loop/code.py
+```
+
+试试这些 prompt:
+
+1. `Create a file called hello.py that prints "Hello, World!"`
+2. `List all Python files in this directory`
+3. `What is the current git branch?`
+
+观察重点:模型什么时候调用工具(循环继续),什么时候不调用(循环结束)?
+
+---
+
+## 接下来
+
+现在模型手里只有 bash 一个工具,读文件要 `cat`,写文件要 `echo ... >`,找个文件要 `find`,不够直观,也容易拼错。
+
+s02 Tool Use → 给它 5 个真正的工具,会发生什么?模型会不会一次调用多个工具?几个工具同时跑会不会互相踩?
+
+
+深入 Claude Code 源码
+
+> 以下内容基于 Claude Code 源码 `src/query.ts`(1729 行)的核查。核心差异就两个:Claude Code 不看 `stop_reason` 字段而是检查内容里有没有 tool_use 块(因为流式响应中 stop_reason 不可靠);Claude Code 有更多的退出路径和恢复策略做生产级保护。
+
+下面每一项都是在教学版循环基础上叠加的保护机制。
+
+
+一、循环结构差异
+
+教学版检查 `response.stop_reason`。Claude Code 不把它作为循环继续的唯一依据——流式响应中 `stop_reason` 可能还没更新但内容里已经有 `tool_use` 块了。Claude Code 用 `needsFollowUp` 标志:接收到流式消息时(`query.ts:830-834`),只要检测到 `tool_use` 块就设为 `true`;`QueryEngine.ts` 会从 `message_delta` 捕获真实 `stop_reason` 用于其他逻辑,但 query loop 本身靠 `needsFollowUp` 决定是否继续。
+
+```typescript
+// query.ts:554-558
+// stop_reason === 'tool_use' is unreliable.
+// Set during streaming whenever a tool_use block arrives.
+let needsFollowUp = false
+```
+
+
+
+
+二、State 对象 10 字段(教学版只用 messages)
+
+| # | 字段 | 用途 | 对应章节 |
+|---|------|------|---------|
+| 1 | `messages` | 当前迭代的消息数组 | s01 |
+| 2 | `toolUseContext` | 工具、信号、权限上下文 | s02 |
+| 3 | `autoCompactTracking` | 压缩状态追踪 | s08 |
+| 4 | `maxOutputTokensRecoveryCount` | token 恢复尝试次数(上限 3) | s11 |
+| 5 | `hasAttemptedReactiveCompact` | 本轮是否已尝试响应式压缩 | s08 |
+| 6 | `maxOutputTokensOverride` | 8K→64K 的升级覆盖 | s11 |
+| 7 | `pendingToolUseSummary` | 后台 Haiku 生成的 tool use 摘要 | s08 |
+| 8 | `stopHookActive` | 停止钩子是否产生阻塞错误 | s04 |
+| 9 | `turnCount` | 轮次计数(maxTurns 检查) | s01 |
+| 10 | `transition` | 上一次继续原因 | s11 |
+
+> 注:`taskBudgetRemaining`(`query.ts:291`)是 loop-local 局部变量,不在 State 上。源码注释明确写了 "Loop-local (not on State)"。
+
+
+
+
+三、多条退出和继续路径
+
+教学版只有 1 条退出路径(模型不调工具就结束)。生产版有多条退出和继续路径,覆盖 blocking limit、prompt too long、model error、abort、hook stop、max turns、token budget continuation、reactive compact retry 等场景。每种场景都有对应的恢复或退出策略。
+
+
+
+
+四、流式工具执行和 QueryEngine
+
+Claude Code 的 `StreamingToolExecutor`(`query.ts:561`)让工具在模型还在生成时就开始并行执行(根据工具是否 concurrency-safe 决定并发或独占)。`QueryEngine.ts` 额外加了费用超限、结构化输出验证失败等保护。教学版不实现这些——目标是概念清晰,不是性能极致。
+
+
+
+所有复杂字段和退出路径都是保护机制,理解核心循环后再看这些会更容易。
+
+
+
+
diff --git a/s01_agent_loop/images/agent-loop.en.svg b/s01_agent_loop/images/agent-loop.en.svg
deleted file mode 100644
index 541ab3f96..000000000
--- a/s01_agent_loop/images/agent-loop.en.svg
+++ /dev/null
@@ -1,86 +0,0 @@
-
diff --git a/s01_agent_loop/images/agent-loop.ja.svg b/s01_agent_loop/images/agent-loop.ja.svg
deleted file mode 100644
index ee726e697..000000000
--- a/s01_agent_loop/images/agent-loop.ja.svg
+++ /dev/null
@@ -1,86 +0,0 @@
-
diff --git a/s01_agent_loop/images/agent-loop.svg b/s01_agent_loop/images/agent-loop.svg
index 87c6b5008..0c4af8c26 100644
--- a/s01_agent_loop/images/agent-loop.svg
+++ b/s01_agent_loop/images/agent-loop.svg
@@ -1,86 +1,69 @@
-