refactor: streamline the course to 17 lessons

This commit is contained in:
Haoran
2026-08-12 03:02:42 +08:00
parent ab35e59672
commit 7e2f2fd99b
250 changed files with 12179 additions and 18653 deletions

View File

@@ -0,0 +1,178 @@
# s11: Background Tasks — 遅い操作はバックグラウンドへ
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → ... → s09 → s10 → `s11` → [s12](../s12_cron_scheduler/) → s13 → ... → s16 → s17
> *"遅い操作はバックグラウンドへ、Agent Loop は処理を継続"* — バックグラウンドスレッドでコマンドを実行し、後続のターンで完了結果を収集する。
>
> **Harness 層**: バックグラウンド — 非同期実行、メインループをブロックしない。
---
## 課題
ファイルの読み込みや `git status` は通常すぐに返るため、同期実行でも待ち時間はほとんど気にならない。しかし、依存関係のインストール、全テストの実行、プロジェクトのビルドには数分かかることがある。コマンドが返るまで、Harness は現在のレスポンスに含まれる次のツール呼び出しを処理できず、次のターンにも進めない。
後続の作業がそのコマンドに依存しないなら、終了まで待つ必要はない。例えば全テストを開始した後も、テストの実行中にドキュメントを確認したり、別のファイルを整理したりできる。
S11 では、時間のかかる Bash コマンドをバックグラウンドで実行し、Agent Loop が他の作業を続けられるようにする。完了結果は後続のターンで収集する。
---
## ソリューション
![Background Tasks Overview](images/background-tasks-overview.ja.svg)
この章では、時間のかかる操作をバックグラウンドスレッドに送る。現在のツール呼び出しはまずプレースホルダー `tool_result` を返すため、Agent Loop は処理を続けられる。後続のターンの開始時に完了済みの結果を収集し、通知として会話に追加する。
同期 vs バックグラウンド:
| | 同期 (s04) | バックグラウンド (s11) |
|---|---|---|
| 遅い操作 | 現在のツール呼び出しがブロックされる | バックグラウンドスレッドで実行 |
| Agent Loop | コマンドの返却を待つ | プレースホルダー結果を受け取って続行 |
| 結果 | コマンド終了後に返す | 先に `bg_id` を返し、後続のターンで結果を収集 |
| 判断基準 | — | bash の `run_in_background` パラメータ |
---
## 仕組み
### should_run_background: 明示的リクエスト
モデルは bash ツールの `run_in_background` パラメータでバックグラウンド実行をリクエストする。ツールが bash で、パラメータが明示的に `true` の場合だけ、この経路に入る。他の呼び出しは同期実行を続ける:
```python
def should_run_background(tool_name: str, tool_input: dict) -> bool:
return (
tool_name == "bash"
and tool_input.get("run_in_background") is True
)
```
`install``build``test` などのキーワードから推測しない。実行方法はツール呼び出しが明示的に選ぶ。
### BackgroundManager: バックグラウンド実行とライフサイクル
`BackgroundManager` がタスク状態と完了キューを保持する。`start()` はタスクを登録して daemon スレッドを起動し、すぐに `bg_id` を返す:
```python
class BackgroundManager:
def __init__(self):
self.tasks = {}
self.results = {}
self._ready = []
self._lock = threading.Lock()
def start(self, block) -> str:
# Register task, then run _run() in a daemon thread.
...
def _run(self, task_id: str, command: str):
output, exit_code = _run_bash_process(command)
status = "completed" if exit_code == 0 else "failed"
with self._lock:
self.tasks[task_id]["status"] = status
self.results[task_id] = _format_bash_result(output, exit_code)
self._ready.append(task_id)
```
command が非ゼロで終了した場合や worker で例外が起きた場合は `failed` となる。Shell は独立した process group で起動し、command の完了、timeout、または Agent が通常経路や `SIGTERM` で終了する時に元の group を停止する。これは lifecycle cleanup であって sandbox ではなく、別の session を作った process は group から離れられる。
### collect_background_results: 通知収集
後続のターンの開始時に、`collect()` が完了キューから結果を取り出し、`<task_notification>` メッセージとしてフォーマットする:
```python
def collect_background_results() -> list[str]:
return BACKGROUND.collect()
```
通知は元の `tool_use_id` を再利用しない。元のツール呼び出しはプレースホルダー `tool_result` で応答済みであり、完了結果を収集した時点で `task_notification` 形式の独立したイベントとして会話に追加する。1 つの `tool_use` に対応する `tool_result` は 1 つのままである。
### ループ統合
各 LLM 呼び出しの前に、Agent Loop は完了済みのバックグラウンド結果を収集する。`execute_tool()` は引き続きメインスレッドで `PreToolUse` を実行し、その後で同期実行かバックグラウンド実行かを選ぶ:
```python
while True:
inject_background_results(messages)
response = client.messages.create(...)
def execute_tool(block) -> str:
blocked = trigger_hooks("PreToolUse", block)
if blocked is not None:
return str(blocked)
if should_run_background(block.name, block.input):
task_id = start_background_task(block)
output = f"[Background task {task_id} started]"
else:
output = call_tool(block)
trigger_hooks("PostToolUse", block, output)
return output
```
遅い操作はまず `bg_id` 付きプレースホルダー tool_result を返す。バックグラウンドタスクの完了だけでは Agent は起動せず、次に Agent Loop が動く時に `inject_background_results()` が結果を収集する。
### 組み合わせて実行
```
Turn 1:
LLM → bash "npm install" (run_in_background=true)
→ start_background_task → bg_0001
→ tool_result: "[Background task bg_0001 started]..."
→ LLM: "OK, I'll check later. Let me also read the config."
Turn 2:
LLM → read_file "package.json" (fast, sync)
→ tool_result: file content
Turn 3:
→ collect bg_0001 as <task_notification>
→ LLM sees: config file + install notification in one message
```
npm install がバックグラウンドで実行されている間、Agent Loop は read_file を続けて実行した。
---
## s11 で追加するもの
| コンポーネント | S04 Kernel | S11 |
|--------------|------------|------------|
| 実行モデル | すべて同期 | 遅い操作はバックグラウンドスレッド + 通知注入 |
| bash スキーマ | `command` | `command` + `run_in_background` |
| 新規関数 | — | `should_run_background`, `start_background_task`, `collect_background_results`, `inject_background_results` |
| 新規型 | — | `BackgroundManager` |
| 通知形式 | — | `<task_notification>`tool_use_id を再利用しない) |
| ループ動作 | ツールを同期実行 | 明示的なバックグラウンド実行、後続のターンで完了結果を収集 |
| ツール | 5 | 5bash スキーマにパラメータを 1 つ追加) |
---
## 試してみる
```sh
cd learn-claude-code
python s11_background_tasks/code.py
```
以下のプロンプトを試してください:
1. `Run pip list in the background and find all Python files in this directory`
2. `Run npm install (use run_in_background) and while waiting, read package.json`
3. `Run a short sleep in the background, then list all Markdown files`
観察ポイント:`run_in_background` を明示的に設定すると、コマンドがバックグラウンドに送られるか?`bg_id` は返されるか?後続のターンで完了結果が `<task_notification>` 形式で収集されるか?
---
## 次の章
バックグラウンドタスクは「遅い操作がブロックしない」を解決した。しかし、定期的に何かをしたい場合は?例えば「毎朝 9 時にテストを実行」「5 分ごとにサーバーステータスを確認」。
s12 Cron Scheduler → Agent にアラームクロックを付ける。
<!-- translation-sync: zh@v7, en@v7, ja@v7 -->

