feat: consolidate course into 21 lessons

This commit is contained in:
Haoran
2026-07-31 03:15:58 +08:00
parent 4bc33ec858
commit 2d69019342
200 changed files with 7338 additions and 10829 deletions

View File

@@ -2,7 +2,7 @@
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 → s22
s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21
> *"遅い操作はバックグラウンドへ、agent は処理を継続"* — バックグラウンドスレッドでコマンドを実行、完了時に通知を注入。
>
@@ -24,7 +24,7 @@ Agent の bash ツールも同じ。`pip install torch` は 10 分、`npm run bu
![Background Tasks Overview](images/background-tasks-overview.ja.svg)
教学版は S12 の簡易タスクシステムとプロンプト組み立てを踏襲。バックグラウンドタスクに集中するため、完全なエラーリカバリ、メモリ、スキルシステムは省略。唯一の変更:遅い操作をバックグラウンドスレッドに投げ、Agent はループを継続、バックグラウンド完了時に通知を注入
この章では、時間のかかる操作をバックグラウンドスレッドに送り、Agent はループを続行する。タスクが完了すると、結果が通知として会話に注入される
同期 vs バックグラウンド:
@@ -41,7 +41,7 @@ Agent の bash ツールも同じ。`pip install torch` は 10 分、`npm run bu
### should_run_background: 明示的リクエスト優先、ヒューリスティックフォールバック
モデルは bash ツールの `run_in_background` パラメータで明示的にバックグラウンド実行をリクエストする。モデルが指定ない場合、教学版はキーワードヒューリスティックにフォールバック
モデルは bash ツールの `run_in_background` パラメータで明示的にバックグラウンド実行をリクエストする。指定ない場合はキーワードヒューリスティックで判断する
```python
def is_slow_operation(tool_name: str, tool_input: dict) -> bool:
@@ -61,8 +61,6 @@ def should_run_background(tool_name: str, tool_input: dict) -> bool:
return is_slow_operation(tool_name, tool_input)
```
CC の bash ツールスキーマには `run_in_background: boolean` パラメータがある(`BashTool.tsx:241`)。モデルがどのコマンドをバックグラウンドにするかを決定、キーワード推測ではない。教学版はヒューリスティックをフォールバックとして残すが、主パスはモデルの明示的リクエスト。
### start_background_task: バックグラウンド実行とライフサイクル
ツール呼び出しをワーカー関数にラップし、daemon スレッドにディスパッチ。各バックグラウンドタスクは一意 ID を持ち、`background_tasks` 辞書で状態を追跡:
@@ -96,7 +94,7 @@ def start_background_task(block) -> str:
return bg_id
```
`[Running in background...]` ではなく `bg_id` を返す。`daemon=True` Agent プロセス終了時にスレッドも終了。教学版はメモリ内辞書で追跡。実際の CC は `LocalShellTaskState` を持ち、出力をファイルにリダイレクト、タスク停止や継続出力読み取りを含む完全なライフサイクルを備える。
`start_background_task()` `bg_id` を返す。`daemon=True` により、Agent プロセス終了時にスレッドも終了る。
### collect_background_results: 通知収集
@@ -157,8 +155,6 @@ messages.append({"role": "user", "content": user_content})
遅い操作は `bg_id` 付きプレースホルダー tool_result を返し、LLM はコマンドがまだ実行中だと知り、先に他のことをできる。バックグラウンド完了時、通知は独立した text block として現在のターンの tool_result と一緒に 1 つの user メッセージを構成する。
教学版は agent loop が継続実行中にバックグラウンド結果をポーリングする。実際の CC は通知キュー(`messageQueueManager.ts`)でバックグラウンド完了イベントを後続ターンに配信、ツールループを待つ必要はない。
### 組み合わせて実行
```
@@ -216,46 +212,5 @@ python s13_background_tasks/code.py
s14 Cron Scheduler → Agent にアラームクロックを付ける。
<details>
<summary>CC ソースコード深掘り</summary>
> 以下は CC ソースコード `query.ts`211, 1054-1060, 1411-1482 行)、`services/toolUseSummary/toolUseSummaryGenerator.ts`L15 プロンプトテキスト)、`LocalShellTask.tsx`L24-25 定数, L59-98 ウォッチドッグロジック)、`messageQueueManager.ts`(通知キュー)、`utils/task/framework.ts`L267 `enqueueTaskNotification`)の完全分析に基づく。
### 一、pendingToolUseSummaryHaiku バックグラウンド生成
CC は各ツール実行バッチの後、Haiku サイドクエリを開始してツール使用サマリを生成。開始コードは `query.ts:1411-1482`、プロンプトテキストは `services/toolUseSummary/toolUseSummaryGenerator.ts:15`(変数 `TOOL_USE_SUMMARY_SYSTEM_PROMPT`)。プロンプトは "Write a short summary label... think git-commit-subject, not sentence"、過去形、約 30 文字。
Haiku サマリ(~1sはメインモデルのストリーミング出力5-30s中に完了。次のターン開始前にサマリを yield。SDK コンシューマーはこれらのサマリをモバイル進捗表示に使用。
### 二、スレッドモデル:本当のスレッドはない
CC は Node.js/Bun のシングルスレッドイベントループで動作。「バックグラウンド」は単に「await しない」こと。`ShellCommand.background(taskId)` は stdout/stderr をファイルにリダイレクトし、プロセスを独立実行。
### 三、7 種のバックグラウンドタスク型
CC は 7 種のバックグラウンドタスク型を定義(`Task.ts:7-13``local_bash``local_agent``remote_agent``in_process_teammate``local_workflow``monitor_mcp``dream`。それぞれ独自の登録、ライフサイクル、通知メカニズムを持つ。
### 四、通知注入:コマンドキュー
バックグラウンドタスク完了時、`enqueueTaskNotification``utils/task/framework.ts:267`)または `enqueuePendingNotification``messageQueueManager.ts`)で共有コマンドキューにエンキュー。通知形式は構造化 XML
```xml
<task_notification>
<status>completed</status>
<summary>Background command "npm test" completed (exit code 0)</summary>
</task_notification>
```
優先度は `next` > `later``messageQueueManager.ts`)。バックグラウンドタスクはデフォルト `later`(ユーザー入力をブロックしない)。消費点は `query.ts:1566-1593`
### 五、停滞ウォッチドッグ
バックグラウンド bash タスクにはウォッチドッグがある(`LocalShellTask.tsx` L24-25 定数, L59-98 ロジック。出力の停滞を定期チェックし、45 秒間増加がない場合にインタラクティブプロンプト(`(y/n)` 等)を検出、バックグラウンドタスクが無応答のインタラクティブダイアログでスタックするのを防ぐ。
### 六、同時実行制限
フォアグラウンドツール呼び出し:`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`(デフォルト 10 同時実行安全ツール)。バックグラウンド bash タスク:ハードリミットなし、独立したサブプロセス。
</details>
<!-- translation-sync: zh@v1, en@v1, ja@v1 -->

View File

@@ -2,7 +2,7 @@
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 → s22
s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21
> *"Slow operations go to the background, agent continues processing"* — Background threads run commands, inject notifications when done.
>
@@ -24,7 +24,7 @@ Reading files is milliseconds, no wait. `git status` returns in under a second,
![Background Tasks Overview](images/background-tasks-overview.en.svg)
Teaching code carries forward S12's simplified task system and prompt assembly; to stay focused on background tasks, it omits full error recovery, memory, and skill systems. The only change: slow operations go to background threads, the agent continues running the loop, and background results are injected as notifications.
This chapter sends slow operations to background threads so the agent can keep running the loop. When a task finishes, its result is injected as a notification.
Sync vs Background:
@@ -41,7 +41,7 @@ Sync vs Background:
### should_run_background: Explicit Request First, Heuristic Fallback
The model explicitly requests background execution via the bash tool's `run_in_background` parameter. If the model doesn't specify, the teaching version falls back to keyword heuristics:
The model explicitly requests background execution via the bash tool's `run_in_background` parameter. If the model does not specify it, keyword heuristics decide:
```python
def is_slow_operation(tool_name: str, tool_input: dict) -> bool:
@@ -61,8 +61,6 @@ def should_run_background(tool_name: str, tool_input: dict) -> bool:
return is_slow_operation(tool_name, tool_input)
```
CC's bash tool schema has a `run_in_background: boolean` parameter (`BashTool.tsx:241`). The model decides which commands go to background, no keyword guessing. The teaching version keeps heuristics as fallback, but the primary path is explicit model request.
### start_background_task: Background Execution and Lifecycle
Wraps the tool call in a worker function, dispatches to a daemon thread. Each background task gets a unique ID, with state tracked in the `background_tasks` dict:
@@ -96,7 +94,7 @@ def start_background_task(block) -> str:
return bg_id
```
Returns `bg_id` instead of just `[Running in background...]`. `daemon=True` ensures threads exit when the agent process exits. The teaching version uses in-memory dicts for tracking; real CC has `LocalShellTaskState`, output redirected to files, with full lifecycle including stopping tasks and reading subsequent output.
`start_background_task()` returns `bg_id`. `daemon=True` ensures the thread exits with the agent process.
### collect_background_results: Notification Collection
@@ -157,8 +155,6 @@ messages.append({"role": "user", "content": user_content})
Slow operations get a placeholder tool_result with `bg_id`, so the LLM knows this command is still running and can do other things first. When background completes, the notification is injected as an independent text block alongside the current turn's tool_results in one user message.
The teaching version polls background results while the agent loop continues running. Real CC uses a notification queue (`messageQueueManager.ts`) to deliver background completion events to subsequent turns, without waiting for the tool loop.
### Putting It Together
```
@@ -216,46 +212,5 @@ Background tasks solved "slow operations don't block." But what if you want to d
s14 Cron Scheduler → Give the agent an alarm clock.
<details>
<summary>Deep Dive into CC Source</summary>
> The following is a complete analysis based on CC source code `query.ts` (lines 211, 1054-1060, 1411-1482), `services/toolUseSummary/toolUseSummaryGenerator.ts` (L15 prompt text), `LocalShellTask.tsx` (L24-25 constants, L59-98 watchdog logic), `messageQueueManager.ts` (notification queue), `utils/task/framework.ts` (L267 `enqueueTaskNotification`).
### 1. pendingToolUseSummary: Haiku Background Generation
CC starts a Haiku side-query after each batch of tool executions to generate a tool use summary. Initiated at `query.ts:1411-1482`, prompt text defined at `services/toolUseSummary/toolUseSummaryGenerator.ts:15` (variable `TOOL_USE_SUMMARY_SYSTEM_PROMPT`). The prompt is "Write a short summary label... think git-commit-subject, not sentence", past tense, ~30 characters.
Haiku summary (~1s) completes during the main model's streaming output (5-30s). Before the next turn starts, the summary is yielded. SDK consumers use these summaries for mobile progress display.
### 2. Thread Model: No Real Threads
CC runs on Node.js/Bun's single-threaded event loop. "Background" just means "don't await". `ShellCommand.background(taskId)` redirects stdout/stderr to files, letting the process run independently.
### 3. Seven Background Task Types
CC defines 7 background task types (`Task.ts:7-13`): `local_bash`, `local_agent`, `remote_agent`, `in_process_teammate`, `local_workflow`, `monitor_mcp`, `dream`. Each has its own registration, lifecycle, and notification mechanism.
### 4. Notification Injection: Command Queue
When a background task completes, it's enqueued via `enqueueTaskNotification` (`utils/task/framework.ts:267`) or `enqueuePendingNotification` (`messageQueueManager.ts`) into a shared command queue. The notification format is structured XML:
```xml
<task_notification>
<status>completed</status>
<summary>Background command "npm test" completed (exit code 0)</summary>
</task_notification>
```
Priority is `next` > `later` (`messageQueueManager.ts`). Background tasks default to `later` (don't block user input). Consumption point at `query.ts:1566-1593`.
### 5. Stall Watchdog
Background bash tasks have a watchdog (`LocalShellTask.tsx` L24-25 constants, L59-98 logic) that periodically checks if output has stalled. After 45 seconds with no growth, it detects interactive prompts (`(y/n)` etc.), preventing background tasks from getting stuck on unanswered interactive dialogs.
### 6. Concurrency Limits
Foreground tool calls: `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` (default 10 concurrent safe tools). Background bash tasks: no hard limit, they're independent subprocesses.
</details>
<!-- translation-sync: zh@v1, en@v1, ja@v1 -->

View File

@@ -2,7 +2,7 @@
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21 → s22
s01 → ... → s11 → s12 → `s13` → [s14](../s14_cron_scheduler/) → s15 → ... → s20 → s21
> *"慢操作丢后台, agent 继续处理"* — 后台线程跑命令, 完成后注入通知。
>
@@ -24,7 +24,7 @@ Agent 的 bash 工具也一样。`pip install torch` 要 10 分钟,`npm run bu
![Background Tasks Overview](images/background-tasks-overview.svg)
教学代码沿用 S12 的简化任务系统和 prompt 组装;为了聚焦后台任务,省略完整错误恢复、记忆和技能系统。唯一的变动:慢操作扔到后台线程Agent 继续跑循环,后台完成后把通知注入对话
本章把慢操作放入后台线程Agent 继续运行循环;任务完成后,结果以通知形式注入对话。
同步 vs 后台:
@@ -41,7 +41,7 @@ Agent 的 bash 工具也一样。`pip install torch` 要 10 分钟,`npm run bu
### should_run_background: 显式请求优先,启发式兜底
模型通过 bash 工具的 `run_in_background` 参数显式请求后台执行。如果模型没指定,教学版用关键词启发式兜底
模型通过 bash 工具的 `run_in_background` 参数显式请求后台执行。如果模型没指定,则使用关键词启发式判断
```python
def is_slow_operation(tool_name: str, tool_input: dict) -> bool:
@@ -61,8 +61,6 @@ def should_run_background(tool_name: str, tool_input: dict) -> bool:
return is_slow_operation(tool_name, tool_input)
```
CC 的 bash 工具 schema 里有 `run_in_background: boolean` 参数(`BashTool.tsx:241`)。模型自己决定哪些命令丢后台,不靠关键词猜。教学版保留启发式作为兜底,但主路径是模型显式请求。
### start_background_task: 后台执行与生命周期
把工具调用包装成 worker 函数,扔到 daemon 线程里执行。每个后台任务有唯一 ID状态存在 `background_tasks` 字典里:
@@ -96,7 +94,7 @@ def start_background_task(block) -> str:
return bg_id
```
返回 `bg_id` 而不是只返回 `[Running in background...]``daemon=True` 确保 Agent 进程退出时线程跟着退出。教学版用内存字典追踪状态;真实 CC 有 `LocalShellTaskState`,输出重定向到文件,支持停止任务、读取后续输出等完整生命周期
`start_background_task()` 返回 `bg_id``daemon=True` 确保 Agent 进程退出时线程一起退出
### collect_background_results: 通知收集
@@ -157,8 +155,6 @@ messages.append({"role": "user", "content": user_content})
慢操作先回一个带 `bg_id` 的占位 tool_resultLLM 知道这个命令还在跑,可以先做别的事。后台完成后,通知作为独立 text block 和当前轮的 tool_result 一起组成 user 消息。
教学版在 agent loop 继续运行时轮询后台结果。真实 CC 通过通知队列(`messageQueueManager.ts`)把后台完成事件送入后续 turn不需要等工具循环。
### 合起来跑
```
@@ -216,46 +212,5 @@ python s13_background_tasks/code.py
s14 Cron Scheduler → 给 Agent 装一个闹钟。
<details>
<summary>深入 CC 源码</summary>
> 以下基于 CC 源码 `query.ts`211, 1054-1060, 1411-1482 行)、`services/toolUseSummary/toolUseSummaryGenerator.ts`L15 prompt 文本)、`LocalShellTask.tsx`L24-25 常量, L59-98 看门狗逻辑)、`messageQueueManager.ts`(通知队列)、`utils/task/framework.ts`L267 `enqueueTaskNotification`)的完整分析。
### 一、pendingToolUseSummaryHaiku 后台生成
CC 在每批工具执行完后,启动一个 Haiku side-query 生成工具使用摘要。发起代码在 `query.ts:1411-1482`prompt 文本定义在 `services/toolUseSummary/toolUseSummaryGenerator.ts:15`(变量名 `TOOL_USE_SUMMARY_SYSTEM_PROMPT`)。提示是 "Write a short summary label... think git-commit-subject, not sentence",过去时态,约 30 字符。
Haiku 摘要(~1s在主模型流式生成5-30s期间完成。下一轮开始前把摘要 yield 出去。SDK 消费这些摘要做移动端进度展示。
### 二、线程模型:没有真正的线程
CC 运行在 Node.js/Bun 单线程事件循环中。"后台"只是 "不 await"。`ShellCommand.background(taskId)` 把 stdout/stderr 重定向到文件,让进程独立运行。
### 三、七种后台任务类型
CC 定义了 7 种后台任务(`Task.ts:7-13``local_bash``local_agent``remote_agent``in_process_teammate``local_workflow``monitor_mcp``dream`。每种有自己的注册、生命周期和通知机制。
### 四、通知注入:命令队列
后台任务完成后通过 `enqueueTaskNotification``utils/task/framework.ts:267`)或 `enqueuePendingNotification``messageQueueManager.ts`)入队到共享命令队列。通知格式是结构化的 XML
```xml
<task_notification>
<status>completed</status>
<summary>Background command "npm test" completed (exit code 0)</summary>
</task_notification>
```
优先级分 `next` > `later``messageQueueManager.ts`)。后台任务默认 `later`(不阻塞用户输入)。消费点在 `query.ts:1566-1593`
### 五、停滞看门狗
后台 bash 任务有一个看门狗(`LocalShellTask.tsx` L24-25 常量, L59-98 逻辑定期检查输出是否停滞45 秒无增长后检测交互式提示(`(y/n)` 等),防止后台任务卡在无人响应的交互式对话框。
### 六、并发限制
前台工具调用:`CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`(默认 10 个并发安全工具)。后台 bash 任务:没有硬性限制,它们是独立的子进程。
</details>
<!-- translation-sync: zh@v1, en@v1, ja@v1 -->

View File

@@ -16,9 +16,8 @@ Changes from s12:
- agent_loop: slow ops → background + placeholder, inject notifications
- Notifications use <task_notification> format, not reused tool_use_id
Note: Teaching code keeps a basic agent loop to stay focused on background
tasks. S11's full error recovery (RecoveryState, backoff, escalation,
reactive compact, fallback model) is omitted.
This chapter keeps the agent loop focused on background tasks. Error recovery
remains the independent layer introduced in s11.
"""
import os, subprocess, json, time, random, threading