feat: refresh course through workflow and goal loops

This commit is contained in:
Haoran
2026-07-30 19:14:04 +08:00
parent 2dd1852d9e
commit cb8fae1bdd
125 changed files with 10882 additions and 7661 deletions

View File

@@ -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
![Agent Loop](images/agent-loop.en.svg)
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?
<details>
<summary>Dive into CC Source Code</summary>
> 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.
<details>
<summary>1. Loop Structure Differences</summary>
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
```
</details>
<details>
<summary>2. State Object — 10 Fields (Teaching Version Only Uses messages)</summary>
| # | 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)".
</details>
<details>
<summary>3. Multiple Exit and Continue Paths</summary>
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.
</details>
<details>
<summary>4. Streaming Tool Execution and QueryEngine</summary>
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.
</details>
**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.
</details>
<!-- translation-sync: zh@v1, en@v1, ja@v1 -->

View File

@@ -1,8 +1,8 @@
# s01: Agent Loop — ループ一つで十分
[中文](README.md) · [English](README.en.md) · [日本語](README.ja.md)
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20
`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 → s22
> *"One loop & Bash is all you need"* — ツール一つ + ループ一つ = 一つの Agent。
>
> **Harness レイヤー**: ループ — モデルと現実世界をつなぐ最初の架け橋。

View File

@@ -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)
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20
> *"One loop & Bash is all you need"* — 一个工具 + 一个循环 = 一个 Agent
`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 → s22
> *"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
![Agent Loop](images/agent-loop.svg)
![Agent Loop](images/agent-loop.en.svg)
一个 `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 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:
**第 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?
<details>
<summary>深入 CC 源码</summary>
<summary>Dive into CC Source Code</summary>
> 以下内容基于 CC 源码 `src/query.ts`1729 的核查。核心差异就两个CC 不看 `stop_reason` 字段而是检查内容里有没有 tool_use 块(因为流式响应中 stop_reason 不可靠CC 有更多的退出路径和恢复策略做生产级保护。
> 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.
**教学版的 30 行 `while True` 就是 CC 1729 行的核心。** 下面每一项都是在这个核心上叠加的保护机制。
**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.
<details>
<summary>一、循环结构差异</summary>
<summary>1. Loop Structure Differences</summary>
教学版检查 `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`. 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
@@ -167,41 +167,41 @@ let needsFollowUp = false
</details>
<details>
<summary>二、State 对象 10 字段(教学版只用 messages</summary>
<summary>2. State Object — 10 Fields (Teaching Version Only Uses messages)</summary>
| # | 字段 | 用途 | 对应章节 |
|---|------|------|---------|
| 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 |
| # | 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 |
> 注:`taskBudgetRemaining``query.ts:291`)是 loop-local 局部变量,不在 State 上。源码注释明确写了 "Loop-local (not on State)"
> Note: `taskBudgetRemaining` (`query.ts:291`) is a loop-local variable, not on State. The source comment explicitly says "Loop-local (not on State)".
</details>
<details>
<summary>三、多条退出和继续路径</summary>
<summary>3. Multiple Exit and Continue Paths</summary>
教学版只有 1 条退出路径(模型不调工具就结束)。生产版有多条退出和继续路径,覆盖 blocking limitprompt too longmodel erroraborthook stopmax turnstoken budget continuationreactive 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.
</details>
<details>
<summary>四、流式工具执行和 QueryEngine</summary>
<summary>4. Streaming Tool Execution and QueryEngine</summary>
CC `StreamingToolExecutor``query.ts:561`)让工具在模型还在生成时就开始并行执行(根据工具是否 concurrency-safe 决定并发或独占)。`QueryEngine.ts` 额外加了费用超限、结构化输出验证失败等保护。教学版不实现这些——目标是概念清晰,不是性能极致。
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.
</details>
**一句话**1729 行的 query.ts 核心就是 30 行 `while True`。所有复杂字段和退出路径都是保护机制。先理解核心循环,后面的一切自然展开。
**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.
</details>
<!-- translation-sync: zh@v1, en@v0, ja@v0 -->
<!-- translation-sync: zh@v1, en@v1, ja@v1 -->

207
s01_agent_loop/README.zh.md Normal file
View File

@@ -0,0 +1,207 @@
# s01: Agent Loop — 一个循环就够了
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
`s01` → [s02](../s02_tool_use/) → s03 → s04 → ... → s20 → s21 → s22
> *"One loop & Bash is all you need"* — 一个工具 + 一个循环 = 一个 Agent。
>
> **Harness 层**: 循环 — 模型与真实世界的第一道连接。
---
## 问题
你提出了一个问题给大模型“帮我读取下我的目录下有哪些文件并且执行XXX.py”。
模型能输出一条 bash 命令,但输出完了就停了,它不会自己跑,也不会看到结果后继续推理。
你可以手动跑一遍,把输出粘贴回对话框,让它接着干。下一个命令出来,你再跑一遍、再贴回去。
每一个来回,你都在做中间层。而把它自动化,就是这一章要做的事。
---
## 解决方案
![Agent Loop](images/agent-loop.svg)
一个 `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 个真正的工具,会发生什么?模型会不会一次调用多个工具?几个工具同时跑会不会互相踩?
<details>
<summary>深入 CC 源码</summary>
> 以下内容基于 CC 源码 `src/query.ts`1729 行的核查。核心差异就两个CC 不看 `stop_reason` 字段而是检查内容里有没有 tool_use 块(因为流式响应中 stop_reason 不可靠CC 有更多的退出路径和恢复策略做生产级保护。
**教学版的 30 行 `while True` 就是 CC 1729 行的核心。** 下面每一项都是在这个核心上叠加的保护机制。
<details>
<summary>一、循环结构差异</summary>
教学版检查 `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` 决定是否继续。
```typescript
// query.ts:554-558
// stop_reason === 'tool_use' is unreliable.
// Set during streaming whenever a tool_use block arrives.
let needsFollowUp = false
```
</details>
<details>
<summary>二、State 对象 10 字段(教学版只用 messages</summary>
| # | 字段 | 用途 | 对应章节 |
|---|------|------|---------|
| 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)"。
</details>
<details>
<summary>三、多条退出和继续路径</summary>
教学版只有 1 条退出路径(模型不调工具就结束)。生产版有多条退出和继续路径,覆盖 blocking limit、prompt too long、model error、abort、hook stop、max turns、token budget continuation、reactive compact retry 等场景。每种场景都有对应的恢复或退出策略。
</details>
<details>
<summary>四、流式工具执行和 QueryEngine</summary>
CC 的 `StreamingToolExecutor``query.ts:561`)让工具在模型还在生成时就开始并行执行(根据工具是否 concurrency-safe 决定并发或独占)。`QueryEngine.ts` 额外加了费用超限、结构化输出验证失败等保护。教学版不实现这些——目标是概念清晰,不是性能极致。
</details>
**一句话**1729 行的 query.ts 核心就是 30 行 `while True`。所有复杂字段和退出路径都是保护机制。先理解核心循环,后面的一切自然展开。
</details>
<!-- translation-sync: zh@v1, en@v0, ja@v0 -->