View File

@@ -0,0 +1,178 @@
# s11: Background Tasks — Slow Operations Go to the Background
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → ... → s09 → s10 → `s11` → [s12](../s12_cron_scheduler/) → s13 → ... → s16 → s17
> *"Slow operations go to the background, the Agent Loop continues"* — Background threads run commands, and later turns collect completed results.
>
> **Harness Layer**: Background — Async execution, doesn't block the main loop.
---
## The Problem
Reading a file or running `git status` usually returns quickly, so synchronous execution causes little noticeable delay. Installing dependencies, running a full test suite, or building a project can take several minutes. Until the command returns, the Harness cannot process the next tool call in the current response or start the next model turn.
If later work does not depend on that command, there is no need to block it. For example, after starting a full test suite, the Agent could inspect documentation or organize other files while the tests run.
S11 addresses this by running slow Bash commands in the background, allowing the Agent Loop to continue and collect completed results on a later turn.
---
## The Solution
![Background Tasks Overview](images/background-tasks-overview.en.svg)
This chapter sends slow operations to background threads. The current tool call first returns a placeholder `tool_result`, allowing the Agent Loop to continue. At the start of a later turn, completed results are collected and added to the conversation as notifications.
Sync vs Background:
| | Sync (s04) | Background (s11) |
|---|---|---|
| Slow operations | Current tool call blocks | Background thread executes |
| Agent Loop | Waits for the command to return | Continues after the placeholder result |
| Result | Returned after the command finishes | Returns `bg_id` first; collects the result on a later turn |
| Decision criteria | — | bash `run_in_background` parameter |
---
## How It Works
### should_run_background: Explicit Request
The model requests background execution through the bash tool's `run_in_background` parameter. Only bash calls with the parameter explicitly set to `true` enter this path. Other calls still run synchronously.
```python
def should_run_background(tool_name: str, tool_input: dict) -> bool:
return (
tool_name == "bash"
and tool_input.get("run_in_background") is True
)
```
The Harness no longer guesses from keywords such as `install`, `build`, or `test`. The tool call chooses the execution mode explicitly.
### BackgroundManager: Background Execution and Lifecycle
`BackgroundManager` owns task state and the completion queue. `start()` registers a task, starts a daemon thread, and returns `bg_id` immediately:
```python
class BackgroundManager:
def __init__(self):
self.tasks = {}
self.results = {}
self._ready = []
self._lock = threading.Lock()
def start(self, block) -> str:
# Register task, then run _run() in a daemon thread.
...
def _run(self, task_id: str, command: str):
output, exit_code = _run_bash_process(command)
status = "completed" if exit_code == 0 else "failed"
with self._lock:
self.tasks[task_id]["status"] = status
self.results[task_id] = _format_bash_result(output, exit_code)
self._ready.append(task_id)
```
A non-zero exit code or worker exception becomes `failed`. The shell starts in its own process group. When the command finishes, times out, or the Agent exits through the normal or `SIGTERM` path, the runtime stops that original group. This is lifecycle cleanup, not a sandbox: a process that creates another session can leave the group.
### collect_background_results: Notification Collection
At the start of a later turn, `collect()` removes completed results from the queue and formats them as `<task_notification>` messages:
```python
def collect_background_results() -> list[str]:
return BACKGROUND.collect()
```
Notifications don't reuse the original `tool_use_id`. The original tool call was already answered with a placeholder `tool_result`; when the completed result is collected, it is added as an independent event in `task_notification` format. One `tool_use` still gets exactly one `tool_result`.
### Loop Integration
Before each LLM call, the Agent Loop collects completed background results. `execute_tool()` still runs `PreToolUse` on the main thread before choosing synchronous or background execution:
```python
while True:
inject_background_results(messages)
response = client.messages.create(...)
def execute_tool(block) -> str:
blocked = trigger_hooks("PreToolUse", block)
if blocked is not None:
return str(blocked)
if should_run_background(block.name, block.input):
task_id = start_background_task(block)
output = f"[Background task {task_id} started]"
else:
output = call_tool(block)
trigger_hooks("PostToolUse", block, output)
return output
```
Slow operations first return a placeholder tool_result with `bg_id`. A completed task does not wake the Agent by itself; `inject_background_results()` collects it the next time the Agent Loop runs.
### Putting It Together
```
Turn 1:
LLM → bash "npm install" (run_in_background=true)
→ start_background_task → bg_0001
→ tool_result: "[Background task bg_0001 started]..."
→ LLM: "OK, I'll check later. Let me also read the config."
Turn 2:
LLM → read_file "package.json" (fast, sync)
→ tool_result: file content
Turn 3:
→ collect bg_0001 as <task_notification>
→ LLM sees: config file + install notification in one message
```
While npm install ran in the background, the Agent Loop continued with read_file.
---
## What s11 Adds
| Component | s04 Kernel | s11 |
|-----------|-------------|-------------|
| Execution model | All synchronous | Slow ops to background thread + notification injection |
| bash schema | `command` | `command` + `run_in_background` |
| New functions | — | `should_run_background`, `start_background_task`, `collect_background_results`, `inject_background_results` |
| New types | — | `BackgroundManager` |
| Notification format | — | `<task_notification>` (doesn't reuse tool_use_id) |
| Loop behavior | Tools execute synchronously | Explicit background execution, completed results collected on later turns |
| Tools | 5 | 5 (one parameter added to the bash schema) |
---
## Try It
```sh
cd learn-claude-code
python s11_background_tasks/code.py
```
Try these prompts:
1. `Run pip list in the background and find all Python files in this directory`
2. `Run npm install (use run_in_background) and while waiting, read package.json`
3. `Run a short sleep in the background, then list all Markdown files`
What to observe: After explicitly setting `run_in_background`, is the command dispatched to the background? Is a `bg_id` returned? Are completed results collected in `<task_notification>` format on a later turn?
---
## What's Next
Background tasks solved "slow operations don't block." But what if you want to do something on a schedule? Like "run tests every morning at 9am" or "check server status every 5 minutes."
s12 Cron Scheduler → Give the agent an alarm clock.
<!-- translation-sync: zh@v7, en@v7, ja@v7 -->

View File

@@ -0,0 +1,178 @@
# s11: Background Tasks — 慢操作放后台
[English](README.md) · [中文](README.zh.md) · [日本語](README.ja.md)
s01 → ... → s09 → s10 → `s11` → [s12](../s12_cron_scheduler/) → s13 → ... → s16 → s17
> *"慢操作放后台Agent Loop 继续运行"* — 后台线程执行命令,后续轮次收集完成结果。
>
> **Harness 层**: 后台 — 异步执行, 不阻塞主循环。
---
## 问题
读取文件或运行 `git status` 通常很快同步执行时等待并不明显。但安装依赖、执行完整测试或构建项目可能持续几分钟。在命令返回前Harness 无法处理当前响应中的下一个工具调用,也不能进入下一轮。
如果后续工作并不依赖这个命令继续等待就没有必要。例如Agent 启动完整测试后,本来还可以检查文档或整理其他文件,但同步执行会让整个 Agent Loop 停在这次 Bash 调用上。
S11 要解决的问题是:让耗时的 Bash 命令在后台执行,使 Agent Loop 可以继续处理其他工作,并在后续轮次收集完成结果。
---
## 解决方案
![Background Tasks Overview](images/background-tasks-overview.svg)
本章把慢操作放入后台线程。当前工具调用先返回一个占位 `tool_result`Agent Loop 可以继续运行;后续轮次开始时再收集已经完成的结果,以通知形式加入对话。
同步 vs 后台:
| | 同步 (s04) | 后台 (s11) |
|---|---|---|
| 慢操作 | 当前工具调用被阻塞 | 后台线程执行 |
| Agent Loop | 等待命令返回 | 收到占位结果后继续运行 |
| 结果 | 命令结束后返回 | 先返回 `bg_id`,后续轮次收集结果 |
| 判断标准 | — | bash 的 `run_in_background` 参数 |
---
## 工作原理
### should_run_background: 显式请求
模型通过 bash 工具的 `run_in_background` 参数请求后台执行。只有参数明确为 `true`,并且工具是 bash 时,才会进入后台执行路径。其他调用仍然同步执行。
```python
def should_run_background(tool_name: str, tool_input: dict) -> bool:
return (
tool_name == "bash"
and tool_input.get("run_in_background") is True
)
```
不再根据 `install``build``test` 等关键词猜测。是否进入后台由工具调用明确决定。
### BackgroundManager: 后台执行与生命周期
`BackgroundManager` 保存任务状态和完成队列。`start()` 先登记任务,再启动 daemon 线程,并立即返回 `bg_id`
```python
class BackgroundManager:
def __init__(self):
self.tasks = {}
self.results = {}
self._ready = []
self._lock = threading.Lock()
def start(self, block) -> str:
# Register task, then run _run() in a daemon thread.
...
def _run(self, task_id: str, command: str):
output, exit_code = _run_bash_process(command)
status = "completed" if exit_code == 0 else "failed"
with self._lock:
self.tasks[task_id]["status"] = status
self.results[task_id] = _format_bash_result(output, exit_code)
self._ready.append(task_id)
```
命令以非零状态退出或 worker 抛出异常时,任务会进入 `failed`。Shell 会在独立的进程组中启动;命令完成、超时,或 Agent 经正常路径、`SIGTERM` 退出时,运行时会停止原进程组。这只是生命周期清理,并不是沙箱;另建 session 的进程仍可能离开该进程组。
### collect_background_results: 通知收集
后续轮次开始时,`collect()` 从完成队列中取出结果,并格式化为 `<task_notification>` 通知:
```python
def collect_background_results() -> list[str]:
return BACKGROUND.collect()
```
通知不复用原始 `tool_use_id`。原始 tool call 已经用占位 `tool_result` 回复了;后续收集完成结果时,会用 `task_notification` 格式把它作为独立事件加入对话。一个 `tool_use` 仍然只对应一个 `tool_result`
### 循环中的集成
每次调用 LLM 前Agent Loop 先收集已经完成的后台结果。`execute_tool()` 仍然在主线程执行 `PreToolUse`,然后再选择同步或后台执行:
```python
while True:
inject_background_results(messages)
response = client.messages.create(...)
def execute_tool(block) -> str:
blocked = trigger_hooks("PreToolUse", block)
if blocked is not None:
return str(blocked)
if should_run_background(block.name, block.input):
task_id = start_background_task(block)
output = f"[Background task {task_id} started]"
else:
output = call_tool(block)
trigger_hooks("PostToolUse", block, output)
return output
```
慢操作先返回一个带 `bg_id` 的占位 tool_result。后台结果不会主动唤醒 Agent下一次进入 Agent Loop 时,`inject_background_results()` 才会收集已经完成的结果。
### 合起来跑
```
Turn 1:
LLM → bash "npm install" (run_in_background=true)
→ start_background_task → bg_0001
→ tool_result: "[Background task bg_0001 started]..."
→ LLM: "OK, I'll check later. Let me also read the config."
Turn 2:
LLM → read_file "package.json" (fast, sync)
→ tool_result: file content
Turn 3:
→ collect bg_0001 as <task_notification>
→ LLM sees: config file + install notification in one message
```
npm install 在后台运行时Agent Loop 继续执行了 read_file。
---
## 本章新增了什么
| 组件 | S04 Kernel | S11 |
|------|-----------|-----------|
| 执行模型 | 全部同步 | 慢操作后台线程 + 通知注入 |
| bash schema | `command` | `command` + `run_in_background` |
| 新函数 | — | `should_run_background`, `start_background_task`, `collect_background_results`, `inject_background_results` |
| 新类型 | — | `BackgroundManager` |
| 通知格式 | — | `<task_notification>`(不复用 tool_use_id |
| 循环行为 | 工具同步执行 | 显式后台执行,后续轮次收集完成结果 |
| 工具 | 5 | 5bash schema 增加一个参数) |
---
## 试一下
```sh
cd learn-claude-code
python s11_background_tasks/code.py
```
试试这些 prompt
1. `Run pip list in the background and find all Python files in this directory`
2. `Run npm install (use run_in_background) and while waiting, read package.json`
3. `Run a short sleep in the background, then list all Markdown files`
观察重点:显式设置 `run_in_background` 后,命令有没有被送到后台?`bg_id` 是否返回?后续轮次有没有以 `<task_notification>` 格式收集完成结果?
---
## 接下来
后台任务解决了"慢操作不阻塞"。但如果想定时做某件事呢?比如"每天早上 9 点跑测试"、"每 5 分钟检查一次服务器状态"。
s12 Cron Scheduler → 给 Agent 装一个闹钟。
<!-- translation-sync: zh@v7, en@v7, ja@v7 -->

View File

@@ -0,0 +1,498 @@
#!/usr/bin/env python3
"""
s11_background_tasks.py - Background Tasks
Main thread Background thread
+------------------------------+ +----------------------+
| bash(run_in_background=True) | ------> | run command |
| return bg_id | | queue result |
| continue agent loop | <------ +----------------------+
| next turn: collect |
+------------------------------+
"""
import atexit
import glob
import os
import signal
import subprocess
import threading
import time
from pathlib import Path
try:
import readline
readline.parse_and_bind("set bind-tty-special-chars off")
readline.parse_and_bind("set input-meta on")
readline.parse_and_bind("set output-meta on")
readline.parse_and_bind("set convert-meta off")
except ImportError:
pass
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv(override=True)
if os.getenv("ANTHROPIC_BASE_URL"):
os.environ.pop("ANTHROPIC_AUTH_TOKEN", None)
WORKDIR = Path.cwd()
client = Anthropic(base_url=os.getenv("ANTHROPIC_BASE_URL"))
MODEL = os.environ["MODEL_ID"]
SYSTEM = (
f"You are a coding agent at {WORKDIR}. Use tools to solve tasks. "
"Set run_in_background to true only for independent Bash commands."
)
# -- From s04: tool implementations --
_shell_processes: set[subprocess.Popen] = set()
_shell_process_lock = threading.RLock()
def _stop_process_group(process: subprocess.Popen):
"""Stop processes that remain in the command's original process group."""
for sig in (signal.SIGTERM, signal.SIGKILL):
try:
os.killpg(process.pid, sig)
except (ProcessLookupError, OSError):
return
time.sleep(0.05)
def _stop_all_shell_processes():
with _shell_process_lock:
processes = list(_shell_processes)
for process in processes:
_stop_process_group(process)
def _handle_termination_signal(signum, _frame):
_stop_all_shell_processes()
raise SystemExit(128 + signum)
atexit.register(_stop_all_shell_processes)
signal.signal(signal.SIGTERM, _handle_termination_signal)
def _run_bash_process(command: str) -> tuple[str, int | None]:
process = None
try:
process = subprocess.Popen(
command,
shell=True,
cwd=WORKDIR,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
start_new_session=True,
)
with _shell_process_lock:
_shell_processes.add(process)
stdout, stderr = process.communicate(timeout=120)
output = (stdout + stderr).strip()
return (output[:50000] if output else "(no output)"), process.returncode
except subprocess.TimeoutExpired:
return "Error: Timeout (120s)", None
except OSError as error:
return f"Error: {type(error).__name__}: {error}", None
finally:
if process is not None:
_stop_process_group(process)
try:
process.wait(timeout=0.2)
except subprocess.TimeoutExpired:
pass
with _shell_process_lock:
_shell_processes.discard(process)
def _format_bash_result(output: str, exit_code: int | None) -> str:
if exit_code in (0, None):
return output
return f"Error: command exited with status {exit_code}\n{output}"
def run_bash(command: str, run_in_background: bool = False) -> str:
return _format_bash_result(*_run_bash_process(command))
def run_read(path: str, limit: int | None = None) -> str:
try:
file_path = (WORKDIR / path).resolve()
lines = file_path.read_text().splitlines()
if limit and limit < len(lines):
lines = lines[:limit] + [f"... ({len(lines) - limit} more lines)"]
return "\n".join(lines)
except Exception as error:
return f"Error: {error}"
def run_write(path: str, content: str) -> str:
try:
file_path = (WORKDIR / path).resolve()
file_path.parent.mkdir(parents=True, exist_ok=True)
file_path.write_text(content)
return f"Wrote {len(content)} bytes to {path}"
except Exception as error:
return f"Error: {error}"
def run_edit(path: str, old_text: str, new_text: str) -> str:
try:
file_path = (WORKDIR / path).resolve()
text = file_path.read_text()
if old_text not in text:
return f"Error: text not found in {path}"
file_path.write_text(text.replace(old_text, new_text, 1))
return f"Edited {path}"
except Exception as error:
return f"Error: {error}"
def run_glob(pattern: str) -> str:
try:
matches = [
match
for match in glob.glob(pattern, root_dir=WORKDIR)
if (WORKDIR / match).resolve().is_relative_to(WORKDIR)
]
return "\n".join(matches) if matches else "(no matches)"
except Exception as error:
return f"Error: {error}"
TOOLS = [
{"name": "bash", "description": "Run a shell command.",
"input_schema": {"type": "object",
"properties": {
"command": {"type": "string"},
"run_in_background": {"type": "boolean"}},
"required": ["command"]}},
{"name": "read_file", "description": "Read file contents.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"limit": {"type": "integer"}},
"required": ["path"]}},
{"name": "write_file", "description": "Write content to a file.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"content": {"type": "string"}},
"required": ["path", "content"]}},
{"name": "edit_file", "description": "Replace exact text in a file once.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"},
"old_text": {"type": "string"},
"new_text": {"type": "string"}},
"required": ["path", "old_text", "new_text"]}},
{"name": "glob", "description": "Find files matching a glob pattern.",
"input_schema": {"type": "object",
"properties": {"pattern": {"type": "string"}},
"required": ["pattern"]}},
]
TOOL_HANDLERS = {
"bash": run_bash,
"read_file": run_read,
"write_file": run_write,
"edit_file": run_edit,
"glob": run_glob,
}
# -- From s04: hooks and permission checks --
HOOKS = {"UserPromptSubmit": [], "PreToolUse": [], "PostToolUse": [], "Stop": []}
def register_hook(event: str, callback):
HOOKS[event].append(callback)
def trigger_hooks(event: str, *args):
for callback in HOOKS[event]:
result = callback(*args)
if result is not None:
return result
return None
DENY_LIST = ["rm -rf /", "sudo", "shutdown", "reboot", "mkfs", "dd if="]
DESTRUCTIVE = ["rm ", "> /etc/", "chmod 777"]
def permission_hook(block):
if block.name == "bash":
command = block.input.get("command", "")
for pattern in DENY_LIST:
if pattern in command:
print(f"\n\033[31m[blocked] '{pattern}'\033[0m")
return "Permission denied by deny list"
if any(keyword in command for keyword in DESTRUCTIVE):
print("\n\033[33m[permission] Potentially destructive command\033[0m")
print(f" Tool: {block.name}({block.input})")
choice = input(" Allow? [y/N] ").strip().lower()
if choice not in ("y", "yes"):
return "Permission denied by user"
if block.name in ("read_file", "write_file", "edit_file"):
path = block.input.get("path", "")
if not (WORKDIR / path).resolve().is_relative_to(WORKDIR):
print("\n\033[33m[permission] Access outside workspace\033[0m")
print(f" Tool: {block.name}({block.input})")
choice = input(" Allow? [y/N] ").strip().lower()
if choice not in ("y", "yes"):
return "Permission denied by user"
return None
def log_hook(block):
preview = str(list(block.input.values())[:2])[:60]
print(f"\033[90m[HOOK] {block.name}({preview})\033[0m")
return None
def large_output_hook(block, output):
if len(str(output)) > 100000:
print(
f"\033[33m[HOOK] Large output from {block.name}: "
f"{len(str(output))} chars\033[0m"
)
return None
def context_inject_hook(query: str):
print(f"\033[90m[HOOK] UserPromptSubmit: working in {WORKDIR}\033[0m")
return None
def summary_hook(messages: list):
tool_count = sum(
1
for message in messages
for block in (
message.get("content")
if isinstance(message.get("content"), list)
else []
)
if isinstance(block, dict) and block.get("type") == "tool_result"
)
print(f"\033[90m[HOOK] Stop: session used {tool_count} tool calls\033[0m")
return None
register_hook("UserPromptSubmit", context_inject_hook)
register_hook("PreToolUse", permission_hook)
register_hook("PreToolUse", log_hook)
register_hook("PostToolUse", large_output_hook)
register_hook("Stop", summary_hook)
def call_tool(block) -> str:
handler = TOOL_HANDLERS.get(block.name)
try:
output = handler(**block.input) if handler else f"Unknown: {block.name}"
except Exception as error:
output = f"Error: {error}"
return str(output)
# -- New in s11: background execution --
class BackgroundManager:
def __init__(self):
self.tasks: dict[str, dict] = {}
self.results: dict[str, str] = {}
self._ready: list[str] = []
self._counter = 0
self._lock = threading.Lock()
def start(self, block) -> str:
if block.name != "bash":
raise ValueError("Only Bash commands can run in the background")
command = block.input.get("command")
if not isinstance(command, str) or not command.strip():
raise ValueError("Bash command cannot be empty")
with self._lock:
self._counter += 1
task_id = f"bg_{self._counter:04d}"
self.tasks[task_id] = {
"tool_use_id": block.id,
"command": command,
"status": "running",
}
thread = threading.Thread(
target=self._run,
args=(task_id, command),
daemon=True,
)
try:
thread.start()
except Exception:
with self._lock:
self.tasks.pop(task_id, None)
raise
print(f" [background] started {task_id}: {command[:60]}")
return task_id
def _run(self, task_id: str, command: str):
try:
output, exit_code = _run_bash_process(command)
result = _format_bash_result(output, exit_code)
status = "completed" if exit_code == 0 else "failed"
except Exception as error:
result = f"Error: {type(error).__name__}: {error}"
status = "failed"
with self._lock:
task = self.tasks.get(task_id)
if task is None:
return
task["status"] = status
self.results[task_id] = result
self._ready.append(task_id)
def collect(self) -> list[str]:
with self._lock:
ready = []
for task_id in self._ready:
task = self.tasks.pop(task_id, None)
result = self.results.pop(task_id, "")
if task is not None:
ready.append((task_id, task, result))
self._ready.clear()
notifications = []
for task_id, task, result in ready:
notifications.append(
f"<task_notification>\n"
f" <task_id>{task_id}</task_id>\n"
f" <status>{task['status']}</status>\n"
f" <command>{task['command']}</command>\n"
f" <summary>{result[:500]}</summary>\n"
f"</task_notification>"
)
print(f" [background] collected {task_id}: {task['status']}")
return notifications
BACKGROUND = BackgroundManager()
background_tasks = BACKGROUND.tasks
background_results = BACKGROUND.results
def should_run_background(tool_name: str, tool_input: dict) -> bool:
return (
tool_name == "bash"
and tool_input.get("run_in_background") is True
)
def start_background_task(block) -> str:
return BACKGROUND.start(block)
def collect_background_results() -> list[str]:
return BACKGROUND.collect()
def inject_background_results(messages: list) -> int:
notifications = collect_background_results()
if not notifications:
return 0
blocks = [{"type": "text", "text": item} for item in notifications]
if messages and messages[-1].get("role") == "user":
content = messages[-1].get("content", "")
if isinstance(content, list):
content.extend(blocks)
else:
messages[-1]["content"] = [
{"type": "text", "text": str(content)},
*blocks,
]
else:
messages.append({"role": "user", "content": blocks})
return len(notifications)
def execute_tool(block) -> str:
blocked = trigger_hooks("PreToolUse", block)
if blocked is not None:
return str(blocked)
if should_run_background(block.name, block.input):
try:
task_id = start_background_task(block)
output = (
f"[Background task {task_id} started] "
"The result will be collected on a later turn."
)
except Exception as error:
output = f"Error: {error}"
else:
output = call_tool(block)
trigger_hooks("PostToolUse", block, output)
return output
# -- Agent loop --
def agent_loop(messages: list):
while True:
inject_background_results(messages)
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":
force = trigger_hooks("Stop", messages)
if force:
messages.append({"role": "user", "content": force})
continue
return
results = []
for block in response.content:
if block.type != "tool_use":
continue
output = execute_tool(block)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": output,
})
messages.append({"role": "user", "content": results})
if __name__ == "__main__":
print("s11: Background Tasks - explicit background Bash execution")
print("Enter a question, press Enter to send. Type q to quit.\n")
history = []
while True:
try:
query = input("\033[36ms11 >> \033[0m")
except (EOFError, KeyboardInterrupt):
break
if query.strip().lower() in ("q", "exit", ""):
break
trigger_hooks("UserPromptSubmit", query)
history.append({"role": "user", "content": query})
agent_loop(history)
for block in history[-1]["content"]:
if getattr(block, "type", None) == "text":
print(block.text)
print()

View File

@@ -0,0 +1,105 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 440" font-family="system-ui, -apple-system, sans-serif">
<defs>
<linearGradient id="header" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#1e3a5f"/><stop offset="100%" stop-color="#ea580c"/>
</linearGradient>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#555"/>
</marker>
<marker id="arrow-orange" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#ea580c"/>
</marker>
</defs>
<rect width="760" height="440" fill="#fafbfc" rx="8"/>
<!-- Title -->
<rect x="0" y="0" width="760" height="44" fill="url(#header)" rx="8"/>
<rect x="0" y="36" width="760" height="8" fill="url(#header)"/>
<text x="380" y="28" fill="#fff" font-size="15" font-weight="700" text-anchor="middle">Background Tasks — Slow ops in background, Agent Loop continues</text>
<!-- Legend -->
<rect x="40" y="56" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="58" y="66" fill="#2563eb" font-size="10" font-weight="600">s04 kernel</text>
<rect x="140" y="56" width="12" height="10" rx="2" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="158" y="66" fill="#ea580c" font-size="10" font-weight="600">s11 new</text>
<!-- ===== Top: s04 loop (compact) ===== -->
<rect x="30" y="86" width="80" height="40" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="70" y="110" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">messages</text>
<line x1="110" y1="106" x2="128" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="131" y="80" width="120" height="52" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="191" y="102" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">system prompt</text>
<text x="191" y="116" fill="#94a3b8" font-size="8" text-anchor="middle">fixed instructions</text>
<line x1="251" y1="106" x2="269" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="272" y="80" width="100" height="52" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="322" y="102" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">LLM call</text>
<text x="322" y="116" fill="#94a3b8" font-size="8" text-anchor="middle">model request</text>
<line x1="372" y1="106" x2="390" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<!-- TOOL DISPATCH (expanded) -->
<rect x="393" y="76" width="210" height="60" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="498" y="94" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">TOOL DISPATCH</text>
<text x="408" y="110" fill="#2563eb" font-size="9">background=false → sync execute</text>
<text x="408" y="124" fill="#ea580c" font-size="9" font-weight="600">background=true → worker thread</text>
<!-- Loop back -->
<path d="M 603 106 L 640 106 L 640 148 L 70 148 L 70 126" fill="none" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)" stroke-dasharray="6,3"/>
<!-- ===== Background execution (orange) ===== -->
<rect x="40" y="172" width="310" height="80" rx="8" fill="#fff7ed" stroke="#ea580c" stroke-width="2"/>
<text x="195" y="194" fill="#9a3412" font-size="11" font-weight="700" text-anchor="middle">Background thread execution</text>
<text x="60" y="212" fill="#ea580c" font-size="9">BackgroundManager.start(block)</text>
<text x="60" y="226" fill="#6b7280" font-size="8">threading.Thread(target=worker, daemon=True)</text>
<text x="60" y="240" fill="#6b7280" font-size="8">result → background_results[id] (threading.Lock protected)</text>
<!-- Arrow: dispatch → background -->
<path d="M 440 136 L 440 158 L 250 158 L 250 172" fill="none" stroke="#ea580c" stroke-width="1.5" marker-end="url(#arrow-orange)"/>
<text x="320" y="170" fill="#ea580c" font-size="9">slow op</text>
<!-- ===== Notification injection (orange) ===== -->
<rect x="390" y="172" width="330" height="80" rx="8" fill="#fff7ed" stroke="#ea580c" stroke-width="2"/>
<text x="555" y="194" fill="#9a3412" font-size="11" font-weight="700" text-anchor="middle">Collect on later turn</text>
<text x="408" y="212" fill="#ea580c" font-size="9">collect_background_results() before LLM call</text>
<text x="408" y="226" fill="#6b7280" font-size="8">completed → task_notification added to messages</text>
<text x="408" y="240" fill="#6b7280" font-size="8">running → task state remains</text>
<!-- Arrow: background → notification -->
<path d="M 350 220 L 390 220" fill="none" stroke="#ea580c" stroke-width="1.5" marker-end="url(#arrow-orange)"/>
<!-- ===== Explicit execution choice ===== -->
<rect x="40" y="274" width="680" height="48" rx="6" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1"/>
<text x="60" y="296" fill="#1e3a5f" font-size="11" font-weight="600">Explicit flag:</text>
<rect x="155" y="284" width="56" height="18" rx="4" fill="#f1f5f9" stroke="#94a3b8" stroke-width="1"/>
<text x="183" y="297" fill="#16a34a" font-size="9" text-anchor="middle">false</text>
<text x="218" y="297" fill="#475569" font-size="9">run_in_background=false · synchronous</text>
<rect x="360" y="284" width="56" height="18" rx="4" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="388" y="297" fill="#ea580c" font-size="9" text-anchor="middle">true</text>
<text x="423" y="297" fill="#475569" font-size="9">run_in_background=true · background</text>
<!-- ===== Timeline comparison ===== -->
<rect x="40" y="340" width="330" height="84" rx="6" fill="#fef2f2" stroke="#dc2626" stroke-width="1"/>
<text x="205" y="360" fill="#991b1b" font-size="10" font-weight="700" text-anchor="middle">s04 synchronous execution</text>
<rect x="60" y="370" width="80" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="100" y="381" fill="#1e40af" font-size="8" text-anchor="middle">LLM call</text>
<rect x="145" y="370" width="160" height="14" rx="3" fill="#fecaca" stroke="#dc2626" stroke-width="1"/>
<text x="225" y="381" fill="#991b1b" font-size="8" text-anchor="middle">wait for bash result</text>
<rect x="310" y="370" width="40" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="330" y="381" fill="#1e40af" font-size="7" text-anchor="middle">next turn</text>
<text x="60" y="410" fill="#991b1b" font-size="9">The loop continues after the command returns</text>
<rect x="390" y="340" width="330" height="84" rx="6" fill="#f0fdf4" stroke="#16a34a" stroke-width="1"/>
<text x="555" y="360" fill="#166534" font-size="10" font-weight="700" text-anchor="middle">s11 background execution</text>
<rect x="410" y="370" width="80" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="450" y="381" fill="#1e40af" font-size="8" text-anchor="middle">LLM call</text>
<rect x="495" y="370" width="100" height="14" rx="3" fill="#dcfce7" stroke="#16a34a" stroke-width="1"/>
<text x="545" y="381" fill="#166534" font-size="8" text-anchor="middle">run other tools</text>
<rect x="600" y="370" width="100" height="14" rx="3" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="650" y="381" fill="#ea580c" font-size="8" text-anchor="middle">collect next turn</text>
<text x="410" y="410" fill="#166534" font-size="9">Bash runs on a background thread</text>
</svg>

After

Width:  |  Height:  |  Size: 7.5 KiB

View File

@@ -0,0 +1,105 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 440" font-family="system-ui, -apple-system, sans-serif">
<defs>
<linearGradient id="header" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#1e3a5f"/><stop offset="100%" stop-color="#ea580c"/>
</linearGradient>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#555"/>
</marker>
<marker id="arrow-orange" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#ea580c"/>
</marker>
</defs>
<rect width="760" height="440" fill="#fafbfc" rx="8"/>
<!-- Title -->
<rect x="0" y="0" width="760" height="44" fill="url(#header)" rx="8"/>
<rect x="0" y="36" width="760" height="8" fill="url(#header)"/>
<text x="380" y="28" fill="#fff" font-size="15" font-weight="700" text-anchor="middle">Background Tasks — 遅い操作はバックグラウンドへ、Agent Loop は継続</text>
<!-- Legend -->
<rect x="40" y="56" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="58" y="66" fill="#2563eb" font-size="10" font-weight="600">s04 Kernel</text>
<rect x="140" y="56" width="12" height="10" rx="2" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="158" y="66" fill="#ea580c" font-size="10" font-weight="600">s11 新規</text>
<!-- ===== Top: s04 loop (compact) ===== -->
<rect x="30" y="86" width="80" height="40" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="70" y="110" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">messages</text>
<line x1="110" y1="106" x2="128" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="131" y="80" width="120" height="52" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="191" y="102" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">system prompt</text>
<text x="191" y="116" fill="#94a3b8" font-size="8" text-anchor="middle">fixed instructions</text>
<line x1="251" y1="106" x2="269" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="272" y="80" width="100" height="52" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="322" y="102" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">LLM call</text>
<text x="322" y="116" fill="#94a3b8" font-size="8" text-anchor="middle">model request</text>
<line x1="372" y1="106" x2="390" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<!-- TOOL DISPATCH (expanded) -->
<rect x="393" y="76" width="210" height="60" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="498" y="94" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">TOOL DISPATCH</text>
<text x="408" y="110" fill="#2563eb" font-size="9">background=false → 同期実行</text>
<text x="408" y="124" fill="#ea580c" font-size="9" font-weight="600">background=true → worker thread</text>
<!-- Loop back -->
<path d="M 603 106 L 640 106 L 640 148 L 70 148 L 70 126" fill="none" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)" stroke-dasharray="6,3"/>
<!-- ===== Background execution (orange) ===== -->
<rect x="40" y="172" width="310" height="80" rx="8" fill="#fff7ed" stroke="#ea580c" stroke-width="2"/>
<text x="195" y="194" fill="#9a3412" font-size="11" font-weight="700" text-anchor="middle">バックグラウンドスレッド実行</text>
<text x="60" y="212" fill="#ea580c" font-size="9">BackgroundManager.start(block)</text>
<text x="60" y="226" fill="#6b7280" font-size="8">threading.Thread(target=worker, daemon=True)</text>
<text x="60" y="240" fill="#6b7280" font-size="8">結果 → background_results[id] (threading.Lock で保護)</text>
<!-- Arrow: dispatch → background -->
<path d="M 440 136 L 440 158 L 250 158 L 250 172" fill="none" stroke="#ea580c" stroke-width="1.5" marker-end="url(#arrow-orange)"/>
<text x="320" y="170" fill="#ea580c" font-size="9">slow op</text>
<!-- ===== Notification injection (orange) ===== -->
<rect x="390" y="172" width="330" height="80" rx="8" fill="#fff7ed" stroke="#ea580c" stroke-width="2"/>
<text x="555" y="194" fill="#9a3412" font-size="11" font-weight="700" text-anchor="middle">後続ターンで収集</text>
<text x="408" y="212" fill="#ea580c" font-size="9">LLM 呼び出し前に collect_background_results()</text>
<text x="408" y="226" fill="#6b7280" font-size="8">完了 → task_notification を messages に追加</text>
<text x="408" y="240" fill="#6b7280" font-size="8">実行中 → タスク状態を保持</text>
<!-- Arrow: background → notification -->
<path d="M 350 220 L 390 220" fill="none" stroke="#ea580c" stroke-width="1.5" marker-end="url(#arrow-orange)"/>
<!-- ===== Explicit execution choice ===== -->
<rect x="40" y="274" width="680" height="48" rx="6" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1"/>
<text x="60" y="296" fill="#1e3a5f" font-size="11" font-weight="600">明示的な指定:</text>
<rect x="155" y="284" width="56" height="18" rx="4" fill="#f1f5f9" stroke="#94a3b8" stroke-width="1"/>
<text x="183" y="297" fill="#16a34a" font-size="9" text-anchor="middle">false</text>
<text x="218" y="297" fill="#475569" font-size="9">run_in_background=false · 同期実行</text>
<rect x="360" y="284" width="56" height="18" rx="4" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="388" y="297" fill="#ea580c" font-size="9" text-anchor="middle">true</text>
<text x="423" y="297" fill="#475569" font-size="9">run_in_background=true · バックグラウンド</text>
<!-- ===== Timeline comparison ===== -->
<rect x="40" y="340" width="330" height="84" rx="6" fill="#fef2f2" stroke="#dc2626" stroke-width="1"/>
<text x="205" y="360" fill="#991b1b" font-size="10" font-weight="700" text-anchor="middle">s04 同期実行</text>
<rect x="60" y="370" width="80" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="100" y="381" fill="#1e40af" font-size="8" text-anchor="middle">LLM 呼び出し</text>
<rect x="145" y="370" width="160" height="14" rx="3" fill="#fecaca" stroke="#dc2626" stroke-width="1"/>
<text x="225" y="381" fill="#991b1b" font-size="8" text-anchor="middle">bash の結果を待つ</text>
<rect x="310" y="370" width="40" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="330" y="381" fill="#1e40af" font-size="7" text-anchor="middle">次のターン</text>
<text x="60" y="410" fill="#991b1b" font-size="9">コマンド終了後にループを継続</text>
<rect x="390" y="340" width="330" height="84" rx="6" fill="#f0fdf4" stroke="#16a34a" stroke-width="1"/>
<text x="555" y="360" fill="#166534" font-size="10" font-weight="700" text-anchor="middle">s11 バックグラウンド実行</text>
<rect x="410" y="370" width="80" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="450" y="381" fill="#1e40af" font-size="8" text-anchor="middle">LLM 呼び出し</text>
<rect x="495" y="370" width="100" height="14" rx="3" fill="#dcfce7" stroke="#16a34a" stroke-width="1"/>
<text x="545" y="381" fill="#166534" font-size="8" text-anchor="middle">他のツールを実行</text>
<rect x="600" y="370" width="100" height="14" rx="3" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="650" y="381" fill="#ea580c" font-size="8" text-anchor="middle">後続ターンで収集</text>
<text x="410" y="410" fill="#166534" font-size="9">bash はバックグラウンドスレッドで実行</text>
</svg>

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@@ -0,0 +1,105 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 760 440" font-family="system-ui, -apple-system, sans-serif">
<defs>
<linearGradient id="header" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#1e3a5f"/><stop offset="100%" stop-color="#ea580c"/>
</linearGradient>
<marker id="arrow" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#555"/>
</marker>
<marker id="arrow-orange" viewBox="0 0 10 10" refX="10" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M 0 0 L 10 5 L 0 10 z" fill="#ea580c"/>
</marker>
</defs>
<rect width="760" height="440" fill="#fafbfc" rx="8"/>
<!-- Title -->
<rect x="0" y="0" width="760" height="44" fill="url(#header)" rx="8"/>
<rect x="0" y="36" width="760" height="8" fill="url(#header)"/>
<text x="380" y="28" fill="#fff" font-size="15" font-weight="700" text-anchor="middle">Background Tasks — 慢操作放后台Agent Loop 继续运行</text>
<!-- Legend -->
<rect x="40" y="56" width="12" height="10" rx="2" fill="#f0f4ff" stroke="#2563eb" stroke-width="1"/>
<text x="58" y="66" fill="#2563eb" font-size="10" font-weight="600">s04 Kernel</text>
<rect x="140" y="56" width="12" height="10" rx="2" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="158" y="66" fill="#ea580c" font-size="10" font-weight="600">s11 新增</text>
<!-- ===== Top: s04 loop (compact) ===== -->
<rect x="30" y="86" width="80" height="40" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="70" y="110" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">messages</text>
<line x1="110" y1="106" x2="128" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="131" y="80" width="120" height="52" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="191" y="102" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">system prompt</text>
<text x="191" y="116" fill="#94a3b8" font-size="8" text-anchor="middle">fixed instructions</text>
<line x1="251" y1="106" x2="269" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<rect x="272" y="80" width="100" height="52" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="322" y="102" fill="#1e3a5f" font-size="9" font-weight="600" text-anchor="middle">LLM call</text>
<text x="322" y="116" fill="#94a3b8" font-size="8" text-anchor="middle">model request</text>
<line x1="372" y1="106" x2="390" y2="106" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)"/>
<!-- TOOL DISPATCH (expanded) -->
<rect x="393" y="76" width="210" height="60" rx="8" fill="#f0f4ff" stroke="#2563eb" stroke-width="1.5"/>
<text x="498" y="94" fill="#1e3a5f" font-size="10" font-weight="600" text-anchor="middle">TOOL DISPATCH</text>
<text x="408" y="110" fill="#2563eb" font-size="9">background=false → 同步执行</text>
<text x="408" y="124" fill="#ea580c" font-size="9" font-weight="600">background=true → 后台线程</text>
<!-- Loop back -->
<path d="M 603 106 L 640 106 L 640 148 L 70 148 L 70 126" fill="none" stroke="#555" stroke-width="1.5" marker-end="url(#arrow)" stroke-dasharray="6,3"/>
<!-- ===== Background execution (orange) ===== -->
<rect x="40" y="172" width="310" height="80" rx="8" fill="#fff7ed" stroke="#ea580c" stroke-width="2"/>
<text x="195" y="194" fill="#9a3412" font-size="11" font-weight="700" text-anchor="middle">后台线程执行</text>
<text x="60" y="212" fill="#ea580c" font-size="9">BackgroundManager.start(block)</text>
<text x="60" y="226" fill="#6b7280" font-size="8">threading.Thread(target=worker, daemon=True)</text>
<text x="60" y="240" fill="#6b7280" font-size="8">结果 → background_results[id] (threading.Lock 保护)</text>
<!-- Arrow: dispatch → background -->
<path d="M 440 136 L 440 158 L 250 158 L 250 172" fill="none" stroke="#ea580c" stroke-width="1.5" marker-end="url(#arrow-orange)"/>
<text x="320" y="170" fill="#ea580c" font-size="9">slow op</text>
<!-- ===== Notification injection (orange) ===== -->
<rect x="390" y="172" width="330" height="80" rx="8" fill="#fff7ed" stroke="#ea580c" stroke-width="2"/>
<text x="555" y="194" fill="#9a3412" font-size="11" font-weight="700" text-anchor="middle">后续轮次收集</text>
<text x="408" y="212" fill="#ea580c" font-size="9">LLM 调用前 collect_background_results()</text>
<text x="408" y="226" fill="#6b7280" font-size="8">已完成 → task_notification 加入 messages</text>
<text x="408" y="240" fill="#6b7280" font-size="8">运行中 → 保留任务状态</text>
<!-- Arrow: background → notification -->
<path d="M 350 220 L 390 220" fill="none" stroke="#ea580c" stroke-width="1.5" marker-end="url(#arrow-orange)"/>
<!-- ===== Explicit execution choice ===== -->
<rect x="40" y="274" width="680" height="48" rx="6" fill="#f8fafc" stroke="#e2e8f0" stroke-width="1"/>
<text x="60" y="296" fill="#1e3a5f" font-size="11" font-weight="600">显式参数:</text>
<rect x="155" y="284" width="56" height="18" rx="4" fill="#f1f5f9" stroke="#94a3b8" stroke-width="1"/>
<text x="183" y="297" fill="#16a34a" font-size="9" text-anchor="middle">false</text>
<text x="218" y="297" fill="#475569" font-size="9">run_in_background=false · 同步执行</text>
<rect x="360" y="284" width="56" height="18" rx="4" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="388" y="297" fill="#ea580c" font-size="9" text-anchor="middle">true</text>
<text x="423" y="297" fill="#475569" font-size="9">run_in_background=true · 后台执行</text>
<!-- ===== Timeline comparison ===== -->
<rect x="40" y="340" width="330" height="84" rx="6" fill="#fef2f2" stroke="#dc2626" stroke-width="1"/>
<text x="205" y="360" fill="#991b1b" font-size="10" font-weight="700" text-anchor="middle">s04 同步执行</text>
<rect x="60" y="370" width="80" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="100" y="381" fill="#1e40af" font-size="8" text-anchor="middle">LLM 调用</text>
<rect x="145" y="370" width="160" height="14" rx="3" fill="#fecaca" stroke="#dc2626" stroke-width="1"/>
<text x="225" y="381" fill="#991b1b" font-size="8" text-anchor="middle">等待 bash 返回</text>
<rect x="310" y="370" width="40" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="330" y="381" fill="#1e40af" font-size="7" text-anchor="middle">下一轮</text>
<text x="60" y="410" fill="#991b1b" font-size="9">命令结束后才能继续</text>
<rect x="390" y="340" width="330" height="84" rx="6" fill="#f0fdf4" stroke="#16a34a" stroke-width="1"/>
<text x="555" y="360" fill="#166534" font-size="10" font-weight="700" text-anchor="middle">s11 后台执行</text>
<rect x="410" y="370" width="80" height="14" rx="3" fill="#dbeafe" stroke="#2563eb" stroke-width="1"/>
<text x="450" y="381" fill="#1e40af" font-size="8" text-anchor="middle">LLM 调用</text>
<rect x="495" y="370" width="100" height="14" rx="3" fill="#dcfce7" stroke="#16a34a" stroke-width="1"/>
<text x="545" y="381" fill="#166534" font-size="8" text-anchor="middle">继续其他工具</text>
<rect x="600" y="370" width="100" height="14" rx="3" fill="#fff7ed" stroke="#ea580c" stroke-width="1"/>
<text x="650" y="381" fill="#ea580c" font-size="8" text-anchor="middle">后续轮次收集</text>
<text x="410" y="410" fill="#166534" font-size="9">bash 在后台线程运行</text>
</svg>

After

Width:  |  Height:  |  Size: 7.4 KiB