Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

docs: cut 0.6 docs version; bump to 0.6.0

xf gong627393c9b147
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b02c963..bc6f17a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,48 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+## [0.6.0] - 2026-05-31
+
+### Added
+
+- **Human-in-the-Loop (HITL)** — first-class suspend/resume for agent runs that
+ need a human decision mid-flight:
+ - `HitlChannel` protocol with `InMemoryChannel` and `CheckpointedChannel`
+ implementations. `CheckpointedChannel` persists pending requests so an
+ agent can be resumed after a process restart.
+ - `Agent(channel=...)` wiring; `agent.respond()`, `agent.detach()`, and
+ `agent.abort_pending()` for external controllers.
+ - `ApprovalPolicyMiddleware` and `ConfirmToolCallMiddleware` for declarative
+ tool-call gating; `ask_user` built-in tool for open-ended prompts.
+ - `ScriptedChannel` and `NoopChannel` for deterministic testing.
+ - `HitlRequestEvent`, `HitlAnswerEvent`, `AgentSuspendedEvent`,
+ `AgentAbortedEvent` stream events.
+ - Lazy OTel `hitl.ask` / `hitl.confirm` spans with outcome attributes.
+ - Pending-request persistence on Memory, SQLite, Postgres, and MySQL
+ checkpointers (schema v2 — additive migration, backwards compatible).
+- **`MySQLCheckpointer`** — full-featured MySQL/MariaDB checkpointer with
+ Alembic schema management, matching the Postgres implementation.
+- **Stream recording + `trace convert`** — `record_stream()` captures a raw
+ provider `MessageStream` to JSONL; `cubepi trace convert` replays the
+ recording as a structured trace. Useful for offline debugging and testing
+ without live API calls.
+- **Trace CLI — run-metadata filtering** (`--meta` / `--show-meta`): filter
+ and display `tracing_context` key/value tags attached to a run.
+- **Trace CLI — span IDs in `trace view`** node labels for easier
+ cross-referencing with external OTLP backends.
+- **Agent steering by ID** — `agent.steer(...)` returns a `steer_id`; pass it
+ to `agent.cancel_steer(steer_id)` to cancel a not-yet-drained steering
+ message.
+
+### Fixed
+
+- **OpenAI provider**: deduplicate `finish_reason` processing that caused
+ spurious extra events on streamed responses.
+- **Agent**: `ToolExecutionStartEvent` is now deferred until the tool coroutine
+ is actually scheduled, preventing early events for tools that are never run.
+- **Tracing**: clear `stream_tool_accumulated` at turn start to avoid stale
+ tool-call data leaking across turns.
+
## [0.5.0] - 2026-05-25
### Added
@@ -51,7 +93,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **[0.2.0]** - 2026-05-10 — see the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.2.0).
- **[0.1.0]** - 2026-05-09 — initial release. See the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.1.0).
-[Unreleased]: https://github.com/cubeplexai/cubepi/compare/v0.5.0...HEAD
+[Unreleased]: https://github.com/cubeplexai/cubepi/compare/v0.6.0...HEAD
+[0.6.0]: https://github.com/cubeplexai/cubepi/compare/v0.5.0...v0.6.0
[0.5.0]: https://github.com/cubeplexai/cubepi/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/cubeplexai/cubepi/compare/v0.3.0...v0.4.0
[0.3.0]: https://github.com/cubeplexai/cubepi/compare/v0.2.0...v0.3.0
diff --git a/pyproject.toml b/pyproject.toml
index 7512f25..bba6926 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "cubepi"
-version = "0.5.0"
+version = "0.6.0"
description = "Pythonic async-native agent framework"
readme = "README.md"
license = "MIT"
diff --git a/uv.lock b/uv.lock
index 19a0e73..4cb7f31 100644
--- a/uv.lock
+++ b/uv.lock
@@ -475,7 +475,7 @@ wheels = [
[[package]]
name = "cubepi"
-version = "0.5.0"
+version = "0.6.0"
source = { editable = "." }
dependencies = [
{ name = "anthropic" },
diff --git a/website/docs/intro.mdx b/website/docs/intro.mdx
index c5bf6eb..ac9c146 100644
--- a/website/docs/intro.mdx
+++ b/website/docs/intro.mdx
@@ -47,6 +47,9 @@ working tool-using agent in under five minutes.
Conventions — works with Jaeger, Tempo, Honeycomb, Datadog, or any
OTLP-compatible backend. No payloads recorded by default; opt in
with `record_content=True` and a `redact` callback.
+- **Human-in-the-Loop.** Suspend an agent mid-run, route a decision to
+ a human (approve/reject/answer), then resume — with full checkpoint
+ persistence so the agent survives a process restart while waiting.
## Where to go next
@@ -68,7 +71,9 @@ the `main` branch. APIs documented here can still change before they
ship in a tagged release.
The latest released version is `v<PackageVersion/>` ([switch to it
-from the version picker, top-right](pathname:///)). The native
+from the version picker, top-right](pathname:///)). Human-in-the-Loop
+([guide →](./guides/hitl/overview)) — `HitlChannel`, `CheckpointedChannel`,
+`ask_user`, `ConfirmToolCallMiddleware` — landed in 0.6. The native
OpenTelemetry tracing module ([guide →](./guides/tracing/overview))
— `Tracer`, `Meter`, content recording, MCP CLIENT spans, per-run
`tracing_context` tags — landed in 0.4.
diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.ts
index b89a1b7..5eeab0d 100644
--- a/website/docusaurus.config.ts
+++ b/website/docusaurus.config.ts
@@ -28,10 +28,11 @@ const classicOptions: ClassicOptions = {
docs: {
sidebarPath: './sidebars.ts',
editUrl: 'https://github.com/cubeplexai/cubepi/edit/main/website/',
- lastVersion: '0.5',
+ lastVersion: '0.6',
versions: {
current: { label: 'Next 🚧', path: 'next', banner: 'unreleased' },
- '0.5': { label: '0.5 (latest)', path: '' },
+ '0.6': { label: '0.6 (latest)', path: '' },
+ '0.5': { label: '0.5', path: '0.5' },
'0.4': { label: '0.4', path: '0.4' },
'0.3': { label: '0.3', path: '0.3' },
},
@@ -45,6 +46,7 @@ const classicOptions: ClassicOptions = {
'/docs/next/**',
'/docs/0.3/**',
'/docs/0.4/**',
+ '/docs/0.5/**',
],
},
};
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx
index 4030407..3ad509e 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx
@@ -45,6 +45,9 @@ pip install cubepi
GenAI 语义约定的 OTel span 树 —— Jaeger、Tempo、Honeycomb、
Datadog 等任意 OTLP 后端都能直接接收。默认不记录任何 payload;
需要时用 `record_content=True` 配合 `redact` 回调显式开启。
+- **人工介入(HITL)。** 在 run 中途挂起 Agent,把决策路由给人工
+ (审批 / 拒绝 / 回答),然后继续执行 —— 支持检查点持久化,
+ 等待期间进程可以重启。
## 接下来去哪儿
@@ -64,7 +67,9 @@ pip install cubepi
这里描述的 API 在打 tag 发布之前还可能变动。
最新已发布版本是 `v<PackageVersion/>`([从右上角版本选择器切换](pathname:///))。
-原生 OpenTelemetry 追踪模块([指南 →](./guides/tracing/overview))——
+人工介入([指南 →](./guides/hitl/overview))—— `HitlChannel`、
+`CheckpointedChannel`、`ask_user`、`ConfirmToolCallMiddleware` ——
+已在 0.6 发布。原生 OpenTelemetry 追踪模块([指南 →](./guides/tracing/overview))——
`Tracer`、`Meter`、内容录制、MCP CLIENT span、按 run 打标签的
`tracing_context` —— 已在 0.4 发布。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5.json
index c6a1140..abccdef 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5.json
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5.json
@@ -1,6 +1,6 @@
{
"version.label": {
- "message": "0.5(最新)",
+ "message": "0.5",
"description": "The label for version 0.5"
},
"sidebar.docs.category.Getting Started": {
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6.json
new file mode 100644
index 0000000..fe26160
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6.json
@@ -0,0 +1,50 @@
+{
+ "version.label": {
+ "message": "0.6(最新)",
+ "description": "The label for version 0.6"
+ },
+ "sidebar.docs.category.Getting Started": {
+ "message": "快速入门",
+ "description": "The label for category 'Getting Started' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Guides": {
+ "message": "指南",
+ "description": "The label for category 'Guides' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Agents": {
+ "message": "Agent",
+ "description": "The label for category 'Agents' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Providers": {
+ "message": "Provider",
+ "description": "The label for category 'Providers' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Checkpointing": {
+ "message": "检查点",
+ "description": "The label for category 'Checkpointing' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Middleware": {
+ "message": "中间件",
+ "description": "The label for category 'Middleware' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Human-in-the-Loop": {
+ "message": "人工介入",
+ "description": "The label for category 'Human-in-the-Loop' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.MCP": {
+ "message": "MCP",
+ "description": "The label for category 'MCP' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Tracing": {
+ "message": "追踪",
+ "description": "The label for category 'Tracing' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Recipes": {
+ "message": "示例",
+ "description": "The label for category 'Recipes' in sidebar 'docs'"
+ },
+ "sidebar.docs.category.Migration": {
+ "message": "迁移指南",
+ "description": "The label for category 'Migration' in sidebar 'docs'"
+ }
+}
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/core-concepts.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/core-concepts.md
new file mode 100644
index 0000000..01d0ebf
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/core-concepts.md
@@ -0,0 +1,233 @@
+---
+title: 核心概念
+description: "了解 CubePi 的六个核心概念:Agent、Tool、Provider、Stream & Events、Middleware 和 Checkpointer。"
+---
+
+# 核心概念
+
+CubePi 的全部能力可以归纳为六个概念。这一页读一遍,后面的文档基本就
+变成查表了。
+
+## Agent
+
+`Agent` 是有状态的门面:你用 provider、model、可选的工具、可选的
+middleware/checkpointer 构造它。然后通过三个方法驱动它:
+
+- `await agent.prompt(message)` —— 用一条 user 消息开启新一轮。
+- `await agent.resume()` —— 从最后一条已持久化的消息继续(配合
+ checkpointer 使用)。
+- `agent.steer(message)` / `agent.follow_up(message)` —— 在正在跑的
+ 过程中插入消息,或为当前运行结束后排队下一条。
+
+Agent 持有一个 `AgentState`(system prompt、tools、model、消息历史、
+未结束的 tool call、流式标志)和一个 subscribers 列表:
+
+```python
+unsubscribe = agent.subscribe(my_listener)
+# ...
+unsubscribe()
+```
+
+Subscriber 会收到循环发出的每一个 `AgentEvent`。可以是同步或异步函数。
+
+## Tool
+
+`AgentTool` = name + description + Pydantic 参数模型 + 异步 `execute`:
+
+```python
+from pydantic import BaseModel
+from cubepi import AgentTool, AgentToolResult, TextContent
+
+class SearchParams(BaseModel):
+ query: str
+ limit: int = 10
+
+async def execute(tool_call_id, params: SearchParams, *, signal=None, on_update=None):
+ # 干活;如果可以被打断,记得检查 signal
+ return AgentToolResult(content=[TextContent(text=f"…")])
+
+search = AgentTool(
+ name="search",
+ description="搜索语料库",
+ parameters=SearchParams,
+ execute=execute,
+)
+```
+
+Pydantic schema 会自动转成 JSON Schema 喂给模型。参数解析、错误包装、
+并行执行都由框架处理。`execution_mode`、`on_update`(增量进度)、
+`terminate`(在工具里结束本轮)见 [工具使用](../guides/agents/tool-use)。
+
+## Provider
+
+任何匹配下面 Protocol 的对象就是 Provider:
+
+```python
+class Provider(Protocol):
+ async def stream(
+ self,
+ model: Model,
+ messages: list[Message],
+ *,
+ system_prompt: str = "",
+ tools: list[ToolDefinition] | None = None,
+ options: StreamOptions | None = None,
+ ) -> MessageStream: ...
+```
+
+它返回一个 `MessageStream` —— 一个统一的异步迭代器,产出 `StreamEvent`,
+并通过 `await stream.result()` 暴露最终的 `AssistantMessage`。内置 Provider:
+
+- `AnthropicProvider` —— Claude(Messages API,支持思考、缓存、工具使用)。
+- `OpenAIProvider` —— GPT 家族(Chat Completions API)。
+- `OpenAIResponsesProvider` —— GPT 家族(Responses API,服务端状态)。
+- `FauxProvider` —— 确定性测试替身(不发任何网络请求)。
+
+实现一个方法就能写自己的。见 [Providers / 自定义](../guides/providers/custom)。
+
+## Stream 和事件
+
+流和事件分两层:
+
+- **Provider 流** —— `MessageStream` 产出的是 *provider* 事件:
+ `start`、`text_start`、`text_delta`、`text_end`、`thinking_*`、
+ `toolcall_*`、`done`、`error`。原始 token 流。
+- **Agent 事件** —— `agent.subscribe(...)` 收到的内容。十四种类型
+ 覆盖整个循环 + HITL:`agent_start`、`agent_end`、`turn_start`、
+ `turn_end`、`message_start`、`message_update`、`message_end`、
+ `tool_execution_start`、`tool_execution_update`、
+ `tool_execution_end`、`hitl_request`、`hitl_answer`、
+ `agent_suspended`、`agent_aborted`。
+
+做 UI 订阅 Agent 事件;做底层 token 路由就钻 `event.stream_event`。
+见 [流式事件](../guides/agents/streaming)。
+
+## Middleware
+
+`Middleware` 是有最多七个类型化 hook 的类:
+
+| Hook | 何时触发 | 组合规则 |
+|---|---|---|
+| `transform_context` | 每次调模型之前,处理消息列表 | 链式 —— 每个收到上一个的输出 |
+| `convert_to_llm` | provider 序列化之前 | 最后一个实现生效 |
+| `transform_system_prompt` | 每次调模型之前,处理 system prompt | 链式 |
+| `before_tool_call` | 每个工具调用之前(在参数校验后) | 第一个 `block=True` 短路 |
+| `after_tool_call` | 每个工具调用之后(在 `execute` 之后) | 后写覆盖先写 |
+| `after_model_response` | assistant 消息落定之后 | 返回 `TurnAction` 控制流向 |
+| `should_stop_after_turn` | 每个轮次结束时 | 任一返回 `True` 即停 |
+
+通过 `Agent(middleware=[...])` 传入。见
+[Middleware → 组合规则](../guides/middleware/composition)。
+
+## Checkpointer
+
+任何匹配下面 Protocol 的对象就是 Checkpointer:
+
+```python
+class Checkpointer(Protocol):
+ async def load(self, thread_id: str) -> CheckpointData | None: ...
+ async def append(self, thread_id: str, messages: list[Message]) -> None: ...
+ async def save_extra(self, thread_id: str, extra: dict) -> None: ...
+```
+
+通过 `Agent(checkpointer=cp, thread_id="…")` 绑定到 Agent,循环就会在
+每条消息落定时追加一行,并在第一次 `prompt()` 时恢复历史。内置后端:
+`MemoryCheckpointer`、`SQLiteCheckpointer`、`PostgresCheckpointer`、`MySQLCheckpointer`。
+见 [Checkpointing → SQLite](../guides/checkpointing/sqlite)。
+
+HITL 为跨进程挂起/恢复新增了两个可选方法:`save_pending_request` /
+`load_pending_request`。所有第一方后���都已实现。见 [HITL 指南](../guides/hitl/overview)。
+
+## HITL(人机协同)
+
+CubePi 内置了 `cubepi.hitl` 模块,用于 agent 需要**暂停并等待人类输入**的
+场景:
+
+- **沙箱确认** —— 危险工具(bash、写入文件)在执行前需要人类
+ approve / deny / edit。
+- **运行中提问** —— agent 在运行中途向用户弹出一个结构化表单,等待回答。
+
+```python
+from cubepi.hitl import InMemoryChannel, ConfirmToolCallMiddleware, ask_user_tool
+
+channel = InMemoryChannel()
+
+agent = Agent(
+ provider=…, model=…,
+ tools=[bash_tool, ask_user_tool(channel)],
+ middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
+ channel=channel,
+)
+```
+
+Channel 是一个可 `await` 的协程协作者:工具和中间件作者写
+`await channel.ask(...)` 或 `await channel.confirm(...)`,channel
+处理暂停。宿主代码(你的 web 应用 / TUI)订阅 `channel.subscribe()` 或
+轮询 `channel.pending`,把请求渲染给用户,然后通过
+`channel.answer(qid, answer)` 回填答案。
+
+内置两种 channel 后端:
+- **`InMemoryChannel`** —— 单进程(CLI、notebook、测试)。
+- **`CheckpointedChannel`** —— 跨进程(web 服务)。挂起的请求持久化到
+ checkpointer;另一个进程可以在数小时后通过
+ `Agent.respond(question_id=, answer=)` 回答。
+
+完整细节——三种 HITL 动词、两套内置中间件、跨进程挂起/恢复协议、事件、
+追踪 span 和错误参考——见 [HITL 指南](../guides/hitl/overview)。
+
+## Tracer(可选)
+
+`Tracer` 输出符合 [OpenTelemetry GenAI 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/)
+的 span,任何 OTLP 后端(Jaeger、Tempo、Honeycomb、Datadog、AWS
+X-Ray 等)都能直接接收,无需额外 instrumentation。先装 extra:
+
+```bash
+pip install "cubepi[tracing]" # OTel SDK
+pip install "cubepi[tracing-otlp]" # + OTLP/HTTP 导出器
+```
+
+然后用 `async with` 包住 Agent:
+
+```python
+from cubepi.tracing import Tracer
+from cubepi.tracing.exporters import JsonlSpanExporter
+
+async with (
+ Tracer(
+ service_name="my-bot",
+ agent_name="assistant",
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+ ) as tracer,
+ tracer.attached(agent),
+):
+ await agent.prompt("…")
+```
+
+每次 run 会发出一个 `invoke_agent` 根 span,其下每轮 LLM 往返对应
+一个 `cubepi.turn`,再嵌套 `chat`(CLIENT)和 `execute_tool` 子
+span。**默认不记录任何 prompt 内容或模型输出** —— 需要的话用
+`Tracer(record_content=True)` 显式打开,搭配 `redact` 回调脱敏。配
+合 `Meter(...)` 还能拿到 token / 时延 / TTFC 直方图。完整指南:
+[追踪 → 概览](../guides/tracing/overview)。
+
+## 拼起来
+
+```
+用户代码
+ │
+ ▼
+┌──────────────────────────────────────────┐
+│ Agent │
+│ ├─ AgentState (messages, tools, …) │
+│ ├─ Middleware ── compose_middleware() │
+│ ├─ Checkpointer ── message_end 时追加 │
+│ └─ run_agent_loop ◀──── 真实的循环 │
+│ │ │
+│ ▼ │
+│ Provider.stream() → MessageStream │
+│ │ │
+│ └─ events → emit → subscribers │
+└──────────────────────────────────────────┘
+```
+
+这张图就是整个框架。文档站的其余部分,都是细节而已。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/installation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/installation.md
new file mode 100644
index 0000000..e05b887
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/installation.md
@@ -0,0 +1,93 @@
+---
+title: 安装
+description: "通过 pip 安装 CubePi。需要 Python 3.11+,支持 Linux、macOS 和 Windows。"
+---
+
+# 安装
+
+CubePi 需要 **Python 3.11 或以上**。核心运行时只有三个依赖:`pydantic`、
+`anthropic`、`openai`。可选功能(SQLite、Postgres、MCP、OpenTelemetry
+追踪)通过 extras 按需安装,不用的话不会被拉进来。
+
+## 使用 pip
+
+```bash
+pip install cubepi
+```
+
+可选 extras:
+
+```bash
+pip install "cubepi[sqlite]" # 安装 aiosqlite,启用 SQLiteCheckpointer
+pip install "cubepi[postgres]" # 安装 asyncpg + sqlalchemy + msgpack
+pip install "cubepi[mcp]" # 安装 MCP SDK,启用 MCP 工具加载器
+pip install "cubepi[tracing]" # 安装 opentelemetry-sdk,启用 Tracer / Meter
+pip install "cubepi[tracing-otlp]" # 加上 OTLP/HTTP 导出器
+pip install "cubepi[sqlite,mcp,tracing]" # 组合
+```
+
+## 使用 uv
+
+[`uv`](https://github.com/astral-sh/uv) 比 pip 快很多,是推荐的工作流:
+
+```bash
+uv add cubepi
+uv add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"
+```
+
+在已有 uv 项目里,改完 `pyproject.toml` 后 `uv sync` 会重新锁定环境。
+
+## 使用 Poetry
+
+```bash
+poetry add cubepi
+poetry add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"
+```
+
+## 验证安装
+
+```bash
+python -c "import cubepi; print(cubepi.__doc__)"
+# cubepi — Pythonic async-native agent framework.
+```
+
+如果报 `ImportError`,大概率是解释器版本低于 3.11——用 `python --version`
+确认一下。
+
+## 配置 provider 凭据
+
+CubePi 的 provider 从构造函数参数读取凭据。大多数部署会从环境变量
+取出来:
+
+```python
+import os
+from cubepi.providers.anthropic import AnthropicProvider
+from cubepi.providers.openai import OpenAIProvider
+
+anthropic = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+openai = OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"])
+```
+
+你也可以传 `base_url=...` 指向自托管端点或兼容代理(如 Anthropic Bedrock、
+LiteLLM、vLLM)。
+
+[FauxProvider](../guides/providers/custom#using-fauxprovider-in-tests)
+(用于测试)不需要任何凭据。
+
+## extras 选择指南
+
+| Extra | 拉入什么 | 什么时候装 |
+|---|---|---|
+| (无) | 仅核心 | 只需要内存里的状态,不用 MCP,不用追踪 |
+| `[sqlite]` | `aiosqlite` | 单进程应用需要落盘 |
+| `[postgres]` | `asyncpg`、`sqlalchemy`、`msgpack` | 多实例 / 生产环境——见 [Postgres 指南](../guides/checkpointing/postgres) |
+| `[mcp]` | `mcp` | 想把 MCP server 工具挂到 Agent 上 |
+| `[tracing]` | `opentelemetry-sdk` | 想要 OpenTelemetry 追踪(含可选指标)——见 [追踪指南](../guides/tracing/overview) |
+| `[tracing-otlp]` | `opentelemetry-exporter-otlp-proto-http` | 把 trace 发往 OTLP/HTTP 后端(Jaeger ≥1.50、Tempo、Honeycomb、Datadog 等)|
+| `[docs]` | `griffe` | 仅文档站构建(贡献者用) |
+
+## 下一步
+
+- [快速开始](./quick-start) —— 五分钟内跑通你的第一个 Agent。
+- [核心概念](./core-concepts) —— 在动手前先弄清 `Agent` / `Tool` /
+ `Provider` / `Checkpointer` 各自是什么。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/quick-start.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/quick-start.md
new file mode 100644
index 0000000..490deac
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/getting-started/quick-start.md
@@ -0,0 +1,123 @@
+---
+title: 快速开始
+description: "在几分钟内构建你的第一个 CubePi agent。"
+---
+
+# 快速开始
+
+五分钟内跑通一个能流式输出、会调用工具的 Agent。我们写一个天气 Agent:
+它把一个 Python 函数当工具调用、把 Claude 的回复逐字符流式打出来,
+然后干净退出。
+
+## 前置条件
+
+- Python 3.11+
+- 已安装 `cubepi`(`pip install cubepi`)
+- 环境变量中有 `ANTHROPIC_API_KEY`
+
+## 完整脚本
+
+存为 `weather_agent.py`:
+
+```python title="weather_agent.py"
+import asyncio
+import os
+from pydantic import BaseModel
+
+from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+class GetWeatherParams(BaseModel):
+ city: str
+
+
+async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+ # 真实应用里:调一个 HTTP 天气 API。这里直接返回一段假数据。
+ return AgentToolResult(
+ content=[TextContent(text=f"{params.city} 现在 72°F,晴")]
+ )
+
+
+async def main():
+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="你是一个简洁的天气助手。",
+ tools=[
+ AgentTool(
+ name="get_weather",
+ description="获取一个城市的当前天气",
+ parameters=GetWeatherParams,
+ execute=get_weather,
+ ),
+ ],
+ )
+
+ # 在 prompt() 之前订阅 —— 这是看到流式事件的关键。
+ def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+ elif event.type == "agent_end":
+ print() # 末尾换行
+
+ agent.subscribe(on_event)
+ await agent.prompt("东京现在天气怎么样?")
+
+
+asyncio.run(main())
+```
+
+跑起来:
+
+```bash
+python weather_agent.py
+```
+
+你会看到 Claude 流式输出类似
+*"东京当前天气 72°F,晴..."* 的句子,工具结果已经被串进去。
+
+## 刚刚发生了什么
+
+CubePi 跑了一个概念上长这样的循环:
+
+1. `agent.prompt("东京现在天气怎么样?")` 把一条 `UserMessage` 入队,
+ 然后调用模型。
+2. 模型决定调用 `get_weather(city="Tokyo")`——CubePi 用你的 Pydantic
+ 模型解析 JSON 参数,调用你的 `async def`,把结果作为
+ `ToolResultMessage` 反馈回去。
+3. 模型产生最终的 assistant 回复,以 `text_delta` 事件流的形式回来。
+4. 循环发出 `agent_end` 然后返回。
+
+`agent.subscribe(...)` 注册了一个回调,接收运行时发出的每一个事件:
+`agent_start`、`turn_start`、`message_start`、`text_delta`、
+`tool_execution_start`、`tool_execution_end`、`message_end`、
+`turn_end`、`agent_end`。这个脚本只关心 `text_delta`,但你可以基于
+任意其他事件渲染 UI。
+
+## 调试之前请先读:常见困惑
+
+- **必须在 prompt 之前订阅。** Listener 只会收到 `subscribe` 之后发出
+ 的事件。先 prompt 再 subscribe,早期事件就丢了。
+- **`Model(id=..., provider=...)` 是必填的。** Agent 使用 `model.provider`
+ 来 clamp 思考等级、给响应打标签。`id` 必须是你的 provider 支持的
+ 模型名。
+- **`execute` 签名是固定的。** 哪怕你不用 keyword-only 参数,签名也得
+ 保留 `(tool_call_id, params, *, signal, on_update)`。CubePi 总是
+ 会传它们。
+- **`agent.prompt()` 一次只能跑一个 prompt。** 跑的过程中,用
+ [`agent.steer()`](../guides/agents/multi-turn) 插入修正,或
+ `agent.follow_up()` 把后续消息排队。
+
+## 下一步
+
+- [核心概念](./core-concepts) —— `Agent`、`Tool`、`Provider`、`Stream`、
+ `Middleware`、`Checkpointer` 背后的心智模型。
+- [构建第一个 Agent](../guides/agents/first-agent) —— 工具、流式、错误
+ 处理的完整走查。
+- [工具使用与并行执行](../guides/agents/tool-use) —— 让 Agent 同时
+ 扇出多个工具。
+- [Recipes → Weather Agent](../recipes/weather-agent) —— 上面这个脚本
+ 的加强版,真的会发 HTTP 请求。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/first-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/first-agent.md
new file mode 100644
index 0000000..9166798
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/first-agent.md
@@ -0,0 +1,181 @@
+---
+title: 第一个 Agent
+description: "从零开始创建并运行你的第一个 CubePi agent。"
+---
+
+# 构建你的第一个 Agent
+
+这是 [快速开始](../../getting-started/quick-start) 的"加长版"。我们
+端到端构建一个单工具 Agent,然后逐层加上你后续大概率会想要的东西:
+流式 UI、错误处理、取消按钮。
+
+## 第 1 步 —— 配 provider 和 model
+
+provider 是到 LLM API 的连接;`Model` 描述你想调哪个模型 + 一些能力
+开关。
+
+```python
+import os
+from cubepi import Model
+from cubepi.providers.anthropic import AnthropicProvider
+
+provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+model = Model(
+ id="claude-sonnet-4-5-20250929",
+ provider="anthropic",
+ max_tokens=4096, # 回复 token 上限
+ context_window=200_000, # 模型硬上限;通常默认就够
+ temperature=0.7,
+)
+```
+
+`Model.provider` 是一个字符串标签(比如 `"anthropic"`、`"openai"`)。
+框架内部用来 clamp 思考等级和打 tag —— 在你的代码库里保持稳定即可,
+不必和 provider 内部命名一致。
+
+## 第 2 步 —— 声明一个工具
+
+每个工具 = Pydantic 参数模型 + 一个异步 `execute` 函数:
+
+```python
+from pydantic import BaseModel
+from cubepi import AgentTool, AgentToolResult, TextContent
+
+
+class GetWeatherParams(BaseModel):
+ city: str
+
+
+async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+ # 真实工作放在这里 —— 调 HTTP API、查 DB 等。
+ return AgentToolResult(
+ content=[TextContent(text=f"{params.city} 现在 72°F,晴")]
+ )
+
+
+weather_tool = AgentTool(
+ name="get_weather",
+ description="获取一个城市的当前天气,返回简短文字。",
+ parameters=GetWeatherParams,
+ execute=get_weather,
+)
+```
+
+注意几点:
+
+- Pydantic 模型自动转成 JSON Schema,作为工具定义发给模型。
+- `execute` 签名是固定的:`(tool_call_id, params, *, signal, on_update)`。
+ 最后两个 keyword-only 参数一定会被传入 —— 哪怕你不用,也得在签名里。
+- `signal` 是用户取消时会被 set 的 `asyncio.Event`。在长时间运行的
+ 代码里检查它,及时退出。
+- `on_update(partial)` 让你流式回报进度(见
+ [工具使用](./tool-use))。
+
+## 第 3 步 —— 组装 Agent
+
+```python
+from cubepi import Agent
+
+agent = Agent(
+ provider=provider,
+ model=model,
+ system_prompt="你是一个简洁的天气助手。",
+ tools=[weather_tool],
+)
+```
+
+不需要工具时传 `tools=[]`(或干脆省掉)。
+
+## 第 4 步 —— 订阅事件
+
+`agent.subscribe(listener)` 是观察运行过程的入口。Listener 会收到
+每一个 `AgentEvent`:
+
+```python
+def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+ elif event.type == "tool_execution_start":
+ print(f"\n→ 调用 {event.tool_name}({event.args})")
+ elif event.type == "tool_execution_end":
+ print(f" ✓ 完成")
+
+agent.subscribe(on_event)
+```
+
+可以注册多个 listener,它们都会收到所有事件。**在 `prompt()` 之前
+订阅** —— 事件在 run 一开始就会发出。
+
+## 第 5 步 —— prompt 然后跑
+
+```python
+import asyncio
+
+async def main():
+ await agent.prompt("东京天气怎么样?")
+
+asyncio.run(main())
+```
+
+`agent.prompt()` 不返回任何值。结果存在 `agent.state.messages`
+(完整历史)和 `agent.state.streaming_message`(当前正在产生的消息,
+在两轮之间为 `None`)上。
+
+## 加上错误处理
+
+当 `provider.stream()` 抛异常时,Agent 循环仍然会产出一条
+`AssistantMessage`,其 `stop_reason="error"`、`error_message` 已填好。
+事件序列是:`message_start` → `message_end` → `turn_end` → `agent_end`。
+
+两种处理方式:
+
+1. 在 subscriber 里捕获 `event.type == "agent_end"`,看最后一条消息
+ 的 `stop_reason`:
+
+ ```python
+ def on_event(event, signal=None):
+ if event.type == "agent_end":
+ last = event.messages[-1]
+ if getattr(last, "stop_reason", "") == "error":
+ print(f"\nerror: {last.error_message}")
+ ```
+
+2. 或者在 `await agent.prompt(...)` 返回之后,检查
+ `agent.state.error_message`。
+
+## 加一个"取消按钮"
+
+`agent.abort()` 会 set run 级别的 signal。Provider 流短路成
+`"aborted"`,正在运行的工具看到 `signal.is_set() == True`,
+循环干净地发出 `agent_end`。
+
+```python
+async def main():
+ task = asyncio.create_task(agent.prompt("搜索…"))
+ await asyncio.sleep(0.5)
+ agent.abort()
+ await task # 一定会 return —— 不会抛异常
+ await agent.wait_for_idle()
+```
+
+## 常见坑
+
+- **`RuntimeError: Agent is already processing a prompt.`** ——
+ 上一次 `prompt()` 没 await 完你又调了一次。用 `await
+ agent.wait_for_idle()`,或用 `steer()` / `follow_up()` 排队。
+- **没有 `text_delta` 事件** —— 是不是在 `prompt()` 之后才订阅的?
+ Listener 只看得到注册之后的事件。
+- **Tool not found** —— 模型调了一个 `name` 不在 `tools=[...]` 里的
+ 工具。CubePi 把这种情况包装成一个 `is_error=True` 的工具结果,
+ 不会崩 —— 在 `tool_execution_end` 事件的 `result` 里能看到。
+- **Pydantic ValidationError 被吞掉了** —— 如果模型产出格式错误的
+ JSON,CubePi 会把 validation error 也包成工具的 error result 喂
+ 回去,模型通常下一轮自动纠正。
+
+## 下一步
+
+- [工具使用与并行执行](./tool-use) —— 同时多个工具、sequential 模式、
+ `terminate`、增量进度。
+- [流式事件](./streaming) —— 完整的事件分类。
+- [多轮会话](./multi-turn) —— 跨轮保留状态、`steer`、`follow_up`、
+ `resume`。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/streaming.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/streaming.md
new file mode 100644
index 0000000..d8451b6
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/streaming.md
@@ -0,0 +1,152 @@
+---
+title: 流式输出
+description: "通过 subscriber 和 MessageStream 实时流式接收 CubePi agent 的事件和 token。"
+---
+
+# 流式事件
+
+CubePi 暴露两层流:
+
+1. **Provider 流** —— `provider.stream(...)` 返回的 `MessageStream`,
+ 产出 `StreamEvent` 描述原始线缆输出:文本 delta、思考 delta、
+ 工具调用 delta,最后是 `done` 或 `error`。
+2. **Agent 事件流** —— `agent.subscribe(...)` 注册的 listener 看到的
+ 内容。十一种事件覆盖 `prompt()` 调用的完整生命周期,包括把 provider
+ 事件包在 `MessageUpdateEvent` 里。
+
+大部分应用代码只需要 Agent 事件流。
+
+## 十一种 Agent 事件
+
+| 事件 | 何时触发 |
+|---|---|
+| `agent_start` | `prompt()` / `resume()` 一开始 |
+| `turn_start` | 每次调模型之前(一次 `prompt` 可能调多次) |
+| `message_start` | 一条新消息(user / assistant / tool result)即将加入历史 |
+| `message_update` | 每个 provider `StreamEvent`(deltas 等);`event.stream_event` 字段会带原始事件 |
+| `message_end` | 一条消息已 finalize |
+| `tool_execution_start` | 一个工具调用被派发(在并行 `asyncio.gather` 之前各发一次) |
+| `tool_execution_update` | 一个工具通过 `on_update(...)` 报告了局部进度 |
+| `tool_execution_end` | 一个工具结束(成功或失败) |
+| `turn_end` | 当前批次的工具都尘埃落定,或一条无工具的 assistant 回复结束 |
+| `agent_end` | 整个 `prompt()` 调用结束 —— 正常结束、abort、或 error 都会发 |
+
+`MessageStartEvent` 和 `MessageEndEvent` 对 *每种* 消息都触发,不只是
+assistant。User 消息和 tool result 消息也有。
+
+## 工具调用一轮的事件顺序
+
+典型 "用户提问 → 模型调一个工具 → 模型回答" 的事件序列:
+
+```
+agent_start
+turn_start
+ message_start (从 prompt 来的 UserMessage)
+ message_end (UserMessage)
+ message_start (空的 AssistantMessage partial)
+ message_update × N (text_delta、toolcall_delta、…)
+ message_end (finalize 后的 AssistantMessage)
+ tool_execution_start
+ tool_execution_end
+ message_start (ToolResultMessage)
+ message_end (ToolResultMessage)
+turn_end
+turn_start (循环带着工具结果再进模型)
+ message_start
+ message_update × N
+ message_end
+turn_end
+agent_end
+```
+
+## 订阅
+
+```python
+def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+
+unsubscribe = agent.subscribe(on_event)
+```
+
+`agent.subscribe(...)` 永远不会收到 `event.type == "text_delta"`
+的事件 —— 那是 *provider* 事件的 type。Agent 把每个 provider 事件
+都包成 `MessageUpdateEvent`,原事件挂在 `event.stream_event` 上。
+所以要同时匹配外层和内层。
+
+Listener 可以是同步或异步,异步的会被 await。第二个参数是 run 级别
+的 `asyncio.Event`(abort signal)—— 你可以查 `signal.is_set()` 判断
+本次运行是否被取消。
+
+要取消订阅,调用 `subscribe` 返回的那个函数。
+
+## 过滤文本增量(最常见的用法)
+
+```python
+def on_event(event, signal=None):
+ if event.type == "message_update":
+ sub = event.stream_event
+ if sub.type == "text_delta":
+ print(sub.delta, end="", flush=True)
+```
+
+CubePi 保证的稳定结构是上面表格里那一种(`message_update.stream_event.delta`)。
+代码里对内部类型做防御性判断。
+
+## Provider 的 `StreamEvent` 类型
+
+在 `MessageUpdateEvent.stream_event` 内部,type 字段告诉你模型正在
+吐什么:
+
+| `stream_event.type` | 含义 | 关键字段 |
+|---|---|---|
+| `start` | assistant 消息开始 | `partial` |
+| `text_start` | 一个文本块开始 | `content_index` |
+| `text_delta` | token 片段 | `delta` |
+| `text_end` | 文本块结束 | `content_index` |
+| `thinking_start` / `thinking_delta` / `thinking_end` | 扩展思考块 | `delta` |
+| `toolcall_start` / `toolcall_delta` / `toolcall_end` | 工具调用的流式 JSON 参数 | `delta`(partial JSON) |
+| `done` | 流正常结束 | — |
+| `error` | 流出错 | `error_message` |
+
+每个事件的 `partial` 字段是当前 `AssistantMessage` 的深拷贝快照,
+方便 UI 不追 delta、每个事件直接重渲染。
+
+## 直接迭代 provider 流
+
+如果你完全跳过 `Agent`(罕见,通常意味着你在写测试或自定义编排),
+直接迭代流即可:
+
+```python
+stream = await provider.stream(
+ model=model,
+ messages=[UserMessage(content=[TextContent(text="hello")])],
+)
+async for event in stream:
+ if event.type == "text_delta":
+ print(event.delta, end="", flush=True)
+final = await stream.result() # 拿最终的 AssistantMessage
+```
+
+`stream.result()` 在迭代结束后也能调用 —— 这是拿最终消息的标准
+方式。
+
+## 常见坑
+
+- **`prompt()` 之后才订阅** —— 早期事件已经发完了。先 subscribe,
+ 再 prompt。
+- **Listener 抛异常会让循环崩吗?** —— 不会,但异常会向上传播到下一个
+ `await`。把风险代码包在 try/except 里。
+- **并行工具的事件顺序** —— `tool_execution_start` 按模型发出顺序,
+ `tool_execution_end` 按完成顺序。别依赖事件成对相邻。
+- **`message_update` 触发太频繁** —— 高频 token 可能压垮慢消费者
+ (比如 websocket)。消费端做批处理。
+- **思考块会触发 `text_delta` 吗?** —— 不会,思考块发 `thinking_*`
+ 事件。只想看可见文本就过滤 `event.stream_event.type`。
+
+## 另请参阅
+
+- [工具使用](./tool-use) —— 详解 `tool_execution_*` 三联事件。
+- [多轮会话](./multi-turn) —— steering 和 resume 周边的事件顺序。
+- [API Reference → StreamEvent](../../api/cubepi-providers#streamevent)
+ 里有字段级 schema。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/tool-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/tool-use.md
new file mode 100644
index 0000000..6e50422
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/agents/tool-use.md
@@ -0,0 +1,180 @@
+---
+title: 工具调用
+description: "注册工具、并行或顺序执行、并通过 Pydantic 校验处理结果的完整指南。"
+---
+
+# 工具使用与并行执行
+
+工具是 Agent 影响世界的方式。CubePi 把每个 `AgentTool` 转成模型可用
+的 JSON Schema、用 Pydantic 校验参数、执行你的代码、把结果作为
+`ToolResultMessage` 喂回。默认情况下,只要模型在一轮里发出多个工具
+调用,它们就会并行执行。
+
+## 工具的结构
+
+```python
+from pydantic import BaseModel, Field
+from cubepi import AgentTool, AgentToolResult, TextContent
+
+
+class SearchParams(BaseModel):
+ query: str = Field(..., description="自然语言查询")
+ limit: int = Field(10, ge=1, le=100)
+
+
+async def search(tool_call_id, params: SearchParams, *, signal=None, on_update=None):
+ results = await my_search_backend(params.query, params.limit)
+ return AgentToolResult(
+ content=[TextContent(text="\n".join(results))],
+ details={"raw_results": results}, # 透传到 ToolResultMessage.details
+ )
+
+
+search_tool = AgentTool(
+ name="search",
+ description="在内部知识库里搜索。",
+ parameters=SearchParams,
+ execute=search,
+)
+```
+
+`description` 是直接展示给模型的 —— 给模型写,不是给人看。Pydantic
+的 `Field(description=…)` 会进 JSON Schema,帮模型理解每个参数。
+
+## 默认并行
+
+模型在一条 assistant 消息里发多个工具调用时,CubePi 会用
+`asyncio.create_task()` 调度它们并 gather。这通常就是你想要的。
+
+```python
+agent = Agent(
+ provider=provider,
+ model=model,
+ tools=[search_tool, fetch_url_tool, summarise_tool],
+)
+```
+
+事件流会先一次性发出所有 `tool_execution_start`,中间穿插每个工具
+报告进度的 `tool_execution_update`,最后按完成顺序发
+`tool_execution_end`。
+
+## 强制顺序执行
+
+两种方式:
+
+1. **整个 agent 级别** —— `Agent(tool_execution="sequential")`。所有
+ 工具批次按模型发出的顺序逐个执行。
+
+2. **单个工具级别** —— 在 `AgentTool` 上设
+ `execution_mode="sequential"`。一旦当前批次里 *任意* 一个工具是
+ sequential,整个批次都退化为顺序执行。
+
+ ```python
+ write_db_tool = AgentTool(
+ name="write_db",
+ description="持久化一条记录。",
+ parameters=WriteDbParams,
+ execute=write_db,
+ execution_mode="sequential", # 出于安全考虑放弃并行
+ )
+ ```
+
+内置的 `ask_user` HITL 工具(见 [HITL 指南](../hitl/overview))设置了
+`execution_mode="sequential"` —— 它会暂停 agent 等待人类输入,因此
+工具批次会逐个运行。
+
+工具会修改共享状态(DB、计数器)且你需要确定顺序时,选 sequential。
+
+## 流式回报工具进度
+
+长耗时工具可以推送增量更新,以 `tool_execution_update` 事件呈现:
+
+```python
+async def slow_search(tool_call_id, params, *, signal=None, on_update=None):
+ for i, page in enumerate(await fetch_pages(params.query)):
+ if signal and signal.is_set():
+ break
+ if on_update:
+ on_update({"progress": i, "total": len(pages), "url": page.url})
+ await process(page)
+ return AgentToolResult(content=[TextContent(text="done")])
+```
+
+事件里的 `partial_result` 就是你传给 `on_update` 的对象。用小 dict 就好,
+它不会进模型的 context。
+
+## 取消正在跑的工具
+
+`signal` 就是 `agent.abort()` set 的那个 `asyncio.Event`。在任何循环
+里检查它:
+
+```python
+async def long_running(tool_call_id, params, *, signal=None, on_update=None):
+ for chunk in big_dataset:
+ if signal and signal.is_set():
+ return AgentToolResult(content=[TextContent(text="cancelled")])
+ await process_chunk(chunk)
+```
+
+如果工作是一个大 `await`,用 `asyncio.wait_for(..., timeout=…)` 包一下,
+或调用底层库自己的取消方法。
+
+## 返回错误
+
+两种姿势:
+
+1. **抛异常。** CubePi 捕获后转成 `is_error=True` 的 `AgentToolResult`,
+ 异常字符串作为 `TextContent`。
+2. **显式返回 `is_error=True`。** 适合你想给结构化错误体的场景:
+
+ ```python
+ return AgentToolResult(
+ content=[TextContent(text="超出限流,60 秒后再试")],
+ is_error=True,
+ )
+ ```
+
+不管哪种方式,模型都会收到一个明确标记错误的工具结果,通常会自适应
+(换参数重试、问用户等)。
+
+## 从工具结束本轮:`terminate`
+
+工具可以声明 *"这次之后,不要再循环到模型了。"* 设
+`terminate=True`:
+
+```python
+async def submit_final_answer(tool_call_id, params, *, signal=None, on_update=None):
+ save_answer(params.answer)
+ return AgentToolResult(
+ content=[TextContent(text="submitted")],
+ terminate=True,
+ )
+```
+
+CubePi 仅在当前批次中 *每个* 工具结果都是 `terminate=True` 时才终止。
+然后循环发 `turn_end`、`agent_end`,退出。
+
+## 常见坑
+
+- **忘了 keyword-only 参数** —— 开发时 `execute(tool_call_id, params)`
+ 能跑,但框架传 `signal=` 时会崩。签名一定保留
+ `*, signal=None, on_update=None`。
+- **`details` 塞太大** —— `details` 透传到 agent 事件里,但 **不会**
+ 给模型看。除非你下游有消费者,否则别堆大 blob。
+- **Pydantic 严格度的意外** —— `Field(..., min_length=1)` 让模型通过
+ JSON Schema 看到约束 —— 约束有帮助,但模型仍然偶尔发坏 JSON。
+ CubePi 把 `ValidationError` 转成工具的 error result,你不用自己包。
+- **`tools=[]` 但模型还是想用工具** —— 一般是 system prompt 里提到了
+ 工具。要么删掉提示,要么真的把工具给它。
+
+## 另请参阅
+
+- [流式事件](./streaming) —— `tool_execution_*` 事件如何嵌入到事件
+ 分类体系。
+- [Middleware → before_tool_call](../middleware/hooks#before_tool_call)
+ 和 [after_tool_call](../middleware/hooks#after_tool_call) ——
+ 拦截、策略、重试。
+- [Recipes → Weather Agent](../../recipes/weather-agent) —— 一个真发
+ HTTP 请求的工具,端到端。
+- [MCP 加载](../mcp/loading) —— 一次性把一个 MCP server 的整套工具
+ 拉下来。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/checkpointing/postgres.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/checkpointing/postgres.md
new file mode 100644
index 0000000..2164f23
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/checkpointing/postgres.md
@@ -0,0 +1,195 @@
+---
+title: Postgres 检查点
+description: "使用 PostgresCheckpointer 实现生产级的 agent 状态持久化。"
+---
+
+# Postgres 检查点
+
+`PostgresCheckpointer` 是生产级持久化后端。它使用 `asyncpg` 搭配连接池、
+`msgpack` 编码 payload、以及每线程的 Postgres advisory lock,让多个进程
+可以安全地写入同一个 `thread_id` 而不会互相干扰。
+
+安装 extra:
+
+```bash
+pip install "cubepi[postgres]"
+```
+
+会拉入 `asyncpg`、`sqlalchemy` 和 `msgpack`。
+
+## 基本用法
+
+```python
+import asyncio
+from cubepi import Agent, Model
+from cubepi.checkpointer import PostgresCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+async def main():
+ provider = AnthropicProvider(api_key="…")
+ async with PostgresCheckpointer("postgresql://user:pass@host/dbname") as cp:
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ checkpointer=cp,
+ thread_id="user-42",
+ )
+ await agent.prompt("hello")
+
+
+asyncio.run(main())
+```
+
+DSN 接受 `asyncpg.create_pool(...)` 支持的任何格式。连接池大小:
+
+```python
+async with PostgresCheckpointer(
+ "postgresql://…",
+ min_pool_size=2,
+ max_pool_size=20,
+) as cp:
+ …
+```
+
+## Schema
+
+checkpointer 需要三张表:`cubepi_threads`、`cubepi_messages` 和
+`cubepi_schema_version`。与 SQLite 不同,CubePi **不会自动创建这些表**——
+它只在 `__aenter__` 时验证它们是否存在且 `schema_version` 是否匹配预期。
+
+如果表不存在,你会收到 `CubepiSchemaUninitialized`。如果版本与本版
+CubePi 不匹配,你会收到 `CubepiSchemaMismatch`。
+
+原因:生产数据库属于宿主应用的迁移系统(Alembic、Atlas……),
+不属于一个可能与你现有迁移冲突的第三方库。
+
+### 通过 Alembic 引导 {#bootstrapping-via-alembic}
+
+CubePi 暴露了 SQLAlchemy `MetaData`,让你的迁移可以采用其 schema:
+
+```python
+# alembic/env.py
+from cubepi.checkpointer.postgres import cubepi_metadata, EXPECTED_SCHEMA_VERSION
+
+target_metadata = [my_app_metadata, cubepi_metadata]
+```
+
+然后生成一个 revision 并执行。迁移还必须在 `cubepi_schema_version` 中
+INSERT schema 版本。使用辅助函数:
+
+```python
+# 在迁移的 upgrade() 中:
+from cubepi.checkpointer.postgres.alembic_helpers import (
+ create_message_partitions_op,
+ write_schema_version_op,
+)
+
+def upgrade():
+ op.create_table(...) # 从 cubepi_metadata 自动生成
+ op.execute(create_message_partitions_op()) # 创建 64 个哈希分区
+ op.execute(write_schema_version_op()) # 记录 EXPECTED_SCHEMA_VERSION
+```
+
+两个辅助函数都返回 SQL 字符串——你需要传入 `op.execute(...)`。
+`write_schema_version_op()` 是幂等的:它会删除之前 CubePi 版本的所有行,
+然后插入当前版本。
+
+当 CubePi 后续升级并提升了 `EXPECTED_SCHEMA_VERSION` 时,生成一个新的
+revision,再次调用 `op.execute(write_schema_version_op())`。
+
+## 数据模型
+
+```
+cubepi_threads
+ thread_id (PK)
+ parent_thread_id -- 用于 fork
+ forked_at_seq -- fork 点处的序列号
+ extra -- JSONB
+ created_at / updated_at
+
+cubepi_messages
+ thread_id, seq -- 复合 PK;按 HASH(thread_id) 分为 64 个分区
+ role -- "user" | "assistant" | "tool"
+ metadata -- JSONB(通过 GIN 索引)
+ payload -- bytea (msgpack)
+ created_at
+
+cubepi_schema_version
+ version (PK)
+```
+
+重要属性:
+
+- **`(thread_id, seq)` 是消息标识。** `seq` 在每线程中单调递增,
+ 在 `pg_advisory_xact_lock(hashtext(thread_id))` 下分配。
+ 两个对同一线程的并发写入者会干净地序列化。
+- **`payload` 是 msgpack 编码的 `model.model_dump(mode="json")`。**
+ CubePi 在读取时重建 Pydantic 模型。
+- **`metadata` 是 JSONB,可查询。** 完整消息的 payload 内部也包含
+ `metadata`,但这一列是 SQL 查询的规范视图。
+- **表按 `HASH(thread_id)` 分为 64 个分区。** 跨分区均匀分布,
+ 无每线程瓶颈。
+
+## 并发
+
+advisory lock 让同一线程上的追加操作跨进程安全:
+
+```python
+# 进程 A 和进程 B 同时追加到线程 "user-42"。
+# 它们通过 pg_advisory_xact_lock 序列化,各自获得连续的 seq。
+```
+
+读取(`load`)不取锁——它们在事务内是快照一致性的。
+
+默认连接池 `min=1, max=10` 对大多数应用足够;如果你的并发 agent 数
+很高,请调大 `max_pool_size`。
+
+## `save_extra` 语义
+
+`save_extra` 做的是 JSONB 合并,而不是替换:
+
+```sql
+extra = cubepi_threads.extra || EXCLUDED.extra
+```
+
+所以先写 `{"foo": 1}` 再写 `{"bar": 2}` 会得到 `{"foo": 1, "bar": 2}`。
+中间件可以安全地写入部分 dict 而不会丢失先前的键。
+
+## Fork
+
+`parent_thread_id` + `forked_at_seq` 列是为将来的 fork 支持预留的。
+CubePi v0.3 尚未暴露 fork API——现在写入它们是为了保持 schema
+的前向兼容性。
+
+## 常见坑
+
+- **`CubepiSchemaUninitialized`** —— 数据库为空或迁移未运行。
+ 先执行宿主 alembic upgrade。
+- **`CubepiSchemaMismatch`** —— 你升级了 CubePi 但未生成新的迁移。
+ 生成一个、执行它,CubePi 就会启动。
+
+ :::info Schema v2(HITL)
+
+ CubePi ≥ HITL 版本将 `EXPECTED_SCHEMA_VERSION` 从 1 提升到 2,
+ 并在 `cubepi_threads` 表中新增 `pending_request JSONB NULL` 列。
+ 宿主 alembic upgrade 必须在提升 schema_version 行之前调用
+ `add_pending_request_column_op()`(来自
+ `cubepi.checkpointer.postgres.alembic_helpers`)。
+ 完整的跨进程流程请参阅 [HITL 指南](../hitl/overview)。
+ :::
+- **负载下连接池耗尽** —— 默认 `max_pool_size=10`。
+ 如果应用的并发 agent 数超过此值,请调大。
+- **`asyncpg.exceptions.UndefinedTableError` 在 `__aenter__` 外部** ——
+ 表示你在 `async with` 之外使用了 checkpointer。连接池尚未连接。
+ 请用 context manager 包裹。
+- **混用宿主 SQLAlchemy `MetaData`** —— CubePi 自带独立的
+ `MetaData` 实例,正是为了能与你的应用模型共存而不冲突。
+ 不要将它们合并到你的全局 metadata 中——分别传给 Alembic。
+
+## 另请参阅
+
+- [SQLite 检查点](./sqlite) —— 单进程替代方案。
+- [自定义后端](./custom) —— Protocol 详情。
+- [配方 → Postgres + FastAPI 服务](../../recipes/postgres-fastapi)
+ —— 一个可部署的 HTTP 前端 agent。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/checkpointing/sqlite.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/checkpointing/sqlite.md
new file mode 100644
index 0000000..bb8c3e0
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/checkpointing/sqlite.md
@@ -0,0 +1,176 @@
+---
+title: SQLite
+description: "使用 SQLiteCheckpointer 实现轻量级单进程 agent 状态持久化。"
+---
+
+# SQLite 检查点
+
+`SQLiteCheckpointer` 是轻量级持久化后端:单个本地文件、无 server、
+追加式消息日志。它是个人电脑、单进程应用、桌面工具,以及任何"单
+进程独占会话"场景下的默认选择。
+
+安装 extra:
+
+```bash
+pip install "cubepi[sqlite]"
+```
+
+会拉入 `aiosqlite`。
+
+## 基本用法
+
+```python
+import asyncio
+from cubepi import Agent, Model
+from cubepi.checkpointer import SQLiteCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+async def main():
+ provider = AnthropicProvider(api_key="…")
+ async with SQLiteCheckpointer("agent.db") as cp:
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ checkpointer=cp,
+ thread_id="user-42",
+ )
+ await agent.prompt("记一下:我最爱的颜色是青色。")
+
+ # 之后再次启动脚本 —— 文件还在。
+ await agent.prompt("我说过我最爱什么颜色?")
+ # → "你说过是青色。"
+
+
+asyncio.run(main())
+```
+
+两件事必须记住:
+
+1. **`thread_id`** 是会话标识符 —— 一般是用户 id 或 session id。
+ 两个 Agent 用同一个 `thread_id` 共享同一段历史。
+2. **`async with SQLiteCheckpointer(...)`** 是必需的:context manager
+ 在 `__aenter__` 里打开连接、做一次性建表。不用 context manager
+ 会抛 `AssertionError`。
+
+## 会持久化什么
+
+`SQLiteCheckpointer` 首次使用时建两张表:
+
+```sql
+CREATE TABLE messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ thread_id TEXT NOT NULL,
+ message_json TEXT NOT NULL,
+ created_at REAL NOT NULL DEFAULT (julianday('now'))
+);
+
+CREATE TABLE thread_extra (
+ thread_id TEXT PRIMARY KEY,
+ extra_json TEXT NOT NULL DEFAULT '{}'
+);
+```
+
+- 每条 `UserMessage`、`AssistantMessage`、`ToolResultMessage` 各占
+ `messages` 一行。JSON payload 通过 Pydantic `model_dump()` 生成。
+- `AgentContext` 的 `extra` dict 在 `agent_end` 时持久化到 `thread_extra`。
+ Middleware 需要持久化线程级状态时,往 `context.extra` 写。
+
+这个 schema 是追加式的。CubePi 从不 update 或 delete 行。
+
+## HITL 挂起表
+
+当使用 [HITL](../hitl/overview) 模块时,每次 `__aenter__` 会自动创建一个额外的表:
+
+```sql
+CREATE TABLE IF NOT EXISTS thread_pending_request (
+ thread_id TEXT PRIMARY KEY,
+ request_json TEXT NOT NULL,
+ created_at REAL NOT NULL DEFAULT (julianday('now'))
+);
+```
+
+无需手动迁移 —— `CREATE TABLE IF NOT EXISTS` 是零等的。
+
+## CubePi 什么时候读
+
+构造 Agent 后的 **第一次** `prompt()`,CubePi 会调
+`load(thread_id)`。如果线程存在,历史恢复到 `agent.state.messages`,
+`extra` 恢复到 agent 私有的 `_extra` dict。
+
+后续 `prompt()` 不再读取 —— 内存里的状态是权威。
+
+这意味着:**不要让一个 `Agent` 实例跨进程共享**。进程 A 的内存状态
+会和进程 B 的写入发散。
+
+## 多线程隔离
+
+```python
+async with SQLiteCheckpointer("agent.db") as cp:
+ alice = Agent(provider=…, model=…, checkpointer=cp, thread_id="alice")
+ bob = Agent(provider=…, model=…, checkpointer=cp, thread_id="bob")
+ # 每个调用只 load/append 自己的 thread。
+```
+
+你可以让多个用户共用一个 checkpointer —— `thread_id` 负责隔离。
+
+## 并发模型
+
+Checkpointer 内部对每次读写都用 `asyncio.Lock`。SQLite 本身允许
+多进程写,但 CubePi 的假设是单 Agent 实例独占一个 thread。多进程
+同时写同一个 `agent.db`:
+
+- 读是安全的。
+- 并发写 **不同** thread 是安全的。
+- 并发写 **同一** thread 会交错 —— 你会看到两条 assistant 消息背靠背
+ 之类的怪事。
+
+如果你需要跨进程共享 thread 写入,请用 [Postgres](./postgres),
+它对每个 thread 都用 advisory lock。
+
+## 文件放哪里
+
+生产环境用绝对路径:
+
+```python
+SQLiteCheckpointer("/var/lib/myapp/agent.db")
+```
+
+相对路径在 `__aenter__` 时按 `os.getcwd()` 解析。目录必须存在,
+请预先创建。
+
+## 备份与查看
+
+文件就是普通 SQLite 数据库:
+
+```bash
+# 看一个 thread 的历史
+sqlite3 agent.db "SELECT message_json FROM messages WHERE thread_id='user-42' ORDER BY id"
+
+# 备份
+cp agent.db agent.db.bak
+
+# VACUUM 回收空间(可选 —— 文件大小随历史线性增长)
+sqlite3 agent.db "VACUUM"
+```
+
+## 常见坑
+
+- **没用 `async with`** —— `AssertionError: self._db is not None`。
+ 一定要用 `async with` 包。
+- **两个进程写同一个 thread** —— 交错历史。要么用 Postgres,要么在
+ 应用层协调。
+- **未启用 WAL 模式** —— CubePi 走默认 journal mode 以确保可移植性。
+ 对单写多读应用,一次性 `sqlite3 agent.db "PRAGMA journal_mode=WAL"`
+ 能显著提升并发读。
+- **忘传 `thread_id`** —— 不传时,Agent 没有持久化绑定。checkpointer
+ 会被静默忽略。一定要同时传两个。
+
+## 另请参阅
+
+- [Postgres 检查点](./postgres) —— 多实例部署。
+- [自定义后端](./custom) —— 为 Redis、DynamoDB 等实现 Protocol。
+- [Recipes → Persistent Chat](../../recipes/persistent-chat) —— 端到端
+ 的 SQLite 应用。
+- [Recipes → 可恢复的长任务](../../recipes/resumable-tasks) —— 工具
+ 执行中途崩溃也能恢复的 Agent。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/durable.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/durable.md
new file mode 100644
index 0000000..5d70035
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/durable.md
@@ -0,0 +1,87 @@
+---
+title: 跨进程与持久化
+sidebar_position: 3
+description: "用 CheckpointedChannel 在一个进程挂起 HITL 请求、在另一个进程恢复;持久化范围规则。"
+---
+
+# 跨进程流程与持久化
+
+## 跨进程(web 服务)流程
+
+```python
+# ───── 进程 1:HTTP POST /chat ─────
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=…, model=…,
+ tools=[bash_tool],
+ middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
+ channel=channel, checkpointer=cp, thread_id="conv-42",
+ )
+
+ task = asyncio.create_task(agent.prompt("删除临时文件"))
+
+ # 轮询挂起(或订阅 channel 用于 SSE 推送)
+ for _ in range(1000):
+ pending = channel.pending
+ if pending is not None:
+ break
+ await asyncio.sleep(0.1)
+
+ # 优雅挂起 — 持久化 assistant message + 未决 tool_calls,
+ # pending_request 留在 DB, 发射 AgentSuspendedEvent.
+ await agent.detach()
+ await task
+
+
+# ───── 进程 2:HTTP POST /respond ─────
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=…, model=…,
+ tools=[bash_tool],
+ middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
+ channel=channel, checkpointer=cp, thread_id="conv-42",
+ )
+
+ await agent.respond(
+ question_id=request.json["call_id"],
+ answer=ApproveAnswer(decision="approve"),
+ )
+ # Bash 工具执行,模型收到 tool_result,产生下一个 assistant turn。
+```
+
+**用户关闭 tab 未回答时:**
+
+```python
+await agent.abort_pending(reason="用户关闭了 tab")
+# Phase 1:发信号给进行中的 HITL await(如有),触发 HitlAborted。
+# Phase 2:为未决的 tool_calls 追加合成 deny ToolResultMessage,
+# 追加终止 AssistantMessage(stop_reason="aborted"),
+# 清除持久化 pending, 发射 AgentAbortedEvent。
+# 不调用模型。对话关闭。
+```
+
+
+## 持久化范围
+
+持久的跨进程恢复(进程死亡后仍能继续)在两个定义明确的安全暂停点支持:
+
+1. **`before_tool_call` 确认门** —— 确认中间件在工具的 `execute()` body
+ 运行*之前*调用 `channel.approve(...)`。此时不存在工具副作用。恢复时
+ 重新进入循环,执行(可能被编辑过的)工具体或替换为合成 deny
+ tool_result。
+2. **`ask_user` 工具体** —— 其整个 `execute()` body 就是
+ `return await channel.ask(...)`。恢复时不会重放任何内容。
+
+**默认情况下,在 `execute()` 内将 HITL 与其他工作混合的自定义工具不
+支持跨进程持久化。** 如果此类工具的进程在执行中途死亡,channel 调用
+前运行的所有内容都会丢失。除非使用 `allow_inside_custom_tool=True`
+构造 `CheckpointedChannel`,否则将抛出 `HitlDurabilityNotGuaranteed` —
+调用者必须承认等幂性契约(工具体在这一点必须是纯 HITL 等待,前面没有
+可观察的副作用)。
+
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/middlewares.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/middlewares.md
new file mode 100644
index 0000000..4076a0f
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/middlewares.md
@@ -0,0 +1,99 @@
+---
+title: 中间件与 ask_user
+sidebar_position: 2
+description: "用 ConfirmToolCallMiddleware / ApprovalPolicyMiddleware 把关工具调用,并用 ask_user 工具让模型发起结构化提问。"
+---
+
+# 中间件与 工具
+
+## 内置中间件
+
+### `ConfirmToolCallMiddleware`
+
+"在集合中的工具名一律询问人类。"
+
+```python
+from cubepi.hitl import ConfirmToolCallMiddleware
+
+agent = Agent(
+ ...,
+ middleware=[
+ ConfirmToolCallMiddleware(
+ channel,
+ require_confirm={"bash", "write_file"},
+ timeout_seconds=180,
+ ),
+ ],
+)
+```
+
+`require_confirm` 选项:
+
+| 值 | 行为 |
+|---|---|
+| `None`(默认) | 确认**所有**工具 |
+| `set[str]` | 仅当 `tool_call.name` 在集合中时确认 |
+| `Callable[[BeforeToolCallContext], bool]` | 自定义断言 —— 检查参数、上下文等 |
+
+### `ApprovalPolicyMiddleware`
+
+适用于需要**策略引擎**将工具调用分为 auto-allow、hard-deny 和
+human-confirm 三类的宿主。
+
+```python
+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
+
+def my_policy(ctx):
+ if ctx.tool_call.name == "read_file":
+ return Approve() # 直接放行
+ if ctx.tool_call.name.startswith("dangerous_"):
+ return Deny(reason="策略阻止") # 硬阻止,不询问人类
+ return AskUser(timeout_seconds=180) # 人类确认
+
+agent = Agent(
+ ...,
+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
+)
+```
+
+策略函数可以是同步或异步(可 `await`)。返回值:
+
+| 返回 | 效果 |
+|---|---|
+| `Approve()` | 工具运行;channel 从未调用 |
+| `Deny(reason)` | 工具阻塞;`hitl_trace["decision"]="policy_deny"` |
+| `AskUser(timeout_seconds=..., details=...)` | 调用 channel;人类选择 approve/deny/edit |
+
+## `ask_user` 内置工具
+
+模型在需要用户结构化输入时调用的工具。工厂函数返回一个名为
+`"ask_user"` 的 `AgentTool`,`execution_mode="sequential"`。
+
+```python
+from cubepi.hitl import ask_user_tool
+
+agent = Agent(
+ ...,
+ tools=[bash_tool, ask_user_tool(channel)],
+)
+```
+
+工具描述明确引导模型不要拿 `ask_user` 做自由文本澄清("对于自由文本
+提问,直接用文本结束 turn——用户的下一条消息就是答案")。
+
+取消和超时以 `tool_result.is_error=True` 体现,
+`details["hitl"]["outcome"]="cancelled"` / `"timed_out"` —— 模型看到
+干净的���误工具结果并能做出反应。其他 HITL 控制异常(HitlDetached、
+HitlAborted)传播到 Agent 层,不暴露给模型。
+
+
+## `ask_user` 对比 end of turn
+
+| 目标 | 用法 |
+|---|---|
+| 对用户的自由文本追问 | 直接用文本结束 turn——用户的下一条消息就是答案 |
+| 结构化选择 (N 选一) | `ask_user` 工具带 `options` |
+| 多选 ("任意选择") | `ask_user` 工具带 `multi_select=True` |
+| "其他" 可自由文本输入 | `ask_user` 工具选项带 `allow_input=True` |
+| 确认/编辑工具参数后才运行 | `ConfirmToolCallMiddleware` 或 `ApprovalPolicyMiddleware` |
+
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/overview.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/overview.md
new file mode 100644
index 0000000..5ceb0f6
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/overview.md
@@ -0,0 +1,80 @@
+---
+title: 概览
+sidebar_position: 1
+description: "CubePi 人机协同:channel、三种动词(confirm、approve、ask)与超时。"
+---
+
+# 人机协同 (HITL)
+
+CubePi 的 HITL channel 让 agent 能够**暂停并等待人类输入**后再继续。
+它用一个统一原语覆盖两种典型模式:
+
+1. **沙箱工具确认** —— 危险工具(bash、文件写入、API 变更)在运行前
+ 需要人类 approve / deny / edit。
+2. **运行中结构化提问** —— agent 需要用户做出选择或填写表单才能继续。
+
+Channel 是一个可 `await` 的协程协作者。工具作者写
+`await channel.ask(...)`,channel 处理暂停。宿主代码订阅挂起请求并回填
+答案。两种后端覆盖全场景:
+
+- `InMemoryChannel` —— CLI、notebook、测试。进程死亡,挂起丢失。
+- `CheckpointedChannel` —— web 服务。将挂起请求持久化到 `Checkpointer`,
+ 让不同进程(或重启后的同一进程)在数小时后拾起并回答。
+
+## 三种动词
+
+### `confirm(prompt, *, details, timeout, signal) → bool`
+
+简单的 yes/no 问题。宿主回答 `True` 或 `False`。
+
+### `approve(tool_name, tool_call_id, args, *, details, timeout, signal) → ApproveAnswer`
+
+沙箱确认动词。返回一个 `ApproveAnswer`,三种决策:
+
+| 决策 | 结果 |
+|---|---|
+| `"approve"` | 以原始参数运行工具 |
+| `"deny"` | 阻塞工具;`tool_result.is_error=True`,`details["hitl"]["decision"]="human_deny"` |
+| `"edit"` | 以编辑后的参数运行(会拿工具的 pydantic 参数模型重新校验) |
+
+对 `approve` 请求,信封的 `question_id` 设为 LLM 的 `tool_call_id` —
+没有独立的 UUID,所以宿主代码可以直接用它已经在工具流中追踪的同一个
+ID 来关联。
+
+### `ask(questions, *, timeout, signal) → dict[str, str | list[str]]`
+
+一个包含一个或多个 `Question` 对象的结构化表单。每个问题可以是:
+
+- **自由文本** (`options=None`)
+- **单选** (`options=[...]`, `multi_select=False`)
+- **多选** (`options=[...]`, `multi_select=True`)
+- **"其他" 可输入**(选项有 `allow_input=True` —— 用户输入自由文本)
+
+```python
+from cubepi.hitl.types import Question, Option
+
+answers = await channel.ask([
+ Question(key="framework", prompt="选择框架?", options=[
+ Option(label="React", value="react"),
+ Option(label="Vue", value="vue"),
+ Option(label="其他", value="other", allow_input=True),
+ ]),
+ Question(key="features", prompt="启用功能:", multi_select=True, options=[
+ Option(label="认证", value="auth"),
+ Option(label="支付", value="payments"),
+ ]),
+])
+# answers == {"framework": "react", "features": ["auth", "payments"]}
+```
+
+## 超时
+
+两个 channel 都在构造函数接受 `default_timeout`,每个动词接受一個
+per-call 的 `timeout` kwarg(per-call 覆盖默认)。
+
+超时到期从 agent 侧的 `await` 抛出 `HitlTimedOut(BaseException)`。
+周围的工具或中间件将其转换为 `tool_result.is_error=True`,
+`details["hitl"]["decision"]="timed_out"`,模型看到干净的拒绝结果
+并能自然反应。信封的 `HitlRequest.timeout_seconds` 会自动填写,
+前端可以渲染倒计时。
+
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/reference.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/reference.md
new file mode 100644
index 0000000..20858c7
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/hitl/reference.md
@@ -0,0 +1,95 @@
+---
+title: API、事件与参考
+sidebar_position: 4
+description: "CubePi HITL 参考:Agent API、事件、追踪 span、错误参考、测试辅助与架构说明。"
+---
+
+# API、事件与参考
+
+## Agent API
+
+| 属性/方法 | 签名 | 说明 |
+|---|---|---|
+| `agent.channel` | `HitlChannel \| None` | 绑定的 channel 或 `None` |
+| `agent.in_flight_hitl_request` | `HitlRequest \| None` | channel 当前 pending(同步属性) |
+| `load_pending_hitl_request()` | `async → HitlRequest \| None` | 从 checkpointer 读取 pending(detach 后也能用) |
+| `detach()` | `async → None` | 发射 `AgentSuspendedEvent` 然后触发 `HitlDetached` |
+| `respond(*, question_id=, answer=)` | `async → None` | 恢复挂起的运行 |
+| `abort_pending(reason=)` | `async → None` | 关闭对话(两阶段:发信号 + 追加合成拒绝) |
+
+## 事件
+
+四个新事件在 agent 事件流上发射:
+
+| 事件 | 何时发射 | 关键字段 |
+|---|---|---|
+| `HitlRequestEvent` | channel 收到新的 `confirm/approve/ask` | `request: HitlRequest` |
+| `HitlAnswerEvent` | `channel.answer()` 或 `channel.cancel()` 触发 | `question_id`, `answer`, `cancelled`, `timed_out` |
+| `AgentSuspendedEvent` | `agent.detach()` 被调用时 HITL pending | `pending_request: HitlRequest` |
+| `AgentAbortedEvent` | `agent.abort_pending()` 关闭对话 | `reason: str` |
+
+## 追踪 span
+
+安装 `cubepi[tracing]` extra 后,每次 HITL await 都会包装在一个
+OpenTelemetry span 中:
+
+| Span 名称 | 属性 |
+|---|---|
+| `hitl.approve` | `hitl.tool_name`, `hitl.tool_call_id`, `hitl.outcome`, `hitl.from_resume`, `hitl.duration_seconds` |
+| `hitl.confirm` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+| `hitl.ask` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+
+`hitl.outcome` 可以是:`approved`, `denied`, `edited`, `answered`,
+`cancelled`, `timed_out`, `aborted`, `detached`。
+
+追踪导入是懒式的 —— 未安装 `opentelemetry` 时,channel 静默回退到
+无操作 span。
+
+## 错误参考
+
+| 异常 | 基类 | 含义 |
+|---|---|---|
+| `HitlCancelled(reason)` | `BaseException` | 宿主调了 `channel.cancel(qid)` |
+| `HitlTimedOut(seconds)` | `BaseException` | per-call 或 channel 默认超时到期 |
+| `HitlDetached` | `BaseException` | HITL await 期间调了 `agent.detach()` |
+| `HitlAborted` | `BaseException` | `agent.abort_pending()` 向 agent 发信号 |
+| `HitlConcurrencyError` | `Exception` | channel 已有 pending 时再次调用 `confirm/approve/ask` |
+| `HitlStaleAnswer` | `Exception` | `channel.answer(qid)` 的 qid 与当前 pending 不匹配 |
+| `HitlNoPendingRequest` | `Exception` | 调了 `agent.respond(…)` 但线程没有 `pending_request` |
+| `HitlDurabilityNotGuaranteed` | `Exception` | 自定义工具调了 `CheckpointedChannel.ask()` 但没有 `allow_inside_custom_tool=True` |
+
+`HitlControlException`(四个 `BaseException` 子类的父类)**故意**不被
+`cubepi.agent.tools._prepare_tool_call` 和 `_execute_prepared` 中现有
+的广泛 `except Exception:` 处理器捕获 —— 这模仿了 `asyncio.CancelledError`
+的模式。
+
+
+## 测试辅助
+
+```python
+from cubepi.hitl.testing import ScriptedChannel, NoopChannel
+
+# ScriptedChannel:预编程答案,按顺序消费
+ch = ScriptedChannel(answers=[
+ ApproveAnswer(decision="approve"),
+ {"color": "red"}, # ask 答案
+])
+assert len(ch.history) == 2 # 所有见过的 HitlRequest
+
+# NoopChannel:自动批准一切。用于测试中的 subagent。
+ch = NoopChannel()
+assert (await ch.approve("bash", "tc", {})).decision == "approve"
+```
+
+## 架构说明
+
+- **每线程单一 pending。** Agent 循环是顺序的——每个 `thread_id` 最多
+ 有一个 HITL 请求。并发 `confirm/approve/ask` 会抛 `HitlConcurrencyError`。
+- **Prompt-cache 前缀不变量。** 暂停与恢复之间,消息列表仅通过在末尾
+ 追加 tool-result 消息和下一条 assistant turn 来改变。不插入、重排或
+ 修改先前的消息——否则会使 provider 端的 prompt cache 失效。
+- **`question_id == tool_call_id` 适用于 approve 请求。** 无需别名或
+ 映射——已从工具流中追踪 `call_id` 的宿主可直接传递。
+- **恢复不重放。** 恢复时将答案预加载到 channel 并重新进入循环。最后一条
+ assistant message 中未决的 tool call 决定了接下来执行什么。没有基于
+ 节点的重放语义。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/composition.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/composition.md
new file mode 100644
index 0000000..3a2df01
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/composition.md
@@ -0,0 +1,157 @@
+---
+title: 组合规则
+description: "了解 CubePi 如何通过 per-hook 规则组合多个中间件。"
+---
+
+# 组合规则
+
+当你传入多个中间件——`Agent(middleware=[m1, m2, m3])`——CubePi 按照
+**每个 hook 各自的规则**进行组合。正确的理解方式是:每个 hook 采用
+最适合其工作的组合规则,你不需要记忆 "before" 或 "after" 优先级猜测。
+
+## 规则速览
+
+| Hook | 规则 | 顺序重要吗? |
+|---|---|---|
+| `transform_context` | **链式**——每个看到上一个的输出 | 是 |
+| `convert_to_llm` | **最后一个胜出** | 只有一个运行 |
+| `transform_system_prompt` | **链式** | 是 |
+| `before_tool_call` | **第一个 block 停止**;非 block 累积 | block 胜出;`edited_args` 最后写入者胜出;`hitl_trace` 合并 |
+| `after_tool_call` | **后面覆盖前面** | 最后写入胜出 |
+| `should_stop_after_turn` | **任一 True 即停止**(OR) | 否 |
+| `after_model_response` | **带合并语义的链式** | 见下文 |
+
+## `transform_context` 和 `transform_system_prompt`
+
+链式:`m1` 的输出成为 `m2` 的输入,`m2` 的输出成为 `m3` 的输入。适用于分层转换:
+
+```python
+agent = Agent(
+ middleware=[
+ SlidingWindow(max_messages=20), # m1: 丢弃最旧的
+ InjectSummary(), # m2: 前置摘要块
+ ],
+)
+```
+
+`m2` 看到的是截断后的列表。用户可见的 `agent.state.messages` 不受影响——
+中间件只改变模型接收到的内容。
+
+## `convert_to_llm`
+
+有意采用最后胜出:这是发送前的最终转换。多个所有者会打架;只选一个。
+CubePi 强制**列表中的最后一个**实现了 `convert_to_llm` 的中间件运行。
+
+如果你发现自己需要两个 `convert_to_llm` 中间件,将它们合并为一个
+(调用点组合:写一个调用两者的中间件)。
+
+## `before_tool_call`
+
+第一个 `block=True` 短路其余中间件。**非 block 返回累积:**
+`edited_args` 向下游传播(每个中间件看到的是前一个编辑后的形式),
+`hitl_trace` 跨链合并(当被覆盖时,旧键在 `_chain` 下归档)。
+
+用于按从最严格到最宽松的顺序链式组合策略层:
+
+```python
+agent = Agent(
+ middleware=[
+ RateLimiter(), # 配额不足时阻止
+ SafetyFilter(), # 参数危险时阻止;可能编辑
+ AuditLogger(), # 永不阻止;记录用于可观测性
+ ],
+)
+```
+
+如果 `RateLimiter` 返回 `block=True`,`SafetyFilter` 和 `AuditLogger`
+的 `before_tool_call` 不会运行。如果 `SafetyFilter` 返回
+`edited_args={"cmd": "rm /tmp/foo"}`,工具将使用编辑后的参数运行,
+`AuditLogger` 通过重建的 `ctx.args` 看到它们。
+`AuditLogger.after_tool_call` 仍然触发,因为那是另一个 hook。
+
+## `after_tool_call`
+
+每个中间件可以返回一个设置了部分字段的 `AfterToolCallResult`;
+CubePi 合并它们,后面的结果在非 `None` 字段上覆盖前面的。完整结果:
+
+```python
+class AfterToolCallResult(BaseModel):
+ content: list[Content] | None = None
+ details: Any = None
+ is_error: bool | None = None
+ terminate: bool | None = None
+```
+
+模式:早期中间件添加丰富的 `details`,后期中间件为模型净化 `content`。
+两者都运行;合并后的结果组合了一个的 `details` 和另一个的脱敏 `content`。
+
+## `should_stop_after_turn`
+
+任一中间件返回 `True` 即结束运行。链中其余中间件不会被执行。
+
+```python
+agent = Agent(
+ middleware=[
+ MaxTurns(10),
+ BudgetCap(usd=0.5),
+ FinalAnswerSentinel(), # 当 assistant 说 "FINAL ANSWER" 时停止
+ ],
+)
+```
+
+## `after_model_response`
+
+带结构化合并的链式。每个中间件看到**当前的 response**(可能已被前面的
+中间件替换),并返回一个 `TurnAction`:
+
+- `response: AssistantMessage | None` —— 若非 None,则替换当前的 response
+ 供下游中间件和循环最终持久化使用。
+- `inject_messages: list[Message]` —— 跨整个链追加到单个列表中,
+ 然后在下一轮之前添加到上下文中。
+- `decision: "natural" | "stop" | "loop_to_model"` —— **最后一个中间件的值胜出**。
+
+```python
+agent = Agent(
+ middleware=[
+ ProfanityRedactor(), # 重写 response
+ StructuredOutputValidator(), # 可能返回 decision="loop_to_model"
+ EventLogger(), # 不改变 decision
+ ],
+)
+```
+
+如果 `StructuredOutputValidator` 返回 `decision="loop_to_model"` 而
+`EventLogger` 返回 `decision="natural"`,循环看到的是 `"natural"`——
+因为最后胜出。如果这不是你想要的,请重新排序。
+
+## 混合中间件与构造函数可调用对象
+
+`Agent(...)` 也接受显式的 hook 可调用对象(`convert_to_llm=…`、
+`before_tool_call=…` 等)。当两者都存在时,**显式可调用对象胜出**:
+
+```python
+agent = Agent(
+ middleware=[LoggingMiddleware()],
+ before_tool_call=my_explicit_hook, # 覆盖中间件版本
+)
+```
+
+一次性 hook 使用显式形式;当行为是一个连贯的包时使用中间件类。
+
+## 关于 `Middleware` 基类的说明
+
+基类 `Middleware` 中未实现的方法会抛出 `NotImplementedError`。
+`compose_middleware` 通过对比基方法检测到这一点,并**只连接**中间件
+实际覆盖的 hook。
+
+```python
+class JustTransform(Middleware):
+ async def transform_context(self, messages, *, signal=None):
+ return messages[-10:]
+ # 没有其他 hook。CubePi 不会调用它们。
+```
+
+## 另请参阅
+
+- [7 个 Hook](./hooks) —— 每个 hook 的作用及触发时机。
+- [示例](./examples) —— 组合在实践中的应用。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/examples.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/examples.md
new file mode 100644
index 0000000..89a9de2
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/examples.md
@@ -0,0 +1,284 @@
+---
+title: 示例
+description: "CubePi 中间件实用示例:速率限制、重试、结构化日志、上下文截断和 HITL。"
+---
+
+# 中间件示例
+
+针对四种最常见需求的实用中间件:速率限制、重试、结构化日志和上下文截断。
+
+## 速率限制 {#rate-limiting}
+
+当用户超过配额时阻止工具调用。将 `before_tool_call` 与外部速率限制器
+(令牌桶、Redis INCR……)结合。
+
+```python
+import time
+from cubepi import Middleware
+from cubepi.agent.types import BeforeToolCallResult
+
+
+class RateLimitMiddleware(Middleware):
+ def __init__(self, max_calls_per_min: int) -> None:
+ self.max = max_calls_per_min
+ self._timestamps: list[float] = []
+
+ async def before_tool_call(self, ctx, *, signal=None):
+ now = time.monotonic()
+ # 丢弃超过 60 秒的记录。
+ self._timestamps = [t for t in self._timestamps if now - t < 60]
+ if len(self._timestamps) >= self.max:
+ return BeforeToolCallResult(
+ block=True,
+ reason=f"Rate limit: {self.max} tool calls/min exceeded. Try again shortly.",
+ )
+ self._timestamps.append(now)
+ return None
+```
+
+使用:
+
+```python
+agent = Agent(provider=…, model=…, middleware=[RateLimitMiddleware(max_calls_per_min=30)])
+```
+
+当达到限制时,模型会看到一个工具结果说"Rate limit exceeded…"并通常会等待或询问用户。
+
+## 带退避的重试 {#retries-with-backoff}
+
+在 `after_tool_call` 中重试失败的工具调用。最多 N 次,指数退避,
+仅针对临时错误。
+
+```python
+import asyncio
+from cubepi import Middleware
+from cubepi.agent.types import AfterToolCallResult
+
+
+class RetryMiddleware(Middleware):
+ def __init__(self, max_retries: int = 3, base_delay: float = 0.5) -> None:
+ self.max_retries = max_retries
+ self.base_delay = base_delay
+
+ async def after_tool_call(self, ctx, *, signal=None):
+ if not ctx.is_error:
+ return None
+
+ # 按名称查找工具并重新执行,最多 max_retries 次。
+ tool = next(
+ (t for t in (ctx.context.tools or []) if t.name == ctx.tool_call.name),
+ None,
+ )
+ if tool is None:
+ return None
+
+ for attempt in range(1, self.max_retries + 1):
+ await asyncio.sleep(self.base_delay * (2 ** (attempt - 1)))
+ try:
+ new_result = await tool.execute(
+ ctx.tool_call.id,
+ ctx.args,
+ signal=signal,
+ on_update=None,
+ )
+ return AfterToolCallResult(
+ content=new_result.content,
+ details={"retried": attempt, "original_error": ctx.result.content},
+ is_error=False,
+ )
+ except Exception:
+ continue
+
+ return None # 放弃——保留原始错误
+```
+
+谨慎组合:重试非幂等工具(写入、发送、删除)可能造成实际损害。
+将这类工具标记为 `execution_mode="sequential"` 并基于 `ctx.tool_call.name` 跳过。
+
+## 结构化日志 {#structured-logging}
+
+记录每一次工具调用及其参数、时长和结果。将 `before_tool_call`(记录开始时间)
+与 `after_tool_call`(记录结果)配对。将开始时间存储在 `ctx.context.extra` 中。
+
+```python
+import time, logging
+from cubepi import Middleware
+
+log = logging.getLogger("cubepi.tools")
+
+
+class ToolLoggingMiddleware(Middleware):
+ async def before_tool_call(self, ctx, *, signal=None):
+ ctx.context.extra.setdefault("_tool_starts", {})[ctx.tool_call.id] = time.monotonic()
+ return None
+
+ async def after_tool_call(self, ctx, *, signal=None):
+ started = ctx.context.extra.get("_tool_starts", {}).pop(ctx.tool_call.id, None)
+ duration_ms = int((time.monotonic() - started) * 1000) if started else None
+ log.info(
+ "tool_call",
+ extra={
+ "tool_name": ctx.tool_call.name,
+ "args": ctx.args.model_dump() if hasattr(ctx.args, "model_dump") else ctx.args,
+ "is_error": ctx.is_error,
+ "duration_ms": duration_ms,
+ },
+ )
+ return None
+```
+
+`ctx.context.extra` 是存储每次运行状态的最佳位置,因为:
+
+- 其他中间件可通过同一个 `ctx.context` 看到。
+- Checkpointer 在 `agent_end` 时通过 `save_extra` 持久化。
+- 新对话开始时(新的 `thread_id`)会自动重置。
+
+## 滑动窗口截断 {#sliding-window-truncation}
+
+通过仅保留最近的 N 条消息(加上 system prompt)来保持模型上下文边界:
+
+```python
+from cubepi import Middleware
+
+
+class SlidingWindow(Middleware):
+ def __init__(self, max_messages: int = 20) -> None:
+ self.max_messages = max_messages
+
+ async def transform_context(self, messages, *, signal=None):
+ if len(messages) <= self.max_messages:
+ return messages
+ return messages[-self.max_messages:]
+```
+
+`transform_context` 不接触 `agent.state.messages`——用户仍然看到完整历史。
+模型只看到最后 N 条。
+
+与注入被丢弃内容摘要的 `transform_system_prompt` 配合效果很好:
+
+```python
+class SummaryInjector(Middleware):
+ async def transform_system_prompt(self, system_prompt, *, signal=None):
+ summary = "Earlier in this conversation we discussed: …"
+ return f"{system_prompt}\n\nContext: {summary}".strip()
+```
+
+## 最大轮次 / 预算上限
+
+在达到最大轮次数或成本上限时硬停止 agent:
+
+```python
+class MaxTurns(Middleware):
+ def __init__(self, max_turns: int) -> None:
+ self.max_turns = max_turns
+ self.turns = 0
+
+ async def should_stop_after_turn(self, ctx):
+ self.turns += 1
+ return self.turns >= self.max_turns
+
+
+class BudgetCap(Middleware):
+ def __init__(self, usd: float, model_cost) -> None:
+ self.cap = usd
+ self.cost = model_cost # cubepi.providers.ModelCost 或类似
+ self.spent = 0.0
+
+ async def should_stop_after_turn(self, ctx):
+ m = ctx.message
+ if m.usage:
+ self.spent += (
+ (m.usage.input_tokens / 1_000_000) * self.cost.input
+ + (m.usage.output_tokens / 1_000_000) * self.cost.output
+ )
+ return self.spent >= self.cap
+```
+
+## 用 `after_model_response` 实现结构化输出
+
+验证 JSON 输出,如果解析失败则重新提示:
+
+```python
+import json
+from cubepi import Middleware
+from cubepi.middleware.base import TurnAction
+from cubepi.providers.base import TextContent, UserMessage
+
+
+class JSONOutputValidator(Middleware):
+ def __init__(self, schema_cls) -> None:
+ self.schema = schema_cls
+
+ async def after_model_response(self, response, ctx, *, signal=None):
+ text = "".join(
+ c.text for c in response.content if isinstance(c, TextContent)
+ )
+ try:
+ obj = json.loads(text)
+ self.schema.model_validate(obj)
+ return None # 有效——正常进行
+ except Exception as e:
+ return TurnAction(
+ inject_messages=[
+ UserMessage(content=[TextContent(text=f"Invalid output: {e}. Return valid JSON.")]),
+ ],
+ decision="loop_to_model",
+ )
+```
+
+Agent 将跳过工具执行,并立即用上下文中的反馈消息重新提示模型。
+
+## 人机协同工具确认
+
+CubePi 在 `cubepi.hitl` 中内置了两个 HITL 中间件:
+
+**`ConfirmToolCallMiddleware`** —— "对此工具始终询问人类":
+
+```python
+from cubepi.hitl import ConfirmToolCallMiddleware, InMemoryChannel
+
+channel = InMemoryChannel()
+agent = Agent(
+ provider=…, model=…,
+ middleware=[
+ ConfirmToolCallMiddleware(
+ channel,
+ require_confirm={"bash", "write_file"},
+ ),
+ ],
+)
+```
+
+Agent 在每次 `bash` 或 `write_file` 调用时暂停,等待宿主调用
+`channel.answer(qid, ApproveAnswer(decision="approve"))`。结果驱动工具:
+`approve` 执行,`deny` 带原因阻止,`edit` 重新校验并运行编辑后的参数。
+
+**`ApprovalPolicyMiddleware`** —— 适用于通过策略引擎对工具调用进行分类的宿主:
+
+```python
+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
+
+def my_policy(ctx):
+ if ctx.tool_call.name in ("read_file", "grep"):
+ return Approve()
+ if ctx.tool_call.name.startswith("dangerous_"):
+ return Deny(reason="blocked")
+ return AskUser(timeout_seconds=180)
+
+agent = Agent(
+ provider=…, model=…,
+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
+)
+```
+
+`Deny` 完全跳过 channel(硬阻止)。`AskUser` 触发 channel 的 approve 流程。
+`Approve` 立即返回。
+
+完整细节——超时语义、编辑语义、事件、追踪 span、跨进程挂起/恢复——
+请参见 [HITL 指南](../hitl/overview)。
+
+## 另请参阅
+
+- [7 个 Hook](./hooks) —— 每个 hook 的精确语义。
+- [组合规则](./composition) —— 多个中间件如何组合。
+- [配方](../../recipes/weather-agent) —— 中间件在真实应用中的组合。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/hooks.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/hooks.md
new file mode 100644
index 0000000..764dbfd
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/middleware/hooks.md
@@ -0,0 +1,190 @@
+---
+title: 7 个 Hook
+description: "CubePi 的 7 个中间件 hook 参考——transform_context、before_tool_call、after_tool_call 等。"
+---
+
+# 7 个 Hook
+
+`Middleware` 是一个最多包含七个可选异步方法的类。每个 hook 在 agent
+循环中的精确位置触发。只实现你需要的——CubePi 只会连接你重写了的方法。
+
+```python
+from cubepi import Middleware
+
+class MyMiddleware(Middleware):
+ async def transform_context(self, messages, *, signal=None):
+ ...
+```
+
+将实例传入 `Agent(middleware=[MyMiddleware(), …])`。
+
+## `transform_context`
+
+```python
+async def transform_context(self, messages: list[Message], *, signal=None) -> list[Message]:
+ ...
+```
+
+**每次调用模型之前**触发,作用于完整的消息列表。用于:
+
+- 截断或总结以适配上下文窗口。
+- 注入系统提醒(更好用 `transform_system_prompt`)。
+- 动态添加或删除特定消息。
+
+返回(可能是新的)列表。**不要修改输入**——返回一个新列表以免其他持有原引用的代码感到意外。
+
+组合方式:链式——每个中间件看到上一个的输出。
+
+## `convert_to_llm`
+
+```python
+async def convert_to_llm(self, messages: list[Message]) -> list[Message]:
+ ...
+```
+
+**在序列化给 provider 之前**触发。这是调整 LLM 看到的最终内容的最后机会。用于:
+
+- 将工具结果精简为纯文本。
+- 为非多模态 provider 将图片内容替换为文字描述。
+- 压缩较长的工具输出。
+
+组合方式:**最后一个实现胜出**(非链式)。当多个中间件可能冲突而你希望只有一个所有者时使用。
+
+## `transform_system_prompt`
+
+```python
+async def transform_system_prompt(self, system_prompt: str, *, signal=None) -> str:
+ ...
+```
+
+**每次调用模型之前**触发,作用于 system prompt 字符串。用于:
+
+- 注入运行时信息(当前时间、用户角色)。
+- 组合模块化的 system prompt 片段。
+- A/B 测试 prompt 变体。
+
+组合方式:链式。
+
+## `before_tool_call`
+
+```python
+async def before_tool_call(self, ctx: BeforeToolCallContext, *, signal=None) -> BeforeToolCallResult | None:
+ ...
+```
+
+**每个工具调用时**触发,在参数校验之后、`tool.execute` 之前。
+context 提供:
+
+- `ctx.assistant_message` —— 发起调用的消息。
+- `ctx.tool_call` —— `ToolCall` 块。
+- `ctx.args` —— *校验后的* Pydantic 实例。
+- `ctx.context` —— 完整的 `AgentContext`。
+
+返回 `BeforeToolCallResult(block=True, reason="…")` 以短路——
+CubePi 会将该原因作为工具结果返回,并标记 `is_error=True`。
+返回 `None`(或无返回)则继续执行。
+
+用于:权限控制、速率限制、dry-run 模式、沙箱、
+人机协同确认(参见 [HITL 指南](../hitl/overview))。
+
+组合方式:**第一个 `block=True` 短路**整个链。
+
+## `after_tool_call`
+
+```python
+async def after_tool_call(self, ctx: AfterToolCallContext, *, signal=None) -> AfterToolCallResult | None:
+ ...
+```
+
+**每个工具调用时**触发,在 `tool.execute` 返回(或抛出异常)之后。
+context 额外提供:
+
+- `ctx.result` —— execute 返回的 `AgentToolResult`。
+- `ctx.is_error` —— 工具是否出错。
+
+返回 `AfterToolCallResult(content=…, details=…, is_error=…, terminate=…)`
+以覆盖结果的单个字段(任何 `None` 字段保持原值)。返回 `None` 则原样通过。
+
+用于:编辑、重试、日志记录、结果转换。
+
+组合方式:后面的覆盖前面的(返回值中的每个非 `None` 字段覆盖前一个值)。
+
+## `should_stop_after_turn`
+
+```python
+async def should_stop_after_turn(self, ctx: ShouldStopAfterTurnContext) -> bool:
+ ...
+```
+
+**在每个轮次边界**触发(任何工具批次之后)。返回 `True` 以结束本次运行,
+不进行下一次模型调用。
+
+用于:最大轮次限制、预算上限、应用定义的停止条件。
+
+组合方式:**任意一个返回 `True` 即停止**(逻辑 OR 跨链)。
+
+## `after_model_response`
+
+```python
+async def after_model_response(
+ self,
+ response: AssistantMessage,
+ ctx: AgentContext,
+ *,
+ signal=None,
+) -> TurnAction | None:
+ ...
+```
+
+**在 assistant 消息落定后立即**触发,在 `message_end` 发出**之前**、
+在任何工具调用分发**之前**。该 hook 返回一个 `TurnAction`:
+
+```python
+from cubepi.middleware.base import TurnAction
+from cubepi.providers.base import UserMessage, TextContent
+
+TurnAction(
+ response=modified_message, # 替换消息;None 则保留原消息
+ inject_messages=[UserMessage(...)], # 在下一轮之前追加的额外消息
+ decision="natural", # "natural" | "stop" | "loop_to_model"
+)
+```
+
+三个控制流旋钮:
+
+- `decision="natural"`(默认)—— 正常进入工具执行 / 下一轮。
+- `decision="stop"` —— 在发出 `turn_end` 和 `agent_end` 后结束运行。
+ 不执行工具,不再调用模型。
+- `decision="loop_to_model"` —— 跳过工具执行,立即重新调用模型(配合
+ `inject_messages` 使用以先添加上下文)。
+
+用于:响应审核、带重新提示的结构化输出验证、条件路由。
+
+组合方式:链式——每个中间件看到前一个中间件的 `response`;
+`inject_messages` 跨链拼接;最后一个中间件的 `decision` 胜出。
+
+## 中间件的构成
+
+一个中间件不需要实现每一个 hook。只覆盖你需要的即可;基类中未实现
+的 hook 会抛出 `NotImplementedError`,但 `compose_middleware` 会自动跳过它们。
+
+```python
+from cubepi import Middleware
+
+class MaxTurnsMiddleware(Middleware):
+ def __init__(self, max_turns: int) -> None:
+ self.max_turns = max_turns
+ self.turns = 0
+
+ async def should_stop_after_turn(self, ctx) -> bool:
+ self.turns += 1
+ return self.turns >= self.max_turns
+
+
+agent = Agent(provider=…, model=…, middleware=[MaxTurnsMiddleware(5)])
+```
+
+## 另请参阅
+
+- [组合规则](./composition) —— 多个中间件定义同一 hook 时的精确语义。
+- [示例](./examples) —— 速率限制、日志、重试、滑动窗口上下文的实用中间件。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/providers/anthropic.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/providers/anthropic.md
new file mode 100644
index 0000000..82f13ed
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/guides/providers/anthropic.md
@@ -0,0 +1,160 @@
+---
+title: Anthropic
+description: "通过 AnthropicProvider 在 CubePi 中使用 Claude 模型——支持思考、缓存和工具调用。"
+---
+
+# Anthropic Provider
+
+`AnthropicProvider` 封装了官方 `anthropic` SDK 的 Messages API。
+支持流式、扩展思考、prompt caching 和工具调用。
+
+## 构造
+
+```python
+from cubepi.providers.anthropic import AnthropicProvider
+
+provider = AnthropicProvider(
+ api_key="sk-ant-…", # 也可让 SDK 自己读 ANTHROPIC_API_KEY
+ base_url=None, # 指向代理 / Bedrock 兼容端点
+ cache_retention="short", # "short"(5 分钟,默认) | "long"(1 小时) | "none"
+)
+```
+
+`api_key=None` 时 SDK 会从环境变量读取。
+
+## `Model`
+
+```python
+from cubepi import Model
+
+model = Model(
+ id="claude-sonnet-4-5-20250929",
+ provider="anthropic",
+ reasoning=True, # 启用思考等级(见下)
+ max_tokens=8192, # 回复 token 上限
+ context_window=200_000, # 模型硬上限
+ temperature=0.7,
+)
+```
+
+`id` 就是你传给 SDK 的模型名。`provider` 字符串是 CubePi 内部用的
+自由标签 —— 保持稳定即可,不必精确匹配 `"anthropic"`。
+
+## 扩展思考
+
+CubePi 把 `ThinkingLevel` 枚举映射到 Anthropic 的 `budget_tokens`:
+
+| Level | 默认 budget |
+|---|---|
+| `"off"` | 关闭思考 |
+| `"minimal"` | 1024 |
+| `"low"` | 2048 |
+| `"medium"` | 8192 |
+| `"high"` | 16384 |
+| `"xhigh"` | clamp 到 `"high"` |
+
+在 Agent 上设置:
+
+```python
+agent = Agent(provider=provider, model=model, thinking="medium")
+```
+
+要自定义 budget,可以通过自己的 `on_payload` hook 传入
+`StreamOptions(thinking_budgets=ThinkingBudgets(low=4096, medium=12288))`。
+
+思考打开时,CubePi **会把 `temperature` 字段省掉** —— 因为 Anthropic
+API 在扩展思考模式下不接受非默认的 temperature([兼容性文档](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#feature-compatibility))。
+关闭思考时再按 `Model.temperature` 走;CubePi 自己处理切换。
+
+思考内容以 `thinking_start` / `thinking_delta` / `thinking_end` 事件
+流式产出,最终作为 `ThinkingContent` 块保存在 `AssistantMessage.content`
+里 —— 后续轮次也会带着,以保证模型的思路连贯性。
+
+## Prompt caching
+
+默认情况下,provider 在每个请求上插入三个缓存断点:
+
+- **system prompt**(最稳定)。
+- **最后一个工具定义**(变化少)。
+- **最后一条消息**(每轮往前推,把之前的历史全部缓存)。
+
+缓存保留期默认 `"short"`(5 分钟,免费)。如果你的回合间隔较长,
+切到 `"long"`:
+
+```python
+AnthropicProvider(api_key=…, cache_retention="long") # 1 小时 TTL
+AnthropicProvider(api_key=…, cache_retention="none") # 完全禁用
+```
+
+每个 `AssistantMessage` 上的 `Usage` 对象会报告 `cache_read_tokens`
+和 `cache_write_tokens`,方便你看命中率。
+
+需要自定义缓存策略(比如换个断点策略)?实现 `CacheMarkerPolicy`
+Protocol 然后 `cache_policy=…` 传入。默认策略类位于
+`cubepi.providers.anthropic.DefaultCacheMarkerPolicy`。
+
+## 用 `on_payload` 自定义请求
+
+`on_payload` 让你在请求发出前查看 / 替换 request dict:
+
+```python
+async def my_payload(payload, model):
+ payload.setdefault("metadata", {})["user_id"] = "u-42"
+ return payload # 返回 None 或不返回保留原 payload
+
+agent = Agent(provider=provider, model=model, on_payload=my_payload)
+```
+
+典型用法:加 `metadata.user_id`(计费)、强制 beta header,或留一份
+调试面板用的 payload 副本。
+
+## 用 `on_response` 自定义响应处理
+
+`on_response` 在收到 HTTP 响应(状态、头)后、流式开始前触发:
+
+```python
+async def my_response(resp, model):
+ if resp.status >= 400:
+ logger.warning("bad status %s", resp.status)
+ rate = resp.headers.get("anthropic-ratelimit-requests-remaining")
+ if rate is not None:
+ metrics.gauge("rate_remaining", int(rate))
+
+agent = Agent(provider=provider, model=model, on_response=my_response)
+```
+
+两个回调都可以是同步或异步。
+
+## 指向 Bedrock / Vertex / 代理
+
+Anthropic SDK 接受 `base_url`,CubePi 透传:
+
+```python
+provider = AnthropicProvider(
+ api_key="…",
+ base_url="https://my-litellm.internal/v1",
+)
+```
+
+对于 Bedrock,使用 `anthropic-bedrock` 适配器、通过 [自定义 provider](./custom)
+注入。
+
+## 常见坑
+
+- **`temperature` 被忽略** —— 预期之内。思考打开时 CubePi 故意 drop
+ 掉,这是 API 约束,不是 bug。
+- **`xhigh` 和 `high` 看起来一样** —— Anthropic 没有更高一档的 budget,
+ 所以 CubePi 把 `xhigh` clamp 到 `high`,token budget 相同。
+- **缓存未命中** —— 缓存按 (内容, ttl) 索引。改 system prompt 会让
+ 整块失效;改工具列表则从工具往后失效。要最大化命中,保持这两个
+ 跨轮稳定。
+- **`anthropic.RateLimitError`** —— 会作为 stream error 事件传出,
+ 错误消息来自 SDK 的 `str(exc)`。在 `agent_end` 里捕获,决定是否
+ 重试。
+
+## 另请参阅
+
+- [OpenAI Provider](./openai) —— 同 Protocol,不同形态。
+- [自定义 Provider](./custom) —— 把不内建的 API 接进来。
+- [Recipes → 多 Provider 容错](../../recipes/multi-provider-failover)
+ —— Anthropic 故障时切到 OpenAI。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/intro.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/intro.mdx
new file mode 100644
index 0000000..4030407
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/intro.mdx
@@ -0,0 +1,72 @@
+---
+id: intro
+title: CubePi
+description: "一个 Pythonic、原生异步的 Agent 框架。普通的 async 函数、追加式 checkpointing、三个依赖。"
+slug: /
+sidebar_position: 0
+---
+
+import PackageVersion from '@site/src/components/PackageVersion';
+
+# CubePi
+
+**CubePi** 是一个 Pythonic、原生异步的 Agent 框架,为高性能、可读性和
+生产级持久化而设计。它把一次 Agent 运行建模为一个线性的 `while`
+循环——可追踪、可调试,没有 DAG、没有图 DSL、没有出人意料的控制流。
+整个核心循环你五分钟就能读完。
+
+```bash
+pip install cubepi
+```
+
+然后跳到 [快速开始](./getting-started/quick-start),五分钟内跑通一个
+能调用工具的 Agent。
+
+## 你能拿到什么
+
+- **普通 async 函数,不是图节点。** Agent 循环就是一个对消息轮次的
+ `while` 循环。你把工具写成 `async def` 函数,框架负责路由调用并并行
+ 执行。
+- **统一的流式模式。** 所有 provider 都通过 `MessageStream` 产出
+ `StreamEvent`。你用 `async for` 迭代它。没有 callback 注册表,也没有
+ 为文本和工具单独的 handler 类型。
+- **追加式检查点。** 每一轮只写入新消息,而不是整段对话历史。无论
+ 会话多长,数据库 I/O 都是 O(1)——SQLite 适合个人开发,Postgres 适合
+ 生产环境。
+- **原生多 provider。** Anthropic 和 OpenAI 开箱即用,通过 `Provider`
+ Protocol 接入。要新增一个 provider 只需要写一个类。
+- **五个 Hook 的中间件。** `transform_context`、`convert_to_llm`、
+ `before_tool_call`、`after_tool_call`、`should_stop_after_turn`——
+ 每一个都有明确的组合规则。没有"节点执行顺序之谜"。
+- **MCP 加载器。** 指向任意
+ [Model Context Protocol](https://modelcontextprotocol.io) 服务器
+ (HTTP 或 stdio),就能拿回一组 `AgentTool`。
+- **原生 OpenTelemetry。** 挂一个 `Tracer`,每次 prompt 就产生符合
+ GenAI 语义约定的 OTel span 树 —— Jaeger、Tempo、Honeycomb、
+ Datadog 等任意 OTLP 后端都能直接接收。默认不记录任何 payload;
+ 需要时用 `record_content=True` 配合 `redact` 回调显式开启。
+
+## 接下来去哪儿
+
+| 如果你想… | 从这里开始 |
+|---|---|
+| 安装并跑通第一个 Agent | [入门 → 安装](./getting-started/installation) |
+| 理解骨架 | [入门 → 核心概念](./getting-started/core-concepts) |
+| 接入一个真实的工具 Agent | [指南 → 构建第一个 Agent](./guides/agents/first-agent) |
+| 跨重启保留对话 | [指南 → SQLite 检查点](./guides/checkpointing/sqlite) |
+| 查找某个具体符号 | [API 参考](./api/) |
+| 看完整的可运行示例 | [Recipes](./recipes/weather-agent) |
+| 从 langgraph Agent 迁移 | [迁移 → 来自 langgraph](./migration/from-langgraph) |
+
+## 状态
+
+你正在浏览的是 **Next 🚧** 频道 —— 跟踪 `main` 分支的未发布文档。
+这里描述的 API 在打 tag 发布之前还可能变动。
+
+最新已发布版本是 `v<PackageVersion/>`([从右上角版本选择器切换](pathname:///))。
+原生 OpenTelemetry 追踪模块([指南 →](./guides/tracing/overview))——
+`Tracer`、`Meter`、内容录制、MCP CLIENT span、按 run 打标签的
+`tracing_context` —— 已在 0.4 发布。
+
+源代码、Issue 和讨论都在
+[GitHub](https://github.com/cubeplexai/cubepi)。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/recipes/ask-user-form.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/recipes/ask-user-form.md
new file mode 100644
index 0000000..3afeb77
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/recipes/ask-user-form.md
@@ -0,0 +1,184 @@
+---
+title: 通过 ask_user 实现多问题表单
+description: "使用 CubePi 的 ask_user HITL 工具构建多问题表单以收集结构化用户输入。"
+---
+
+# 配方:通过 `ask_user` 实现多问题表单
+
+适用场景:agent 在继续之前需要用户的**结构化答案** —— 配置向导、
+偏好选择器、功能开关。
+
+## 步骤 1:注册工具
+
+```python
+from cubepi.agent.agent import Agent
+from cubepi.hitl import InMemoryChannel, ask_user_tool
+
+channel = InMemoryChannel()
+
+agent = Agent(
+ provider=...,
+ model=...,
+ system_prompt=(
+ "当您需要用户在选项中选择时,请使用 ask_user 工具。"
+ "对于自由形式的澄清问题,直接用文本结束当前轮次——"
+ "用户的下一条消息就是答案。"
+ ),
+ tools=[ask_user_tool(channel)],
+ channel=channel,
+)
+```
+
+`ask_user` 工具像其他工具一样注册。它的
+`execution_mode="sequential"` 使工具批次逐一执行——
+HITL 暂停不能与并行工具执行重叠。
+
+## 步骤 2:宿主渲染表单
+
+模型调用 `ask_user` 并传入一个问题对象列表。宿主在 channel 上收到
+一个 `AskRequest` payload:
+
+```python
+async def host():
+ async for req in channel.subscribe():
+ if req.payload.kind == "ask":
+ answers = {}
+ for q in req.payload.questions:
+ if q.options is None:
+ # 自由文本问题
+ answers[q.key] = await my_ui.text_input(q.prompt)
+ elif q.multi_select:
+ answers[q.key] = await my_ui.checkbox_group(
+ q.prompt, [(o.label, o.value) for o in q.options],
+ )
+ else:
+ answers[q.key] = await my_ui.radio_group(
+ q.prompt,
+ [(o.label, o.value) for o in q.options],
+ allow_input_indexes=[
+ i for i, o in enumerate(q.options) if o.allow_input
+ ],
+ )
+ await channel.answer(req.question_id, answers)
+```
+
+## 模型看到的工具参数
+
+模型可以传入混合了自由文本、单选和多选字段的问题:
+
+```json
+{
+ "questions": [
+ {
+ "key": "project_type",
+ "prompt": "什么类型的项目?",
+ "options": [
+ {"label": "Web 应用", "value": "web"},
+ {"label": "CLI 工具", "value": "cli"},
+ {"label": "库", "value": "lib"}
+ ]
+ },
+ {
+ "key": "framework",
+ "prompt": "哪个框架?",
+ "options": [
+ {"label": "React", "value": "react"},
+ {"label": "Vue", "value": "vue"},
+ {"label": "其他", "value": "other", "allow_input": true}
+ ]
+ },
+ {
+ "key": "features",
+ "prompt": "你需要哪些功能?",
+ "multi_select": true,
+ "options": [
+ {"label": "认证", "value": "auth"},
+ {"label": "支付", "value": "payments"},
+ {"label": "文件上传", "value": "uploads"}
+ ]
+ },
+ {
+ "key": "project_name",
+ "prompt": "这个项目叫什么名字?"
+ }
+ ]
+}
+```
+
+## 答案结构
+
+宿主用一个 `key → value` 的 dict 回答:
+
+```python
+# 上述表单的答案示例:
+{
+ "project_type": "web",
+ "framework": "svelte", # 用户选择了"其他"并输入了"svelte"
+ "features": ["auth", "uploads"],
+ "project_name": "my-saas"
+}
+```
+
+答案被填入工具结果的 `details["hitl"]["answers"]`。
+模型可以通过文本内容看到人类可读的摘要,也可以通过 dict 进行结构化消费。
+
+## 取消与超时
+
+如果宿主通过 `channel.cancel(qid, reason)` 取消:
+
+```python
+await channel.cancel(req.question_id, reason="user closed the form")
+```
+
+工具会向模型显示一个错误结果:
+
+```
+tool_result.is_error = True
+tool_result.details["hitl"]["outcome"] = "cancelled"
+tool_result.details["hitl"]["reason"] = "user closed the form"
+```
+
+如果超时到期:
+
+```
+tool_result.details["hitl"]["outcome"] = "timed_out"
+tool_result.details["hitl"]["seconds"] = 30.0
+```
+
+两种情况下模型都会看到干净的错误结果,并能做出相应反应——
+再次提问、回退到默认值或向用户报告。
+
+## 进程内示例(完整可运行代码段)
+
+```python
+import asyncio
+from cubepi.agent.agent import Agent
+from cubepi.hitl import InMemoryChannel, ask_user_tool
+
+channel = InMemoryChannel()
+
+agent = Agent(
+ provider=...,
+ model=...,
+ tools=[ask_user_tool(channel)],
+ channel=channel,
+)
+
+async def host():
+ async for req in channel.subscribe():
+ if req.payload.kind == "ask":
+ answers = {
+ q.key: q.options[0].value if q.options else ""
+ for q in req.payload.questions
+ }
+ await channel.answer(req.question_id, answers)
+
+async def main():
+ host_task = asyncio.create_task(host())
+ try:
+ await agent.prompt("Scaffold a new project.")
+ finally:
+ host_task.cancel()
+
+asyncio.run(main())
+```
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/recipes/sandbox-confirm.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/recipes/sandbox-confirm.md
new file mode 100644
index 0000000..a36fbbf
--- /dev/null
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.6/recipes/sandbox-confirm.md
@@ -0,0 +1,138 @@
+---
+title: 使用 ApprovalPolicyMiddleware 做沙箱确认
+description: "使用 CubePi 的 ApprovalPolicyMiddleware 实现沙箱工具确认——自动放行、拒绝或人工确认。"
+---
+
+# 配方:使用 `ApprovalPolicyMiddleware` 做沙箱确认
+
+适用场景:一个 web 服务中每个工具调用都经过规则引擎,被分类为自动放行、
+硬阻止或人类确认。
+
+## 步骤 1:定义策略函数
+
+策略接收一个 `BeforeToolCallContext` 并返回一个 `ApprovalDecision` ——
+`Approve()`、`Deny(reason)` 或 `AskUser(...)`。
+
+```python
+from cubepi.hitl import Approve, AskUser, Deny
+
+# 模拟规则引擎 —— 替换为你实际的策略目录。
+def classify_command(cmd: str) -> tuple[str, str | None]:
+ """(tier, reason) — "allow", "block", 或 "confirm"."""
+ if cmd.startswith(("ls", "cat", "head", "grep", "find")):
+ return ("allow", None)
+ if "rm -rf /" in cmd or cmd.startswith("dd"):
+ return ("block", "destructive I/O")
+ return ("confirm", "needs human review")
+
+
+def sandbox_policy(ctx):
+ cmd = ctx.args.cmd # ctx.args 是校验后的 pydantic 模型
+ tier, reason = classify_command(cmd)
+
+ if tier == "allow":
+ return Approve()
+ if tier == "block":
+ return Deny(reason=reason or "blocked by policy")
+ return AskUser(
+ timeout_seconds=180,
+ details={"matched_rule": tier, "impact": reason or "unknown"},
+ )
+```
+
+`ctx.args` 是**校验后的 pydantic 模型**。通过属性访问字段
+(`ctx.args.cmd`)。中间件内部会将其转为 dict 用于 channel 的 approve payload,
+但你的策略收到的仍然是类型化的模型。
+
+## 步骤 2:接入 agent
+
+```python
+from cubepi.agent.agent import Agent
+from cubepi.checkpointer.postgres import PostgresCheckpointer
+from cubepi.hitl import ApprovalPolicyMiddleware, CheckpointedChannel
+
+async def main():
+ async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="session-1")
+
+ agent = Agent(
+ provider=anthropic,
+ model=Model(id="claude-sonnet-4-6", provider="anthropic"),
+ system_prompt="You are a helpful assistant with access to a bash shell.",
+ tools=[bash_tool],
+ middleware=[
+ ApprovalPolicyMiddleware(channel, policy=sandbox_policy),
+ ],
+ channel=channel,
+ checkpointer=cp,
+ thread_id="session-1",
+ )
+
+ await agent.prompt("list files then delete temp logs")
+ # Agent 运行中;当 bash 被调用时,sandbox_policy 决定:
+ # ls → Approve() → 立即执行
+ # rm /tmp/logs → AskUser() → channel 挂起,HitlRequestEvent 触发
+```
+
+## 步骤 3:宿主处理挂起的请求
+
+```python
+async def host_loop(channel: CheckpointedChannel):
+ async for req in channel.subscribe():
+ if req.payload.kind == "approve":
+ tool_name = req.payload.tool_name
+ command = req.payload.args.get("cmd", "")
+ details = req.payload.details or {}
+ timeout = req.timeout_seconds # 前端倒计时用的秒数
+
+ # 渲染给前端:tool_name、command、details["matched_rule"]、
+ # details["impact"]、以及基于 timeout 的倒计时。
+ human_answer = await my_frontend.show_confirm(
+ tool_name=tool_name,
+ command=command,
+ details=details,
+ timeout=timeout,
+ )
+ # 根据人类的决定构建 ApproveAnswer。
+ from cubepi.hitl import ApproveAnswer
+ human_answer = ApproveAnswer(
+ decision=ui_response["decision"], # "approve" | "deny" | "edit"
+ reason=ui_response.get("reason"), # 仅用于 deny
+ edited_args=ui_response.get("edited_args"), # 仅用于 edit
+ )
+ await channel.answer(req.question_id, human_answer)
+ elif req.payload.kind == "ask":
+ await channel.answer(req.question_id, await my_frontend.show_form(req))
+ else: # confirm
+ await channel.answer(req.question_id, await my_frontend.show_confirm(req))
+```
+
+## 决策语义
+
+| 人类选择 | 工具结果 | `hitl_trace["decision"]` | 模型看到 |
+|---|---|---|---|
+| 批准 | 使用原始参数执行 | 未设置(直通,无 HITL 细节) | 正常 `tool_result` |
+| 拒绝 | 被阻止 | `"human_deny"` | `tool_result.is_error=True` 及用户的原因 |
+| 编辑 | 使用编辑后的参数执行 | `"edit"` + `original_args` / `edited_args` | 正常 `tool_result`(来自编辑后的执行) |
+
+策略决策(不经询问人类直接硬阻止)携带
+`hitl_trace["decision"]="policy_deny"`。
+
+## 超时行为
+
+如果人类在 `timeout_seconds` 内未响应,中间件会转换为
+`BeforeToolCallResult(block=True, deny_reason="approval_timeout")`。
+模型看到 `tool_result.is_error=True`,其中
+`details.hitl.decision="timed_out"`,并自然产生一个解释超时的后续轮次。
+
+## 中止
+
+如果用户关闭标签页或管理员终止对话:
+
+```python
+await agent.abort_pending(reason="user closed tab")
+```
+
+这会干净地关闭对话:为所有未解决的 tool call 追加合成的 deny tool_result,
+持久化一个终止性的 `AssistantMessage(stop_reason="aborted")`,并触发
+`AgentAbortedEvent`。下一次 `agent.prompt(...)` 重新开始。
diff --git a/website/versioned_docs/version-0.6/api/index.mdx b/website/versioned_docs/version-0.6/api/index.mdx
new file mode 100644
index 0000000..0765f52
--- /dev/null
+++ b/website/versioned_docs/version-0.6/api/index.mdx
@@ -0,0 +1,18 @@
+---
+title: API Reference
+description: "Reference documentation for the CubePi Python API."
+---
+
+# API Reference
+
+Auto-generated from CubePi's public modules.
+
+- `cubepi.agent`
+- `cubepi.providers`
+- `cubepi.checkpointer`
+- `cubepi.middleware`
+- `cubepi.mcp`
+- `cubepi.tracing`
+- `cubepi.utils`
+
+The module pages above are generated at build time from docstrings and are not editable by hand.
diff --git a/website/versioned_docs/version-0.6/getting-started/core-concepts.md b/website/versioned_docs/version-0.6/getting-started/core-concepts.md
new file mode 100644
index 0000000..c6bac97
--- /dev/null
+++ b/website/versioned_docs/version-0.6/getting-started/core-concepts.md
@@ -0,0 +1,249 @@
+---
+title: Core Concepts
+description: "Learn the six core concepts of CubePi: Agent, Tool, Provider, Stream & Events, Middleware, and Checkpointer."
+---
+
+# Core Concepts
+
+Six concepts cover everything CubePi does. Read this page once, then
+the rest of the docs become a lookup table.
+
+## Agent
+
+`Agent` is the stateful façade: you construct it with a provider, a
+model, optional tools, and optional middleware/checkpointer. You drive
+it through three methods:
+
+- `await agent.prompt(message)` — start a new turn from a user message.
+- `await agent.resume()` — continue from the last persisted message
+ (used with a checkpointer).
+- `agent.steer(message)` / `agent.follow_up(message)` — queue a
+ message mid-flight or after the current run.
+
+The agent owns an `AgentState` (system prompt, tools, model, message
+history, pending tool calls, streaming flag) and a list of subscribers:
+
+```python
+unsubscribe = agent.subscribe(my_listener)
+# ...
+unsubscribe()
+```
+
+Subscribers receive every `AgentEvent` the loop emits. They can be
+sync or async.
+
+## Tool
+
+An `AgentTool` is a name + description + Pydantic parameter model +
+async `execute` function:
+
+```python
+from pydantic import BaseModel
+from cubepi import AgentTool, AgentToolResult, TextContent
+
+class SearchParams(BaseModel):
+ query: str
+ limit: int = 10
+
+async def execute(tool_call_id, params: SearchParams, *, signal=None, on_update=None):
+ # do work; respect `signal` if you can be aborted
+ return AgentToolResult(content=[TextContent(text=f"…")])
+
+search = AgentTool(
+ name="search",
+ description="Search the corpus",
+ parameters=SearchParams,
+ execute=execute,
+)
+```
+
+The Pydantic schema is auto-converted to JSON Schema and passed to the
+model. Arg parsing, error wrapping, and parallel execution are
+handled by the framework. See [Tool Use](../guides/agents/tool-use)
+for `execution_mode`, `on_update` (incremental progress), and
+`terminate` (end the turn from a tool).
+
+## Provider
+
+A `Provider` is anything matching this Protocol:
+
+```python
+class Provider(Protocol):
+ async def stream(
+ self,
+ model: Model,
+ messages: list[Message],
+ *,
+ system_prompt: str = "",
+ tools: list[ToolDefinition] | None = None,
+ options: StreamOptions | None = None,
+ ) -> MessageStream: ...
+```
+
+It returns a `MessageStream` — a single async iterator that yields
+`StreamEvent`s and exposes the final `AssistantMessage` via `await
+stream.result()`. Built-in providers:
+
+- `AnthropicProvider` — Claude (Messages API, with thinking, caching,
+ tool use).
+- `OpenAIProvider` — GPT family (Chat Completions API).
+- `OpenAIResponsesProvider` — GPT family (Responses API, server-side
+ state).
+- `FauxProvider` — deterministic test double (no network).
+
+Write your own by implementing one method. See [Providers / Custom](../guides/providers/custom).
+
+## Stream and events
+
+Streams and events are two layers:
+
+- **Provider streams** — `MessageStream` yields *provider* events:
+ `start`, `text_start`, `text_delta`, `text_end`, `thinking_*`,
+ `toolcall_*`, `done`, `error`. This is the raw token stream.
+- **Agent events** — what `agent.subscribe(...)` receives. 14
+ types covering the entire loop + HITL: `agent_start`, `agent_end`,
+ `turn_start`, `turn_end`, `message_start`, `message_update`,
+ `message_end`, `tool_execution_start`, `tool_execution_update`,
+ `tool_execution_end`, `hitl_request`, `hitl_answer`,
+ `agent_suspended`, `agent_aborted`.
+
+Subscribe to agent events for UI; for low-level token routing dig into
+`event.stream_event`. See [Streaming Events](../guides/agents/streaming).
+
+## Middleware
+
+`Middleware` is a class with up to seven typed hooks:
+
+| Hook | When it runs | Composition rule |
+|---|---|---|
+| `transform_context` | Before each model call, on the message list | Chained — each receives previous result |
+| `convert_to_llm` | Right before serialisation to the provider | Last implementation wins |
+| `transform_system_prompt` | Before each model call, on the system prompt | Chained |
+| `before_tool_call` | Per tool call, after arg validation | First `block=True` short-circuits |
+| `after_tool_call` | Per tool call, after `execute` | Later override earlier |
+| `after_model_response` | After the assistant message lands | Returns a `TurnAction` controlling flow |
+| `should_stop_after_turn` | At each turn boundary | Any `True` stops |
+
+Pass middleware as a list to `Agent(middleware=[...])`. See
+[Middleware → Composition](../guides/middleware/composition).
+
+## Checkpointer
+
+A `Checkpointer` is anything matching:
+
+```python
+class Checkpointer(Protocol):
+ async def load(self, thread_id: str) -> CheckpointData | None: ...
+ async def append(self, thread_id: str, messages: list[Message]) -> None: ...
+ async def save_extra(self, thread_id: str, extra: dict) -> None: ...
+```
+
+Bind one to an agent with `Agent(checkpointer=cp, thread_id="…")` and
+the loop will append each new message as it lands, restoring history
+on the first `prompt()`. Built-in backends: `MemoryCheckpointer`,
+`SQLiteCheckpointer`, `PostgresCheckpointer`, `MySQLCheckpointer`.
+
+HITL adds two optional methods for cross-process suspend/resume:
+`save_pending_request` / `load_pending_request`. All first-party
+backends implement them. See [HITL guide](../guides/hitl/overview).
+
+## HITL (Human-in-the-Loop)
+
+CubePi ships a built-in `cubepi.hitl` module for scenarios where the
+agent needs to **pause and wait for a human**:
+
+- **Sandbox confirmation** — a dangerous tool (bash, file write) needs
+ approve / deny / edit before running.
+- **Mid-run questions** — the agent surfaces a structured form to the user
+ and waits for the answer.
+
+```python
+from cubepi.hitl import InMemoryChannel, ConfirmToolCallMiddleware, ask_user_tool
+
+channel = InMemoryChannel()
+
+agent = Agent(
+ provider=…, model=…,
+ tools=[bash_tool, ask_user_tool(channel)],
+ middleware=[ConfirmToolCallMiddleware(channel, require_confirm={"bash"})],
+ channel=channel,
+)
+```
+
+The channel is an `await`-able coroutine collaborator: tool and
+middleware authors write `await channel.ask(...)` or
+`await channel.confirm(...)` and the channel handles the suspend. Host
+code (your web app / TUI) subscribes to `channel.subscribe()` or polls
+`channel.pending`, renders the request to the user, and posts the
+answer via `channel.answer(qid, answer)`.
+
+Two channel backends ship in-box:
+- **`InMemoryChannel`** — single process (CLI, notebook, tests).
+- **`CheckpointedChannel`** — cross-process (web service). The pending
+ request is persisted to the checkpointer; a different process can
+ answer hours later via `Agent.respond(question_id=, answer=)`.
+
+Full details — the three HITL verbs, both built-in middlewares, the
+cross-process suspend/resume protocol, events, trace spans, and error
+reference — are in the [HITL guide](../guides/hitl/overview).
+
+## Tracer (optional)
+
+`Tracer` produces OpenTelemetry spans aligned with the
+[GenAI Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/),
+so any OTLP backend (Jaeger, Tempo, Honeycomb, Datadog, AWS X-Ray, …)
+can ingest agent runs without custom instrumentation. Install the
+extra:
+
+```bash
+pip install "cubepi[tracing]" # OTel SDK
+pip install "cubepi[tracing-otlp]" # + OTLP/HTTP exporter
+```
+
+then wrap your agent in an `async with`:
+
+```python
+from cubepi.tracing import Tracer
+from cubepi.tracing.exporters import JsonlSpanExporter
+
+async with (
+ Tracer(
+ service_name="my-bot",
+ agent_name="assistant",
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+ ) as tracer,
+ tracer.attached(agent),
+):
+ await agent.prompt("…")
+```
+
+Each run emits an `invoke_agent` root span containing one
+`cubepi.turn` per LLM round-trip, plus `chat` (CLIENT) and
+`execute_tool` children. By default **no prompt content or model
+output is recorded** — opt in with `Tracer(record_content=True)` and
+a `redact` callback for PII. Pair with `Meter(...)` for token /
+duration / TTFC histograms. Full guide:
+[Tracing → Overview](../guides/tracing/overview).
+
+## Putting it together
+
+```
+User code
+ │
+ ▼
+┌──────────────────────────────────────────┐
+│ Agent │
+│ ├─ AgentState (messages, tools, …) │
+│ ├─ Middleware ── compose_middleware() │
+│ ├─ Checkpointer ── append on message_end │
+│ └─ run_agent_loop ◀──── the actual loop │
+│ │ │
+│ ▼ │
+│ Provider.stream() → MessageStream │
+│ │ │
+│ └─ events → emit → subscribers │
+└──────────────────────────────────────────┘
+```
+
+That diagram is the whole framework. The rest of this site is just
+the details.
diff --git a/website/versioned_docs/version-0.6/getting-started/installation.md b/website/versioned_docs/version-0.6/getting-started/installation.md
new file mode 100644
index 0000000..7e2c560
--- /dev/null
+++ b/website/versioned_docs/version-0.6/getting-started/installation.md
@@ -0,0 +1,97 @@
+---
+title: Installation
+description: "Install CubePi via pip. Python 3.11+ required. Supports Linux, macOS, and Windows."
+---
+
+# Installation
+
+CubePi runs on **Python 3.11+**. The core has three runtime
+dependencies: `pydantic`, `anthropic`, `openai`. Optional features
+(SQLite, Postgres, MCP, OpenTelemetry tracing) are gated behind extras
+so you only install what you use.
+
+## With pip
+
+```bash
+pip install cubepi
+```
+
+Optional extras:
+
+```bash
+pip install "cubepi[sqlite]" # adds aiosqlite for SQLiteCheckpointer
+pip install "cubepi[postgres]" # adds asyncpg + sqlalchemy + msgpack
+pip install "cubepi[mcp]" # adds the MCP SDK for tool loaders
+pip install "cubepi[tracing]" # adds opentelemetry-sdk for Tracer / Meter
+pip install "cubepi[tracing-otlp]" # adds the OTLP/HTTP span exporter
+pip install "cubepi[sqlite,mcp,tracing]" # combine
+```
+
+## With uv
+
+[`uv`](https://github.com/astral-sh/uv) is significantly faster than
+pip and is the recommended workflow:
+
+```bash
+uv add cubepi
+uv add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"
+```
+
+In an existing uv project, `uv sync` re-locks the environment after
+edits to `pyproject.toml`.
+
+## With Poetry
+
+```bash
+poetry add cubepi
+poetry add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"
+```
+
+## Verifying the install
+
+```bash
+python -c "import cubepi; print(cubepi.__doc__)"
+# cubepi — Pythonic async-native agent framework.
+```
+
+If you see an `ImportError`, your interpreter is likely \< 3.11 — check
+`python --version`.
+
+## Configuring provider credentials
+
+CubePi providers read credentials from constructor arguments. Most
+deployments pull them from environment variables:
+
+```python
+import os
+from cubepi.providers.anthropic import AnthropicProvider
+from cubepi.providers.openai import OpenAIProvider
+
+anthropic = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+openai = OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"])
+```
+
+You can also pass `base_url=...` to either provider to point at a
+self-hosted endpoint or compatible proxy (e.g. Anthropic Bedrock,
+LiteLLM, vLLM).
+
+For the [FauxProvider](../guides/providers/custom#using-fauxprovider-in-tests)
+(used in tests), no credentials are required.
+
+## Choosing extras: which to install
+
+| Extra | Pulls in | Install when |
+|---|---|---|
+| (none) | core only | You only need in-memory state, no MCP, no tracing |
+| `[sqlite]` | `aiosqlite` | Single-process app needs disk persistence |
+| `[postgres]` | `asyncpg`, `sqlalchemy`, `msgpack` | Multi-instance / production — see [Postgres guide](../guides/checkpointing/postgres) |
+| `[mcp]` | `mcp` | You want to mount MCP server tools into your agent |
+| `[tracing]` | `opentelemetry-sdk` | You want OpenTelemetry traces (and optionally metrics) — see [Tracing guide](../guides/tracing/overview) |
+| `[tracing-otlp]` | `opentelemetry-exporter-otlp-proto-http` | Ship traces to an OTLP/HTTP backend (Jaeger ≥1.50, Tempo, Honeycomb, Datadog, …) |
+| `[docs]` | `griffe` | You're building the docs site (contributors only) |
+
+## Next steps
+
+- [Quick Start](./quick-start) — your first agent in five minutes.
+- [Core Concepts](./core-concepts) — what `Agent` / `Tool` / `Provider`
+ / `Checkpointer` actually mean before you start gluing them.
diff --git a/website/versioned_docs/version-0.6/getting-started/quick-start.md b/website/versioned_docs/version-0.6/getting-started/quick-start.md
new file mode 100644
index 0000000..aa98eb9
--- /dev/null
+++ b/website/versioned_docs/version-0.6/getting-started/quick-start.md
@@ -0,0 +1,127 @@
+---
+title: Quick Start
+description: "Build your first CubePi agent in minutes with this step-by-step quick-start guide."
+---
+
+# Quick Start
+
+Ship a streaming, tool-using agent in five minutes. We'll build a
+weather agent that calls a Python function as a tool, streams Claude's
+response token-by-token, and exits cleanly.
+
+## Prerequisites
+
+- Python 3.11+
+- `cubepi` installed (`pip install cubepi`)
+- An `ANTHROPIC_API_KEY` in your environment
+
+## The full script
+
+Save this as `weather_agent.py`:
+
+```python title="weather_agent.py"
+import asyncio
+import os
+from pydantic import BaseModel
+
+from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+class GetWeatherParams(BaseModel):
+ city: str
+
+
+async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+ # In a real app: call an HTTP weather API. Here we hard-code a reply.
+ return AgentToolResult(
+ content=[TextContent(text=f"72°F and sunny in {params.city}")]
+ )
+
+
+async def main():
+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="You are a concise weather assistant.",
+ tools=[
+ AgentTool(
+ name="get_weather",
+ description="Get current weather for a city",
+ parameters=GetWeatherParams,
+ execute=get_weather,
+ ),
+ ],
+ )
+
+ # Subscribe BEFORE prompt() — that's how you see streaming events.
+ def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+ elif event.type == "agent_end":
+ print() # final newline
+
+ agent.subscribe(on_event)
+ await agent.prompt("What's the weather in Tokyo?")
+
+
+asyncio.run(main())
+```
+
+Run it:
+
+```bash
+python weather_agent.py
+```
+
+You should see Claude stream a sentence like
+*"The weather in Tokyo is currently 72°F and sunny…"*, with the
+tool result threaded through.
+
+## What just happened
+
+CubePi ran a loop that looks (conceptually) like this:
+
+1. `agent.prompt("What's the weather in Tokyo?")` enqueued a
+ `UserMessage` and called the model.
+2. The model decided to invoke `get_weather(city="Tokyo")` — CubePi
+ parsed the JSON args with your Pydantic model, called your `async
+ def`, and fed the result back as a `ToolResultMessage`.
+3. The model produced a final assistant response, streamed back as
+ `text_delta` events.
+4. The loop emitted `agent_end` and returned.
+
+`agent.subscribe(...)` registered a callback for every event the
+runtime emits: `agent_start`, `turn_start`, `message_start`,
+`text_delta`, `tool_execution_start`, `tool_execution_end`,
+`message_end`, `turn_end`, `agent_end`. The script only cared about
+`text_delta`, but you can hang any UI off the rest.
+
+## Sources of confusion (read before you debug)
+
+- **Subscribe before you prompt.** Listeners only receive events
+ emitted *after* `subscribe` was called. Calling `prompt` first means
+ the early events are gone.
+- **`Model(id=…, provider=…)` is required.** The agent uses
+ `model.provider` to clamp thinking levels and route metadata. The id
+ must match a model the provider supports.
+- **The `execute` signature is fixed.** Keep `(tool_call_id, params,
+ *, signal, on_update)` even if you don't use the keyword-only
+ arguments. CubePi always passes them.
+- **`agent.prompt()` can only run one prompt at a time.** While it's
+ running, use [`agent.steer()`](../guides/agents/multi-turn) to
+ inject a follow-up, or `agent.follow_up()` to queue one for after
+ the current run.
+
+## Next steps
+
+- [Core Concepts](./core-concepts) — the mental model behind `Agent`,
+ `Tool`, `Provider`, `Stream`, `Middleware`, `Checkpointer`.
+- [Building Your First Agent](../guides/agents/first-agent) — full
+ walkthrough of tools, streaming, and error handling.
+- [Tool Use & Parallel Execution](../guides/agents/tool-use) — make
+ the agent fan out across multiple tools at once.
+- [Recipes → Weather Agent](../recipes/weather-agent) — a slightly
+ beefier version of this script with real HTTP calls.
diff --git a/website/versioned_docs/version-0.6/guides/agents/first-agent.md b/website/versioned_docs/version-0.6/guides/agents/first-agent.md
new file mode 100644
index 0000000..4bf1df0
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/agents/first-agent.md
@@ -0,0 +1,190 @@
+---
+title: Building Your First Agent
+description: "Create and run your first CubePi agent — choose a provider, define a system prompt, and send a message."
+---
+
+# Building Your First Agent
+
+This guide is the longer cousin of the [Quick Start](../../getting-started/quick-start).
+We'll build a single-tool agent end-to-end, then layer on the things
+you'll want next: streaming UI, error handling, and a cancel button.
+
+## Step 1 — set up the provider and model
+
+The provider is the connection to the LLM API; the `Model` describes
+which model you want to invoke and a few capabilities.
+
+```python
+import os
+from cubepi import Model
+from cubepi.providers.anthropic import AnthropicProvider
+
+provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+model = Model(
+ id="claude-sonnet-4-5-20250929",
+ provider="anthropic",
+ max_tokens=4096, # response cap
+ context_window=200_000, # hard model limit; defaults are usually fine
+ temperature=0.7,
+)
+```
+
+The `provider` field on `Model` is a string label (e.g. `"anthropic"`,
+`"openai"`). It's used by the framework to clamp thinking levels and
+tag responses — keep it stable, it doesn't have to match the
+provider's internal name.
+
+## Step 2 — declare a tool
+
+Every tool is a Pydantic param model + an async `execute` function:
+
+```python
+from pydantic import BaseModel
+from cubepi import AgentTool, AgentToolResult, TextContent
+
+
+class GetWeatherParams(BaseModel):
+ city: str
+
+
+async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+ # do real work here — call an HTTP API, query a DB, etc.
+ return AgentToolResult(
+ content=[TextContent(text=f"72°F and sunny in {params.city}")]
+ )
+
+
+weather_tool = AgentTool(
+ name="get_weather",
+ description="Get current weather for a city. Returns a short text summary.",
+ parameters=GetWeatherParams,
+ execute=get_weather,
+)
+```
+
+A few details:
+
+- The Pydantic model is auto-converted to JSON Schema and sent to the
+ model as part of the tool definition.
+- The `execute` signature is fixed:
+ `(tool_call_id, params, *, signal, on_update)`. The two
+ keyword-only args are always passed — keep them in your signature
+ even if you ignore them.
+- `signal` is an `asyncio.Event` that's set when the user cancels.
+ Check it inside long-running work and bail out early.
+- `on_update(partial)` lets you stream incremental progress (covered
+ in [Tool Use](./tool-use#streaming-tool-progress)).
+
+## Step 3 — assemble the agent
+
+```python
+from cubepi import Agent
+
+agent = Agent(
+ provider=provider,
+ model=model,
+ system_prompt="You are a concise weather assistant.",
+ tools=[weather_tool],
+)
+```
+
+You can pass `tools=[]` (or omit it) for a plain chat agent.
+
+## Step 4 — subscribe to events
+
+`agent.subscribe(listener)` is how you observe the run. The listener
+receives every `AgentEvent`:
+
+```python
+def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+ elif event.type == "tool_execution_start":
+ print(f"\n→ calling {event.tool_name}({event.args})")
+ elif event.type == "tool_execution_end":
+ print(f" ✓ done")
+
+agent.subscribe(on_event)
+```
+
+You can register multiple listeners and they all receive every event.
+Subscribe **before** `prompt()` — events fire as soon as the run
+starts.
+
+## Step 5 — prompt and run
+
+```python
+import asyncio
+
+async def main():
+ await agent.prompt("What's the weather in Tokyo?")
+
+asyncio.run(main())
+```
+
+`agent.prompt()` does not return any value. The result lives on
+`agent.state.messages` (the full history) and `agent.state.streaming_message`
+(the current in-flight message, or `None` between turns).
+
+## Adding error handling
+
+When `provider.stream()` raises, the agent loop still produces an
+`AssistantMessage` with `stop_reason="error"` and `error_message`
+filled in. The event sequence is:
+`message_start` → `message_end` → `turn_end` → `agent_end`.
+
+You can either:
+
+1. Catch in the subscriber, looking for `event.type == "agent_end"` and
+ the last message's `stop_reason`:
+
+ ```python
+ def on_event(event, signal=None):
+ if event.type == "agent_end":
+ last = event.messages[-1]
+ if getattr(last, "stop_reason", "") == "error":
+ print(f"\nerror: {last.error_message}")
+ ```
+
+2. Or inspect `agent.state.error_message` after `await
+ agent.prompt(...)` returns.
+
+## Adding a cancel button
+
+`agent.abort()` sets the run-level signal. The provider stream
+short-circuits to `"aborted"`, in-flight tools see `signal.is_set()
+== True`, and the loop emits `agent_end` cleanly.
+
+```python
+async def main():
+ task = asyncio.create_task(agent.prompt("Search for…"))
+ await asyncio.sleep(0.5)
+ agent.abort()
+ await task # always completes — never raises
+ await agent.wait_for_idle()
+```
+
+## Common pitfalls
+
+- **`RuntimeError: Agent is already processing a prompt.`** — You called
+ `prompt()` twice without awaiting the first. Use `await
+ agent.wait_for_idle()` or queue with `steer()` / `follow_up()`
+ instead.
+- **No `text_delta` events** — Did you subscribe *before* calling
+ `prompt()`? Listeners only see events emitted after registration.
+- **Tool not found** — The model invoked a tool whose `name` doesn't
+ match any tool in `tools=[...]`. CubePi reports this as a tool result
+ with `is_error=True` rather than crashing — check the
+ `tool_execution_end` event's `result`.
+- **Pydantic ValidationError swallowed** — If the model produces
+ malformed JSON, CubePi captures the validation error and feeds it
+ back as a tool error result. The model usually corrects itself on
+ the next turn.
+
+## Next
+
+- [Tool Use & Parallel Execution](./tool-use) — multiple tools at once,
+ sequential mode, `terminate`, incremental progress.
+- [Streaming Events](./streaming) — the full event taxonomy.
+- [Multi-turn Conversations](./multi-turn) — keeping state across
+ turns, `steer`, `follow_up`, `resume`.
diff --git a/website/versioned_docs/version-0.6/guides/agents/multi-turn.md b/website/versioned_docs/version-0.6/guides/agents/multi-turn.md
new file mode 100644
index 0000000..4a525f0
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/agents/multi-turn.md
@@ -0,0 +1,164 @@
+---
+title: Multi-turn Conversations
+description: "Build multi-turn conversational agents with CubePi's stateful agent loop and message history."
+---
+
+# Multi-turn Conversations
+
+A "turn" in CubePi is one round of: user input → model response (and
+maybe tools) → optional more model responses to tool results. The
+agent's `_messages` list grows across turns; this guide covers how to
+drive multi-turn flows correctly and how to inject input while the
+agent is mid-thought.
+
+## The basic pattern
+
+Just call `prompt` again after the previous call returns:
+
+```python
+await agent.prompt("Hi, my name is Sam.")
+await agent.prompt("What's my name?")
+# → "Your name is Sam."
+```
+
+History lives on `agent.state.messages`. CubePi appends each user
+message, each assistant message, and each tool result. The provider
+gets the full list every time, so context windows matter (see
+[Context Management](#context-management) below).
+
+## In-flight steering: `agent.steer()`
+
+Sometimes the user has a correction or extra context while the model
+is still mid-turn. Use `steer()`:
+
+```python
+import asyncio
+
+async def main():
+ task = asyncio.create_task(agent.prompt("Plan a 5-day trip to Kyoto."))
+ await asyncio.sleep(2)
+ # User changed their mind:
+ agent.steer(UserMessage(content=[TextContent(text="Make it 3 days, not 5.")]))
+ await task
+```
+
+A steering message is enqueued; the loop picks it up between turns (in
+practice, between a tool batch and the next model call). The agent
+sees it before its next response — it's not lost.
+
+`steering_mode` on `Agent` controls drain behaviour:
+
+- `"one-at-a-time"` (default) — one queued message per pickup point.
+- `"all"` — every queued message is drained at once.
+
+## Queued follow-ups: `agent.follow_up()`
+
+`follow_up` is for *"after the current run, start a new turn with
+this."* It's the typical pattern for a chat UI: the user types while
+the assistant is still responding.
+
+```python
+agent.follow_up(UserMessage(content=[TextContent(text="And what about Osaka?")]))
+# When the current prompt() finishes, the loop picks this up
+# automatically and starts a new turn.
+```
+
+If the agent is idle when you call `follow_up`, you still need to
+trigger a run — most apps call `await agent.resume()` once `prompt()`
+returns, to drain the queue.
+
+## `resume()` — continue from the last message
+
+`resume()` is the "pick up where we left off" entry point. Two uses:
+
+1. **After loading from a checkpointer.** The state has messages but
+ no in-flight prompt. `resume()` looks at the last message and acts:
+ - assistant → expects a queued steer/follow_up to convert into a
+ new user turn; otherwise raises.
+ - tool_result → re-invokes the model with the tool output.
+ - user → re-invokes the model on the user message.
+2. **After abort.** Once `agent.abort()` has cleanly torn down a run,
+ you can resume.
+
+```python
+async with SQLiteCheckpointer("conv.db") as cp:
+ agent = Agent(provider=…, model=…, checkpointer=cp, thread_id="conv-1")
+ await agent.prompt("hello") # loads existing history first
+ await agent.prompt("how are you?")
+```
+
+The first `prompt()` after instantiation loads any existing thread.
+Subsequent calls just append.
+
+## Context management
+
+CubePi does **not** truncate or summarise context on your behalf. The
+full message list is sent to the model on every turn. Strategies:
+
+- **Manual truncation** — Implement a
+ [`transform_context`](../middleware/hooks#transform_context)
+ middleware that returns a sliding window.
+- **Summarisation pass** — Periodically inject a summary message and
+ drop older ones via `transform_context`.
+- **Different `convert_to_llm`** — Reshape the history just before
+ serialisation (the last opportunity), without mutating
+ `agent.state.messages`. The user-visible history stays full; the
+ model sees less.
+
+See [Middleware → Examples](../middleware/examples#sliding-window-truncation)
+for a working example.
+
+## Cancellation and idle waits
+
+```python
+agent.abort() # signals the current run to stop
+await agent.wait_for_idle() # awaits the run-cleanup
+```
+
+`wait_for_idle()` is a no-op if the agent is already idle. It's safe
+to call anywhere.
+
+## Restoring state from disk
+
+```python
+from cubepi.checkpointer import SQLiteCheckpointer
+
+async with SQLiteCheckpointer("conv.db") as cp:
+ agent = Agent(
+ provider=provider,
+ model=model,
+ checkpointer=cp,
+ thread_id="user-42",
+ )
+ # First prompt() restores the saved history if any.
+ await agent.prompt("continue our chat")
+```
+
+The `_extra` slot (an arbitrary `dict[str, Any]`) is also restored.
+Middleware that wants to persist per-thread state should write into
+`context.extra`; the checkpointer's `save_extra` is called at
+`agent_end`.
+
+## Common pitfalls
+
+- **`prompt()` while another `prompt()` is in flight** raises
+ `RuntimeError`. Use `steer()` or `follow_up()`, or `wait_for_idle()`
+ first.
+- **`resume()` with last message = assistant and no queue** raises
+ `"Cannot continue from message role: assistant"`. Either queue a
+ follow-up first or call `prompt()` instead.
+- **History grows unbounded** — without a `transform_context`
+ middleware you'll eventually hit context limits. Plan for
+ truncation/summarisation early.
+- **Concurrent agents on the same `thread_id`** — Append-only is safe
+ for ordering but two agents writing the same thread will interleave
+ messages. Use one agent instance per thread or coordinate at the
+ application layer.
+
+## See also
+
+- [Streaming Events](./streaming) — exact event order around
+ steering/follow_up.
+- [Checkpointing → SQLite](../checkpointing/sqlite) — persisting history.
+- [Recipes → Persistent Chat](../../recipes/persistent-chat) — full
+ multi-turn app with history reload.
diff --git a/website/versioned_docs/version-0.6/guides/agents/streaming.md b/website/versioned_docs/version-0.6/guides/agents/streaming.md
new file mode 100644
index 0000000..288931d
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/agents/streaming.md
@@ -0,0 +1,171 @@
+---
+title: Streaming Events
+description: "Stream events and tokens from CubePi agents in real time using subscribers and MessageStream."
+---
+
+# Streaming Events
+
+CubePi exposes two streams, layered:
+
+1. **Provider stream** — `MessageStream` you get from
+ `provider.stream(...)`. Yields `StreamEvent`s describing the raw
+ wire output: text deltas, thinking deltas, tool-call deltas, then
+ `done` or `error`.
+2. **Agent event stream** — what listeners registered with
+ `agent.subscribe(...)` see. Eleven event types covering the full
+ lifecycle of a `prompt()` call, including provider events wrapped
+ inside `MessageUpdateEvent`.
+
+Most app code only needs the agent event stream.
+
+## The eleven agent events
+
+| Event | Fires when |
+|---|---|
+| `agent_start` | At the very beginning of `prompt()` / `resume()` |
+| `turn_start` | Before each model invocation (one or more per `prompt`) |
+| `message_start` | Right before a new message (user / assistant / tool result) is added to history |
+| `message_update` | On every provider `StreamEvent` (deltas, etc.); has `event.stream_event` attached |
+| `message_end` | After a message is finalised |
+| `tool_execution_start` | A tool call is dispatched (one per call, before parallel `asyncio.gather`) |
+| `tool_execution_update` | A tool reported partial progress via `on_update(...)` |
+| `tool_execution_end` | A tool finished (or failed) |
+| `turn_end` | After all tools in a batch settled, or after a tool-less assistant response |
+| `agent_end` | The whole `prompt()` call has finished — clean exit, abort, or error |
+
+`MessageStartEvent` and `MessageEndEvent` apply to *every* message,
+not just assistant ones. User and tool-result messages also get them.
+
+## Event order for a tool-using turn
+
+A typical "user asks question → model calls one tool → model responds"
+sequence:
+
+```
+agent_start
+turn_start
+ message_start (UserMessage from prompt)
+ message_end (UserMessage)
+ message_start (AssistantMessage — empty partial)
+ message_update × N (text_delta, toolcall_delta, …)
+ message_end (AssistantMessage — finalised)
+ tool_execution_start
+ tool_execution_end
+ message_start (ToolResultMessage)
+ message_end (ToolResultMessage)
+turn_end
+turn_start (loop continues with the tool result in context)
+ message_start
+ message_update × N
+ message_end
+turn_end
+agent_end
+```
+
+## Subscribing
+
+```python
+def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+
+unsubscribe = agent.subscribe(on_event)
+```
+
+`agent.subscribe(...)` never receives an event whose top-level `.type`
+equals `"text_delta"` — that's a *provider* event type. The agent
+wraps every provider event in a `MessageUpdateEvent` and tucks the
+original under `event.stream_event`. Match on both fields, as above.
+
+Listeners can be sync or async; async ones are awaited. The second
+argument is the run-level `asyncio.Event` (the abort signal) — you can
+inspect `signal.is_set()` to know if the run was cancelled.
+
+To stop receiving events, call the function returned by `subscribe`.
+
+## Filtering for text deltas (the common case)
+
+```python
+def on_event(event, signal=None):
+ if event.type == "message_update":
+ sub = event.stream_event
+ if sub.type == "text_delta":
+ print(sub.delta, end="", flush=True)
+```
+
+Equivalent defensive form using `getattr`, since only
+`MessageUpdateEvent` carries a `stream_event` attribute:
+
+```python
+def on_event(event, signal=None):
+ if getattr(event, "stream_event", None) and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+```
+
+The shape that CubePi guarantees is the one in the table above
+(`MessageUpdateEvent.stream_event.delta`). Always match the outer
+event's `type == "message_update"` (or check `stream_event` exists)
+before reaching into `stream_event.type`.
+
+## Provider `StreamEvent` types
+
+Inside a `MessageUpdateEvent.stream_event`, the type tells you what
+the model is emitting:
+
+| `stream_event.type` | Meaning | Useful fields |
+|---|---|---|
+| `start` | Start of an assistant message | `partial` |
+| `text_start` | Beginning of a text block | `content_index` |
+| `text_delta` | Token chunk | `delta` |
+| `text_end` | End of a text block | `content_index` |
+| `thinking_start` / `thinking_delta` / `thinking_end` | Extended thinking blocks | `delta` |
+| `toolcall_start` / `toolcall_delta` / `toolcall_end` | Streaming JSON args for a tool call | `delta` (partial JSON) |
+| `done` | Stream finished normally | — |
+| `error` | Stream errored | `error_message` |
+
+The `partial` field on every event is a deep-copied snapshot of the
+in-progress `AssistantMessage` — handy for UIs that re-render
+on every event without tracking deltas themselves.
+
+## Iterating a raw provider stream
+
+If you're skipping `Agent` entirely (rare — usually means you're
+writing a test or a custom orchestrator), iterate the stream
+directly:
+
+```python
+stream = await provider.stream(
+ model=model,
+ messages=[UserMessage(content=[TextContent(text="hello")])],
+)
+async for event in stream:
+ if event.type == "text_delta":
+ print(event.delta, end="", flush=True)
+final = await stream.result() # waits for the AssistantMessage
+```
+
+`stream.result()` returns even after iteration ends; it's the
+canonical way to get the final message.
+
+## Common pitfalls
+
+- **Subscribing after `prompt()`** — Early events are gone.
+ `agent.subscribe(...)` first, always.
+- **Listener exceptions crash the loop?** — They don't, but they
+ propagate up to the next `await`. Wrap risky work in `try/except`.
+- **Order on parallel tools** — `tool_execution_start` events come in
+ the model's emit order; `tool_execution_end` events come in
+ completion order. Don't rely on pairs being adjacent.
+- **`message_update` fires for every delta** — High-frequency tokens
+ can flood a slow listener (e.g. a websocket). Batch on the consumer
+ side if needed.
+- **`text_delta` for thinking?** — No. Thinking blocks emit
+ `thinking_*` events. Filter on `event.stream_event.type` if you only
+ want visible text.
+
+## See also
+
+- [Tool Use](./tool-use) — the `tool_execution_*` triplet in detail.
+- [Multi-turn](./multi-turn) — event order around steering and resume.
+- [API Reference → StreamEvent](../../api/cubepi-providers#streamevent)
+ for the field-level schema.
diff --git a/website/versioned_docs/version-0.6/guides/agents/tool-use.md b/website/versioned_docs/version-0.6/guides/agents/tool-use.md
new file mode 100644
index 0000000..6a335eb
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/agents/tool-use.md
@@ -0,0 +1,195 @@
+---
+title: Tool Use & Parallel Execution
+description: "Register tools, execute them in parallel or sequentially, and handle results with Pydantic validation in CubePi."
+---
+
+# Tool Use & Parallel Execution
+
+Tools are how an agent acts on the world. CubePi turns each `AgentTool`
+into a JSON Schema for the model, validates arguments with Pydantic,
+runs the work, and feeds the result back as a `ToolResultMessage`. By
+default tools run in parallel when the model calls more than one in a
+single turn.
+
+## Anatomy of a tool
+
+```python
+from pydantic import BaseModel, Field
+from cubepi import AgentTool, AgentToolResult, TextContent
+
+
+class SearchParams(BaseModel):
+ query: str = Field(..., description="The natural-language query")
+ limit: int = Field(10, ge=1, le=100)
+
+
+async def search(tool_call_id, params: SearchParams, *, signal=None, on_update=None):
+ results = await my_search_backend(params.query, params.limit)
+ return AgentToolResult(
+ content=[TextContent(text="\n".join(results))],
+ details={"raw_results": results}, # passes through to ToolResultMessage.details
+ )
+
+
+search_tool = AgentTool(
+ name="search",
+ description="Search the internal knowledge base.",
+ parameters=SearchParams,
+ execute=search,
+)
+```
+
+The `description` is shown to the model verbatim — write it for the
+model, not for humans. Pydantic `Field(description=...)` propagates
+into the JSON Schema and helps the model understand each parameter.
+
+## Parallel by default
+
+When the model emits multiple tool calls in one assistant message,
+CubePi schedules them on `asyncio.create_task()` and gathers them.
+That's almost always what you want.
+
+```python
+agent = Agent(
+ provider=provider,
+ model=model,
+ tools=[search_tool, fetch_url_tool, summarise_tool],
+)
+```
+
+The event stream emits `tool_execution_start` for all of them up
+front, interleaved `tool_execution_update` events as each tool reports
+progress, then `tool_execution_end` per tool in completion order.
+
+## Forcing sequential execution
+
+There are two ways to opt out of parallel mode:
+
+1. **Per agent** — `Agent(tool_execution="sequential")`. All tool
+ batches run one-by-one in the order the model emitted them.
+
+2. **Per tool** — set `execution_mode="sequential"` on the
+ `AgentTool`. If *any* tool in the current batch is sequential, the
+ whole batch falls back to sequential.
+
+ ```python
+ write_db_tool = AgentTool(
+ name="write_db",
+ description="Persist a record.",
+ parameters=WriteDbParams,
+ execute=write_db,
+ execution_mode="sequential", # opt out of parallelism for safety
+ )
+ ```
+
+The built-in `ask_user` HITL tool (see [HITL guide](../hitl/overview)) sets
+`execution_mode="sequential"` — it pauses the agent for human input, so
+the tool batch runs one-by-one.
+
+Use sequential mode when tools mutate shared state (a DB, a counter)
+and you want a deterministic order.
+
+## Streaming tool progress
+
+Long-running tools can stream partial updates that show up as
+`tool_execution_update` events on the agent stream:
+
+```python
+async def slow_search(tool_call_id, params, *, signal=None, on_update=None):
+ for i, page in enumerate(await fetch_pages(params.query)):
+ if signal and signal.is_set():
+ break
+ if on_update:
+ on_update({"progress": i, "total": len(pages), "url": page.url})
+ await process(page)
+ return AgentToolResult(content=[TextContent(text="done")])
+```
+
+`partial_result` in the event is whatever object you handed to
+`on_update`. Use a small dict; it doesn't end up in the model's
+context.
+
+## Cancelling in-flight tools
+
+The `signal` argument is the same `asyncio.Event` that
+`agent.abort()` sets. Check it in any loop:
+
+```python
+async def long_running(tool_call_id, params, *, signal=None, on_update=None):
+ for chunk in big_dataset:
+ if signal and signal.is_set():
+ return AgentToolResult(content=[TextContent(text="cancelled")])
+ await process_chunk(chunk)
+```
+
+If your work is one big `await`, wrap it in
+`asyncio.wait_for(..., timeout=…)` or use the abort callbacks of the
+underlying library.
+
+## Returning errors
+
+Two ways:
+
+1. **Raise an exception.** CubePi catches it, turns it into an
+ `AgentToolResult` with `is_error=True` and the exception string as
+ `TextContent`.
+2. **Return `is_error=True` explicitly.** Useful when you want a
+ structured error body:
+
+ ```python
+ return AgentToolResult(
+ content=[TextContent(text="Rate limit exceeded; try again in 60s")],
+ is_error=True,
+ )
+ ```
+
+Either way, the model receives a tool result that's clearly marked as
+an error and usually adapts (retries with different args, asks the
+user, etc.).
+
+## Ending the turn from a tool: `terminate`
+
+A tool can declare *"after this, stop looping — don't ask the model
+again."* Set `terminate=True`:
+
+```python
+async def submit_final_answer(tool_call_id, params, *, signal=None, on_update=None):
+ save_answer(params.answer)
+ return AgentToolResult(
+ content=[TextContent(text="submitted")],
+ terminate=True,
+ )
+```
+
+CubePi only terminates if *every* tool result in the current batch is
+`terminate=True`. The agent loop emits `turn_end`, then `agent_end`,
+and exits.
+
+## Common pitfalls
+
+- **Forgetting the keyword-only args** — `execute(tool_call_id,
+ params)` will work in dev but crash when the framework passes
+ `signal=`. Keep `*, signal=None, on_update=None` in the signature.
+- **Heavy `details` payloads** — `details` is preserved through the
+ agent event but is *not* shown to the model. Don't pack massive blobs
+ there unless you have a downstream consumer.
+- **Pydantic strictness surprises** — `Field(..., min_length=1)` lets
+ the model see the constraint via JSON Schema; constraints help, but
+ remember the model still sometimes sends bad JSON. CubePi turns the
+ `ValidationError` into a tool error result; you don't need to wrap
+ validation yourself.
+- **`tools=[]` and the model still asks for a tool** — Usually means
+ the prompt mentions one. Either remove the suggestion from the
+ system prompt or pass the tool.
+
+## See also
+
+- [Streaming Events](./streaming) — how `tool_execution_*` events fit
+ the larger event taxonomy.
+- [Middleware → before_tool_call](../middleware/hooks#before_tool_call)
+ and [after_tool_call](../middleware/hooks#after_tool_call) —
+ interception, policy, retries.
+- [Recipes → Weather Agent](../../recipes/weather-agent) — a real
+ HTTP-calling tool, end-to-end.
+- [MCP Loading](../mcp/loading) — pull an entire toolset off an MCP
+ server in one call.
diff --git a/website/versioned_docs/version-0.6/guides/checkpointing/custom.md b/website/versioned_docs/version-0.6/guides/checkpointing/custom.md
new file mode 100644
index 0000000..e36e0b5
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/checkpointing/custom.md
@@ -0,0 +1,202 @@
+---
+title: Custom Backends
+description: "Implement a custom checkpointer backend for CubePi using the Checkpointer protocol."
+---
+
+# Custom Checkpointing Backends
+
+The `Checkpointer` protocol is three async methods:
+
+```python
+class Checkpointer(Protocol):
+ async def load(self, thread_id: str) -> CheckpointData | None: ...
+ async def append(self, thread_id: str, messages: list[Message]) -> None: ...
+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None: ...
+```
+
+That's the whole contract. Implement it for Redis, DynamoDB, S3, a
+filesystem, an in-memory dict — anything that can append-and-list.
+
+## When the agent calls each method
+
+| Method | Called when |
+|---|---|
+| `load(thread_id)` | Once, on the first `prompt()` after agent construction |
+| `append(thread_id, messages)` | Inside `message_end`, every time a message is finalised |
+| `save_extra(thread_id, extra)` | At `agent_end`, with the current `_extra` dict |
+
+`load` returns `None` for unknown threads. `append` and `save_extra`
+do nothing useful if you don't already have a thread; create the row
+on first call.
+
+## A minimal Redis example
+
+```python
+import json
+from typing import Any
+import redis.asyncio as aredis
+from cubepi.checkpointer.base import CheckpointData
+from cubepi.providers.base import AssistantMessage, Message, ToolResultMessage, UserMessage
+
+
+_ROLE_TO_CLS: dict[str, type[Message]] = {
+ "user": UserMessage,
+ "assistant": AssistantMessage,
+ "tool_result": ToolResultMessage,
+}
+
+
+class RedisCheckpointer:
+ def __init__(self, redis_url: str, prefix: str = "cubepi:") -> None:
+ self._url = redis_url
+ self._prefix = prefix
+ self._r: aredis.Redis | None = None
+
+ async def __aenter__(self):
+ self._r = aredis.from_url(self._url)
+ return self
+
+ async def __aexit__(self, *args):
+ if self._r is not None:
+ await self._r.aclose()
+ self._r = None
+
+ def _msgs_key(self, thread_id: str) -> str:
+ return f"{self._prefix}msgs:{thread_id}"
+
+ def _extra_key(self, thread_id: str) -> str:
+ return f"{self._prefix}extra:{thread_id}"
+
+ async def load(self, thread_id: str) -> CheckpointData | None:
+ raw_msgs = await self._r.lrange(self._msgs_key(thread_id), 0, -1)
+ raw_extra = await self._r.get(self._extra_key(thread_id))
+
+ if not raw_msgs and raw_extra is None:
+ return None
+
+ messages: list[Message] = []
+ for item in raw_msgs:
+ data = json.loads(item)
+ cls = _ROLE_TO_CLS.get(data.get("role"))
+ if cls is not None:
+ messages.append(cls.model_validate(data))
+
+ extra: dict[str, Any] = json.loads(raw_extra) if raw_extra else {}
+ return CheckpointData(messages=messages, extra=extra)
+
+ async def append(self, thread_id: str, messages: list[Message]) -> None:
+ if not messages:
+ return
+ pipe = self._r.pipeline()
+ for m in messages:
+ pipe.rpush(self._msgs_key(thread_id), json.dumps(m.model_dump(mode="json")))
+ await pipe.execute()
+
+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:
+ # Merge-style: load existing, update, write back.
+ raw = await self._r.get(self._extra_key(thread_id))
+ existing = json.loads(raw) if raw else {}
+ existing.update(extra)
+ await self._r.set(self._extra_key(thread_id), json.dumps(existing))
+```
+
+Usage:
+
+```python
+async with RedisCheckpointer("redis://localhost:6379") as cp:
+ agent = Agent(provider=…, model=…, checkpointer=cp, thread_id="user-42")
+ await agent.prompt("hi")
+```
+
+## Invariants worth holding
+
+1. **Append-only.** Don't update past messages. The agent assumes the
+ history it appended is what you'll return on `load`.
+2. **Order preserved.** `load` returns messages in the order they were
+ appended. Use a list, a sorted key, or a sequence column.
+3. **Idempotent re-`load`.** Calling `load` twice on the same thread
+ should yield identical results. (CubePi calls it once, but tools
+ often need to too.)
+4. **`extra` is a merge.** `save_extra({"a": 1})` followed by
+ `save_extra({"b": 2})` should leave `{"a": 1, "b": 2}` — not just
+ `{"b": 2}`. The agent calls this with the full dict, but middleware
+ composes its writes.
+5. **Reconstruct messages with `model_validate`.** Use the role
+ discriminator (`UserMessage` / `AssistantMessage` /
+ `ToolResultMessage`) to pick the right class.
+
+## Custom backend without async context manager
+
+The `Checkpointer` Protocol doesn't require `__aenter__` /
+`__aexit__`. Built-in checkpointers use it because they manage
+network resources, but a pure in-memory or local-file backend can
+skip it:
+
+```python
+class FileCheckpointer:
+ def __init__(self, dir_path: str) -> None:
+ self._dir = pathlib.Path(dir_path)
+ self._dir.mkdir(parents=True, exist_ok=True)
+
+ async def load(self, thread_id: str) -> CheckpointData | None:
+ ...
+ async def append(self, thread_id: str, messages: list[Message]) -> None:
+ ...
+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:
+ ...
+
+# Pass directly:
+agent = Agent(provider=…, model=…, checkpointer=FileCheckpointer("/tmp/cp"), thread_id="x")
+```
+
+## Testing your backend
+
+Drop-in test pattern using `FauxProvider`:
+
+```python
+from cubepi import Agent, Model
+from cubepi.providers import FauxProvider, faux_assistant_message
+
+async def test_roundtrip():
+ cp = MyCheckpointer(…)
+ provider = FauxProvider()
+ provider.set_responses([faux_assistant_message("hello")])
+
+ agent1 = Agent(provider=provider, model=Model(id="t", provider="faux"),
+ checkpointer=cp, thread_id="t1")
+ agent1.subscribe(lambda e, s=None: None)
+ await agent1.prompt("hi")
+
+ # Fresh agent, same thread — should restore history.
+ provider2 = FauxProvider()
+ provider2.set_responses([faux_assistant_message("hello again")])
+ agent2 = Agent(provider=provider2, model=Model(id="t", provider="faux"),
+ checkpointer=cp, thread_id="t1")
+ agent2.subscribe(lambda e, s=None: None)
+ await agent2.prompt("hi again")
+
+ assert len(agent2.state.messages) == 4 # 2 user + 2 assistant
+```
+
+## Common pitfalls
+
+- **Mutating returned `CheckpointData`** — Either deep-copy on the way
+ in, or document that the agent owns the list. CubePi's built-ins
+ copy.
+- **Losing `metadata`** — `model_dump(mode="json")` preserves
+ `metadata`. If you serialise via `__dict__` you'll drop it.
+- **Race on `save_extra` merge** — A read-modify-write pattern can
+ lose concurrent writes. Use a SQL `JSONB ||` or a Redis Lua script
+ if you have concurrent writers per thread.
+- **Forgetting to register the role for tool results** — Easy to map
+ `"user"` and `"assistant"` and forget `"tool_result"`. All three are
+ needed.
+
+## See also
+
+- [`Checkpointer` Protocol API](../../api/cubepi-checkpointer) — full
+ signature.
+- [SQLiteCheckpointer source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/sqlite.py)
+ — a complete reference implementation.
+- [PostgresCheckpointer source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/postgres/checkpointer.py)
+ — production-grade reference.
diff --git a/website/versioned_docs/version-0.6/guides/checkpointing/mysql.md b/website/versioned_docs/version-0.6/guides/checkpointing/mysql.md
new file mode 100644
index 0000000..a35a103
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/checkpointing/mysql.md
@@ -0,0 +1,206 @@
+---
+title: MySQL Checkpointing
+description: "Use MySQLCheckpointer for persistent agent state in CubePi with the MySQL backend."
+---
+
+# MySQL Checkpointing
+
+`MySQLCheckpointer` is a production-grade persistence backend for
+deployments standardized on MySQL. It mirrors
+[`PostgresCheckpointer`](./postgres): `aiomysql` connection pool,
+`msgpack` payloads, a queryable JSON `metadata` column, and a
+host-managed schema verified on connect. Per-thread `seq` allocation is
+serialized with a `SELECT … FOR UPDATE` row lock so multiple processes
+can append to the same `thread_id` safely.
+
+**Requires MySQL 8.0.13+** (for JSON expression defaults) on the InnoDB
+engine.
+
+Install the extra:
+
+```bash
+pip install "cubepi[mysql]"
+```
+
+This pulls in `aiomysql`, `sqlalchemy`, and `msgpack`.
+
+## Basic usage
+
+```python
+import asyncio
+from cubepi import Agent, Model
+from cubepi.checkpointer import MySQLCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+async def main():
+ provider = AnthropicProvider(api_key="…")
+ async with MySQLCheckpointer("mysql://user:pass@host:3306/dbname") as cp:
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ checkpointer=cp,
+ thread_id="user-42",
+ )
+ await agent.prompt("hello")
+
+
+asyncio.run(main())
+```
+
+The connection is configured from a `mysql://user:pass@host:port/db`
+DSN. Pool sizing:
+
+```python
+async with MySQLCheckpointer(
+ "mysql://…",
+ min_pool_size=2,
+ max_pool_size=20,
+) as cp:
+ …
+```
+
+## Schema
+
+The checkpointer expects three tables: `cubepi_threads`,
+`cubepi_messages`, and `cubepi_schema_version`. Like Postgres (and
+unlike SQLite), CubePi **does not create these for you** — it verifies
+on `__aenter__` that they exist with the expected `schema_version`.
+
+If they're missing, you get `CubepiSchemaUninitialized`. If the version
+doesn't match this CubePi release, you get `CubepiSchemaMismatch`. A
+production database belongs to the host application's migration system
+(Alembic, …), not to a third-party library.
+
+### Bootstrapping via Alembic
+
+CubePi exposes the SQLAlchemy `MetaData` so your migrations can adopt
+the schema:
+
+```python
+# alembic/env.py
+from cubepi.checkpointer.mysql import cubepi_metadata, EXPECTED_SCHEMA_VERSION
+
+target_metadata = [my_app_metadata, cubepi_metadata]
+```
+
+Then autogenerate a revision:
+
+```bash
+alembic revision --autogenerate -m "add cubepi checkpointer"
+```
+
+The `cubepi_messages` table is `KEY`-partitioned, which SQLAlchemy's
+autogenerate cannot express, so append the partition clause and the
+schema-version write with the provided helpers:
+
+```python
+# In a migration's upgrade():
+from cubepi.checkpointer.mysql.alembic_helpers import (
+ messages_partition_clause,
+ write_schema_version_op,
+)
+
+def upgrade():
+ op.create_table("cubepi_threads", ...)
+ op.create_table(
+ "cubepi_messages", ...,
+ mysql_engine="InnoDB",
+ )
+ # KEY(thread_id) partitioning is not autogenerated — apply it explicitly:
+ op.execute(
+ "ALTER TABLE cubepi_messages " + messages_partition_clause()
+ )
+ op.create_table("cubepi_schema_version", ...)
+ # write_schema_version_op() returns two ';'-separated statements
+ # (DELETE then INSERT). MySQL/pymysql runs one statement per execute,
+ # so split and execute each:
+ for stmt in write_schema_version_op().split(";"):
+ if stmt.strip():
+ op.execute(stmt)
+```
+
+`write_schema_version_op()` is idempotent: it deletes any rows from a
+prior CubePi version and inserts the current one. When CubePi later
+bumps `EXPECTED_SCHEMA_VERSION`, generate a new revision and run it
+again.
+
+## Data model
+
+```
+cubepi_threads
+ thread_id (PK) -- VARCHAR(255) utf8mb4_bin (case-sensitive)
+ parent_thread_id -- self-FK, for forks
+ forked_at_seq -- seq number at fork point
+ extra -- JSON
+ created_at / updated_at
+
+cubepi_messages
+ thread_id, seq -- composite PK; partitioned by KEY(thread_id) into 64
+ role -- "user" | "assistant" | "tool"
+ metadata -- JSON (not indexed; see below)
+ payload -- LONGBLOB (msgpack)
+ created_at
+
+cubepi_schema_version
+ version (PK)
+```
+
+Important properties:
+
+- **`(thread_id, seq)` is the message identity.** `seq` is monotonic
+ per thread, allocated under a `SELECT … FOR UPDATE` row lock on the
+ thread row. Two concurrent writers on the same thread serialize
+ cleanly.
+- **`payload` is msgpack-encoded `model.model_dump(mode="json")`.**
+ CubePi reconstructs the Pydantic model on read.
+- **`metadata` is JSON, queryable** via MySQL JSON functions. It is
+ **not** indexed — MySQL can't index a JSON column directly. If you
+ need to query messages by metadata, add a generated-column index
+ host-side.
+- **Messages are partitioned by `KEY(thread_id)` into 64 partitions.**
+ Even distribution, no per-thread bottleneck. The table has **no
+ foreign key** to `cubepi_threads` (MySQL forbids FKs on partitioned
+ tables); integrity is preserved by the lazy thread-row insert on
+ `append`.
+
+## Differences from the Postgres backend
+
+| | Postgres | MySQL |
+|---|---|---|
+| Driver | `asyncpg` | `aiomysql` |
+| `seq` lock | `pg_advisory_xact_lock` | `SELECT … FOR UPDATE` |
+| Messages partitioning | `HASH(thread_id)` + FK | `KEY(thread_id)`, no FK |
+| `metadata` index | GIN | none (add a generated column) |
+| Thread IDs | `TEXT` | `VARCHAR(255) utf8mb4_bin` |
+| Min version | — | MySQL 8.0.13+, InnoDB |
+
+## `save_extra` semantics
+
+`save_extra` does a shallow top-level merge, not a replace — the same
+behavior as Postgres and SQLite. Writing `{"foo": 1}` then `{"bar": 2}`
+leaves `{"foo": 1, "bar": 2}`. (Internally it reads the current `extra`
+under a row lock and writes the merged dict, rather than using
+`JSON_MERGE_PATCH`, whose null-deletion and deep-merge semantics differ
+from `dict.update`.)
+
+## Common pitfalls
+
+- **`CubepiSchemaUninitialized`** — Your DB is empty, your migrations
+ didn't run, or the `cubepi_schema_version` table is malformed. Apply
+ the host alembic upgrade first.
+- **`CubepiSchemaMismatch`** — You upgraded CubePi but didn't generate a
+ new migration. Generate one, apply it, and CubePi will start.
+- **JSON default errors on older MySQL** — JSON columns use
+ `DEFAULT (JSON_OBJECT())`, which requires MySQL 8.0.13+.
+- **Case-insensitive thread-ID collisions** — Thread IDs use the
+ `utf8mb4_bin` collation so `UserA` and `usera` stay distinct. If you
+ hand-roll the DDL, keep that collation.
+
+## See also
+
+- [Postgres Checkpointing](./postgres) — the Postgres-backed sibling.
+- [SQLite Checkpointing](./sqlite) — single-process alternative.
+- [Custom Backends](./custom) — Protocol details.
+- [Package README](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/mysql/README.md)
+ — the full host-integration runbook next to the code.
diff --git a/website/versioned_docs/version-0.6/guides/checkpointing/postgres.md b/website/versioned_docs/version-0.6/guides/checkpointing/postgres.md
new file mode 100644
index 0000000..ae346a6
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/checkpointing/postgres.md
@@ -0,0 +1,219 @@
+---
+title: Postgres Checkpointing
+description: "Use PostgresCheckpointer for production-grade agent state persistence with asyncpg and advisory locks."
+---
+
+# Postgres Checkpointing
+
+`PostgresCheckpointer` is the production-grade persistence backend.
+It uses `asyncpg` with a connection pool, `msgpack` for payloads, and
+a per-thread Postgres advisory lock so multiple processes can write
+the same `thread_id` without trampling each other.
+
+Install the extra:
+
+```bash
+pip install "cubepi[postgres]"
+```
+
+This pulls in `asyncpg`, `sqlalchemy`, and `msgpack`.
+
+## Basic usage
+
+```python
+import asyncio
+from cubepi import Agent, Model
+from cubepi.checkpointer import PostgresCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+async def main():
+ provider = AnthropicProvider(api_key="…")
+ async with PostgresCheckpointer("postgresql://user:pass@host/dbname") as cp:
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ checkpointer=cp,
+ thread_id="user-42",
+ )
+ await agent.prompt("hello")
+
+
+asyncio.run(main())
+```
+
+The DSN is whatever `asyncpg.create_pool(...)` accepts. Pool sizing:
+
+```python
+async with PostgresCheckpointer(
+ "postgresql://…",
+ min_pool_size=2,
+ max_pool_size=20,
+) as cp:
+ …
+```
+
+## Schema
+
+The checkpointer expects three tables: `cubepi_threads`,
+`cubepi_messages`, and `cubepi_schema_version`. Unlike SQLite, CubePi
+**does not create these for you** — it verifies on `__aenter__` that
+they exist with the expected `schema_version`.
+
+If they're missing, you get `CubepiSchemaUninitialized`. If the
+version doesn't match this CubePi release, you get
+`CubepiSchemaMismatch`.
+
+The reason: a production database belongs to the host application's
+migration system (Alembic, Atlas, …), not to a third-party library
+that might fight your existing migrations.
+
+### Bootstrapping via Alembic
+
+CubePi exposes the SQLAlchemy `MetaData` so your migrations can adopt
+the schema:
+
+```python
+# alembic/env.py
+from cubepi.checkpointer.postgres import cubepi_metadata, EXPECTED_SCHEMA_VERSION
+
+target_metadata = [my_app_metadata, cubepi_metadata]
+```
+
+Then autogenerate a revision:
+
+```bash
+alembic revision --autogenerate -m "add cubepi checkpointer"
+```
+
+Autogenerate emits the `CREATE TABLE`s from `cubepi_metadata`, but
+SQLAlchemy `MetaData` **cannot model two things CubePi needs**, so add
+them to the generated migration by hand: the 64 hash partitions of
+`cubepi_messages` (via `create_message_partitions_op()`) and the
+`cubepi_schema_version` row (via `write_schema_version_op()`). Use the
+helpers:
+
+```python
+# In a migration's upgrade():
+from cubepi.checkpointer.postgres.alembic_helpers import (
+ create_message_partitions_op,
+ write_schema_version_op,
+)
+
+def upgrade():
+ op.create_table(...) # auto-generated from cubepi_metadata
+ op.execute(create_message_partitions_op()) # creates the 64 hash partitions
+ op.execute(write_schema_version_op()) # records EXPECTED_SCHEMA_VERSION
+```
+
+Both helpers return a SQL string — you pass them to `op.execute(...)`.
+`write_schema_version_op()` is idempotent: it deletes any rows from a
+prior CubePi version and inserts the current one.
+
+When CubePi later upgrades and bumps `EXPECTED_SCHEMA_VERSION`, you
+generate a new revision and call `op.execute(write_schema_version_op())`
+again.
+
+## Data model
+
+```
+cubepi_threads
+ thread_id (PK)
+ parent_thread_id -- for forks
+ forked_at_seq -- seq number at fork point
+ extra -- JSONB
+ created_at / updated_at
+
+cubepi_messages
+ thread_id, seq -- composite PK; partitioned by HASH(thread_id) into 64
+ role -- "user" | "assistant" | "tool"
+ metadata -- JSONB (indexed via GIN)
+ payload -- bytea (msgpack)
+ created_at
+
+cubepi_schema_version
+ version (PK)
+```
+
+Important properties:
+
+- **`(thread_id, seq)` is the message identity.** `seq` is monotonic
+ per thread, allocated under a `pg_advisory_xact_lock(hashtext(thread_id))`.
+ Two concurrent writers on the same thread serialize cleanly.
+- **`payload` is msgpack-encoded `model.model_dump(mode="json")`.**
+ CubePi reconstructs the Pydantic model on read.
+- **`metadata` is JSONB, queryable.** The full message also has
+ `metadata` inside the payload, but the column is the canonical view
+ for SQL queries.
+- **Tables are partitioned by `HASH(thread_id)` into 64 partitions.**
+ Even distribution across partitions, no per-thread bottleneck.
+
+## Concurrency
+
+The advisory lock makes append-on-the-same-thread safe across
+processes:
+
+```python
+# Process A and Process B both append to thread "user-42" at the same time.
+# They serialize through pg_advisory_xact_lock and each gets a consecutive seq.
+```
+
+Reads (`load`) take no lock — they're snapshot-consistent within the
+transaction.
+
+The pool default of `min=1, max=10` is fine for most apps; bump
+`max_pool_size` if you have many concurrent agents.
+
+## `save_extra` semantics
+
+`save_extra` does a JSONB merge, not a replace:
+
+```sql
+extra = cubepi_threads.extra || EXCLUDED.extra
+```
+
+So writing `{"foo": 1}` then `{"bar": 2}` leaves `{"foo": 1, "bar":
+2}`. Middleware can safely write partial dicts without losing prior
+keys.
+
+## Forks
+
+The `parent_thread_id` + `forked_at_seq` columns exist for future fork
+support. CubePi v0.3 doesn't expose a fork API yet — they're written
+to so the schema is forward-compatible.
+
+## Common pitfalls
+
+- **`CubepiSchemaUninitialized`** — Your DB is empty or your
+ migrations didn't run. Apply the host alembic upgrade first.
+- **`CubepiSchemaMismatch`** — You upgraded CubePi but didn't generate
+ a new migration. Generate one, apply it, and CubePi will start.
+
+ :::info Schema v2 (HITL)
+
+ CubePi ≥ the HITL feature bumps `EXPECTED_SCHEMA_VERSION` from 1 to 2
+ and adds a `pending_request JSONB NULL` column to `cubepi_threads`.
+ Your host alembic upgrade must call
+ `add_pending_request_column_op()` (from
+ `cubepi.checkpointer.postgres.alembic_helpers`) before bumping the
+ schema_version row. See the [HITL guide](../hitl/overview) for the full
+ cross-process flow.
+ :::
+- **Connection pool exhaustion under load** — Default `max_pool_size=10`.
+ Bump it if your app's concurrent agent count is higher than that.
+- **`asyncpg.exceptions.UndefinedTableError` outside `__aenter__`** —
+ Means you're using the checkpointer outside of `async with`. The
+ pool isn't connected yet. Wrap in the context manager.
+- **Mixing host SQLAlchemy `MetaData`** — CubePi ships its own
+ `MetaData` instance precisely so it can coexist with your app's
+ models without colliding. Don't merge them into your global metadata
+ — pass both to Alembic separately.
+
+## See also
+
+- [SQLite Checkpointing](./sqlite) — single-process alternative.
+- [Custom Backends](./custom) — Protocol details.
+- [Recipes → Postgres + FastAPI Service](../../recipes/postgres-fastapi)
+ — a deployable HTTP-fronted agent.
+- [Package README](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/postgres/README.md)
+ — the full host-integration runbook next to the code.
diff --git a/website/versioned_docs/version-0.6/guides/checkpointing/sqlite.md b/website/versioned_docs/version-0.6/guides/checkpointing/sqlite.md
new file mode 100644
index 0000000..b687d2a
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/checkpointing/sqlite.md
@@ -0,0 +1,191 @@
+---
+title: SQLite Checkpointing
+description: "Use SQLiteCheckpointer for lightweight single-process agent state persistence in CubePi."
+---
+
+# SQLite Checkpointing
+
+`SQLiteCheckpointer` is the lightweight persistence backend: a single
+local file, no server, append-only message log. It's the default
+choice for laptops, single-process apps, desktop tools, and any
+environment where one Python process owns the conversation.
+
+Install the extra:
+
+```bash
+pip install "cubepi[sqlite]"
+```
+
+This pulls in `aiosqlite`.
+
+## Basic usage
+
+```python
+import asyncio
+from cubepi import Agent, Model
+from cubepi.checkpointer import SQLiteCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+async def main():
+ provider = AnthropicProvider(api_key="…")
+ async with SQLiteCheckpointer("agent.db") as cp:
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ checkpointer=cp,
+ thread_id="user-42",
+ )
+ await agent.prompt("Remember: my favourite colour is teal.")
+
+ # Restart the script later — the file persists.
+ await agent.prompt("What did I say my favourite colour was?")
+ # → "You said teal."
+
+
+asyncio.run(main())
+```
+
+Two things to internalise:
+
+1. **`thread_id`** is your conversation identifier — usually a user id
+ or a session id. Two agents on the same `thread_id` share the same
+ history.
+2. **`async with SQLiteCheckpointer(...)`** is required: the context
+ manager opens the connection and runs the one-time table creation
+ on `__aenter__`. Using it without the context manager will raise
+ `AssertionError`.
+
+## What gets persisted
+
+`SQLiteCheckpointer` writes two tables on first use:
+
+```sql
+CREATE TABLE messages (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ thread_id TEXT NOT NULL,
+ message_json TEXT NOT NULL,
+ created_at REAL NOT NULL DEFAULT (julianday('now'))
+);
+
+CREATE TABLE thread_extra (
+ thread_id TEXT PRIMARY KEY,
+ extra_json TEXT NOT NULL DEFAULT '{}'
+);
+```
+
+- Every `UserMessage`, `AssistantMessage`, and `ToolResultMessage`
+ becomes one row in `messages`. Pydantic `model_dump()` is used for
+ the JSON payload.
+- The `extra` dict on `AgentContext` is persisted on `agent_end` into
+ `thread_extra`. Middleware that wants thread-scoped state should
+ write into `context.extra`.
+
+This schema is append-only. CubePi never updates or deletes rows.
+
+## HITL pending table
+
+When the [HITL](../hitl/overview) module is in use, an additional table is
+created automatically on `__aenter__`:
+
+```sql
+CREATE TABLE IF NOT EXISTS thread_pending_request (
+ thread_id TEXT PRIMARY KEY,
+ request_json TEXT NOT NULL,
+ created_at REAL NOT NULL DEFAULT (julianday('now'))
+);
+```
+
+No manual migration is needed — `CREATE TABLE IF NOT EXISTS` is
+idempotent.
+
+## When CubePi reads
+
+On the **first** `prompt()` after instantiation, CubePi calls
+`load(thread_id)`. If the thread exists, history is restored into
+`agent.state.messages` and `extra` is restored into the agent's
+private `_extra` dict.
+
+Subsequent `prompt()` calls don't re-read — the in-memory state is
+authoritative.
+
+This means: **don't share one `Agent` instance across processes**.
+Process A's in-memory state will diverge from Process B's writes.
+
+## Multi-thread isolation
+
+```python
+async with SQLiteCheckpointer("agent.db") as cp:
+ alice = Agent(provider=…, model=…, checkpointer=cp, thread_id="alice")
+ bob = Agent(provider=…, model=…, checkpointer=cp, thread_id="bob")
+ # Each call only loads/appends its own thread.
+```
+
+You can pool one checkpointer across many users; the `thread_id`
+isolates them.
+
+## Concurrency model
+
+The checkpointer uses an `asyncio.Lock` around every read and write.
+SQLite itself can be written from multiple processes, but CubePi's
+expectation is that a single agent instance owns a thread. If you
+have multiple processes writing the same `agent.db`:
+
+- Reads are safe.
+- Concurrent writes to **different** threads are safe.
+- Concurrent writes to the **same** thread will interleave and the
+ resulting history won't make sense — you'll see two assistant
+ messages back-to-back, etc.
+
+If you need multi-process writers on shared threads, jump to
+[Postgres](./postgres) which uses an advisory lock per thread.
+
+## Where the file lives
+
+Use an absolute path in production:
+
+```python
+SQLiteCheckpointer("/var/lib/myapp/agent.db")
+```
+
+Relative paths resolve against `os.getcwd()` at the moment of
+`__aenter__`. The directory must exist; create it ahead of time.
+
+## Backup and inspection
+
+The file is a normal SQLite database. You can:
+
+```bash
+# Inspect history for a thread
+sqlite3 agent.db "SELECT message_json FROM messages WHERE thread_id='user-42' ORDER BY id"
+
+# Back up
+cp agent.db agent.db.bak
+
+# Vacuum to reclaim space (optional — file grows linearly with history)
+sqlite3 agent.db "VACUUM"
+```
+
+## Common pitfalls
+
+- **Used without `async with`** — `AssertionError: self._db is not
+ None`. Always wrap in `async with`.
+- **Two processes writing the same thread** — Interleaved history.
+ Use Postgres or coordinate at the application layer.
+- **WAL mode not enabled** — CubePi uses the default journal mode for
+ portability. For a single-writer, many-reader app, enable WAL once
+ via `sqlite3 agent.db "PRAGMA journal_mode=WAL"` for better read
+ concurrency.
+- **Forgetting to set `thread_id`** — Without it, the agent has no
+ persistence binding. The checkpointer is silently ignored. Always
+ pass both.
+
+## See also
+
+- [Postgres Checkpointing](./postgres) — for multi-instance deployments.
+- [Custom Backends](./custom) — implement the protocol for Redis,
+ DynamoDB, etc.
+- [Recipes → Persistent Chat](../../recipes/persistent-chat) —
+ end-to-end app with SQLite.
+- [Recipes → Resumable Long Tasks](../../recipes/resumable-tasks) —
+ agents that survive a process restart mid-tool.
diff --git a/website/versioned_docs/version-0.6/guides/hitl/durable.md b/website/versioned_docs/version-0.6/guides/hitl/durable.md
new file mode 100644
index 0000000..47da37a
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/hitl/durable.md
@@ -0,0 +1,119 @@
+---
+title: Cross-process & durability
+sidebar_position: 3
+description: "Suspend a CubePi agent on a HITL request and resume it in another process with a CheckpointedChannel; durable-scope rules."
+---
+
+# Cross-process flow & durability
+
+## Cross-process (web service) flow
+
+Full lifecycle of a suspend/resume cycle:
+
+```python
+import asyncio
+from cubepi.agent.agent import Agent
+from cubepi.checkpointer.postgres import PostgresCheckpointer
+from cubepi.hitl import (
+ ApproveAnswer, CheckpointedChannel, ConfirmToolCallMiddleware,
+)
+
+# ---------- Process 1: HTTP POST /chat ----------
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=..., model=...,
+ tools=[bash_tool],
+ middleware=[
+ ConfirmToolCallMiddleware(channel, require_confirm={"bash"}),
+ ],
+ channel=channel,
+ checkpointer=cp,
+ thread_id="conv-42",
+ )
+
+ # prompt() blocks until the HITL request is answered OR the host
+ # calls detach(). Same-process host coroutines can answer directly
+ # via channel.answer(); cross-process hosts use respond().
+ task = asyncio.create_task(agent.prompt("delete temp files"))
+
+ # Poll for pending (or subscribe to channel for SSE push)
+ for _ in range(1000):
+ pending = channel.pending
+ if pending is not None:
+ break
+ await asyncio.sleep(0.1)
+
+ assert pending is not None
+ # Render pending.payload to the frontend (an ApproveRequest:
+ # tool_name="bash", args={"cmd":"rm /tmp/foo"}, ...)
+
+ # Graceful suspend — persist the assistant message + unresolved
+ # tool_calls, keep pending_request in DB, emit AgentSuspendedEvent.
+ # The HTTP handler returns 200 { status: "awaiting_approval" }.
+ await agent.detach()
+ await task # prompt() unwinds with HitlDetached
+
+
+# ---------- Process 2: HTTP POST /respond ----------
+
+async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="conv-42")
+
+ agent = Agent(
+ provider=..., model=...,
+ tools=[bash_tool],
+ middleware=[
+ ConfirmToolCallMiddleware(channel, require_confirm={"bash"}),
+ ],
+ channel=channel,
+ checkpointer=cp,
+ thread_id="conv-42",
+ )
+
+ # Loads the persisted history + pending, validates the question_id
+ # matches, attaches the answer to the channel, re-enters the loop
+ # where the last assistant message had unresolved tool calls.
+ await agent.respond(
+ question_id=request.json["call_id"],
+ answer=ApproveAnswer(decision="approve"),
+ )
+ # The bash tool executes, the model receives the tool_result and
+ # produces the next assistant turn. Conversation continues normally.
+```
+
+**If the user closes the tab without answering:**
+
+```python
+await agent.abort_pending(reason="user closed tab")
+# Phase 1: signals the in-flight HITL await (if any) to raise HitlAborted.
+# Phase 2: appends synthetic deny ToolResultMessage(s) for unresolved
+# tool_calls, appends a terminal AssistantMessage(stop_reason="aborted"),
+# clears persisted pending, emits AgentAbortedEvent.
+# No model call is made. The conversation is closed.
+```
+
+
+## Durable scope
+
+Durable cross-process resume (survives process death) is supported at two
+well-defined safe suspension points:
+
+1. **`before_tool_call` approval gate** — the approval middleware calls
+ `channel.approve(...)` *before* the tool's `execute()` body runs. No tool
+ side effects exist yet. Resume re-enters the loop and either runs the
+ (possibly edited) tool body or substitutes a synthetic deny tool_result.
+2. **`ask_user` tool body** — whose entire `execute()` body is
+ `return await channel.ask(...)`. Resume replays nothing because nothing
+ else happened.
+
+**Custom tools that mix HITL with other work inside `execute()` are NOT
+durable cross-process by default.** If such a tool's process dies mid-execute,
+anything that ran before the channel call would be lost. CubePi will raise
+`HitlDurabilityNotGuaranteed` unless the `CheckpointedChannel` is constructed
+with `allow_inside_custom_tool=True` — the caller must acknowledge the
+idempotency contract (the tool body must be a pure HITL wait with no
+preceding observable side effects).
+
diff --git a/website/versioned_docs/version-0.6/guides/hitl/middlewares.md b/website/versioned_docs/version-0.6/guides/hitl/middlewares.md
new file mode 100644
index 0000000..1184c41
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/hitl/middlewares.md
@@ -0,0 +1,124 @@
+---
+title: Middlewares & ask_user
+sidebar_position: 2
+description: "Gate tool calls with ConfirmToolCallMiddleware / ApprovalPolicyMiddleware, and let the model ask structured questions with the ask_user tool."
+---
+
+# Middlewares & the `ask_user` tool
+
+## Built-in middlewares
+
+### `ConfirmToolCallMiddleware`
+
+"Always ask the human for tool *names* in this set."
+
+```python
+from cubepi.hitl import ConfirmToolCallMiddleware
+
+# Set-based matching — only ask for these tool names
+agent = Agent(
+ ...,
+ middleware=[
+ ConfirmToolCallMiddleware(
+ channel,
+ require_confirm={"bash", "write_file", "http_post"},
+ timeout_seconds=180,
+ ),
+ ],
+)
+```
+
+`require_confirm` options:
+
+| Value | Behavior |
+|---|---|
+| `None` (default) | Confirm **every** tool. |
+| `set[str]` | Confirm if `tool_call.name` is in the set. |
+| `Callable[[BeforeToolCallContext], bool]` | Custom predicate — inspect args, context, etc. |
+
+An optional `details_fn(ctx: BeforeToolCallContext) -> dict` enriches the
+approve request payload with extra context the frontend can render (e.g.
+matched rule name, impact preview, affected file list).
+
+### `ApprovalPolicyMiddleware`
+
+For hosts with a **policy engine** that classifies tool calls into three
+tiers — auto-allow, hard-deny, or human-confirm.
+
+```python
+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
+
+def my_policy(ctx):
+ if ctx.tool_call.name == "read_file":
+ return Approve() # passthrough
+ if ctx.tool_call.name.startswith("dangerous_"):
+ return Deny(reason="blocked by policy") # hard block, no human asked
+ return AskUser(timeout_seconds=180) # human confirm
+
+agent = Agent(
+ ...,
+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
+)
+```
+
+The policy function can be sync or async (`await`-able). It returns one of:
+
+| Return | Effect |
+|---|---|
+| `Approve()` | Tool runs; channel never invoked. |
+| `Deny(reason)` | Tool blocked; `hitl_trace["decision"]="policy_deny"`. |
+| `AskUser(timeout_seconds=..., details=...)` | Channel invoked; human chooses approve/deny/edit. |
+
+Policy-deny and human-deny produce different `hitl_trace` keys (`policy_deny`
+vs `human_deny`) so audit and trace can distinguish them.
+
+## `ask_user` built-in tool
+
+A tool the **model** invokes when it needs structured input from the user.
+The factory returns an `AgentTool` named `"ask_user"` with
+`execution_mode="sequential"` — it can't run in parallel with other tools.
+
+```python
+from cubepi.hitl import ask_user_tool
+
+agent = Agent(
+ ...,
+ tools=[bash_tool, ask_user_tool(channel)],
+)
+```
+
+The tool description explicitly steers the model away from using `ask_user`
+for free-form clarification ("for free-form questions, end your turn with
+text — the user's next message is your answer"). The model should only
+invoke it when a **structured** answer is needed.
+
+The `Parameters` prompt schema the model sees:
+
+| Field | Type | Description |
+|---|---|---|
+| `questions` | array | One or more question objects. |
+| `questions[].key` | string | Field name in the answer dict. |
+| `questions[].prompt` | string | The question text. |
+| `questions[].options` | array (optional) | Selection options. `None` = free text. |
+| `questions[].options[].label` | string | Human-facing label. |
+| `questions[].options[].value` | string | Value returned to agent. |
+| `questions[].options[].allow_input` | bool (default `false`) | "Other / please specify." |
+| `questions[].multi_select` | bool (default `false`) | Allow multiple selections. |
+| `questions[].required` | bool (default `true`) | Can the user skip this? |
+
+Cancel and timeout are surfaced as `tool_result.is_error=True` with
+`details["hitl"]["outcome"]="cancelled"` / `"timed_out"` — the model sees
+a clean error tool result and can react. Other HITL control exceptions
+(HitlDetached, HitlAborted) propagate to the Agent layer, not the model.
+
+
+## When to use `ask_user` vs end of turn
+
+| Goal | Use |
+|---|---|
+| Free-text follow-up question to user | Just end the turn with the question as text; the user's next message is your answer. |
+| Structured selection (one of N) | `ask_user` tool with `options`. |
+| Multi-select ("pick any of") | `ask_user` tool with `multi_select=True`. |
+| "Other" with free-text input | `ask_user` tool option with `allow_input=True`. |
+| Confirm/edit tool args before run | `ConfirmToolCallMiddleware` or `ApprovalPolicyMiddleware`. |
+
diff --git a/website/versioned_docs/version-0.6/guides/hitl/overview.md b/website/versioned_docs/version-0.6/guides/hitl/overview.md
new file mode 100644
index 0000000..35d95c2
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/hitl/overview.md
@@ -0,0 +1,171 @@
+---
+title: Overview
+sidebar_position: 1
+description: "CubePi human-in-the-loop: the channel, the three verbs (confirm, approve, ask), and timeouts."
+---
+
+# Human-in-the-Loop (HITL)
+
+CubePi's HITL channel lets an agent **pause and ask a human** before proceeding.
+It handles two recurring patterns with a single primitive:
+
+1. **Sandbox tool confirmation** — a dangerous tool (bash, file writes, API
+ mutations) needs approve / deny / edit from a human before running.
+2. **Mid-run structured questions** — the agent needs a specific selection or
+ form answer from the user before it can continue.
+
+The channel is an `await`-able coroutine collaborator. Tool authors write
+`await channel.ask(...)` and the channel handles the pause. Host code
+(subscribers) renders the pending request and posts an answer. Two backends
+cover the full spectrum:
+
+- `InMemoryChannel` — CLI, notebooks, tests. Process dies, pending is lost.
+- `CheckpointedChannel` — web services. Persists the pending request to a
+ `Checkpointer` so a different process (or the same process after restart)
+ can pick up and answer hours later.
+
+## Architecture
+
+```text
+┌────────────────────────────────────────────────────────┐
+│ Host (cubebox web service / CLI / TUI) │
+│ │
+│ subscribe to channel.pending ◄──── answer / cancel │
+└──────────────────────┬─────────────────────────────────┘
+ │
+ ┌─────────────▼──────────────┐
+ │ HitlChannel (Protocol) │
+ │ confirm / approve / ask │
+ │ pending / answer / cancel │
+ └──────┬──────────────┬──────┘
+ │ │
+ ┌──────────▼───┐ ┌──────▼────────────┐
+ │InMemoryChannel│ │CheckpointedChannel│
+ │ (Future+Queue)│ │ (Future + persi- │
+ │ │ │ sts to Checkpo- │
+ │ │ │ inter) │
+ └───────────────┘ └───────────────────┘
+ │ │
+ │ used by ────┤
+ │ │
+ ┌──────────▼──────────────▼────────────┐
+ │ ask_user tool ConfirmToolCallMW │
+ │ (structured form) (approve/deny/ │
+ │ edit per-tool) │
+ └──────────────────────────────────────┘
+ │
+ ┌─────────────▼──────────────┐
+ │ cubepi Agent loop │
+ │ (BeforeToolCallResult │
+ │ carries hitl_trace) │
+ └────────────────────────────┘
+```
+
+## Channel types
+
+### `InMemoryChannel`
+
+For single-process use. Holds an `asyncio.Future` internally — the host
+calls `channel.answer()` from the same event loop.
+
+```python
+from cubepi.hitl import InMemoryChannel
+
+channel = InMemoryChannel(
+ default_timeout=180.0, # per-call timeout; None = no timeout (default)
+)
+```
+
+### `CheckpointedChannel`
+
+For cross-process use. On every `confirm / approve / ask`, the `HitlRequest`
+is persisted via `Checkpointer.save_pending_request(thread_id, ...)`. On
+`channel.answer()`, the pending is cleared. On `HitlDetached` (graceful
+suspend), the pending stays so a later `Agent.respond()` can resume.
+
+```python
+from cubepi.hitl import CheckpointedChannel
+from cubepi.checkpointer.sqlite import SQLiteCheckpointer # or postgres / mysql
+
+async with SQLiteCheckpointer("path/to.db") as cp:
+ channel = CheckpointedChannel(
+ checkpointer=cp,
+ thread_id="conversation-42",
+ default_timeout=None, # cross-process: typical to disable
+ allow_inside_custom_tool=False, # safety gate (see Cross-process & durability)
+ )
+```
+
+`CheckpointedChannel.__init__` validates the checkpointer implements
+`save_pending_request` and `load_pending_request` — it fails early with
+`HitlError` if not.
+
+## The three verbs
+
+### `confirm(prompt, *, details, timeout, signal) → bool`
+
+A simple yes/no question. The host answers `True` or `False`.
+
+```python
+if await channel.confirm("Deploy to production?", details={"env": "prod"}):
+ await deploy()
+```
+
+### `approve(tool_name, tool_call_id, args, *, details, timeout, signal) → ApproveAnswer`
+
+The sandbox-confirm verb. Returns an `ApproveAnswer` with one of three decisions:
+
+| Decision | Result |
+|---|---|
+| `"approve"` | Tool runs with the original args. |
+| `"deny"` | Tool is blocked; `tool_result.is_error=True` with `details["hitl"]["decision"]="human_deny"`. |
+| `"edit"` | Tool runs with the edited args (re-validated against the tool's pydantic parameter model). |
+
+For `approve` requests, the envelope's `question_id` is set to the LLM's
+`tool_call_id` — no separate UUID, so host code can correlate by the same
+ID it already tracks from the tool stream.
+
+### `ask(questions, *, timeout, signal) → dict[str, str | list[str]]`
+
+A structured form with one or more `Question` objects. Each question can be:
+
+- **Free-text** (`options=None`)
+- **Single-select** (`options=[...]`, `multi_select=False`)
+- **Multi-select** (`options=[...]`, `multi_select=True`)
+- **"Other" with input** (option has `allow_input=True` — user types free text)
+
+```python
+from cubepi.hitl.types import Question, Option
+
+answers = await channel.ask([
+ Question(key="framework", prompt="Which framework?", options=[
+ Option(label="React", value="react"),
+ Option(label="Vue", value="vue"),
+ Option(label="Other", value="other", allow_input=True),
+ ]),
+ Question(key="features", prompt="Enable:", multi_select=True, options=[
+ Option(label="Auth", value="auth"),
+ Option(label="Payments", value="payments"),
+ ]),
+])
+# answers == {"framework": "react", "features": ["auth", "payments"]}
+```
+
+## Timeout
+
+Both channels accept a `default_timeout` constructor arg and every verb
+accepts a per-call `timeout` kwarg (per-call overrides default).
+
+| Layer | API |
+|---|---|
+| Channel constructor | `InMemoryChannel(default_timeout=30.0)` |
+| Per-call override | `channel.confirm("ok?", timeout=10.0)` |
+| Per-call off | `channel.approve(..., timeout=None)` when channel default is set |
+
+Timeout expiry raises `HitlTimedOut(BaseException)` from the agent-side
+`await`. The surrounding tool or middleware translates it to
+`tool_result.is_error=True` with `details["hitl"]["decision"]="timed_out"`,
+so the model sees a clean denial and can react naturally. The envelope's
+`HitlRequest.timeout_seconds` is filled automatically so the frontend can
+render a countdown.
+
diff --git a/website/versioned_docs/version-0.6/guides/hitl/reference.md b/website/versioned_docs/version-0.6/guides/hitl/reference.md
new file mode 100644
index 0000000..345a0fb
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/hitl/reference.md
@@ -0,0 +1,132 @@
+---
+title: API, events & reference
+sidebar_position: 4
+description: "CubePi HITL reference: Agent API, events, trace spans, error reference, testing helpers, and architecture notes."
+---
+
+# API, events & reference
+
+## Agent API
+
+### Constructor
+
+```python
+Agent(
+ ...,
+ channel: HitlChannel | None = None, # bind a channel to this agent
+)
+```
+
+If a channel is bound, the Agent wires its `_process_event` as the channel's
+emit callback so `HitlRequestEvent` / `HitlAnswerEvent` are dispatched to all
+agent listeners. A `_run_lock` (`asyncio.Lock`) serialises `prompt`,
+`resume`, and `respond` calls.
+
+### Properties
+
+| Property | Returns | Description |
+|---|---|---|
+| `agent.channel` | `HitlChannel \| None` | The bound channel or `None`. |
+| `agent.in_flight_hitl_request` | `HitlRequest \| None` | The channel's current pending payload. Raises `HitlError` if no channel bound. |
+
+### Methods
+
+| Method | Signature | Description |
+|---|---|---|
+| `load_pending_hitl_request()` | `async → HitlRequest \| None` | Reads the pending from the checkpointer (even post-detach). |
+| `detach()` | `async → None` | Emits `AgentSuspendedEvent(pending_request=...)` then triggers `HitlDetached` on the channel future. The loop exits silently; assistant message retains unresolved tool calls; `pending_request` stays persisted. |
+| `respond(*, question_id=, answer=)` | `async → None` | Resumes a suspended run. Validates qid matches persistent pending, attaches answer to channel, re-enters the loop via `run_agent_loop_resume`. |
+| `abort_pending(reason=)` | `async → None` | Closes the conversation. Two-phase: Phase 1 signals in-flight await (no lock). Phase 2 appends synthetic deny tool_results + terminal `stop_reason="aborted"` assistant (under lock). |
+
+`in_flight_hitl_request` is a synchronous property (reads the in-memory
+channel slot). `load_pending_hitl_request()` is async (reads from the
+checkpointer; useful post-detach or in a fresh process).
+
+## Events
+
+Four new events are emitted on the agent's event stream:
+
+| Event | When | Key fields |
+|---|---|---|
+| `HitlRequestEvent` | Channel receives a new `confirm/approve/ask`. | `request: HitlRequest` |
+| `HitlAnswerEvent` | `channel.answer()` or `channel.cancel()` fires. | `question_id: str`, `answer: Any`, `cancelled: bool`, `timed_out: bool` |
+| `AgentSuspendedEvent` | `agent.detach()` called while HITL was pending. | `pending_request: HitlRequest` |
+| `AgentAbortedEvent` | `agent.abort_pending()` closes the conversation. | `reason: str` |
+
+These are all included in the `AgentEvent` union, so typed listeners
+automatically cover them. `HitlRequestEvent` and `HitlAnswerEvent` are
+emitted by the channel through the agent's emit binding. `AgentSuspendedEvent`
+and `AgentAbortedEvent` are emitted by the Agent layer (not the loop — the
+Agent has the channel handle to populate the real `pending_request` payload).
+
+## Trace spans
+
+When the `cubepi[tracing]` extra is installed, each HITL await is wrapped
+in an OpenTelemetry span:
+
+| Span name | Attributes |
+|---|---|
+| `hitl.approve` | `hitl.tool_name`, `hitl.tool_call_id`, `hitl.outcome`, `hitl.from_resume`, `hitl.duration_seconds` |
+| `hitl.confirm` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+| `hitl.ask` | `hitl.question_id`, `hitl.outcome`, `hitl.duration_seconds` |
+
+`hitl.outcome` is one of: `approved`, `denied`, `edited`, `answered`,
+`cancelled`, `timed_out`, `aborted`, `detached`.
+
+The tracing import is lazy — if `opentelemetry` is not installed, the
+channel silently falls back to a no-op span.
+
+## Error reference
+
+| Exception | Base class | Meaning |
+|---|---|---|
+| `HitlCancelled(reason)` | `BaseException` | Host called `channel.cancel(qid)`. |
+| `HitlTimedOut(seconds)` | `BaseException` | Per-call or channel-default timeout expired. |
+| `HitlDetached` | `BaseException` | `agent.detach()` called during HITL await. |
+| `HitlAborted` | `BaseException` | `agent.abort_pending()` signalled the agent. |
+| `HitlConcurrencyError` | `Exception` | `confirm/approve/ask` called while channel already has a pending request. |
+| `HitlStaleAnswer` | `Exception` | `channel.answer(qid)` with a `question_id` that doesn't match the current pending. |
+| `HitlNoPendingRequest` | `Exception` | `agent.respond(…)` called but no `pending_request` on the thread. |
+| `HitlDurabilityNotGuaranteed` | `Exception` | Custom tool called `CheckpointedChannel.ask()` without `allow_inside_custom_tool=True`. |
+
+`HitlControlException` (the parent of the four `BaseException` subclasses)
+is intentionally NOT caught by the existing broad `except Exception:` handlers
+in `cubepi.agent.tools._prepare_tool_call` and `_execute_prepared` — this
+mirrors `asyncio.CancelledError`'s pattern.
+
+
+## Testing helpers
+
+```python
+from cubepi.hitl.testing import ScriptedChannel, NoopChannel
+
+# ScriptedChannel: pre-programmed answers, consumed in order.
+ch = ScriptedChannel(answers=[
+ ApproveAnswer(decision="approve"),
+ {"color": "red"}, # ask answer
+ lambda req: ApproveAnswer(decision="deny", reason="test") # callable
+])
+assert len(ch.history) == 3 # all HitlRequests ever seen
+
+# NoopChannel: auto-approves everything. Useful for subagents.
+ch = NoopChannel()
+assert (await ch.approve("bash", "tc", {})).decision == "approve"
+assert (await ch.confirm("?")) is True
+assert await ch.ask([Question(key="k", prompt="p")]) == {"k": ""}
+```
+
+## Architecture notes
+
+- **Single pending per thread.** The agent loop is sequential — at most one
+ HITL request is outstanding per `thread_id`. Concurrent `confirm/approve/ask`
+ raises `HitlConcurrencyError`.
+- **Prompt-cache prefix invariant.** Between pause and resume, the messages
+ list changes only by appending tool-result messages and the next assistant
+ turn at the tail. No inserting, reordering, or mutating prior messages —
+ that would invalidate the provider-side prompt cache.
+- **`question_id == tool_call_id` for approve requests.** No aliasing or
+ mapping needed — hosts that already track `call_id` from the tool stream
+ pass it directly.
+- **Resume does not replay.** It re-enters the loop with the answer pre-loaded
+ into the channel. The last assistant message's unresolved tool calls dictate
+ what executes next. No node-based replay semantics.
diff --git a/website/versioned_docs/version-0.6/guides/mcp/auth.md b/website/versioned_docs/version-0.6/guides/mcp/auth.md
new file mode 100644
index 0000000..d40ecd5
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/mcp/auth.md
@@ -0,0 +1,213 @@
+---
+title: MCP Server Authentication
+description: "Configure authentication — API keys, OAuth, and custom headers — for MCP servers in CubePi."
+---
+
+# MCP Server Authentication
+
+The MCP transport layer doesn't dictate an auth scheme — servers
+decide. In practice, three patterns cover almost every case:
+
+1. **Bearer token in `Authorization` header** (HTTP transport).
+2. **Arbitrary custom headers** (HTTP transport).
+3. **Environment variables** (stdio transport — server reads them
+ from its own process env).
+
+This page walks through each.
+
+## HTTP: bearer tokens
+
+The dominant pattern for hosted MCP servers (GitHub, Sentry,
+internal). Pass an `Authorization` header to `load_mcp_tools_http`:
+
+```python
+import os
+from cubepi.mcp import load_mcp_tools_http
+
+tools = await load_mcp_tools_http(
+ server_url="https://mcp.example.com/sse",
+ headers={"Authorization": f"Bearer {os.environ['MCP_TOKEN']}"},
+)
+```
+
+`headers` is forwarded to *every* request the transport makes,
+including subsequent `tools/call` invocations. There's no separate
+"login then call" step — the token rides every connection.
+
+## HTTP: custom headers
+
+Some servers use API-key headers instead:
+
+```python
+tools = await load_mcp_tools_http(
+ server_url="https://mcp.internal/sse",
+ headers={
+ "X-API-Key": os.environ["MCP_API_KEY"],
+ "X-Tenant-Id": "acme-corp",
+ },
+)
+```
+
+Combine as needed:
+
+```python
+headers = {
+ "Authorization": f"Bearer {token}",
+ "X-Trace-Id": str(uuid.uuid4()),
+}
+```
+
+## HTTP: short-lived tokens / refresh
+
+CubePi's loaders take a static `headers` dict at load time. For tokens
+that expire (OAuth, JWT with short TTL), you have two options:
+
+### Option A — Re-load on expiry
+
+Catch the error, re-fetch the token, re-load the tools:
+
+```python
+async def load_with_fresh_token():
+ token = await fetch_token()
+ return await load_mcp_tools_http(
+ server_url="…",
+ headers={"Authorization": f"Bearer {token}"},
+ )
+
+tools = await load_with_fresh_token()
+```
+
+Practical for tokens that live longer than a single agent run.
+
+### Option B — Wrap and refresh inside the tool
+
+Build the `AgentTool` yourself with a closure that knows how to
+refresh:
+
+```python
+from cubepi.mcp._adapter import make_mcp_agent_tool
+from cubepi.mcp import load_mcp_tools_http
+
+async def call_remote_with_refresh(tool_name, args):
+ headers = {"Authorization": f"Bearer {await fetch_token()}"}
+ # Re-implement the http_loader's call_remote with fresh headers each time
+ from mcp.client.sse import sse_client
+ from mcp import ClientSession
+ async with sse_client(server_url, headers=headers, timeout=30) as streams:
+ async with ClientSession(*streams) as session:
+ await session.initialize()
+ resp = await session.call_tool(tool_name, args)
+ return _serialize_call_tool_response(resp)
+
+# Use the adapter directly:
+my_tool = make_mcp_agent_tool(
+ name="…",
+ description="…",
+ input_schema={…},
+ call_remote=call_remote_with_refresh,
+)
+```
+
+Only worth it for tokens with very short TTLs. For anything longer,
+Option A is simpler.
+
+## stdio: environment variables
+
+stdio servers read credentials from their own process environment.
+Pass an `env` dict:
+
+```python
+import os
+from cubepi.mcp import load_mcp_tools_stdio
+
+tools = await load_mcp_tools_stdio(
+ command="npx",
+ args=["-y", "@modelcontextprotocol/server-github"],
+ env={
+ "GITHUB_PERSONAL_ACCESS_TOKEN": os.environ["GH_TOKEN"],
+ **os.environ, # inherit the rest
+ },
+)
+```
+
+If you omit `env`, the subprocess inherits **all** parent env vars
+(standard subprocess behaviour). For a clean slate, pass an explicit
+dict:
+
+```python
+env = {
+ "PATH": os.environ["PATH"],
+ "HOME": os.environ["HOME"],
+ "GITHUB_PERSONAL_ACCESS_TOKEN": token,
+}
+```
+
+## stdio: file-based credentials
+
+When a server reads credentials from `~/.config/...`, pass `cwd` to
+ensure consistent path resolution, and rely on the inherited
+environment:
+
+```python
+tools = await load_mcp_tools_stdio(
+ command="/usr/local/bin/my-mcp",
+ args=["--config", "config.yaml"],
+ cwd="/etc/myapp",
+)
+```
+
+## Per-user / per-tenant credentials
+
+In a multi-tenant service, each agent invocation needs different
+credentials. **Load tools per-request**:
+
+```python
+async def build_agent_for_user(user_id: str) -> Agent:
+ token = await fetch_user_token(user_id)
+ tools = await load_mcp_tools_http(
+ server_url="https://mcp.example.com/sse",
+ headers={"Authorization": f"Bearer {token}"},
+ )
+ return Agent(provider=provider, model=model, tools=tools)
+```
+
+Don't cache a single `tools` list across users — the closures retain
+the auth headers from load time.
+
+## Auditing / observability
+
+Log MCP calls inside a [`before_tool_call`](../middleware/hooks#before_tool_call)
+middleware. Tools loaded from MCP look identical to hand-written
+tools in event streams, so existing logging middleware Just Works.
+
+To tag MCP tools specifically, check for the synthesised parameter
+model's name (prefix `MCP_`):
+
+```python
+class MCPAuditMiddleware(Middleware):
+ async def before_tool_call(self, ctx, *, signal=None):
+ param_name = type(ctx.args).__name__
+ if param_name.startswith("MCP_"):
+ log.info("mcp_call", extra={"tool": ctx.tool_call.name})
+ return None
+```
+
+## Common pitfalls
+
+- **`401 Unauthorized` only on call, not on `list_tools`** — Some
+ servers gate per-tool. Ensure the token has scopes for every tool
+ you intend the agent to use.
+- **Tokens leaking into logs** — Don't log the `headers` dict.
+ Especially watch out for exception messages that include URLs with
+ query-string credentials.
+- **stdio server fails silently** — Server prints auth errors to its
+ own stderr. Add `stdout`/`stderr` redirection or use the MCP SDK's
+ diagnostic logging.
+- **Re-loading every request is slow** — Cache the loaded tools per
+ `(user_id, token)` pair. Just remember tokens have TTLs.
+
+## See also
+
+- [Loading MCP Tools](./loading) — the basic loader API.
+- [Middleware → Examples → Logging](../middleware/examples#structured-logging)
+ — pairs naturally with MCP audit needs.
diff --git a/website/versioned_docs/version-0.6/guides/mcp/loading.md b/website/versioned_docs/version-0.6/guides/mcp/loading.md
new file mode 100644
index 0000000..93e1646
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/mcp/loading.md
@@ -0,0 +1,170 @@
+---
+title: Loading MCP Tools
+description: "Load tools from MCP servers into your CubePi agent, including SSE-based remote servers."
+---
+
+# Loading MCP Tools
+
+The [Model Context Protocol](https://modelcontextprotocol.io) defines
+a standard way for tool servers to expose capabilities to agents.
+CubePi ships two loaders that connect to an MCP server, enumerate its
+tools, and turn each one into a regular `AgentTool` you can hand to
+`Agent(tools=…)`.
+
+Install the extra:
+
+```bash
+pip install "cubepi[mcp]"
+```
+
+This pulls in the `mcp` SDK.
+
+## stdio transport: local subprocess
+
+For tools that run as a local process (e.g. npm-published servers, a
+Python module, an internal CLI):
+
+```python
+import asyncio
+import sys
+from cubepi import Agent, Model
+from cubepi.mcp import load_mcp_tools_stdio
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+async def main():
+ # Spawn a stdio MCP server and discover its tools.
+ tools = await load_mcp_tools_stdio(
+ command="npx",
+ args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp/sandbox"],
+ timeout=30.0,
+ )
+
+ agent = Agent(
+ provider=AnthropicProvider(api_key="…"),
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ tools=tools, # all server tools, ready to use
+ )
+ agent.subscribe(lambda e, s=None: None)
+ await agent.prompt("List files in /tmp/sandbox.")
+
+
+asyncio.run(main())
+```
+
+`load_mcp_tools_stdio` connects, calls `list_tools`, disconnects, and
+returns the `AgentTool` list. **Each tool call spawns a fresh
+subprocess** — v0.3 keeps things simple, no process pool.
+
+Arguments:
+
+| Parameter | Purpose |
+|---|---|
+| `command` | The executable (e.g. `"npx"`, `sys.executable`, `/usr/bin/uvx`) |
+| `args` | argv for the server |
+| `env` | Environment variables (optional) |
+| `cwd` | Working directory (optional) |
+| `timeout` | Per-call wall-clock timeout for `initialize` / `list` / `call` |
+
+## HTTP/SSE transport: remote server
+
+For hosted MCP servers (Sentry, GitHub, internal services):
+
+```python
+from cubepi.mcp import load_mcp_tools_http
+
+tools = await load_mcp_tools_http(
+ server_url="https://mcp.example.com/sse",
+ headers={"Authorization": "Bearer <token>"},
+ timeout=30.0,
+)
+```
+
+`load_mcp_tools_http` uses the MCP SDK's SSE client. Same model as
+stdio: one connection to enumerate, then a fresh connection per tool
+call.
+
+See [MCP Auth](./auth) for the auth patterns you'll likely need with
+HTTP servers.
+
+## What you get back
+
+Each entry in the returned list is an `AgentTool`:
+
+- `name` — the MCP tool name.
+- `description` — straight from the server (no rewrites).
+- `parameters` — a Pydantic model synthesised from the MCP
+ `inputSchema` (JSON Schema → Pydantic via `pydantic.create_model`).
+- `execute` — closure that calls `tools/call` over the same transport.
+
+The synthesised Pydantic model covers: `string`, `integer`, `number`,
+`boolean`, `array`, `object` (as `dict[str, Any]`), and enum (via
+`Literal`). Top-level constraints are preserved: `description`,
+`pattern`, `minLength`/`maxLength`, `minimum`/`maximum` (incl.
+exclusive variants), `minItems`/`maxItems`.
+
+## Mixing MCP tools with hand-written tools
+
+They're the same type. Just concatenate the lists:
+
+```python
+mcp_tools = await load_mcp_tools_stdio(command="…", args=[…])
+my_tools = [weather_tool, search_tool]
+
+agent = Agent(
+ provider=provider,
+ model=model,
+ tools=my_tools + mcp_tools,
+)
+```
+
+The model sees one combined JSON Schema; the loop dispatches each
+call to the right implementation.
+
+## Per-call vs reusable connections
+
+CubePi opens a new transport per `execute` call. That's:
+
+- ✅ Simple — no pool lifecycle to manage.
+- ✅ Robust — a hung connection can't poison other tools.
+- ⚠️ Slower for stdio servers with heavy startup (a `npx` server can
+ add seconds per call).
+
+For high-throughput stdio servers, run the server as a persistent
+HTTP service instead and use `load_mcp_tools_http`.
+
+## Image and structured content
+
+If an MCP tool returns image content blocks, CubePi maps them to
+`ImageContent` and includes them in the `AgentToolResult.content`.
+Anthropic provider relays these as image blocks in tool results;
+OpenAI providers currently strip them (the wire format doesn't
+support image-bearing tool results).
+
+If the server returns `structuredContent`, it's exposed under
+`AgentToolResult.details["structuredContent"]` — useful for
+downstream programmatic access, but not shown to the model.
+
+## Common pitfalls
+
+- **`asyncio.TimeoutError` immediately on first call** — Server didn't
+ finish `initialize` within `timeout`. Bump `timeout=60` or higher;
+ some servers do heavy setup.
+- **Each tool call is slow** — stdio subprocess spawn overhead. Run
+ the server as HTTP, or write a custom adapter that keeps the
+ subprocess alive.
+- **Tools missing from the list** — Server failed to advertise them.
+ Run the server in isolation and call `list_tools` manually with the
+ MCP CLI to inspect.
+- **Pydantic validation rejects model output** — The MCP `inputSchema`
+ has constraints the model isn't honouring. Either loosen the schema
+ on the server side or add a `before_tool_call` middleware that
+ coerces.
+
+## See also
+
+- [MCP Auth](./auth) — bearer tokens, headers, env-based credentials.
+- [Tool Use](../agents/tool-use) — how tools (MCP or otherwise) are
+ dispatched.
+- [`make_mcp_agent_tool` source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/mcp/_adapter.py)
+ — the schema → Pydantic adapter, if you need to customise.
diff --git a/website/versioned_docs/version-0.6/guides/middleware/composition.md b/website/versioned_docs/version-0.6/guides/middleware/composition.md
new file mode 100644
index 0000000..b5315be
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/middleware/composition.md
@@ -0,0 +1,176 @@
+---
+title: Composition Rules
+description: "Learn how CubePi composes multiple middlewares with per-hook rules: chain, last-wins, first-block-stops, and more."
+---
+
+# Composition Rules
+
+When you pass multiple middlewares — `Agent(middleware=[m1, m2,
+m3])` — CubePi composes them according to **per-hook rules** that
+differ on purpose. The right way to think about it is: each hook has
+the composition rule that makes sense for its job, and you don't have
+to remember "before" or "after" precedence guesses.
+
+## The rules at a glance
+
+| Hook | Rule | Order matters? |
+|---|---|---|
+| `transform_context` | **Chain** — each sees previous output | Yes |
+| `convert_to_llm` | **Last wins** | Only the last one runs |
+| `transform_system_prompt` | **Chain** | Yes |
+| `before_tool_call` | **First block stops**; non-block accumulates | Block wins; `edited_args` last-writer-wins; `hitl_trace` merges |
+| `after_tool_call` | **Later overrides earlier** | Last write wins |
+| `should_stop_after_turn` | **Any `True` stops** (OR) | No |
+| `after_model_response` | **Chain with merge semantics** | See below |
+
+## `transform_context` and `transform_system_prompt`
+
+Chain: `m1`'s output becomes `m2`'s input becomes `m3`'s input. Useful
+for layered transforms:
+
+```python
+agent = Agent(
+ middleware=[
+ SlidingWindow(max_messages=20), # m1: drop oldest
+ InjectSummary(), # m2: prepend a summary block
+ ],
+)
+```
+
+`m2` sees the truncated list. The user-visible
+`agent.state.messages` is untouched — middleware only changes what
+the model receives.
+
+## `convert_to_llm`
+
+Last-wins on purpose: this is the final transform before wire
+serialisation. Multiple owners would fight; pick one. CubePi enforces
+that the **last** middleware in the list that implements
+`convert_to_llm` is the one that runs.
+
+If you find yourself needing two `convert_to_llm` middlewares,
+collapse them into one (call site composition: write one that calls
+both).
+
+## `before_tool_call`
+
+First `block=True` short-circuits the rest. **Non-block returns
+accumulate:** `edited_args` propagates downstream (each middleware sees
+the edited form from the one above), and `hitl_trace` merges across the
+chain (with older keys archived under `_chain` when overwritten).
+
+Use to chain policy layers from most-restrictive to least:
+
+```python
+agent = Agent(
+ middleware=[
+ RateLimiter(), # blocks on rate quota
+ SafetyFilter(), # blocks on dangerous args; may edit
+ AuditLogger(), # never blocks; records for observability
+ ],
+)
+```
+
+If `RateLimiter` returns `block=True`, `SafetyFilter` and
+`AuditLogger`'s `before_tool_call` don't run. If `SafetyFilter` returns
+`edited_args={"cmd": "rm /tmp/foo"}`, the *tool* runs with the edited
+args and `AuditLogger` sees them via the rebuilt `ctx.args`.
+`AuditLogger.after_tool_call` still fires because that's a different
+hook.
+
+## `after_tool_call`
+
+Each middleware can return an `AfterToolCallResult` with some fields
+set; CubePi merges them, with later results overriding earlier ones
+for any field that's not `None`. The full result:
+
+```python
+class AfterToolCallResult(BaseModel):
+ content: list[Content] | None = None
+ details: Any = None
+ is_error: bool | None = None
+ terminate: bool | None = None
+```
+
+Pattern: an early middleware adds rich `details`, a later one
+sanitises `content` for the model. Both run; the merged result
+combines `details` from one with the redacted `content` from the
+other.
+
+## `should_stop_after_turn`
+
+Any middleware returning `True` ends the run. The rest of the chain
+isn't evaluated.
+
+```python
+agent = Agent(
+ middleware=[
+ MaxTurns(10),
+ BudgetCap(usd=0.5),
+ FinalAnswerSentinel(), # stops when assistant says "FINAL ANSWER"
+ ],
+)
+```
+
+## `after_model_response`
+
+Chain with structured merge. Each middleware sees the **current
+response** (which may have been replaced by an earlier middleware) and
+returns a `TurnAction`:
+
+- `response: AssistantMessage | None` — if non-None, replaces the
+ current response for downstream middlewares and for what the loop
+ ultimately persists.
+- `inject_messages: list[Message]` — appended into a single list
+ across the whole chain, then added to context before the next turn.
+- `decision: "natural" | "stop" | "loop_to_model"` — the **last
+ middleware's value wins**.
+
+```python
+agent = Agent(
+ middleware=[
+ ProfanityRedactor(), # rewrites response
+ StructuredOutputValidator(), # may decide="loop_to_model"
+ EventLogger(), # decision unchanged
+ ],
+)
+```
+
+If `StructuredOutputValidator` returns `decision="loop_to_model"` and
+`EventLogger` returns `decision="natural"`, the loop sees `"natural"`
+— because last wins. Reorder if that's not what you wanted.
+
+## Mixing middleware with constructor callables
+
+`Agent(...)` also accepts explicit hook callables (`convert_to_llm=…`,
+`before_tool_call=…`, etc.). When both are present, the **explicit
+callable wins**:
+
+```python
+agent = Agent(
+ middleware=[LoggingMiddleware()],
+ before_tool_call=my_explicit_hook, # overrides the middleware version
+)
+```
+
+Use the explicit form for one-off hooks; use middleware classes when
+behaviour is a coherent bundle.
+
+## A note on `Middleware` base class
+
+The base `Middleware` class's unimplemented methods raise
+`NotImplementedError`. `compose_middleware` detects this by comparing
+to the base method and **only** wires hooks the middleware actually
+overrides. You don't need to `pass`-implement every method.
+
+```python
+class JustTransform(Middleware):
+ async def transform_context(self, messages, *, signal=None):
+ return messages[-10:]
+ # No other hooks. CubePi won't call them.
+```
+
+## See also
+
+- [The 7 Hooks](./hooks) — what each hook does and when it fires.
+- [Examples](./examples) — composition in practice.
diff --git a/website/versioned_docs/version-0.6/guides/middleware/examples.md b/website/versioned_docs/version-0.6/guides/middleware/examples.md
new file mode 100644
index 0000000..b8a13d3
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/middleware/examples.md
@@ -0,0 +1,297 @@
+---
+title: Examples
+description: "Working middleware examples for CubePi: rate limiting, retries with backoff, structured logging, context truncation, and HITL."
+---
+
+# Middleware Examples
+
+Working middleware for the four most common needs: rate limiting,
+retries, structured logging, and context truncation.
+
+## Rate limiting
+
+Block tool calls when a user exceeds quota. Combine
+`before_tool_call` with an external rate-limiter (a token bucket, a
+Redis INCR, …).
+
+```python
+import time
+from cubepi import Middleware
+from cubepi.agent.types import BeforeToolCallResult
+
+
+class RateLimitMiddleware(Middleware):
+ def __init__(self, max_calls_per_min: int) -> None:
+ self.max = max_calls_per_min
+ self._timestamps: list[float] = []
+
+ async def before_tool_call(self, ctx, *, signal=None):
+ now = time.monotonic()
+ # Drop entries older than 60 s.
+ self._timestamps = [t for t in self._timestamps if now - t < 60]
+ if len(self._timestamps) >= self.max:
+ return BeforeToolCallResult(
+ block=True,
+ reason=f"Rate limit: {self.max} tool calls/min exceeded. Try again shortly.",
+ )
+ self._timestamps.append(now)
+ return None
+```
+
+Use:
+
+```python
+agent = Agent(provider=…, model=…, middleware=[RateLimitMiddleware(max_calls_per_min=30)])
+```
+
+When the limit hits, the model sees a tool result that says "Rate
+limit exceeded…" and usually waits or asks the user.
+
+## Retries with backoff
+
+Retry failed tool calls inside `after_tool_call`. Up to N times, with
+exponential backoff, only for transient errors.
+
+```python
+import asyncio
+from cubepi import Middleware
+from cubepi.agent.types import AfterToolCallResult
+
+
+class RetryMiddleware(Middleware):
+ def __init__(self, max_retries: int = 3, base_delay: float = 0.5) -> None:
+ self.max_retries = max_retries
+ self.base_delay = base_delay
+
+ async def after_tool_call(self, ctx, *, signal=None):
+ if not ctx.is_error:
+ return None
+
+ # Find the tool by name and re-execute up to max_retries times.
+ tool = next(
+ (t for t in (ctx.context.tools or []) if t.name == ctx.tool_call.name),
+ None,
+ )
+ if tool is None:
+ return None
+
+ for attempt in range(1, self.max_retries + 1):
+ await asyncio.sleep(self.base_delay * (2 ** (attempt - 1)))
+ try:
+ new_result = await tool.execute(
+ ctx.tool_call.id,
+ ctx.args,
+ signal=signal,
+ on_update=None,
+ )
+ return AfterToolCallResult(
+ content=new_result.content,
+ details={"retried": attempt, "original_error": ctx.result.content},
+ is_error=False,
+ )
+ except Exception:
+ continue
+
+ return None # give up — original error stays
+```
+
+Combine with caution: retrying non-idempotent tools (writes, sends,
+deletes) can cause real damage. Mark such tools `execution_mode="sequential"`
+and skip them here based on `ctx.tool_call.name`.
+
+## Structured logging
+
+Log every tool call with its arguments, duration, and outcome.
+Pairs `before_tool_call` (to record start time) with `after_tool_call`
+(to record the result). Stash the start time in `ctx.context.extra`.
+
+```python
+import time, logging
+from cubepi import Middleware
+
+log = logging.getLogger("cubepi.tools")
+
+
+class ToolLoggingMiddleware(Middleware):
+ async def before_tool_call(self, ctx, *, signal=None):
+ ctx.context.extra.setdefault("_tool_starts", {})[ctx.tool_call.id] = time.monotonic()
+ return None
+
+ async def after_tool_call(self, ctx, *, signal=None):
+ started = ctx.context.extra.get("_tool_starts", {}).pop(ctx.tool_call.id, None)
+ duration_ms = int((time.monotonic() - started) * 1000) if started else None
+ log.info(
+ "tool_call",
+ extra={
+ "tool_name": ctx.tool_call.name,
+ "args": ctx.args.model_dump() if hasattr(ctx.args, "model_dump") else ctx.args,
+ "is_error": ctx.is_error,
+ "duration_ms": duration_ms,
+ },
+ )
+ return None
+```
+
+`ctx.context.extra` is the right place to stash per-run state because
+it's:
+
+- Visible to other middleware via the same `ctx.context`.
+- Persisted by checkpointers via `save_extra` at `agent_end`.
+- Reset when a new conversation starts (a new `thread_id`).
+
+## Sliding-window truncation
+
+Keep the model's context bounded by retaining only the most recent N
+messages, plus the system prompt:
+
+```python
+from cubepi import Middleware
+
+
+class SlidingWindow(Middleware):
+ def __init__(self, max_messages: int = 20) -> None:
+ self.max_messages = max_messages
+
+ async def transform_context(self, messages, *, signal=None):
+ if len(messages) <= self.max_messages:
+ return messages
+ return messages[-self.max_messages:]
+```
+
+`transform_context` doesn't touch `agent.state.messages` — the user
+keeps seeing the full history. The model just sees the last N.
+
+Pairs well with a `transform_system_prompt` that injects a summary of
+what was dropped:
+
+```python
+class SummaryInjector(Middleware):
+ async def transform_system_prompt(self, system_prompt, *, signal=None):
+ summary = "Earlier in this conversation we discussed: …"
+ return f"{system_prompt}\n\nContext: {summary}".strip()
+```
+
+## Max turns / budget cap
+
+Hard-stop the agent after a maximum number of turns or a cost cap:
+
+```python
+class MaxTurns(Middleware):
+ def __init__(self, max_turns: int) -> None:
+ self.max_turns = max_turns
+ self.turns = 0
+
+ async def should_stop_after_turn(self, ctx):
+ self.turns += 1
+ return self.turns >= self.max_turns
+
+
+class BudgetCap(Middleware):
+ def __init__(self, usd: float, model_cost) -> None:
+ self.cap = usd
+ self.cost = model_cost # cubepi.providers.ModelCost or similar
+ self.spent = 0.0
+
+ async def should_stop_after_turn(self, ctx):
+ m = ctx.message
+ if m.usage:
+ self.spent += (
+ (m.usage.input_tokens / 1_000_000) * self.cost.input
+ + (m.usage.output_tokens / 1_000_000) * self.cost.output
+ )
+ return self.spent >= self.cap
+```
+
+## Structured output with `after_model_response`
+
+Validate JSON output and re-prompt if it doesn't parse:
+
+```python
+import json
+from cubepi import Middleware
+from cubepi.middleware.base import TurnAction
+from cubepi.providers.base import TextContent, UserMessage
+
+
+class JSONOutputValidator(Middleware):
+ def __init__(self, schema_cls) -> None:
+ self.schema = schema_cls
+
+ async def after_model_response(self, response, ctx, *, signal=None):
+ text = "".join(
+ c.text for c in response.content if isinstance(c, TextContent)
+ )
+ try:
+ obj = json.loads(text)
+ self.schema.model_validate(obj)
+ return None # valid — proceed naturally
+ except Exception as e:
+ return TurnAction(
+ inject_messages=[
+ UserMessage(content=[TextContent(text=f"Invalid output: {e}. Return valid JSON.")]),
+ ],
+ decision="loop_to_model",
+ )
+```
+
+The agent will skip tool execution and immediately re-prompt the
+model with the feedback message in context.
+
+## Human-in-the-loop tool confirmation
+
+CubePi ships two built-in HITL middlewares in `cubepi.hitl`:
+
+**`ConfirmToolCallMiddleware`** — "always ask the human for this tool":
+
+```python
+from cubepi.hitl import ConfirmToolCallMiddleware, InMemoryChannel
+
+channel = InMemoryChannel()
+agent = Agent(
+ provider=…, model=…,
+ middleware=[
+ ConfirmToolCallMiddleware(
+ channel,
+ require_confirm={"bash", "write_file"},
+ ),
+ ],
+)
+```
+
+The agent pauses on every `bash` or `write_file` call and waits for the
+host to `channel.answer(qid, ApproveAnswer(decision="approve"))`. The
+result drives the tool: `approve` runs it, `deny` blocks with a reason,
+`edit` re-validates and runs the edited args.
+
+**`ApprovalPolicyMiddleware`** — for hosts that classify tool calls via
+a policy engine:
+
+```python
+from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny
+
+def my_policy(ctx):
+ if ctx.tool_call.name in ("read_file", "grep"):
+ return Approve()
+ if ctx.tool_call.name.startswith("dangerous_"):
+ return Deny(reason="blocked")
+ return AskUser(timeout_seconds=180)
+
+agent = Agent(
+ provider=…, model=…,
+ middleware=[ApprovalPolicyMiddleware(channel, policy=my_policy)],
+)
+```
+
+`Deny` skips the channel entirely (hard block). `AskUser` triggers the
+channel's approve flow. `Approve` returns immediately.
+
+Full details — timeout semantics, edit semantics, events, trace spans,
+cross-process suspend/resume — are in the [HITL guide](../hitl/overview).
+
+## See also
+
+- [The 7 Hooks](./hooks) — exact semantics of each hook.
+- [Composition Rules](./composition) — how multiple middlewares
+ combine.
+- [Recipes](../../recipes/weather-agent) — middleware composed into
+ real-world apps.
diff --git a/website/versioned_docs/version-0.6/guides/middleware/hooks.md b/website/versioned_docs/version-0.6/guides/middleware/hooks.md
new file mode 100644
index 0000000..a2ed5c4
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/middleware/hooks.md
@@ -0,0 +1,207 @@
+---
+title: The 7 Hooks
+description: "Reference for the 7 middleware hooks in CubePi — transform_context, convert_to_llm, before_tool_call, after_tool_call, and more."
+---
+
+# The 7 Hooks
+
+`Middleware` is a class with up to seven optional async methods. Each
+hook fires at a precise point in the agent loop. Implement only the
+ones you need — CubePi only wires in the ones you override.
+
+```python
+from cubepi import Middleware
+
+class MyMiddleware(Middleware):
+ async def transform_context(self, messages, *, signal=None):
+ ...
+```
+
+Pass instances to `Agent(middleware=[MyMiddleware(), …])`.
+
+## `transform_context`
+
+```python
+async def transform_context(self, messages: list[Message], *, signal=None) -> list[Message]:
+ ...
+```
+
+Fires **before each model call**, on the full message list. Use to:
+
+- Truncate or summarise to fit context windows.
+- Inject system reminders (better: use `transform_system_prompt`).
+- Add or remove specific messages dynamically.
+
+Return the (possibly new) list. **Don't mutate the input** — return a
+new list so other code that holds the original isn't surprised.
+
+Composition: chained — each middleware sees the previous one's
+output.
+
+## `convert_to_llm`
+
+```python
+async def convert_to_llm(self, messages: list[Message]) -> list[Message]:
+ ...
+```
+
+Fires **right before serialisation** to the provider. This is the last
+chance to reshape what the LLM sees. Use for:
+
+- Stripping tool results to text-only.
+- Replacing image content with text descriptions for non-multimodal
+ providers.
+- Compacting long tool outputs.
+
+Composition: **last implementation wins** (not chained). Use this when
+multiple middlewares would conflict and you want a single owner.
+
+## `transform_system_prompt`
+
+```python
+async def transform_system_prompt(self, system_prompt: str, *, signal=None) -> str:
+ ...
+```
+
+Fires **before each model call**, on the system prompt string. Use to:
+
+- Inject runtime info (current time, user role).
+- Compose modular system-prompt fragments.
+- A/B test prompt variants.
+
+Composition: chained.
+
+## `before_tool_call`
+
+```python
+async def before_tool_call(self, ctx: BeforeToolCallContext, *, signal=None) -> BeforeToolCallResult | None:
+ ...
+```
+
+Fires **per tool call**, after argument validation, before
+`tool.execute`. The context provides:
+
+- `ctx.assistant_message` — the message that initiated the call.
+- `ctx.tool_call` — the `ToolCall` block.
+- `ctx.args` — the *validated* Pydantic instance.
+- `ctx.context` — the full `AgentContext`.
+
+Return `BeforeToolCallResult(block=True, reason="…")` to short-circuit
+— CubePi feeds the reason back as the tool result with
+`is_error=True`. Return `None` (or no return) to proceed.
+
+Use for: permissions, rate limiting, dry-run modes, sandboxing,
+human-in-the-loop confirmation (see [HITL guide](../hitl/overview)).
+
+Composition: **first `block=True` short-circuits** the chain.
+
+## `after_tool_call`
+
+```python
+async def after_tool_call(self, ctx: AfterToolCallContext, *, signal=None) -> AfterToolCallResult | None:
+ ...
+```
+
+Fires **per tool call**, after `tool.execute` returns (or raises).
+The context adds:
+
+- `ctx.result` — the `AgentToolResult` from execute.
+- `ctx.is_error` — whether the tool errored.
+
+Return `AfterToolCallResult(content=…, details=…, is_error=…, terminate=…)`
+to override individual fields of the result (any `None` field keeps
+the original). Return `None` to pass through unchanged.
+
+Use for: redaction, retries, logging, transforming results.
+
+Composition: later overrides earlier (each non-`None` field in a
+return value overrides the prior).
+
+## `should_stop_after_turn`
+
+```python
+async def should_stop_after_turn(self, ctx: ShouldStopAfterTurnContext) -> bool:
+ ...
+```
+
+Fires **at each turn boundary** (after any tool batch). Return `True`
+to end the run without another model call.
+
+Use for: max-turn limits, budget caps, application-defined stop
+conditions.
+
+Composition: **any `True` stops** (logical OR across the chain).
+
+## `after_model_response`
+
+```python
+async def after_model_response(
+ self,
+ response: AssistantMessage,
+ ctx: AgentContext,
+ *,
+ signal=None,
+) -> TurnAction | None:
+ ...
+```
+
+Fires **immediately after** the assistant message lands, **before**
+`message_end` is emitted and **before** any tool calls dispatch. The
+hook returns a `TurnAction`:
+
+```python
+from cubepi.middleware.base import TurnAction
+from cubepi.providers.base import UserMessage, TextContent
+
+TurnAction(
+ response=modified_message, # replace the message; None to keep
+ inject_messages=[UserMessage(...)], # extra messages to append before next turn
+ decision="natural", # "natural" | "stop" | "loop_to_model"
+)
+```
+
+Three control-flow knobs:
+
+- `decision="natural"` (default) — proceed to tool execution / next
+ turn as normal.
+- `decision="stop"` — end the run after emitting `turn_end` and
+ `agent_end`. No tools run, no more model calls.
+- `decision="loop_to_model"` — skip tool execution and re-invoke the
+ model immediately (use with `inject_messages` to add context first).
+
+Use for: response moderation, structured-output validation with
+re-prompts, conditional routing.
+
+Composition: chain — each middleware sees the previous
+middleware's `response`; `inject_messages` concatenate across the
+chain; the last middleware's `decision` wins.
+
+## Anatomy of a middleware
+
+A middleware doesn't have to implement every hook. Only override the
+ones you need; the base class's unimplemented hooks raise
+`NotImplementedError`, but `compose_middleware` skips them
+automatically.
+
+```python
+from cubepi import Middleware
+
+class MaxTurnsMiddleware(Middleware):
+ def __init__(self, max_turns: int) -> None:
+ self.max_turns = max_turns
+ self.turns = 0
+
+ async def should_stop_after_turn(self, ctx) -> bool:
+ self.turns += 1
+ return self.turns >= self.max_turns
+
+
+agent = Agent(provider=…, model=…, middleware=[MaxTurnsMiddleware(5)])
+```
+
+## See also
+
+- [Composition Rules](./composition) — exact semantics when multiple
+ middlewares define the same hook.
+- [Examples](./examples) — working middleware for rate limiting,
+ logging, retries, sliding-window context.
diff --git a/website/versioned_docs/version-0.6/guides/providers/anthropic.md b/website/versioned_docs/version-0.6/guides/providers/anthropic.md
new file mode 100644
index 0000000..0da6971
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/providers/anthropic.md
@@ -0,0 +1,203 @@
+---
+title: Anthropic
+description: "Use Anthropic Claude models with CubePi's AnthropicProvider — supports thinking, caching, and tool use."
+---
+
+# Anthropic Provider
+
+`AnthropicProvider` wraps the official `anthropic` SDK against the
+Messages API. It supports streaming, extended thinking, prompt
+caching, and tool use.
+
+## Construction
+
+```python
+from cubepi.providers.anthropic import AnthropicProvider
+
+provider = AnthropicProvider(
+ api_key="sk-ant-…", # or read from os.environ["ANTHROPIC_API_KEY"]
+ base_url=None, # set to point at a proxy / Bedrock-compatible endpoint
+ cache_retention="short", # "short" (5 min, default) | "long" (1 h) | "none"
+)
+```
+
+`api_key=None` lets the underlying SDK read `ANTHROPIC_API_KEY` from
+the environment.
+
+## The `Model`
+
+```python
+from cubepi import Model
+
+model = Model(
+ id="claude-sonnet-4-5-20250929",
+ provider="anthropic",
+ reasoning=True, # enables thinking levels (see below)
+ max_tokens=8192, # response cap
+ context_window=200_000, # hard model limit
+ temperature=0.7,
+)
+```
+
+The `id` is the model name exactly as you'd pass it to the SDK. The
+`provider` string is a free-form label used by CubePi internals — keep
+it stable across your codebase but it doesn't have to match
+`"anthropic"` literally.
+
+## Extended thinking
+
+CubePi maps a `ThinkingLevel` enum onto Anthropic's `budget_tokens`:
+
+| Level | Default budget |
+|---|---|
+| `"off"` | thinking disabled |
+| `"minimal"` | 1024 |
+| `"low"` | 2048 |
+| `"medium"` | 8192 |
+| `"high"` | 16384 |
+| `"xhigh"` | clamped to `"high"` |
+
+Set it per-agent:
+
+```python
+agent = Agent(provider=provider, model=model, thinking="medium")
+```
+
+To change the per-level budgets, supply a
+[`CapabilityDescriptor`](./capability-and-presets) with a
+`reasoning_level` of `kind="int_budget"` at construction — its
+`level_budgets` map is the single source of truth for budget values.
+
+```python
+from cubepi import CapabilityDescriptor, ReasoningLevelSpec
+from cubepi.providers.anthropic import AnthropicProvider
+
+provider = AnthropicProvider(
+ api_key="sk-ant-…",
+ capability=CapabilityDescriptor(
+ reasoning_off_payload={"thinking": {"type": "disabled"}},
+ reasoning_on_payload={"thinking": {"type": "enabled"}},
+ reasoning_level=ReasoningLevelSpec(
+ path="thinking.budget_tokens",
+ kind="int_budget",
+ level_budgets={"off": 0, "minimal": 1024, "low": 4096,
+ "medium": 12288, "high": 16384, "xhigh": 16384},
+ ),
+ ),
+)
+```
+
+:::note Changed in 0.5
+`AnthropicProvider` no longer honors
+`StreamOptions(thinking_budgets=…)` — the capability descriptor's
+`level_budgets` is now the only way to override budgets.
+:::
+
+When thinking is on, CubePi **omits `temperature`** because the
+Anthropic API rejects non-default temperatures alongside extended
+thinking ([feature compatibility](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#feature-compatibility)).
+Set `Model.temperature` to the value you want when thinking is off;
+CubePi handles the rest.
+
+Thinking content streams as `thinking_start` / `thinking_delta` /
+`thinking_end` events and ends up in `AssistantMessage.content` as
+`ThinkingContent` blocks, preserved on subsequent turns so the model
+keeps continuity.
+
+## Prompt caching
+
+By default the provider marks three cache breakpoints on each request:
+
+- The **system prompt** (most stable).
+- The **last tool definition** (changes rarely).
+- The **last message** (the cache moves forward each turn so prior
+ history stays warm).
+
+Cache retention is `"short"` (5 minutes, free). Bump to `"long"` if
+your turns are slower than that:
+
+```python
+AnthropicProvider(api_key=…, cache_retention="long") # 1-hour TTL
+AnthropicProvider(api_key=…, cache_retention="none") # disable entirely
+```
+
+The `Usage` object on each `AssistantMessage` reports
+`cache_read_tokens` and `cache_write_tokens` so you can see your hit
+rate.
+
+For custom cache strategies (a different breakpoint policy), implement
+the `CacheMarkerPolicy` Protocol and pass `cache_policy=…`. The
+default policy lives at `cubepi.providers.anthropic.DefaultCacheMarkerPolicy`.
+
+## Custom payloads with `on_payload`
+
+`on_payload` lets you inspect or replace the request dict right before
+it's sent:
+
+```python
+async def my_payload(payload, model):
+ payload.setdefault("metadata", {})["user_id"] = "u-42"
+ return payload # return None or no return to keep the original
+
+agent = Agent(provider=provider, model=model, on_payload=my_payload)
+```
+
+Use this for: adding `metadata.user_id` (for billing), forcing
+beta-header flags, or tracking the exact payloads you sent for a
+debug pane.
+
+## Custom response handling with `on_response`
+
+`on_response` fires after the HTTP response is received (status,
+headers), before streaming begins:
+
+```python
+async def my_response(resp, model):
+ if resp.status >= 400:
+ logger.warning("bad status %s", resp.status)
+ rate = resp.headers.get("anthropic-ratelimit-requests-remaining")
+ if rate is not None:
+ metrics.gauge("rate_remaining", int(rate))
+
+agent = Agent(provider=provider, model=model, on_response=my_response)
+```
+
+Both callbacks may be sync or async.
+
+## Pointing at Bedrock / Vertex / proxies
+
+The Anthropic SDK accepts a `base_url`; CubePi forwards it:
+
+```python
+provider = AnthropicProvider(
+ api_key="…",
+ base_url="https://my-litellm.internal/v1",
+)
+```
+
+For Bedrock specifically, use the `anthropic-bedrock` adapter directly
+and inject it via a [custom provider](./custom).
+
+## Common pitfalls
+
+- **`temperature` ignored** — Expected. CubePi drops it when thinking
+ is on; that's an API constraint, not a bug.
+- **`xhigh` looks the same as `high`** — Anthropic doesn't expose a
+ budget tier above `high`, so CubePi clamps `xhigh` down. The token
+ budget is the same.
+- **Cache misses you didn't expect** — Caches are keyed by content +
+ ttl. Changing the system prompt invalidates everything; changing the
+ tool list invalidates from the tools onward. Make those two stable
+ across turns to maximise hits.
+- **`anthropic.RateLimitError`** — Propagates as a stream error event
+ with the SDK's `str(exc)`. Catch in `agent_end` and decide whether
+ to retry.
+
+## See also
+
+- [OpenAI Provider](./openai) — same protocol, different shape.
+- [Capabilities & Preset Catalog](./capability-and-presets) — tune
+ reasoning budgets and temperature handling as data.
+- [Custom Provider](./custom) — wrap a non-built-in API.
+- [Recipes → Multi-Provider Failover](../../recipes/multi-provider-failover)
+ — fall back to OpenAI when Anthropic is down.
diff --git a/website/versioned_docs/version-0.6/guides/providers/capability-and-presets.md b/website/versioned_docs/version-0.6/guides/providers/capability-and-presets.md
new file mode 100644
index 0000000..bd97f84
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/providers/capability-and-presets.md
@@ -0,0 +1,193 @@
+---
+title: Capability Descriptors
+description: "Provider capabilities and model presets in CubePi — compare features across providers."
+---
+
+# Capability Descriptors
+
+_Capability descriptors added in CubePi `0.5`._
+
+This page is about reaching **any** model — the big SaaS APIs, a regional
+endpoint, a coding-plan tier, or your own vLLM box — without writing
+per-vendor glue. The progression is deliberate:
+
+1. **The default is zero config.** For Anthropic and OpenAI you write a
+ provider and a model. Nothing on this page is required.
+2. **For an off-default endpoint, describe the quirks as data.** A
+ `CapabilityDescriptor` captures the differences declaratively — no
+ subclassing, no forking.
+
+:::note Preset catalogs live in the host application
+CubePi ships the **mechanism** (the `CapabilityDescriptor` and the wire
+runtime that applies it), not a catalog of vendors. A ready-made list of
+providers — base URLs, auth, regional/coding-plan endpoints, model lists —
+is product data and belongs to the application embedding CubePi (for
+example, cubebox maintains its own provider catalog). To reach a specific
+vendor, build the provider with the right `base_url` + `CapabilityDescriptor`
+as shown below.
+:::
+
+## 1. The simple case — no config at all
+
+Most users never touch capabilities. The built-in providers ship with
+sensible defaults:
+
+```python
+import cubepi
+from cubepi import Agent, Model
+from cubepi.providers.anthropic import AnthropicProvider
+
+agent = Agent(
+ provider=AnthropicProvider(), # reads ANTHROPIC_API_KEY
+ model=Model(id="claude-sonnet-4-6", provider="anthropic"),
+)
+await agent.prompt("Hello!")
+```
+
+That's the whole setup. A provider built without `capability=` produces
+byte-identical output to CubePi `0.4` — the machinery below only kicks in
+when you ask for it.
+
+## 2. Off-default endpoints — the CapabilityDescriptor
+
+When you want a model that isn't OpenAI or Anthropic — DeepSeek, Qwen,
+Doubao, an OpenRouter route, a local server — the awkward part is each
+one's wire dialect (does it want `max_tokens` or `max_completion_tokens`?
+how is reasoning toggled?). You don't subclass a provider; you describe the
+quirks as a [`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html)
+and pass it in, along with the right `base_url` and provider class for the
+endpoint's wire shape:
+
+```python
+import os
+from cubepi import CapabilityDescriptor
+from cubepi.providers.openai import OpenAIProvider
+
+provider = OpenAIProvider(
+ api_key=os.environ["DEEPSEEK_API_KEY"],
+ base_url="https://api.deepseek.com",
+ capability=CapabilityDescriptor(
+ reasoning_off_payload={"extra_body": {"reasoning": {"exclude": True}}},
+ reasoning_on_payload={"extra_body": {"reasoning": {"exclude": False}}},
+ ),
+)
+```
+
+Pick the provider class by the endpoint's wire dialect:
+
+| Wire dialect | Provider class |
+| --- | --- |
+| `anthropic-messages` | `AnthropicProvider` |
+| `openai-completions` | `OpenAIProvider` |
+| `openai-responses` | `OpenAIResponsesProvider` |
+
+Each field maps to one wire behavior, and an unset field does nothing — so
+you only declare what's actually different.
+
+### `max_tokens_field`
+
+`"max_tokens"` (default) or `"max_completion_tokens"`. Some
+OpenAI-compatible servers accept only one spelling; this renames the key
+on the way out. **Effect:** wrong choice → the server ignores your output
+cap or 400s.
+
+### `temperature`
+
+A `TemperatureSpec` controlling how the caller's temperature is treated:
+
+```python
+from cubepi import TemperatureSpec
+
+TemperatureSpec(mode="free", min=0.0, max=2.0, default=1.0) # clamp into [min, max]
+TemperatureSpec(mode="fixed", fixed_value=1.0) # always overwrite
+TemperatureSpec(mode="ignored") # drop the key
+```
+
+- **`free`** — the caller's value is clamped into `[min, max]`; if none was
+ sent, nothing is written. **Effect:** protects against an out-of-range
+ value the backend would reject.
+- **`fixed`** — `fixed_value` always wins. **Effect:** use for models that
+ permit only one temperature (e.g. some o-series reasoning models).
+- **`ignored`** — the key is stripped entirely. **Effect:** for backends
+ that 400 on any `temperature` while reasoning.
+
+### Reasoning toggle: `reasoning_off_payload` / `reasoning_on_payload`
+
+When thinking is off, `reasoning_off_payload` is deep-merged into the
+request; when it's on, `reasoning_on_payload` is. **Effect:** this is how
+"turn reasoning on/off" becomes whatever field the vendor expects:
+
+```python
+CapabilityDescriptor(
+ reasoning_off_payload={"extra_body": {"enable_thinking": False}},
+ reasoning_on_payload={"extra_body": {"enable_thinking": True}},
+)
+```
+
+The merge recurses into nested dicts; arrays are atomic; on a collision
+the capability value wins.
+
+### Reasoning level: `reasoning_level` (three shapes)
+
+Beyond on/off, CubePi maps a `ThinkingLevel`
+(`off`/`minimal`/`low`/`medium`/`high`/`xhigh`) onto a concrete wire value
+written at a dotted `path`. `kind` picks the shape:
+
+```python
+from cubepi import ReasoningLevelSpec
+
+# int_budget — a token budget (Anthropic).
+ReasoningLevelSpec(
+ path="thinking.budget_tokens", kind="int_budget",
+ level_budgets={"off": 0, "minimal": 1024, "low": 2048,
+ "medium": 8192, "high": 16384, "xhigh": 16384},
+)
+
+# effort — an effort string (OpenAI Responses).
+ReasoningLevelSpec(
+ path="reasoning.effort", kind="effort",
+ level_to_effort={"minimal": "minimal", "low": "low",
+ "medium": "medium", "high": "high", "xhigh": "high"},
+)
+
+# enum — a vendor-specific state (Doubao's 3-state thinking).
+ReasoningLevelSpec(
+ path="thinking.type", kind="enum",
+ level_to_enum={"off": "disabled", "low": "enabled", "high": "enabled"},
+)
+```
+
+**Effect:** a level missing from the map is simply not written, so the
+endpoint keeps its own default for that level.
+
+### `supports_tools` / `supports_images` / `supports_streaming`
+
+Declarative flags read by host applications and frontends (for example, to
+grey out image upload). The providers themselves don't gate on them.
+
+### Per-model overrides on a shared endpoint
+
+One gateway (OpenRouter, LiteLLM, an internal proxy) often serves both
+reasoning and non-reasoning models. `model_capability_overrides` maps a
+`model_id` to a descriptor that **replaces** the base one for that model:
+
+```python
+provider = OpenAIProvider(
+ api_key="…",
+ base_url="https://openrouter.ai/api/v1",
+ capability=base_cap, # default for unlisted models
+ model_capability_overrides={
+ "deepseek/deepseek-r1": reasoning_cap, # this model only
+ },
+)
+```
+
+Resolution is exact-match on `model_id`; anything not listed falls back to
+`capability`.
+
+## See also
+
+- [OpenAI Provider](./openai) — concrete OpenAI / OpenAI-compatible setup.
+- [Anthropic Provider](./anthropic) — the `int_budget` reasoning shape in practice.
+- [Writing a Custom Provider](./custom) — when the endpoint isn't even OpenAI/Anthropic-shaped.
+- [API Reference → `cubepi.providers`](../../api/cubepi-providers).
diff --git a/website/versioned_docs/version-0.6/guides/providers/custom.md b/website/versioned_docs/version-0.6/guides/providers/custom.md
new file mode 100644
index 0000000..d6b91b1
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/providers/custom.md
@@ -0,0 +1,240 @@
+---
+title: Writing a Custom Provider
+description: "Write a custom provider for CubePi by implementing the Provider protocol."
+---
+
+# Writing a Custom Provider
+
+A provider is any class with one method:
+
+```python
+class Provider(Protocol):
+ async def stream(
+ self,
+ model: Model,
+ messages: list[Message],
+ *,
+ system_prompt: str = "",
+ tools: list[ToolDefinition] | None = None,
+ options: StreamOptions | None = None,
+ ) -> MessageStream: ...
+```
+
+That's the whole interface. Implement it and `Agent(provider=…)`
+accepts your class.
+
+This page covers two scenarios:
+
+1. **A new real provider** — Bedrock, Vertex, Replicate, an internal
+ LLM gateway, …
+2. **`FauxProvider`** — the built-in deterministic provider that's
+ essential for unit tests.
+
+## A minimal real provider
+
+The pattern: create a `MessageStream`, kick off a producer task that
+pushes events into it, return the stream immediately.
+
+```python
+import asyncio
+import time
+from cubepi.providers.base import (
+ AssistantMessage,
+ Message,
+ MessageStream,
+ Model,
+ StreamEvent,
+ StreamOptions,
+ TextContent,
+ ToolDefinition,
+ Usage,
+)
+
+
+class MyProvider:
+ def __init__(self, *, api_key: str) -> None:
+ self._api_key = api_key
+
+ async def stream(
+ self,
+ model: Model,
+ messages: list[Message],
+ *,
+ system_prompt: str = "",
+ tools: list[ToolDefinition] | None = None,
+ options: StreamOptions | None = None,
+ ) -> MessageStream:
+ opts = options or StreamOptions()
+ ms = MessageStream()
+
+ async def _produce():
+ try:
+ partial = AssistantMessage(
+ content=[TextContent(text="")],
+ usage=Usage(),
+ timestamp=time.time(),
+ provider_id=model.provider,
+ model_id=model.id,
+ )
+ ms.push(StreamEvent(type="start", partial=partial.model_copy(deep=True)))
+
+ # Call your backend. Stream tokens:
+ async for token in call_my_backend(messages, model.id, signal=opts.signal):
+ if opts.signal and opts.signal.is_set():
+ ms.push(StreamEvent(type="error", error_message="aborted"))
+ ms.set_result(partial.model_copy(update={"stop_reason": "aborted"}))
+ return
+ partial.content[-1] = TextContent(text=partial.content[-1].text + token)
+ ms.push(StreamEvent(
+ type="text_delta",
+ delta=token,
+ partial=partial.model_copy(deep=True),
+ ))
+
+ ms.push(StreamEvent(type="done"))
+ ms.set_result(partial)
+
+ except Exception as exc:
+ error_msg = AssistantMessage(
+ content=[],
+ stop_reason="error",
+ error_message=str(exc),
+ usage=Usage(),
+ timestamp=time.time(),
+ )
+ ms.push(StreamEvent(type="error", error_message=str(exc)))
+ ms.set_result(error_msg)
+
+ ms.attach_task(asyncio.create_task(_produce()))
+ return ms
+```
+
+Things to get right:
+
+1. **Always push `start` first.** Subscribers count on it for UI
+ bootstrapping.
+2. **Always end with `done` or `error`.** The agent loop waits on the
+ `MessageStream` until one of those arrives.
+3. **Always call `ms.set_result(...)`** so `await stream.result()` can
+ complete. Even on error.
+4. **`ms.attach_task(...)` is required** if the producer is its own
+ task — it wires the task's exception state into the stream so a
+ crash surfaces as `error`, not a hang.
+5. **Respect `opts.signal`.** Check it inside your read loop; emit an
+ `aborted` stop_reason so the agent can shut down cleanly.
+
+## Supporting tool calls
+
+If your model emits tool calls, append `ToolCall` blocks to
+`partial.content` as they stream in and emit `toolcall_start` /
+`toolcall_delta` / `toolcall_end`:
+
+```python
+from cubepi.providers.base import ToolCall
+
+tc = ToolCall(id=block_id, name=tool_name, arguments={})
+partial.content.append(tc)
+ms.push(StreamEvent(type="toolcall_start", content_index=len(partial.content)-1,
+ partial=partial.model_copy(deep=True)))
+# ... as JSON args arrive:
+ms.push(StreamEvent(type="toolcall_delta", delta=partial_json_chunk, …))
+# ... on completion:
+# replace tc.arguments with the parsed dict, push toolcall_end
+```
+
+CubePi's agent loop will dispatch the tool calls automatically once
+`done` is emitted.
+
+## Hooking `on_payload` / `on_response`
+
+If your provider sends an HTTP request, call the helpers in
+`cubepi.providers.base`:
+
+```python
+from cubepi.providers.base import (
+ ProviderResponse,
+ invoke_on_payload,
+ invoke_on_response,
+)
+
+payload = await invoke_on_payload(opts.on_payload, payload, model)
+http_resp = await self._client.post(..., json=payload)
+await invoke_on_response(
+ opts.on_response,
+ ProviderResponse(status=http_resp.status_code, headers=dict(http_resp.headers)),
+ model,
+)
+```
+
+This mirrors what built-in providers do; your users get the same
+inspection points for free.
+
+## Using `FauxProvider` in tests
+
+CubePi ships `FauxProvider` for deterministic tests — no network, no
+flakiness, real streaming events:
+
+```python
+from cubepi import Agent, Model
+from cubepi.providers import FauxProvider, faux_assistant_message, faux_text, faux_tool_call
+
+
+def test_my_agent():
+ provider = FauxProvider()
+ provider.set_responses([
+ faux_assistant_message([
+ faux_tool_call("search", {"query": "python"}),
+ ]),
+ faux_assistant_message("Here are the results: …"),
+ ])
+
+ agent = Agent(
+ provider=provider,
+ model=Model(id="test", provider="faux"),
+ tools=[my_search_tool],
+ )
+ events = []
+ agent.subscribe(lambda e, signal=None: events.append(e))
+ await agent.prompt("Search for python")
+
+ assert any(e.type == "tool_execution_start" for e in events)
+ assert events[-1].type == "agent_end"
+```
+
+`set_responses` is a FIFO queue: each model call pops one. The faux
+provider replays it with realistic deltas (token-by-token), so your
+streaming code paths actually exercise.
+
+Helpers:
+
+- `faux_text("Hello!")` — wraps a string into a `TextContent` block.
+- `faux_thinking("Pondering…")` — a `ThinkingContent` block.
+- `faux_tool_call("name", {"arg": …})` — a `ToolCall` block.
+- `faux_assistant_message(content_or_text)` — builds a complete
+ `AssistantMessage`.
+
+## Common pitfalls
+
+- **Missing `start` event** — Subscribers don't see the partial
+ message. Always push it first.
+- **Forgot `ms.set_result(...)`** — `await agent.prompt()` hangs
+ forever. Set the result on both happy and error paths.
+- **Synchronous `produce`** — `stream()` must return *immediately* —
+ do the work inside the task. If you `await` your backend before
+ `return ms`, you've blocked the caller.
+- **Modifying `partial` after pushing** — Push `deep=True` copies; the
+ caller iterates events asynchronously, and a mutation during
+ iteration creates very hard-to-debug aliasing.
+
+## See also
+
+- [Capabilities & Preset Catalog](./capability-and-presets) — before
+ writing a class from scratch, check whether your backend is just an
+ OpenAI/Anthropic-compatible endpoint a `CapabilityDescriptor` or
+ bundled preset already covers.
+- [API Reference → providers/base](../../api/cubepi-providers) — the
+ full type list.
+- [Anthropic Provider source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/anthropic.py)
+ — a real, complete example.
+- [`FauxProvider` source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/faux.py)
+ — the testing primitive, including stream-realism details.
diff --git a/website/versioned_docs/version-0.6/guides/providers/openai.md b/website/versioned_docs/version-0.6/guides/providers/openai.md
new file mode 100644
index 0000000..8c764cc
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/providers/openai.md
@@ -0,0 +1,188 @@
+---
+title: OpenAI
+description: "Use OpenAI GPT models with CubePi's OpenAIProvider — Chat Completions API integration."
+---
+
+# OpenAI Provider
+
+CubePi ships two OpenAI providers covering the two API surfaces:
+
+- **`OpenAIProvider`** — Chat Completions API
+ (`/v1/chat/completions`). Use this for the GPT-4/5 family and most
+ OpenAI-compatible servers (vLLM, LiteLLM, DeepSeek, Qwen, MiniMax,
+ DouBao, …).
+- **`OpenAIResponsesProvider`** — Responses API
+ (`/v1/responses`). Use this when you want server-side state and
+ reasoning summaries.
+
+Both implement the same `Provider` protocol; pick one per agent.
+
+## Chat Completions: `OpenAIProvider`
+
+```python
+from cubepi import Model
+from cubepi.providers.openai import OpenAIProvider
+
+provider = OpenAIProvider(
+ api_key="sk-…", # or reads OPENAI_API_KEY
+ base_url=None, # set for OpenAI-compatible servers
+ extra_body=None, # merged into every request
+ extra_headers=None,
+)
+
+model = Model(
+ id="gpt-5",
+ provider="openai",
+ reasoning=True, # enables thinking level mapping
+ max_tokens=8192,
+ context_window=128_000,
+)
+```
+
+### Thinking on Chat Completions
+
+OpenAI exposes reasoning content through `delta.reasoning_content` on
+o-series and gpt-5 models. CubePi captures it as `ThinkingContent` and
+emits `thinking_*` events identically to Anthropic. The same
+`ThinkingLevel` enum (`"off"` → `"high"`) works.
+
+Many OpenAI-compatible OSS backends emit reasoning under different
+fields. CubePi understands three in priority order:
+
+1. `delta.reasoning_content` (DeepSeek, Qwen, DouBao)
+2. `delta.reasoning` (vLLM)
+3. `delta.reasoning_details` (MiniMax)
+
+No configuration needed — the provider picks whichever field is
+present.
+
+### `extra_body` for OSS quirks
+
+Most OpenAI-compatible servers accept extensions through the request
+body. Set them once at construction:
+
+```python
+provider = OpenAIProvider(
+ api_key="…",
+ base_url="https://api.deepseek.com/v1",
+ extra_body={"enable_thinking": True, "stream_options": {"include_usage": True}},
+)
+```
+
+If you need per-request mutation, use `on_payload` (see below).
+
+### Capability descriptor
+
+Wire-shape differences between OpenAI and OpenAI-compatible backends
+(e.g. `max_tokens` vs `max_completion_tokens`, reasoning field names,
+temperature handling) are configured through a
+[`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html)
+passed at construction. For example, `max_tokens_field="max_completion_tokens"`
+renames the key on the way out. See
+[Capability Descriptors](./capability-and-presets) for the full set of
+knobs (CubePi `0.5+`).
+
+### Pointing at vLLM / LiteLLM / DeepSeek
+
+```python
+provider = OpenAIProvider(
+ api_key="dummy", # vLLM ignores it
+ base_url="http://localhost:8000/v1",
+ extra_headers={"Authorization": "Bearer dummy"},
+)
+```
+
+For LiteLLM:
+
+```python
+provider = OpenAIProvider(
+ api_key=os.environ["LITELLM_KEY"],
+ base_url="https://litellm.internal/v1",
+)
+```
+
+For the wire quirks of these backends (reasoning toggles, token-field
+renames, …), see [Capability Descriptors](./capability-and-presets).
+
+## Responses API: `OpenAIResponsesProvider`
+
+```python
+from cubepi.providers.openai_responses import OpenAIResponsesProvider
+
+provider = OpenAIResponsesProvider(api_key="sk-…")
+model = Model(id="gpt-5", provider="openai_responses", reasoning=True)
+```
+
+The Responses API keeps state server-side (referenced by
+`previous_response_id`). CubePi tracks `AssistantMessage.response_id`
+and feeds it back automatically — your code looks identical to the
+Chat Completions path.
+
+Use the Responses provider when:
+
+- You want reasoning **summaries** (not just text) surfaced as
+ thinking blocks.
+- You're using the `o`-series and want the server to hold the
+ reasoning chain across turns (smaller payloads, faster reuse).
+
+Stay on `OpenAIProvider` when you want full control over the message
+list and prompt caching strategy.
+
+## `on_payload` / `on_response`
+
+Same shape as the [Anthropic](./anthropic) provider. The payload dict
+differs (`messages` instead of `messages` + `system` separately,
+OpenAI-style `tools` schema), so inspect it once before mutating.
+
+```python
+async def add_user_metadata(payload, model):
+ payload["user"] = "u-42" # billable user attribution
+ return payload
+
+agent = Agent(provider=provider, model=model, on_payload=add_user_metadata)
+```
+
+## Tool calling
+
+Tool definitions are auto-converted to OpenAI's
+`{"type": "function", "function": {...}}` shape. The streaming format
+emits incremental JSON arguments under `toolcall_delta`; CubePi
+buffers and parses them through
+[`cubepi.utils.json_parse.parse_streaming_json`](../../api/cubepi-utils)
+so partials always validate to the closest well-formed object.
+
+Multiple parallel tool calls in one assistant message just work —
+they're routed through the same parallel executor as the Anthropic
+provider.
+
+## Common pitfalls
+
+- **`stream_options.include_usage` rejected** — Some compatibles
+ reject the whole `stream_options` field. **`on_payload` cannot fix
+ this**: CubePi 0.3 calls `kwargs.setdefault("stream_options", {})`
+ *after* your callback runs, so deleting the key in `on_payload` is
+ silently undone. Workarounds:
+ - Subclass `OpenAIProvider` and override `stream()` to skip the
+ `setdefault` for your backend.
+ - Set `include_usage=False` in `on_payload` (the field still goes
+ out, but is usually accepted as a no-op even by strict
+ backends).
+ - Use a [`CapabilityDescriptor`](./capability-and-presets) (CubePi
+ `0.5+`) to describe your backend's reasoning wiring declaratively.
+- **Thinking events but no `thinking_*` events** — Your backend
+ surfaces reasoning under a non-standard field. Either add a fourth
+ branch via PR or transcode it with `on_payload`.
+- **Mixed providers in one process** — Each provider holds its own
+ HTTP client. Reuse a single instance per `(base_url, api_key)`
+ pair instead of creating one per agent.
+- **Usage shows 0 input tokens** — Most compatibles omit usage
+ entirely or only emit it on the final chunk. Inspect the trailing
+ chunk in `on_payload` for a hint, or treat token counts as
+ best-effort on those backends.
+
+## See also
+
+- [Anthropic Provider](./anthropic) — the other built-in.
+- [Custom Provider](./custom) — write your own from scratch.
+- [Recipes → Multi-Provider Failover](../../recipes/multi-provider-failover)
+ — combine both providers for resilience.
diff --git a/website/versioned_docs/version-0.6/guides/tracing/cli.md b/website/versioned_docs/version-0.6/guides/tracing/cli.md
new file mode 100644
index 0000000..602cbaa
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/tracing/cli.md
@@ -0,0 +1,176 @@
+---
+title: The trace CLI
+description: "Use the CubePi trace CLI to inspect, filter, and display OpenTelemetry trace spans."
+---
+
+# Inspecting traces with `cubepi trace`
+
+The `JsonlSpanExporter` writes one file per trace under
+`./cubepi-traces/<date>/<trace_id>.jsonl`. The `cubepi trace` CLI (provided by
+the `trace-cli` extra) reads those files so you can see exactly what a run did
+— which LLM and tool calls fired, in what order, what each returned, where it
+errored, and the token counts — without re-running it.
+
+```bash
+pip install 'cubepi[trace-cli]' # or: uv sync --extra trace-cli
+cubepi trace --help
+```
+
+`--dir` defaults to `./cubepi-traces`; pass `--dir <path>` if your traces live
+elsewhere. Each file is one **trace**: the run plus any nested subagent runs,
+which inherit the parent's `trace_id` and so land in the same file.
+
+## `ls` — list recent traces
+
+```bash
+cubepi trace ls # newest first; -n N to limit
+```
+
+| column | meaning |
+|---|---|
+| `started` | trace start time (UTC) |
+| `trace_id` | the id you pass to `view` / `follow` / `stats` |
+| `spans` | span count for the whole trace (incl. subagents) |
+| `status` | `ok` or `error` |
+| `duration` | wall-clock span of the trace |
+| `input` | the user's prompt, to identify the run |
+
+### Filter by run metadata (`--meta`)
+
+If the host stamped run-scoped metadata onto the trace (via
+`tracing_context(metadata=…)` — e.g. cubebox records `conversation_id`,
+`user_id`, `org_id`, `workspace_id` on the root `invoke_agent` span), filter to
+just those traces:
+
+```bash
+cubepi trace ls --meta conversation_id=conv_123
+cubepi trace ls --meta user_id=usr_9 --meta org_id=org_1 # repeatable = AND, exact match
+```
+
+Each `--meta KEY=VALUE` is matched exactly against the trace's root metadata;
+repeating the flag ANDs the conditions.
+
+To **display** metadata values as columns (rather than only filter by them),
+add `--show-meta KEY[,KEY…]`:
+
+```bash
+cubepi trace ls --show-meta conversation_id,user_id
+cubepi trace ls --meta org_id=org_1 --show-meta conversation_id # filter + show
+```
+
+(Or see all of a single trace's metadata with `cubepi trace view <id> -v`.)
+
+## `view` — render a trace as a span tree
+
+A trace-id **prefix** is enough (the table truncates ids); an ambiguous prefix
+lists candidates.
+
+```bash
+cubepi trace view 1cd97cdb
+```
+
+```
+trace
+└── invoke_agent 14425.8ms [0x1cd97cdb]
+ ├── cubepi.turn 1283.1ms [0x5cfda93e]
+ │ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]
+ │ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]
+ │ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested
+ │ └── cubepi.turn 9598.4ms [0x57c5cfc7]
+ │ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]
+ │ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]
+ └── cubepi.turn 491.9ms ERROR [0xce25f242]
+ └── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]
+ └── error: Error code: 400 - ... `tool_use` ids were found without
+ `tool_result` blocks immediately after: call_01_...
+```
+
+Read it top-down: `invoke_agent` (a run) → `cubepi.turn` (one agent-loop turn)
+→ `chat <model>` (an LLM call, with `tok <input>/<output>`) and
+`execute_tool <name>` (a tool call). A **subagent** shows up as
+`execute_tool subagent` with its own `invoke_agent → cubepi.turn → …` nested
+directly beneath it. The `[0x…]` suffix on each node is the span's `span_id` —
+grep it in the raw JSONL to inspect that exact span. Errors print inline under
+the failing span.
+
+Flags:
+
+```bash
+cubepi trace view <id> --content # expand gen_ai prompts / tool args / results
+cubepi trace view <id> -v # expand ALL span attributes (verbose, large)
+```
+
+`--content` requires the run to have been recorded with
+`record_content=True` (see [Content & Redaction](./content-recording)).
+
+## `follow` — watch a trace live
+
+```bash
+cubepi trace follow <id> # polls as spans complete; good for a run in progress
+```
+
+## `stats` — aggregate across traces
+
+```bash
+cubepi trace stats --by model # latency p50/p95, error rate, tokens
+cubepi trace stats --by tool --since 2026-05-20
+```
+
+`stats` also accepts `--meta KEY=VALUE` (same semantics as `ls`) to aggregate
+only the traces that match — e.g. latency / error-rate / tokens for one user or
+conversation:
+
+```bash
+cubepi trace stats --by model --meta user_id=usr_9
+cubepi trace stats --by tool --meta conversation_id=conv_123
+```
+
+## `convert` — reconstruct an API request body
+
+When you need to replay a specific LLM call — reproduce a failure, test a prompt
+change, or run a raw `curl` against the same context — `convert` reads a recorded
+`chat` span and outputs the complete request body.
+
+Requires `record_content=True`.
+
+```bash
+# Default: last chat span in the trace, OpenAI JSON format
+cubepi trace convert <trace_id>
+
+# Select which LLM call to reconstruct
+cubepi trace convert <trace_id> --turn 2 # 2nd chat span (1-indexed)
+cubepi trace convert <trace_id> --span 0xbb7eb1 # by span_id prefix (from `view`)
+
+# Output formats
+cubepi trace convert <trace_id> --format openai # default — JSON request body
+cubepi trace convert <trace_id> --format anthropic # Anthropic Messages API body
+cubepi trace convert <trace_id> --format curl # shell-executable curl command
+```
+
+The `[0x…]` span id from `view` output goes directly into `--span`:
+
+```
+├── chat kimi-k2.6 31704.5ms [0xbb7eb192] ← paste as: --span 0xbb7eb1
+├── chat kimi-k2.6 32420.2ms [0x7c76f48d] ← or: --span 0x7c76f4
+```
+
+The reconstructed body includes the full conversation history, the system prompt,
+all tool definitions, and request parameters (`model`, `max_tokens`,
+`temperature`). Pipe to `python -m json.tool`, `jq`, or directly to a replay script.
+
+## Beyond the CLI
+
+The files are plain JSONL — one span per line — so you can parse them directly
+(`jq`, `python -c`) to pull a specific attribute (`gen_ai.usage.*`,
+`gen_ai.tool.call.result`, `gen_ai.input.messages`, …). Error detail lives in a
+span **event** named `gen_ai.client.operation.exception`.
+
+:::tip For AI agents
+A bundled `cubepi-trace` skill drives this CLI for debugging ("why did the run
+end with no reply?", "the tool result is wrong"). It encodes the fast path
+(`ls` → `view <prefix>`) and the token/cache-rate conventions.
+
+```bash
+npx skills add cubeplexai/cubepi@cubepi-trace -a claude-code
+```
+:::
diff --git a/website/versioned_docs/version-0.6/guides/tracing/content-recording.md b/website/versioned_docs/version-0.6/guides/tracing/content-recording.md
new file mode 100644
index 0000000..a469c95
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/tracing/content-recording.md
@@ -0,0 +1,164 @@
+---
+title: Content & Redaction
+description: "Configure prompt content recording and redaction in CubePi's OpenTelemetry tracing."
+sidebar_position: 4
+---
+
+# Recording Prompts, Responses, and Tool Payloads
+
+By default CubePi's tracing emits structural attributes only — operation
+names, models, token counts, finish reasons, durations. **No prompt content,
+no model output, no tool arguments or results leave the process.** This is
+deliberate: many agent setups handle PII, customer data, or trade-secret
+prompts that don't belong in a third-party observability backend.
+
+When you _do_ want content captured — for offline evaluation, debugging a
+flaky tool call, or building a labelled dataset — opt in explicitly with
+`record_content=True`, and combine it with a `redact` callback to strip the
+sensitive parts before they leave the process.
+
+## Turning content recording on
+
+```python
+tracer = Tracer(
+ service_name="my-bot",
+ agent_name="assistant",
+ record_content=True, # ← opt-in
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+)
+```
+
+With `record_content=True`, each span layer carries the relevant content
+attributes per the OTel GenAI semconv:
+
+| Span | Content attributes added |
+|---|---|
+| `invoke_agent` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.output.messages` |
+| `cubepi.turn` | `gen_ai.input.messages` (per-turn slice), `gen_ai.output.messages` (per-turn slice) |
+| `chat <model>` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.tool.definitions`, `cubepi.llm.raw_request`, `cubepi.llm.raw_response` |
+| `execute_tool <tool_name>` | `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result` |
+
+The `chat` span's `gen_ai.input.messages` contains the **full chronological
+context** the provider request actually carried — including prior assistant
+turns and tool results — not just the new user prompt. This matters for
+multi-turn tool-using runs: trace consumers can reconstruct exactly what
+the model saw at each call.
+
+## Redacting before export
+
+`redact` is a `(key, value) -> value | None` callback invoked at every
+content-attribute set site. Return:
+
+- The original value unchanged → keep as-is
+- A modified value of the same shape → substitute
+- `None` → drop the attribute entirely
+
+```python
+def redact(key: str, value):
+ # Strip secrets from prompts before they leave the process.
+ if key in ("gen_ai.input.messages", "gen_ai.output.messages"):
+ return _scrub_messages(value)
+ # Don't ship raw bodies at all in prod — keep only the normalised shape.
+ if key in ("cubepi.llm.raw_request", "cubepi.llm.raw_response"):
+ return None
+ return value
+
+
+tracer = Tracer(
+ service_name="my-bot",
+ record_content=True,
+ redact=redact,
+ exporters=[…],
+)
+```
+
+`redact` is the single chokepoint for content — the recorder calls it once
+per attribute before serializing into the OTel attribute, so anything the
+function returns is what hits the wire. Exceptions inside `redact` are
+swallowed (the attribute is dropped in that case), so a buggy redactor
+fails closed rather than leaking.
+
+### Common patterns
+
+Drop everything but per-message length so dashboards still work without
+shipping content:
+
+```python
+def redact(key, value):
+ if key in ("gen_ai.input.messages", "gen_ai.output.messages"):
+ return [{"role": m["role"], "parts": [{"type": "text", "content": "<redacted>",
+ "length": sum(len(p.get("content", "")) for p in m["parts"])}]}
+ for m in value]
+ return value
+```
+
+Tag-based selective recording — strip everything unless a thread is opted in:
+
+```python
+import contextvars
+RECORD = contextvars.ContextVar("trace.record_content", default=False)
+
+def redact(key, value):
+ return value if RECORD.get() else None
+```
+
+then `RECORD.set(True)` for the runs you want captured.
+
+## Size budgets
+
+OTel attribute values are JSON-serialized inside the recorder. Most backends
+truncate or reject attributes over a few hundred KB. If you're recording
+the raw provider response on every chat span, multi-turn agentic runs can
+get large fast. Drop or summarise via `redact` for any field over your
+budget.
+
+## Stream-level recording
+
+`record_content` captures the final assembled request and response on each `chat`
+span, but not the individual streaming chunks. For post-mortem debugging of
+streaming failures — empty tool call arguments, duplicate events, truncated
+output — enable `record_stream` to write a chunk-by-chunk event log alongside the
+main trace:
+
+```python
+tracer = Tracer(
+ record_content=True, # needed for trace convert
+ record_stream=True, # ← per-chunk event log
+ stream_dir="./cubepi-traces", # where to write <run_id>.stream.jsonl
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+)
+```
+
+`record_stream` writes `<stream_dir>/<run_id>.stream.jsonl` (one JSON line per
+`StreamEvent`). Every line carries `t` (elapsed seconds from run start) and
+`type`. Tool-call lines also include `ci` (content index), `id`, `name`, delta
+sizes, and argument previews:
+
+```json
+{"t": 5.873, "type": "toolcall_start", "ci": 1, "id": "toolu_...", "name": "show_widget"}
+{"t": 5.875, "type": "toolcall_delta", "ci": 1, "chars": 11, "accumulated": 11, "preview": "{\"title\": \""}
+{"t": 33.177, "type": "toolcall_end", "ci": 1, "id": "toolu_...", "args_chars": 7465, "args_preview": "{\"title\": \"CubePi..."}
+```
+
+This makes it straightforward to confirm whether argument chunks ever arrived, or
+whether the same event fired twice (e.g. a provider that sends `finish_reason`
+twice produces two `toolcall_end` lines for the same `ci`).
+
+`record_stream` is independent of `record_content` — turn it on only in debugging
+sessions. Files can grow large for long-running, tool-heavy agents.
+
+## Auditing what's recorded
+
+The recorder always sets `service.name`, `gen_ai.agent.name`, and
+`cubepi.run_id` on every span — regardless of `record_content`. Use these
+to filter the trace backend to a single run and visually confirm what
+landed.
+
+For deeper audits, `JsonlSpanExporter` writes one line per span, so you can
+grep / `jq` the local files before pointing the same exporter at a remote
+backend:
+
+```bash
+jq -r 'select(.attributes["gen_ai.input.messages"]) | .attributes["gen_ai.input.messages"]' \
+ cubepi-traces/2026-05-19/*.jsonl
+```
diff --git a/website/versioned_docs/version-0.6/guides/tracing/getting-started.md b/website/versioned_docs/version-0.6/guides/tracing/getting-started.md
new file mode 100644
index 0000000..31445e8
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/tracing/getting-started.md
@@ -0,0 +1,232 @@
+---
+title: Getting Started
+description: "Get started with OpenTelemetry tracing in CubePi — install, configure, and export spans."
+sidebar_position: 2
+---
+
+# Getting Started with Tracing
+
+## Install the extra
+
+CubePi keeps OpenTelemetry an optional dependency:
+
+```bash
+pip install "cubepi[tracing]"
+```
+
+This pulls in `opentelemetry-sdk` and friends. Without the extra, the
+`cubepi.tracing` import raises a clear error so you find out at import time
+rather than mid-run.
+
+## Attach a Tracer
+
+The minimal end-to-end setup — local JSONL export, idiomatic RAII:
+
+```python
+import asyncio
+from cubepi import Agent, Model
+from cubepi.providers.anthropic import AnthropicProvider
+from cubepi.tracing import Tracer
+from cubepi.tracing.exporters import JsonlSpanExporter
+
+
+async def main() -> None:
+ agent = Agent(
+ provider=AnthropicProvider(api_key="…"),
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="Be helpful.",
+ )
+
+ async with (
+ Tracer(
+ service_name="my-bot",
+ agent_name="assistant",
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+ ) as tracer,
+ tracer.attached(agent),
+ ):
+ await agent.prompt("Say hello.")
+ await agent.wait_for_idle()
+ # On exit: auto-detach (closes any cancelled-run spans, awaits the
+ # flush) + tracer shutdown (flushes + closes exporters). No
+ # try/finally needed.
+
+
+asyncio.run(main())
+```
+
+If you can't restructure into an `async with` (e.g. long-lived web
+handler that hands the agent around), the explicit pattern still
+works and is fully equivalent:
+
+```python
+detach = tracer.attach(agent)
+try:
+ await agent.prompt("…")
+finally:
+ # Either is enough on its own:
+ # await detach() # awaits the scheduled flush
+ # await tracer.shutdown() # flushes + closes exporters
+ detach()
+ await tracer.shutdown()
+```
+
+Even if you forget the cleanup entirely, `Tracer` registers an
+`atexit` hook by default that sync-flushes buffered spans at process
+exit — pass `atexit_flush=False` to opt out, or rely on it as a
+safety net while you're still building. (Doesn't run on `SIGKILL` or
+`os._exit`; for guaranteed delivery there, use the synchronous
+`SimpleSpanProcessor` from OTel.)
+
+The run produces one JSONL file per trace (sharded by `trace_id`):
+
+```text
+./cubepi-traces/
+ 2026-05-19/
+ 8e1c9a3f4b2d…d976a.jsonl ← one trace, one file, one span per line
+```
+
+A trace is the whole run, including any nested subagent runs (they inherit the
+parent's `trace_id`, so they land in the same file). Each span still carries
+`cubepi.run_id` as an attribute if you want to filter by individual run.
+
+Open it with any tool that reads OTLP/JSON or with `jq` directly:
+
+```bash
+jq -r '"\(.name) \(.attributes."gen_ai.operation.name" // "")"' \
+ cubepi-traces/2026-05-19/*.jsonl
+# invoke_agent invoke_agent
+# cubepi.turn
+# chat claude-sonnet-4-5-20250929 chat
+```
+
+## Span hierarchy
+
+For a single prompt with one LLM round-trip, the recorder produces three spans:
+
+```text
+invoke_agent assistant [INTERNAL] gen_ai.operation.name=invoke_agent
+└── cubepi.turn [INTERNAL] cubepi.turn.index=0
+ └── chat <model> [CLIENT] gen_ai.operation.name=chat
+```
+
+When the model calls a tool, you get an extra layer per tool:
+
+```text
+invoke_agent assistant
+└── cubepi.turn ← turn index 0
+ ├── chat <model> ← first round trip
+ └── execute_tool <tool_name> ← gen_ai.tool.name, gen_ai.tool.call.id
+└── cubepi.turn ← turn index 1 (response after tool result)
+ └── chat <model>
+```
+
+For MCP tools the `execute_tool` span gets a CLIENT child:
+
+```text
+execute_tool <tool_name> [INTERNAL] cubepi-side wrapper
+└── tools/call <tool_name> [CLIENT] gen_ai.operation.name=execute_tool
+ mcp.method.name=tools/call
+ mcp.session.id=…
+ server.address / server.port
+```
+
+The CLIENT span injects W3C `traceparent` into outgoing HTTP headers, so an
+instrumented MCP server can continue the trace.
+
+## Cancellation, errors, aborts
+
+The recorder treats cancellation as a control signal, not a failure:
+
+- `agent.abort()` mid-stream → spans close with `cubepi.aborted=true` and
+ `error.type=cubepi.aborted`, **status UNSET** (per OTel guidance — cancellation
+ isn't an error).
+- A provider raising → chat/turn/root close with **status ERROR**, an
+ `exception` event on the chat span, and `error.type` derived from the
+ exception class (`timeout`, `connection_error`, fully-qualified class name, …).
+- An MCP `tools/call` returning `isError=true` → CLIENT span closes
+ ERROR + `error.type=mcp.is_error`.
+
+Either way, `detach()` and `tracer.shutdown()` always close any span the run
+left open, so cancelled runs are still visible in your backend rather than
+silently disappearing.
+
+## What's on each span
+
+Defaults (no opt-in needed):
+
+- `invoke_agent` (root) — `gen_ai.operation.name`, `gen_ai.provider.name`,
+ `gen_ai.agent.name`, `cubepi.run_id`, `cubepi.agent.system_prompt.sha256`,
+ `cubepi.agent.tools` (names list), `cubepi.input_messages.count`,
+ `cubepi.output_messages.count`
+- `cubepi.turn` — `cubepi.turn.index`, `cubepi.turn.stop_reason`,
+ `cubepi.turn.tool_calls.count`, `cubepi.turn.terminated_by_tool`,
+ `cubepi.run_id`
+- `chat <model>` — `gen_ai.operation.name`, `gen_ai.provider.name`,
+ `gen_ai.request.model`, `gen_ai.request.max_tokens` / `temperature` /
+ `top_p`, `gen_ai.request.stream`, `gen_ai.usage.input_tokens` /
+ `output_tokens` / `cache_read_input_tokens` / `cache_creation_input_tokens` /
+ `reasoning_output_tokens`, `gen_ai.response.model` /
+ `finish_reasons` / `id`, `gen_ai.response.time_to_first_chunk`, plus
+ OpenAI-specific extras (`openai.api.type`, service tier, system fingerprint)
+- `execute_tool <tool_name>` — `gen_ai.operation.name=execute_tool`,
+ `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.description`,
+ `gen_ai.tool.type`, `cubepi.tool.is_error`, `cubepi.tool.execution_mode`
+- `tools/call <tool_name>` (MCP only) — `mcp.method.name`, `mcp.session.id`,
+ `mcp.protocol.version`, `server.address`, `server.port`, `gen_ai.tool.name`
+
+Optional, opt-in via `Tracer(record_content=True)`:
+`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`,
+`gen_ai.tool.definitions`, `gen_ai.tool.call.arguments`,
+`gen_ai.tool.call.result`, `cubepi.llm.raw_request`,
+`cubepi.llm.raw_response`. See [Content & Redaction](./content-recording).
+
+## Multiple agents, one process
+
+Both `Tracer` and `Meter` are fine to share across agents — call
+`attach(agent)` multiple times. Each attach gets its own recorder /
+metric state so concurrent agents don't share span or histogram state,
+and MCP CLIENT spans route through the right Tracer based on which
+agent's `execute_tool` span is the parent.
+
+With the RAII helper, stacking them is one `async with`:
+
+```python
+async with (
+ Tracer(...) as tracer,
+ tracer.attached(agent_a),
+ tracer.attached(agent_b),
+):
+ await asyncio.gather(agent_a.prompt("…"), agent_b.prompt("…"))
+```
+
+## Tagging individual runs
+
+`cubepi.tracing.tracing_context` scopes per-run tags / metadata onto
+the `invoke_agent` span — perfect for `user_id`, `session_id`,
+A/B-test arm, anything you'd want to filter by in the backend later:
+
+```python
+from cubepi.tracing import tracing_context
+
+async with tracer.attached(agent):
+ with tracing_context(tags=["beta-arm"], metadata={"user_id": "u-42"}):
+ await agent.prompt("Hello.")
+```
+
+Attributes on the span:
+
+- `cubepi.tags = ("beta-arm",)`
+- `cubepi.metadata.user_id = "u-42"`
+
+The `cubepi.metadata.*` prefix keeps user keys from clobbering
+recorder-owned schema (e.g. `cubepi.run_id`). Tags and metadata
+contextvars are per-asyncio-task, so concurrent agents see
+independent values, and nested `tracing_context` blocks merge
+(tags concatenate, metadata keys union with inner winning).
+
+## Next
+
+- [OTLP & Backends](./otlp) — Jaeger, Tempo, Honeycomb, Datadog, …
+- [Content Recording & Redaction](./content-recording)
+- [Metrics](./metrics)
diff --git a/website/versioned_docs/version-0.6/guides/tracing/metrics.md b/website/versioned_docs/version-0.6/guides/tracing/metrics.md
new file mode 100644
index 0000000..fc5d315
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/tracing/metrics.md
@@ -0,0 +1,153 @@
+---
+title: Metrics
+description: "Collect token usage, latency, and time-to-first-content metrics in CubePi tracing."
+sidebar_position: 5
+---
+
+# Metrics with `Meter`
+
+Spans tell you the shape of one run; histograms tell you the shape of the
+fleet. `cubepi.tracing.Meter` mirrors `Tracer` and emits the OTel GenAI
+metric set so dashboards work out of the box.
+
+## What it emits
+
+| Instrument | Description |
+|---|---|
+| `gen_ai.client.operation.duration` | Histogram (seconds) — recorded for `chat`, `execute_tool`, and `invoke_agent` on close |
+| `gen_ai.client.operation.time_to_first_chunk` | Histogram (seconds) — recorded for `chat` when at least one content chunk arrived |
+| `gen_ai.client.token.usage` | Histogram (`{token}`) — one observation per `gen_ai.token.type` (`input`, `output`) per chat response |
+
+Each point carries the operation, provider, and request model attributes
+so failed / cancelled requests (where no response body / response model
+landed) are still groupable by what was asked for:
+
+- `gen_ai.operation.name` — `chat` / `execute_tool` / `invoke_agent`
+- `gen_ai.provider.name` — `anthropic`, `openai`, `openai_responses`, …
+- `gen_ai.request.model` — e.g. `claude-sonnet-4-5-20250929`
+- `gen_ai.response.model` — e.g. `claude-sonnet-4-5-20250929` (success only)
+- `gen_ai.token.type` — `input` or `output` (token usage only)
+
+## Attaching a Meter
+
+The idiomatic RAII form — `async with` everything, no manual cleanup:
+
+```python
+from opentelemetry.exporter.otlp.proto.http.metric_exporter import (
+ OTLPMetricExporter,
+)
+from cubepi.tracing import Tracer, Meter
+from cubepi.tracing.exporters import JsonlSpanExporter
+
+async with (
+ Tracer(
+ service_name="my-bot",
+ agent_name="assistant",
+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],
+ ) as tracer,
+ Meter(
+ resource=tracer.resource, # share Resource so service.* matches spans
+ exporters=[
+ OTLPMetricExporter(endpoint="http://otel-collector:4318/v1/metrics"),
+ ],
+ ) as meter,
+ tracer.attached(agent),
+ meter.attached(agent),
+):
+ await agent.prompt("...")
+# Exit order auto: detach both (closes any cancelled-run spans, flushes
+# the trace pipeline) → shutdown both (flush + close exporters).
+```
+
+`Meter.attach()` is independent from `Tracer.attach()`. You can run
+either on its own; the recommended setup is both, sharing one
+`Resource` so the backend treats them as the same service.
+
+If you need the explicit, non-RAII form (e.g. attaching agents
+dynamically over the lifetime of a long-running server):
+
+```python
+tracer_detach = tracer.attach(agent)
+meter_detach = meter.attach(agent)
+try:
+ ...
+finally:
+ tracer_detach() # closes any cancelled-run spans
+ meter_detach() # unsubscribes the meter's listeners
+ await tracer.shutdown()
+ await meter.shutdown()
+```
+
+## Bucket boundaries
+
+The duration histograms ship with the OTel GenAI semconv's recommended
+boundaries (in seconds):
+
+```text
+0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300
+```
+
+OTel exposes these as the `_advisory` boundaries; backends are free to use
+them as-is or override.
+
+## Concurrent agents on one Meter
+
+Like `Tracer`, one `Meter` instance is safe to attach to multiple agents
+in the same process. Each `attach()` call gets its own internal
+`_MeterState` holding the open-ns timestamps and attribute dicts, so
+overlapping runs from two agents never share or overwrite each other's
+metric state.
+
+```python
+meter = Meter(resource=tracer.resource, exporters=[exporter])
+meter.attach(agent_a)
+meter.attach(agent_b)
+```
+
+Both agents emit independent duration / token / TTFC observations,
+filterable by `gen_ai.agent.name` (set at the `Resource` level when
+`Tracer(agent_name=…)` is used) or by `gen_ai.request.model`.
+
+## Shutting down
+
+The RAII form (`async with … as tracer, … as meter, tracer.attached(agent),
+meter.attached(agent):` from above) handles the shutdown ordering for you:
+detach inner first → outer `Tracer/Meter` `__aexit__` runs `shutdown()`.
+
+For the manual pattern, order matters — `tracer_detach()` must run before
+`tracer.shutdown()` so any spans an in-flight cancellation left open get
+closed and exported in the same flush:
+
+```python
+finally:
+ tracer_detach()
+ meter_detach()
+ await tracer.shutdown()
+ await meter.shutdown()
+```
+
+`Meter.shutdown()` awaits a flush of the metric reader, then closes it.
+`PeriodicExportingMetricReader` exports on a fixed interval (60 s by
+default) — `shutdown` is the only way to guarantee the final window lands
+before the process exits.
+
+## Querying example (Honeycomb)
+
+p95 chat latency by provider over the last hour:
+
+```text
+VISUALIZE P95(duration_s)
+GROUP BY gen_ai.provider.name
+WHERE gen_ai.operation.name = "chat"
+TIME last 1 hour
+```
+
+Token usage by model:
+
+```text
+VISUALIZE SUM(token_count)
+GROUP BY gen_ai.request.model, gen_ai.token.type
+WHERE gen_ai.operation.name = "chat"
+```
+
+Substitute your backend's query DSL — same attributes, same aggregations.
diff --git a/website/versioned_docs/version-0.6/guides/tracing/otlp.md b/website/versioned_docs/version-0.6/guides/tracing/otlp.md
new file mode 100644
index 0000000..0b3d352
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/tracing/otlp.md
@@ -0,0 +1,175 @@
+---
+title: OTLP & Backends
+description: "Export CubePi OpenTelemetry traces to OTLP-compatible backends like Jaeger, Tempo, or Honeycomb."
+sidebar_position: 3
+---
+
+# Exporting to OTLP Backends
+
+`cubepi.tracing.Tracer` accepts any `opentelemetry.sdk.trace.export.SpanExporter`,
+so anything in the OpenTelemetry ecosystem works. Pick the wire format
+(HTTP or gRPC), point it at your collector, hand the exporter to the Tracer.
+
+## HTTP (OTLP/HTTP)
+
+```bash
+pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-http
+```
+
+```python
+from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
+ OTLPSpanExporter,
+)
+from cubepi.tracing import Tracer
+
+tracer = Tracer(
+ service_name="my-bot",
+ service_version="1.4.2",
+ deployment_environment="prod",
+ agent_name="assistant",
+ exporters=[
+ OTLPSpanExporter(
+ endpoint="http://otel-collector:4318/v1/traces",
+ headers={"x-api-key": "…"}, # backend-specific
+ ),
+ ],
+)
+```
+
+`service_name`, `service_version`, `deployment_environment`, and `agent_name`
+flow through as OTel Resource attributes (`service.*`, `gen_ai.agent.name`,
+`deployment.environment.name`) so backends can group runs without further
+config.
+
+## gRPC (OTLP/gRPC)
+
+```bash
+pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-grpc
+```
+
+```python
+from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
+ OTLPSpanExporter,
+)
+
+exporter = OTLPSpanExporter(endpoint="otel-collector:4317", insecure=True)
+tracer = Tracer(service_name="my-bot", exporters=[exporter])
+```
+
+## Backend recipes
+
+These all consume OTLP — the only thing that differs is the endpoint and
+auth header.
+
+### Jaeger (>=1.50)
+
+Jaeger natively accepts OTLP/HTTP on port 4318:
+
+```python
+OTLPSpanExporter(endpoint="http://jaeger:4318/v1/traces")
+```
+
+### Grafana Tempo
+
+Send to your collector, or directly to Tempo's OTLP endpoint:
+
+```python
+OTLPSpanExporter(endpoint="http://tempo:4318/v1/traces")
+```
+
+### Honeycomb
+
+```python
+OTLPSpanExporter(
+ endpoint="https://api.honeycomb.io/v1/traces",
+ headers={"x-honeycomb-team": HONEYCOMB_API_KEY},
+)
+```
+
+### Datadog (via the OTel collector)
+
+Configure the collector with the Datadog exporter, then ship to it:
+
+```python
+OTLPSpanExporter(endpoint="http://otel-collector:4318/v1/traces")
+```
+
+Datadog also accepts native OTLP HTTP directly — same shape, different URL.
+
+### AWS X-Ray (via collector)
+
+The OTel collector includes the AWS X-Ray exporter; treat it like any other
+OTLP target.
+
+## Continuing an upstream trace
+
+`Tracer.attach(agent)` currently roots every agent run in its own trace —
+there is no public API yet for passing an inbound `traceparent` so that
+spans nest under a caller's HTTP handler trace. The internal hook
+(`Tracer._make_parent_context`) exists for a future `run_scope` feature;
+until that ships, agent runs and the surrounding service trace are linked
+only by their resource attributes (`service.name`, `gen_ai.agent.name`,
+`cubepi.run_id`).
+
+If you need the upstream trace to continue into CubePi today, the
+workaround is to set the OTel current span yourself before calling
+`agent.prompt(...)` and let the agent's spans inherit it via OTel's
+ambient context — CubePi never overrides an active parent.
+
+On the way out, MCP `tools/call` does inject W3C `traceparent` as an HTTP
+header automatically, so an instrumented MCP server downstream of the
+agent can continue the trace through to its own backend.
+
+## Combining exporters
+
+You can pass multiple exporters and they'll receive every span. Common
+pattern — JSONL for local debugging plus OTLP for the production backend:
+
+```python
+tracer = Tracer(
+ service_name="my-bot",
+ exporters=[
+ JsonlSpanExporter(directory="./cubepi-traces"),
+ OTLPSpanExporter(endpoint="https://api.honeycomb.io/v1/traces", headers={…}),
+ ],
+)
+```
+
+## Flushing
+
+`Tracer` uses `BatchSpanProcessor` under the hood, so spans are exported in
+the background. The recommended pattern — and the one that exercises all
+the cleanup paths automatically — is the `async with` form:
+
+```python
+async with Tracer(...) as tracer, tracer.attached(agent):
+ await agent.prompt("...")
+# On exit:
+# - detach() runs synchronously: closes any spans a cancelled run left
+# open, then schedules the flush as an asyncio.Task and awaits it.
+# - tracer.shutdown() flushes again (idempotent) and closes exporters.
+```
+
+If you've stored `detach` from a manual `tracer.attach(agent)` call, it
+returns the scheduled flush `Task`. Two valid manual patterns:
+
+```python
+# (a) Belt-and-braces — safest, both run.
+finally:
+ detach() # closes cancelled-run spans, schedules flush
+ await tracer.shutdown() # awaits force_flush, then shuts the SDK down
+
+# (b) Awaited detach — single call when you're not also shutting down.
+finally:
+ await detach() # awaits the scheduled flush
+```
+
+Outside an async context (no running loop) `detach()` returns `None` — the
+sync part has run, but the flush is the caller's responsibility via
+`await tracer.shutdown()`.
+
+If even that gets missed — say a script raises before reaching `finally` —
+`Tracer(atexit_flush=True)` (the default) registers a process-exit handler
+that sync-flushes buffered spans through `BatchSpanProcessor`. Doesn't run
+on `SIGKILL` / `os._exit`; for guaranteed delivery there, use
+`SimpleSpanProcessor` (sync export per span).
diff --git a/website/versioned_docs/version-0.6/guides/tracing/overview.md b/website/versioned_docs/version-0.6/guides/tracing/overview.md
new file mode 100644
index 0000000..d6fa591
--- /dev/null
+++ b/website/versioned_docs/version-0.6/guides/tracing/overview.md
@@ -0,0 +1,100 @@
+---
+title: Tracing Overview
+description: "Overview of CubePi's OpenTelemetry-native tracing system — spans, attributes, exporters, and semantic conventions."
+sidebar_position: 1
+---
+
+# Tracing Overview
+
+CubePi emits [OpenTelemetry](https://opentelemetry.io/) spans that follow the
+[GenAI Semantic Conventions v1.41](https://opentelemetry.io/docs/specs/semconv/gen-ai/)
+so any OTel-compatible backend (Jaeger, Tempo, Honeycomb, Datadog, AWS X-Ray,
+Azure Monitor, …) can ingest agent runs without custom instrumentation.
+
+Attach a `Tracer` to an `Agent` and every prompt produces a tree of spans you
+can pivot, query, and join with the rest of your service traces:
+
+```
+trace
+└── invoke_agent 14425.8ms [0x1cd97cdb] ← one per agent.prompt()
+ ├── cubepi.turn 1283.1ms [0x5cfda93e] ← one per LLM round-trip
+ │ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]
+ │ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]
+ │ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested
+ │ └── cubepi.turn 9598.4ms [0x57c5cfc7]
+ │ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]
+ │ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]
+ └── cubepi.turn 491.9ms ERROR [0xce25f242]
+ └── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]
+ └── error: Error code: 400 - ... `tool_use` ids were found without
+ `tool_result` blocks immediately after: call_01_...
+```
+
+Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,
+`gen_ai.request.model`, `gen_ai.provider.name`, `gen_ai.usage.input_tokens`,
+`gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`, …
+
+## What ships out of the box
+
+- **Tracer** — builds an SDK `TracerProvider`, attaches one
+ `BatchSpanProcessor` per exporter, wires the CubePi event stream into spans.
+- **Meter** — sibling for OTel histograms:
+ `gen_ai.client.operation.duration`, `gen_ai.client.operation.time_to_first_chunk`,
+ `gen_ai.client.token.usage`.
+- **JsonlSpanExporter** — write one JSON line per span to
+ `./cubepi-traces/<date>/<trace_id>.jsonl`. Files are sharded by `trace_id`,
+ so one file holds a whole trace — the run plus any nested subagent runs
+ (which inherit the trace). Useful for local dev and offline debugging; works
+ with any OTel viewer that reads JSONL, and with the [`cubepi trace`
+ CLI](./cli).
+- **OTLP** — bring your own exporter via `opentelemetry-exporter-otlp-proto-http`
+ (HTTP) or `…-grpc` and hand it to `Tracer(exporters=[…])`.
+- **W3C trace context propagation** — outgoing MCP calls inject the active
+ `traceparent` as an HTTP header so an instrumented MCP server can continue
+ the trace.
+- **`tracer.attached(agent)` / `meter.attached(agent)`** — async context
+ managers that RAII-wrap attach/detach, so cleanup is one `async with`
+ block instead of an explicit `try/finally`.
+- **`atexit` flush hook** — `Tracer(atexit_flush=True)` (default) registers
+ a process-exit handler that sync-flushes any buffered spans, so callers
+ who forget `await tracer.shutdown()` still get their spans exported on
+ normal exit / Ctrl-C / unhandled exception.
+- **`tracing_context()`** — set per-run tags and metadata
+ (`cubepi.tags = ("beta-arm",)`, `cubepi.metadata.user_id = "u-42"`)
+ via a contextvar-scoped block. Concurrent agents each see their own
+ values.
+
+## What it costs
+
+- One pure-Python recorder per agent run subscribing to the agent's event
+ stream and the provider's listener registry — no monkey-patching, no extra
+ threads.
+- One OTel SDK span per layer above. `BatchSpanProcessor` batches export off
+ the hot path.
+- **No payloads are recorded by default.** `gen_ai.input.messages`,
+ `gen_ai.output.messages`, raw request/response, and tool args/results all
+ require explicit opt-in via `record_content=True` so you don't accidentally
+ ship PII to your backend. See [Content & Redaction](./content-recording).
+
+## When to use each piece
+
+| You want | Use |
+|---|---|
+| Trace one local agent run and inspect a JSONL file | `Tracer` + `JsonlSpanExporter` |
+| Ship to Jaeger / Tempo / Honeycomb / Datadog | `Tracer` + OTLP exporter |
+| Latency + token histograms next to the spans | `Meter` alongside `Tracer` |
+| Record prompts / model outputs for evaluation | `Tracer(record_content=True)` |
+| Redact PII before it leaves the process | `Tracer(redact=…)` |
+| Tag runs with `user_id` / `session_id` / A-B arm | `tracing_context(tags=…, metadata=…)` |
+| One-liner cleanup, no try/finally | `async with tracer.attached(agent): …` |
+| Forget to call `shutdown()` and not lose spans | `Tracer(atexit_flush=True)` (default) |
+| Continue a trace from an upstream service | `Tracer(resource=…)` + W3C `traceparent` (auto for MCP, manual for HTTP) |
+
+## Where to go next
+
+- [Getting Started](./getting-started) — install the extra and emit your
+ first spans
+- [OTLP & Backends](./otlp) — point CubePi at Jaeger, Tempo, Honeycomb, …
+- [Content Recording & Redaction](./content-recording) — record prompts and
+ responses safely
+- [Metrics](./metrics) — histograms via `Meter`
diff --git a/website/versioned_docs/version-0.6/intro.mdx b/website/versioned_docs/version-0.6/intro.mdx
new file mode 100644
index 0000000..c5bf6eb
--- /dev/null
+++ b/website/versioned_docs/version-0.6/intro.mdx
@@ -0,0 +1,77 @@
+---
+id: intro
+title: CubePi
+description: "A Pythonic, async-native agent framework. Plain async functions, append-only checkpointing, three dependencies."
+slug: /
+sidebar_position: 0
+---
+
+import PackageVersion from '@site/src/components/PackageVersion';
+
+# CubePi
+
+**CubePi** is a Pythonic, async-native agent framework designed for high
+performance, readability, and production-grade persistence. It provides a
+leaner alternative to graph-based agent runtimes by modeling agent logic as
+a linear `while` loop that developers can easily trace and debug.
+
+```bash
+pip install cubepi
+```
+
+Then jump to the [Quick Start](./getting-started/quick-start) to ship a
+working tool-using agent in under five minutes.
+
+## What you get
+
+- **Plain async functions, not graph nodes.** The agent loop is a
+ `while` loop over message turns. You build tools as `async def`
+ functions; the framework routes calls and executes them in parallel.
+- **One streaming pattern.** Every provider yields `StreamEvent`s
+ through a `MessageStream`. You iterate it with `async for`. No
+ callback registries, no separate handler types for text vs. tools.
+- **Append-only checkpointing.** Persistence writes the new messages on
+ each turn, not the full transcript. O(1) DB I/O regardless of
+ conversation length — SQLite for laptops, Postgres for production.
+- **Native multi-provider.** Anthropic and OpenAI ship in the box,
+ through a `Provider` Protocol. Add a new provider in one class.
+- **Seven-hook middleware.** `transform_context`, `convert_to_llm`,
+ `transform_system_prompt`, `before_tool_call`, `after_tool_call`,
+ `should_stop_after_turn`, `after_model_response` — each with explicit
+ composition rules. No mystery node ordering.
+- **MCP loaders.** Point at any
+ [Model Context Protocol](https://modelcontextprotocol.io) server
+ (HTTP or stdio) and get back a list of `AgentTool`s.
+- **OpenTelemetry built in.** Attach a `Tracer` and every prompt
+ produces a tree of OTel spans aligned with the GenAI Semantic
+ Conventions — works with Jaeger, Tempo, Honeycomb, Datadog, or any
+ OTLP-compatible backend. No payloads recorded by default; opt in
+ with `record_content=True` and a `redact` callback.
+
+## Where to go next
+
+| If you want to… | Start here |
+|---|---|
+| Install and run your first agent | [Getting Started → Installation](./getting-started/installation) |
+| Understand the building blocks | [Getting Started → Core Concepts](./getting-started/core-concepts) |
+| Wire a real tool-using agent | [Guides → Building Your First Agent](./guides/agents/first-agent) |
+| Persist a conversation across restarts | [Guides → SQLite Checkpointing](./guides/checkpointing/sqlite) |
+| Ship traces to Jaeger / Tempo / Honeycomb | [Guides → Tracing](./guides/tracing/overview) |
+| Look up a specific symbol | [API Reference](./api/) |
+| See full working examples | [Recipes](./recipes/weather-agent) |
+| Port an existing langgraph agent | [Migration → From langgraph](./migration/from-langgraph) |
+
+## Status
+
+You are reading the **Next 🚧** channel — unreleased docs that track
+the `main` branch. APIs documented here can still change before they
+ship in a tagged release.
+
+The latest released version is `v<PackageVersion/>` ([switch to it
+from the version picker, top-right](pathname:///)). The native
+OpenTelemetry tracing module ([guide →](./guides/tracing/overview))
+— `Tracer`, `Meter`, content recording, MCP CLIENT spans, per-run
+`tracing_context` tags — landed in 0.4.
+
+Source, issues, and discussion live on
+[GitHub](https://github.com/cubeplexai/cubepi).
diff --git a/website/versioned_docs/version-0.6/migration/from-langgraph.md b/website/versioned_docs/version-0.6/migration/from-langgraph.md
new file mode 100644
index 0000000..2214b18
--- /dev/null
+++ b/website/versioned_docs/version-0.6/migration/from-langgraph.md
@@ -0,0 +1,244 @@
+---
+title: From langgraph
+description: "Migrate your agents from LangGraph to CubePi."
+---
+
+# Migrating from langgraph
+
+CubePi and [langgraph](https://github.com/langchain-ai/langgraph) both
+build tool-using LLM agents, but they have different mental models.
+This page maps langgraph concepts onto CubePi so you can port code
+without having to re-learn from scratch.
+
+## Mental-model shift
+
+| langgraph | CubePi | Why |
+|---|---|---|
+| **State graph** with nodes, edges, channels | **Agent loop** that's a plain `while` loop you can read | A linear loop is easier to reason about than a graph; CubePi never branches at runtime — control flow lives in middleware |
+| **Channels** (typed state slots) | **`AgentContext.extra`** + `AgentState.messages` | A single dict + a single message list cover every state shape we've seen |
+| **`StateGraph.add_node(name, fn)`** | A middleware hook or a tool | Functions in langgraph nodes split into two roles in CubePi: tool execution (when the model decides) vs. middleware (always-on transforms) |
+| **`add_edge(a, b)`** / `add_conditional_edges` | Built-in: tools → next turn → tools → … | The conditional shape (tool calls → re-prompt) is the loop; you don't reify it |
+| **`MemorySaver` / `SqliteSaver` / `PostgresSaver`** | `MemoryCheckpointer` / `SQLiteCheckpointer` / `PostgresCheckpointer` | Same idea, append-only schema instead of full snapshots |
+| **`config: {"configurable": {"thread_id": …}}`** | `Agent(thread_id=…)` | First-class agent parameter |
+| **`stream_mode="messages"` / `"values"` / `"updates"`** | `agent.subscribe(listener)` — one event stream | One pattern, eleven event types |
+| **Tools as `@tool` decorated functions** | `AgentTool` with Pydantic params + async execute | Closer to OpenAI/Anthropic native shape |
+| **`HumanMessage`, `AIMessage`** | `UserMessage`, `AssistantMessage` | Same role-tagged messages, just renamed |
+| **Interrupts via `interrupt_before` / `interrupt_after`** | `agent.steer(...)`, `agent.follow_up(...)`, `agent.abort()` | Imperative control instead of declarative interrupt points |
+| **`config_schema`** | Constructor parameters on `Agent` | No separate schema layer |
+
+## Side-by-side: a tool-using agent
+
+### langgraph
+
+```python
+from typing import TypedDict
+from langchain_anthropic import ChatAnthropic
+from langgraph.graph import StateGraph, END
+from langgraph.prebuilt import ToolNode
+from langchain_core.tools import tool
+
+
+@tool
+def get_weather(city: str) -> str:
+ """Get current weather for a city."""
+ return f"72°F and sunny in {city}"
+
+
+llm = ChatAnthropic(model="claude-sonnet-4-5-20250929").bind_tools([get_weather])
+
+class State(TypedDict):
+ messages: list
+
+def call_model(state: State):
+ return {"messages": [llm.invoke(state["messages"])]}
+
+def should_continue(state: State):
+ last = state["messages"][-1]
+ return "tools" if last.tool_calls else END
+
+graph = StateGraph(State)
+graph.add_node("llm", call_model)
+graph.add_node("tools", ToolNode([get_weather]))
+graph.add_edge("__start__", "llm")
+graph.add_conditional_edges("llm", should_continue)
+graph.add_edge("tools", "llm")
+app = graph.compile()
+
+for chunk in app.stream({"messages": [("user", "Weather in Tokyo?")]}):
+ print(chunk)
+```
+
+### CubePi
+
+```python
+import asyncio
+from pydantic import BaseModel
+from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+class GetWeatherParams(BaseModel):
+ city: str
+
+
+async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text=f"72°F and sunny in {params.city}")])
+
+
+agent = Agent(
+ provider=AnthropicProvider(api_key="…"),
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ tools=[AgentTool(
+ name="get_weather",
+ description="Get current weather for a city.",
+ parameters=GetWeatherParams,
+ execute=get_weather,
+ )],
+)
+agent.subscribe(lambda e, s=None: print(e.type))
+asyncio.run(agent.prompt("Weather in Tokyo?"))
+```
+
+CubePi version removes:
+
+- The `StateGraph`, edges, nodes, `END` sentinel, conditional edges.
+- The `ToolNode` registry — tools go directly to the `Agent`.
+- The `should_continue` function — the loop knows when there are tool
+ calls.
+- The `State` TypedDict — state lives on the agent.
+
+## Mapping common patterns
+
+### Checkpointing
+
+```python
+# langgraph
+from langgraph.checkpoint.sqlite import SqliteSaver
+graph.compile(checkpointer=SqliteSaver.from_conn_string(":memory:"))
+
+# CubePi
+from cubepi.checkpointer import SQLiteCheckpointer
+async with SQLiteCheckpointer("agent.db") as cp:
+ agent = Agent(..., checkpointer=cp, thread_id="conv-1")
+```
+
+CubePi's append-only model is O(1) per message, regardless of
+conversation length. langgraph saves full snapshots, which scales
+linearly with history.
+
+### Streaming
+
+```python
+# langgraph
+for chunk in app.stream(state, stream_mode="messages"):
+ if chunk["event"] == "on_chat_model_stream":
+ print(chunk["data"]["chunk"].content, end="")
+
+# CubePi
+def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="")
+
+agent.subscribe(on_event)
+await agent.prompt("…")
+```
+
+One subscriber, one stream — no mode flag.
+
+### Interrupting / human-in-the-loop
+
+```python
+# langgraph
+graph.compile(interrupt_before=["tools"])
+
+# CubePi
+class HumanApproval(Middleware):
+ async def before_tool_call(self, ctx, *, signal=None):
+ approved = await ask_human(f"Run {ctx.tool_call.name}({ctx.args})?")
+ if not approved:
+ return BeforeToolCallResult(block=True, reason="rejected")
+ return None
+```
+
+Imperative interrupts via middleware. You decide per call instead of
+configuring graph-level interrupt points.
+
+### Branching
+
+```python
+# langgraph
+graph.add_conditional_edges("llm", lambda s: "tools" if s["messages"][-1].tool_calls else "summary")
+graph.add_node("summary", summarize)
+graph.add_edge("summary", END)
+```
+
+```python
+# CubePi
+class SummariseAtEnd(Middleware):
+ async def should_stop_after_turn(self, ctx) -> bool:
+ msg = ctx.message
+ if not any(isinstance(c, ToolCall) for c in msg.content):
+ # No more tool calls; we're done. Inject a summary turn first.
+ ...
+ return True
+ return False
+```
+
+There's no built-in branching primitive; flow control happens through
+`should_stop_after_turn` and `after_model_response`.
+
+## What langgraph does that CubePi doesn't (yet)
+
+- **Multi-agent supervisor patterns.** No first-class "agents
+ spawning agents" abstraction. You can build it by running multiple
+ `Agent` instances with shared tools.
+- **Visual graph rendering.** No `app.get_graph().draw_mermaid()`
+ equivalent. CubePi's flow is linear so the picture would be a single
+ line anyway.
+- **Time travel / fork** at arbitrary checkpoints. The Postgres schema
+ has fork columns but no API surface in v0.4.
+- **First-party UI for traces.** CubePi doesn't render its own trace
+ visualizer the way LangSmith / Langfuse do; instead it emits
+ vendor-neutral OpenTelemetry — point any OTLP backend
+ (LangSmith's OTel endpoint, Langfuse v3, Jaeger, Tempo,
+ Honeycomb, Datadog, …) at it via
+ `Tracer(exporters=[OTLPSpanExporter(...)])`. See
+ [Tracing → OTLP & Backends](../guides/tracing/otlp).
+
+## What CubePi does that langgraph doesn't
+
+- **Native OpenTelemetry tracing** — `Tracer` + `Meter` emit OTel
+ spans + GenAI-semconv attributes out of the box, ingestible by
+ any OTLP backend. See [Tracing → Overview](../guides/tracing/overview).
+- **Native async-first** — every entry point is async. No
+ `app.invoke` vs. `app.ainvoke` split.
+- **Append-only persistence** — O(1) DB writes, JSONB-queryable
+ messages.
+- **3 core deps** vs. langchain-core + langgraph-sdk + transitives.
+- **Streaming-realistic test provider** (`FauxProvider`) ships in the
+ box.
+- **MCP loaders** for HTTP + stdio transports.
+
+## Porting checklist
+
+1. Replace `StateGraph` construction with a single `Agent(...)` call.
+2. Move `@tool`-decorated functions to `AgentTool` instances (Pydantic
+ models for params, async execute).
+3. Replace `MemorySaver` / `SqliteSaver` / `PostgresSaver` with
+ `MemoryCheckpointer` / `SQLiteCheckpointer` / `PostgresCheckpointer`.
+4. Replace `stream_mode` callbacks with `agent.subscribe(...)`.
+5. Convert custom nodes that did message transforms → `Middleware`
+ hooks.
+6. Convert `interrupt_before/after` → `before_tool_call` /
+ `after_model_response` middleware.
+7. If you had a `summary` or `route` node — fold it into
+ `after_model_response` with `decision="stop"` or `"loop_to_model"`.
+
+## See also
+
+- [Core Concepts](../getting-started/core-concepts) — the building
+ blocks you're mapping to.
+- [Middleware → Composition](../guides/middleware/composition) — where
+ flow-control logic lives.
+- [Checkpointing](../guides/checkpointing/sqlite) — the new
+ persistence story.
diff --git a/website/versioned_docs/version-0.6/recipes/ask-user-form.md b/website/versioned_docs/version-0.6/recipes/ask-user-form.md
new file mode 100644
index 0000000..e0f1eee
--- /dev/null
+++ b/website/versioned_docs/version-0.6/recipes/ask-user-form.md
@@ -0,0 +1,186 @@
+---
+title: Multi-question Form via ask_user
+description: "Build a multi-question form with CubePi's ask_user HITL tool for structured user input."
+---
+
+# Recipe: Multi-question Form via `ask_user`
+
+Use case: the agent needs a structured answer from the user before it can
+proceed — a configuration wizard, a preference selector, a feature toggle.
+
+## Step 1: Register the tool
+
+```python
+from cubepi.agent.agent import Agent
+from cubepi.hitl import InMemoryChannel, ask_user_tool
+
+channel = InMemoryChannel()
+
+agent = Agent(
+ provider=...,
+ model=...,
+ system_prompt=(
+ "When you need the user to choose among options, use the ask_user tool. "
+ "For free-form clarification questions, just end your turn with text — "
+ "the user's next message will be your answer."
+ ),
+ tools=[ask_user_tool(channel)],
+ channel=channel,
+)
+```
+
+The `ask_user` tool is registered like any other tool. Its
+`execution_mode="sequential"` makes the tool batch run one-by-one —
+the HITL pause can't overlap with parallel tool execution.
+
+## Step 2: Host renders the form
+
+The model invokes `ask_user` with a list of question objects. The host
+receives an `AskRequest` payload on the channel:
+
+```python
+async def host():
+ async for req in channel.subscribe():
+ if req.payload.kind == "ask":
+ answers = {}
+ for q in req.payload.questions:
+ if q.options is None:
+ # Free-text question
+ answers[q.key] = await my_ui.text_input(q.prompt)
+ elif q.multi_select:
+ answers[q.key] = await my_ui.checkbox_group(
+ q.prompt, [(o.label, o.value) for o in q.options],
+ )
+ else:
+ answers[q.key] = await my_ui.radio_group(
+ q.prompt,
+ [(o.label, o.value) for o in q.options],
+ allow_input_indexes=[
+ i for i, o in enumerate(q.options) if o.allow_input
+ ],
+ )
+ await channel.answer(req.question_id, answers)
+```
+
+## What the model sees as tool parameters
+
+The model can pass questions that mix free-text, single-select, and
+multi-select fields in a single call:
+
+```json
+{
+ "questions": [
+ {
+ "key": "project_type",
+ "prompt": "What kind of project?",
+ "options": [
+ {"label": "Web app", "value": "web"},
+ {"label": "CLI tool", "value": "cli"},
+ {"label": "Library", "value": "lib"}
+ ]
+ },
+ {
+ "key": "framework",
+ "prompt": "Which framework?",
+ "options": [
+ {"label": "React", "value": "react"},
+ {"label": "Vue", "value": "vue"},
+ {"label": "Other", "value": "other", "allow_input": true}
+ ]
+ },
+ {
+ "key": "features",
+ "prompt": "Which features do you need?",
+ "multi_select": true,
+ "options": [
+ {"label": "Authentication", "value": "auth"},
+ {"label": "Payments", "value": "payments"},
+ {"label": "File uploads", "value": "uploads"}
+ ]
+ },
+ {
+ "key": "project_name",
+ "prompt": "What should we call this project?"
+ }
+ ]
+}
+```
+
+## Answer shape
+
+The host answers with a dict mapping `key → value`:
+
+```python
+# Example answer for the above form:
+{
+ "project_type": "web",
+ "framework": "svelte", # user chose "Other" and typed "svelte"
+ "features": ["auth", "uploads"],
+ "project_name": "my-saas"
+}
+```
+
+The answer is stuffed into the tool result as
+`details["hitl"]["answers"]`. The model receives a human-readable summary
+in the text content and can reference the dict for structured consumption.
+
+## Cancel and timeout
+
+If the host cancels via `channel.cancel(qid, reason)`:
+
+```python
+await channel.cancel(req.question_id, reason="user closed the form")
+```
+
+The tool surfaces an error result to the model:
+
+```
+tool_result.is_error = True
+tool_result.details["hitl"]["outcome"] = "cancelled"
+tool_result.details["hitl"]["reason"] = "user closed the form"
+```
+
+If the timeout expires:
+
+```
+tool_result.details["hitl"]["outcome"] = "timed_out"
+tool_result.details["hitl"]["seconds"] = 30.0
+```
+
+In both cases the model sees a clean error result and can react
+accordingly — ask again, fall back to a default, or report to the user.
+
+## In-process example (full runnable snippet)
+
+```python
+import asyncio
+from cubepi.agent.agent import Agent
+from cubepi.hitl import InMemoryChannel, ask_user_tool
+
+channel = InMemoryChannel()
+
+agent = Agent(
+ provider=...,
+ model=...,
+ tools=[ask_user_tool(channel)],
+ channel=channel,
+)
+
+async def host():
+ async for req in channel.subscribe():
+ if req.payload.kind == "ask":
+ answers = {
+ q.key: q.options[0].value if q.options else ""
+ for q in req.payload.questions
+ }
+ await channel.answer(req.question_id, answers)
+
+async def main():
+ host_task = asyncio.create_task(host())
+ try:
+ await agent.prompt("Scaffold a new project.")
+ finally:
+ host_task.cancel()
+
+asyncio.run(main())
+```
diff --git a/website/versioned_docs/version-0.6/recipes/multi-provider-failover.md b/website/versioned_docs/version-0.6/recipes/multi-provider-failover.md
new file mode 100644
index 0000000..5b61895
--- /dev/null
+++ b/website/versioned_docs/version-0.6/recipes/multi-provider-failover.md
@@ -0,0 +1,259 @@
+---
+title: Multi-Provider Failover
+description: "Configure multi-provider failover in CubePi for resilience — automatic fallback between providers."
+---
+
+# Recipe: Multi-Provider Failover
+
+When Anthropic is rate-limited or down, fail over to OpenAI without
+crashing the agent. We'll wrap both providers behind a single
+`Provider` adapter that does its own retry/failover logic.
+
+**Time to run:** 10 minutes.
+**Deps:** `cubepi`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`.
+
+## The wrapper provider
+
+```python title="failover.py"
+import asyncio
+import logging
+import time
+from typing import Sequence
+
+from cubepi.providers.base import (
+ AssistantMessage,
+ Message,
+ MessageStream,
+ Model,
+ Provider,
+ StreamEvent,
+ StreamOptions,
+ ToolDefinition,
+ Usage,
+)
+from cubepi.providers.anthropic import AnthropicProvider
+from cubepi.providers.openai import OpenAIProvider
+
+log = logging.getLogger(__name__)
+
+
+class FailoverProvider:
+ """Try providers in order; fall over on construction or first-event errors.
+
+ Built-in providers swallow API/network errors and surface them as
+ `StreamEvent(type="error")` on the returned stream — never as exceptions
+ out of `provider.stream()`. So we peek at the first event from each
+ inner stream and only commit to it once we see a non-error event.
+
+ Limitation: errors that arrive *after* the first event (e.g. mid-stream
+ rate limit, server disconnect) are forwarded to the agent as-is.
+ Fully replaying a half-streamed turn against a fallback provider would
+ require buffering the whole turn — out of scope here.
+ """
+
+ def __init__(self, primary_pair: tuple[Provider, Model], *fallbacks: tuple[Provider, Model]) -> None:
+ self._chain: list[tuple[Provider, Model]] = [primary_pair, *fallbacks]
+
+ async def stream(
+ self,
+ model: Model,
+ messages: list[Message],
+ *,
+ system_prompt: str = "",
+ tools: list[ToolDefinition] | None = None,
+ options: StreamOptions | None = None,
+ ) -> MessageStream:
+ last_error: str | None = None
+
+ for provider, mapped_model in self._chain:
+ # Construction-time failures (rare — most stay inside the producer task).
+ try:
+ inner = await provider.stream(
+ mapped_model,
+ messages,
+ system_prompt=system_prompt,
+ tools=tools,
+ options=options,
+ )
+ except Exception as e:
+ log.warning("provider %s failed at construction: %s", mapped_model.provider, e)
+ last_error = repr(e)
+ continue
+
+ # Peek at the first event to learn whether the stream is healthy.
+ iterator = inner.__aiter__()
+ try:
+ first = await iterator.__anext__()
+ except StopAsyncIteration:
+ last_error = "stream ended before producing any events"
+ continue
+
+ if first.type == "error":
+ log.warning("provider %s errored on first event: %s",
+ mapped_model.provider, first.error_message)
+ last_error = first.error_message or "stream error"
+ continue
+
+ # Healthy — commit to this provider. Forward `first` plus the rest
+ # through a fresh outer MessageStream so the caller sees a complete
+ # stream starting at the start event.
+ outer = MessageStream()
+
+ async def _forward(first_event=first, src=iterator, src_stream=inner):
+ try:
+ outer.push(first_event)
+ async for ev in src:
+ outer.push(ev)
+ final = await src_stream.result()
+ outer.set_result(final)
+ except Exception as exc:
+ fallback_msg = AssistantMessage(
+ content=[],
+ stop_reason="error",
+ error_message=str(exc),
+ usage=Usage(),
+ timestamp=time.time(),
+ )
+ outer.push(StreamEvent(type="error", error_message=str(exc)))
+ outer.set_result(fallback_msg)
+
+ outer.attach_task(asyncio.create_task(_forward()))
+ return outer
+
+ raise RuntimeError(f"all providers exhausted; last error: {last_error!r}")
+```
+
+## Use it
+
+```python title="main.py"
+import asyncio
+import os
+
+from cubepi import Agent, Model
+from cubepi.providers.anthropic import AnthropicProvider
+from cubepi.providers.openai import OpenAIProvider
+from failover import FailoverProvider
+
+
+async def main():
+ failover = FailoverProvider(
+ (
+ AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"]),
+ Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ ),
+ (
+ OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"]),
+ Model(id="gpt-5", provider="openai"),
+ ),
+ )
+
+ # The model passed here is overridden inside FailoverProvider; pass any
+ # placeholder. We use the primary's so usage tracking labels match the
+ # happy path.
+ agent = Agent(
+ provider=failover,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="You answer concisely.",
+ )
+ agent.subscribe(lambda e, s=None: None)
+ await agent.prompt("Capital of Mongolia?")
+ last = agent.state.messages[-1]
+ print(last.content[0].text)
+
+
+asyncio.run(main())
+```
+
+## What about smarter failover policies?
+
+The example above falls back on **any** error event. That's fine for
+`RateLimitError`, `APIConnectionError`, or 5xx — but arguably wrong for
+`BadRequestError` (your code is wrong; the next provider will fail the
+same way).
+
+The first-event `error_message` comes from `str(exc)` on the
+underlying SDK exception. Filter on substrings, or — better — wrap each
+provider's `_produce` to tag the error category:
+
+```python
+NON_RETRYABLE_HINTS = ("bad request", "invalid_request_error", "401", "403")
+
+if first.type == "error":
+ msg = (first.error_message or "").lower()
+ if any(h in msg for h in NON_RETRYABLE_HINTS):
+ raise RuntimeError(f"non-retryable error from {mapped_model.provider}: {msg}")
+ last_error = first.error_message
+ continue
+```
+
+A more robust approach is to fork the built-in providers and re-raise
+specific SDK exceptions from `_produce` so they reach `provider.stream()`
+as real Python exceptions — but that's a larger change against
+CubePi itself.
+
+## Adding circuit breaking
+
+Don't keep retrying a provider that's clearly down. A simple counter:
+
+```python
+import time
+
+class CircuitBreaker:
+ def __init__(self, failure_threshold: int = 3, recovery_seconds: float = 60) -> None:
+ self._failures = 0
+ self._opened_at: float | None = None
+ self._threshold = failure_threshold
+ self._recovery = recovery_seconds
+
+ def can_attempt(self) -> bool:
+ if self._opened_at and time.monotonic() - self._opened_at < self._recovery:
+ return False
+ if self._opened_at:
+ self._opened_at = None # half-open
+ return True
+
+ def record_failure(self) -> None:
+ self._failures += 1
+ if self._failures >= self._threshold:
+ self._opened_at = time.monotonic()
+ self._failures = 0
+
+ def record_success(self) -> None:
+ self._failures = 0
+```
+
+Hold one `CircuitBreaker` per provider in the `FailoverProvider`,
+skip if `can_attempt()` is False.
+
+## Per-tool failover doesn't apply
+
+This recipe handles **provider** failures. Tool failures are different
+— see [Middleware → Retries](../guides/middleware/examples#retries-with-backoff)
+for that pattern.
+
+## Common pitfalls
+
+- **Different tool schemas across providers** — Both built-in
+ providers accept the same `ToolDefinition`, but extra-body
+ customisations (e.g. OpenAI `parallel_tool_calls=False`) won't carry
+ to Anthropic. Keep cross-provider behaviour in
+ [`transform_context`](../guides/middleware/hooks#transform_context),
+ not in `extra_body`.
+- **Different cost** — Failover from Anthropic to OpenAI changes
+ per-token cost. Track which provider answered (via `on_response` or
+ `AssistantMessage.provider_id`) and bill accordingly.
+- **Streaming consistency** — The wrapper forwards events through a
+ fresh `MessageStream`, so consumers see the same `StreamEvent` shape
+ regardless of which provider answered. The original `start` event
+ comes from the inner provider unchanged.
+- **Mid-stream errors aren't recovered** — Once we've seen a healthy
+ first event, the wrapper commits to that provider. If it errors
+ halfway through a long response, the agent sees the error. Full
+ mid-stream replay would require buffering — out of scope here.
+
+## See also
+
+- [Providers / Anthropic](../guides/providers/anthropic) and
+ [OpenAI](../guides/providers/openai) — provider-specific details.
+- [Writing a Custom Provider](../guides/providers/custom) — the same
+ Protocol used by this wrapper.
diff --git a/website/versioned_docs/version-0.6/recipes/persistent-chat.md b/website/versioned_docs/version-0.6/recipes/persistent-chat.md
new file mode 100644
index 0000000..4ff1f15
--- /dev/null
+++ b/website/versioned_docs/version-0.6/recipes/persistent-chat.md
@@ -0,0 +1,178 @@
+---
+title: Persistent Chat
+description: "Build a persistent chat application with CubePi and SQLiteCheckpointer."
+---
+
+# Recipe: Persistent Chat (SQLite)
+
+A REPL chat that survives restarts. Conversation history is kept in a
+SQLite file; each user gets a `thread_id`.
+
+**Time to run:** 5 minutes.
+**Deps:** `cubepi[sqlite]`, an `ANTHROPIC_API_KEY`.
+
+## The script
+
+```python title="chat.py"
+import asyncio
+import os
+import sys
+
+from cubepi import Agent, Model
+from cubepi.checkpointer import SQLiteCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+async def main(thread_id: str):
+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+
+ async with SQLiteCheckpointer("chat.db") as cp:
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="You are a concise, friendly assistant.",
+ checkpointer=cp,
+ thread_id=thread_id,
+ )
+
+ def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+ elif event.type == "agent_end":
+ print()
+
+ agent.subscribe(on_event)
+
+ print(f"chatting on thread {thread_id!r}. Ctrl-D to quit.\n")
+ loop = asyncio.get_event_loop()
+ while True:
+ try:
+ user_input = await loop.run_in_executor(None, input, "you> ")
+ except EOFError:
+ print()
+ return
+ if not user_input.strip():
+ continue
+ print("ai > ", end="", flush=True)
+ await agent.prompt(user_input)
+
+
+if __name__ == "__main__":
+ asyncio.run(main(thread_id=sys.argv[1] if len(sys.argv) > 1 else "default"))
+```
+
+Run:
+
+```bash
+pip install "cubepi[sqlite]"
+export ANTHROPIC_API_KEY=sk-…
+python chat.py alice
+# Have a chat, then Ctrl-D.
+
+python chat.py alice
+# History is restored. Ask "what did I just tell you?" — the model
+# remembers the previous session.
+
+python chat.py bob
+# Different thread, clean slate.
+```
+
+## What's going on
+
+- **First `prompt()` per process loads history.** CubePi checks the
+ checkpointer once at the start of the first prompt, restores
+ `agent.state.messages`, and proceeds.
+- **Each `message_end` appends to the database.** No batching, no
+ lossy buffering. If the process crashes mid-stream, the next run
+ picks up at the last committed message.
+- **The system prompt isn't persisted** — it's part of agent
+ construction, not state. Keep it in your code (or in env config).
+
+## Multi-user routing
+
+In a web service, derive `thread_id` from the authenticated user:
+
+```python
+agent = Agent(
+ provider=provider,
+ model=model,
+ checkpointer=cp,
+ thread_id=f"user-{user_id}",
+)
+```
+
+You can serve thousands of users from one `SQLiteCheckpointer` —
+threads are isolated by `thread_id`.
+
+## Pruning a thread
+
+There's no built-in "delete thread" API by design — checkpointers are
+append-only. To prune, drop rows by `thread_id` directly:
+
+```bash
+sqlite3 chat.db "DELETE FROM messages WHERE thread_id='alice'; DELETE FROM thread_extra WHERE thread_id='alice'"
+```
+
+Or implement a small admin tool that does the SQL on demand.
+
+## Sliding the context window
+
+After a long conversation, the model's context gets expensive. Add a
+[`SlidingWindow`](../guides/middleware/examples#sliding-window-truncation)
+middleware:
+
+```python
+from cubepi import Middleware
+
+class SlidingWindow(Middleware):
+ def __init__(self, n: int) -> None:
+ self.n = n
+
+ async def transform_context(self, messages, *, signal=None):
+ return messages[-self.n:] if len(messages) > self.n else messages
+
+
+agent = Agent(
+ provider=provider,
+ model=model,
+ checkpointer=cp,
+ thread_id=thread_id,
+ middleware=[SlidingWindow(40)],
+)
+```
+
+The DB keeps every message; the model only sees the last 40. The
+user-visible history (e.g. for a chat UI rendering past turns) stays
+complete.
+
+## Switching to Postgres
+
+Same code, different checkpointer:
+
+```python
+from cubepi.checkpointer import PostgresCheckpointer
+
+async with PostgresCheckpointer("postgresql://…") as cp:
+ agent = Agent(provider=…, model=…, checkpointer=cp, thread_id=…)
+```
+
+Postgres is the right choice for multi-instance services or many
+concurrent users — see [Postgres + FastAPI](./postgres-fastapi).
+
+## Common pitfalls
+
+- **`async with` forgotten** — Without it, the SQLite connection is
+ never opened. You get `AssertionError`. Wrap.
+- **Multiple processes writing the same `thread_id`** — Interleaved
+ history. One agent per thread, or move to Postgres.
+- **`chat.db` in `/tmp`** — Some OSes wipe `/tmp` on reboot. Use
+ `~/.local/share/myapp/chat.db` or similar for user data.
+
+## See also
+
+- [Multi-turn Conversations](../guides/agents/multi-turn) — `steer`,
+ `follow_up`, `resume`.
+- [SQLite Checkpointing](../guides/checkpointing/sqlite) — the backend
+ in detail.
+- [Resumable Long Tasks](./resumable-tasks) — when crashes happen
+ mid-tool, not just between turns.
diff --git a/website/versioned_docs/version-0.6/recipes/postgres-fastapi.md b/website/versioned_docs/version-0.6/recipes/postgres-fastapi.md
new file mode 100644
index 0000000..55963d4
--- /dev/null
+++ b/website/versioned_docs/version-0.6/recipes/postgres-fastapi.md
@@ -0,0 +1,256 @@
+---
+title: Postgres + FastAPI Service
+description: "Deploy a FastAPI-backed CubePi agent with PostgresCheckpointer for production."
+---
+
+# Recipe: Postgres + FastAPI Service
+
+A production-shaped HTTP service that fronts a CubePi agent: FastAPI
+for routing, server-sent events for streaming, a shared
+`PostgresCheckpointer` for persistence, and `thread_id` derived from
+the authenticated user.
+
+**Time to run:** 30 minutes.
+**Deps:** `cubepi[postgres]`, `fastapi`, `uvicorn[standard]`,
+`sse-starlette`, a running Postgres with the CubePi schema applied.
+
+## Schema first
+
+Before the service starts, run the CubePi schema migration. The
+quickest way for this recipe:
+
+```bash
+psql "$DATABASE_URL" <<'SQL'
+CREATE TABLE cubepi_threads (
+ thread_id TEXT PRIMARY KEY,
+ parent_thread_id TEXT REFERENCES cubepi_threads(thread_id),
+ forked_at_seq BIGINT,
+ extra JSONB NOT NULL DEFAULT '{}'::jsonb,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+
+CREATE TABLE cubepi_messages (
+ thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) ON DELETE CASCADE,
+ seq BIGINT NOT NULL,
+ role TEXT NOT NULL,
+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,
+ payload BYTEA NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (thread_id, seq)
+) PARTITION BY HASH (thread_id);
+
+-- 64 hash partitions
+DO $$
+BEGIN
+ FOR i IN 0..63 LOOP
+ EXECUTE format(
+ 'CREATE TABLE cubepi_messages_p%s PARTITION OF cubepi_messages FOR VALUES WITH (MODULUS 64, REMAINDER %s)',
+ i, i
+ );
+ END LOOP;
+END$$;
+
+CREATE INDEX ix_cubepi_messages_metadata_gin
+ON cubepi_messages USING gin (metadata jsonb_path_ops);
+
+CREATE TABLE cubepi_schema_version (version INT PRIMARY KEY);
+INSERT INTO cubepi_schema_version VALUES (1);
+SQL
+```
+
+For a real deployment, generate this via Alembic — see
+[Postgres Checkpointing → Bootstrapping via Alembic](../guides/checkpointing/postgres#bootstrapping-via-alembic).
+
+## The service
+
+```python title="service.py"
+import asyncio
+import os
+from contextlib import asynccontextmanager
+from typing import AsyncIterator
+
+from fastapi import FastAPI, Depends, HTTPException
+from pydantic import BaseModel
+from sse_starlette.sse import EventSourceResponse
+
+from cubepi import Agent, Model
+from cubepi.checkpointer import PostgresCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+# --- App lifecycle ------------------------------------------------------
+
+_provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+_checkpointer: PostgresCheckpointer | None = None
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ global _checkpointer
+ _checkpointer = await PostgresCheckpointer(
+ os.environ["DATABASE_URL"],
+ min_pool_size=2,
+ max_pool_size=20,
+ ).__aenter__()
+ yield
+ await _checkpointer.__aexit__(None, None, None)
+
+
+app = FastAPI(lifespan=lifespan)
+
+
+# --- Auth (stub — replace with your real auth) -------------------------
+
+async def current_user_id() -> str:
+ # In production: decode JWT, look up session, etc.
+ return "demo-user"
+
+
+# --- Routes -------------------------------------------------------------
+
+class PromptBody(BaseModel):
+ text: str
+
+
[email protected]("/chat/{conversation_id}/messages")
+async def post_message(
+ conversation_id: str,
+ body: PromptBody,
+ user_id: str = Depends(current_user_id),
+):
+ thread_id = f"{user_id}:{conversation_id}"
+
+ async def event_generator() -> AsyncIterator[dict]:
+ agent = Agent(
+ provider=_provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="You are a helpful assistant.",
+ checkpointer=_checkpointer,
+ thread_id=thread_id,
+ )
+
+ queue: asyncio.Queue = asyncio.Queue()
+ agent.subscribe(lambda e, s=None: queue.put_nowait(e))
+
+ async def run():
+ try:
+ await agent.prompt(body.text)
+ finally:
+ queue.put_nowait(None) # sentinel
+
+ task = asyncio.create_task(run())
+
+ try:
+ while True:
+ event = await queue.get()
+ if event is None:
+ break
+ # Emit a small subset to the client.
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ yield {"event": "delta", "data": event.stream_event.delta}
+ elif event.type == "tool_execution_start":
+ yield {"event": "tool_start", "data": event.tool_name}
+ elif event.type == "agent_end":
+ yield {"event": "done", "data": ""}
+ finally:
+ await task
+
+ return EventSourceResponse(event_generator())
+
+
[email protected]("/chat/{conversation_id}/history")
+async def get_history(
+ conversation_id: str,
+ user_id: str = Depends(current_user_id),
+):
+ thread_id = f"{user_id}:{conversation_id}"
+ data = await _checkpointer.load(thread_id)
+ if data is None:
+ return {"messages": []}
+ return {
+ "messages": [m.model_dump(mode="json") for m in data.messages],
+ }
+```
+
+Run:
+
+```bash
+pip install "cubepi[postgres]" fastapi "uvicorn[standard]" sse-starlette
+export DATABASE_URL=postgresql://user:pass@localhost/cubepi
+export ANTHROPIC_API_KEY=sk-…
+uvicorn service:app --reload --port 8000
+```
+
+Test:
+
+```bash
+curl -N -X POST http://localhost:8000/chat/conv1/messages \
+ -H "content-type: application/json" \
+ -d '{"text":"hi"}'
+# event: delta
+# data: Hello
+# event: delta
+# data: !
+# event: done
+```
+
+## Design notes
+
+- **One `PostgresCheckpointer` per process, shared across requests.**
+ It holds a connection pool; opening one per request would defeat
+ the pool.
+- **One `Agent` per request.** Agents own per-conversation state
+ (steering queues, listeners). Don't reuse them.
+- **`thread_id = f"{user_id}:{conversation_id}"`** — user isolation by
+ prefix. The agent reads/writes only its own thread.
+- **SSE for streaming.** Each text delta goes to the client as a
+ separate event. Tool starts get their own event type — clients can
+ render a "thinking" indicator without rebuilding event handling.
+- **No load balancer affinity needed.** Because state is in Postgres,
+ any service instance can pick up any conversation.
+
+## Concurrency on the same thread
+
+If a user double-clicks send, two `POST` requests arrive simultaneously.
+Both create an `Agent` bound to the same `thread_id`. The Postgres
+advisory lock serialises their appends, but the **in-memory** states
+diverge — the second request's agent might not see the first's
+in-progress message in its `agent.state.messages`.
+
+For most chat UIs this is fine (the client controls send timing).
+If you need strict ordering, add an application-layer mutex
+(`asyncio.Lock` keyed by `thread_id`) or queue.
+
+## Production hardening checklist
+
+- **Auth:** Replace `current_user_id()` with real JWT / session
+ validation.
+- **Rate limiting:** Add a [`RateLimitMiddleware`](../guides/middleware/examples#rate-limiting)
+ to the agent constructor, keyed by `user_id`.
+- **Cost tracking:** Subscribe to `agent_end`, sum `usage` on each
+ `AssistantMessage`, write to a billing table.
+- **Observability:** Use `on_response` to capture `anthropic-*` rate
+ headers; export to Prometheus.
+- **Backups:** Postgres native — `pg_dump`, point-in-time recovery.
+- **Graceful shutdown:** uvicorn's lifespan handler closes the pool;
+ add `signal.signal(SIGTERM, ...)` if you have other resources.
+
+## Common pitfalls
+
+- **CubepiSchemaUninitialized at startup** — Your migrations didn't
+ run. Apply the schema first.
+- **Connection pool exhaustion** — Default `max_pool_size=10`. Bump
+ it if your service has more concurrent agents than that.
+- **SSE behind a load balancer** — Some LBs buffer SSE. Disable
+ buffering (`X-Accel-Buffering: no` for nginx).
+- **Long requests timing out** — Tool-heavy agents can run minutes.
+ Set generous proxy timeouts and uvicorn `--timeout-keep-alive 600`.
+
+## See also
+
+- [Postgres Checkpointing](../guides/checkpointing/postgres) — the
+ backend in depth.
+- [Persistent Chat](./persistent-chat) — the same flow with SQLite.
+- [Multi-Provider Failover](./multi-provider-failover) — combine with
+ this service for resilience.
diff --git a/website/versioned_docs/version-0.6/recipes/resumable-tasks.md b/website/versioned_docs/version-0.6/recipes/resumable-tasks.md
new file mode 100644
index 0000000..6b52af2
--- /dev/null
+++ b/website/versioned_docs/version-0.6/recipes/resumable-tasks.md
@@ -0,0 +1,230 @@
+---
+title: Resumable Long Tasks
+description: "Build crash-resilient long-running tasks with CubePi checkpointing and recovery."
+---
+
+# Recipe: Resumable Long Tasks
+
+When an agent is mid-flight through a long-running operation (a series
+of tool calls, a multi-turn reasoning session) and the process dies,
+you want to come back and pick up where it left off — not start over.
+CubePi's append-only checkpointing plus `agent.resume()` makes this
+trivial *between turns*; for resumption *mid-tool*, you need a little
+more care.
+
+**Time to run:** 15 minutes.
+**Deps:** `cubepi[sqlite]`, an `ANTHROPIC_API_KEY`.
+
+## The pattern
+
+There are three crash points to think about:
+
+1. **Between turns** — The model has answered, no tools to run, the
+ loop is between iterations. `resume()` re-invokes the model. *Free
+ with the checkpointer.*
+2. **After tool results, before model call** — Tool results are
+ persisted. `resume()` sees the last message is a `ToolResultMessage`
+ and re-invokes the model. *Free with the checkpointer.*
+3. **Mid-tool** — The tool started but didn't finish. Nothing is
+ persisted yet (CubePi only persists messages). You need
+ tool-internal idempotency. *Requires care.*
+
+This recipe focuses on case 3.
+
+## Idempotent tools with external state
+
+The pattern: each tool action has a deterministic, idempotent key.
+Before doing the work, check whether it's been done.
+
+```python title="tools.py"
+import os
+import json
+from pathlib import Path
+
+from pydantic import BaseModel
+from cubepi import AgentTool, AgentToolResult, TextContent
+
+
+# Simple file-backed job store; replace with Redis / Postgres in prod.
+JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubepi-jobs"))
+JOB_DIR.mkdir(parents=True, exist_ok=True)
+
+
+class TranscodeParams(BaseModel):
+ source_path: str
+ output_path: str
+
+
+async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None, on_update=None):
+ job_key = f"transcode:{params.source_path}->{params.output_path}"
+ job_file = JOB_DIR / f"{job_key.replace('/', '_')}.json"
+
+ if job_file.exists():
+ # Already done in a previous run.
+ state = json.loads(job_file.read_text())
+ return AgentToolResult(
+ content=[TextContent(text=f"Already transcoded to {state['output_path']}.")],
+ details=state,
+ )
+
+ # Do the actual work (long-running, expensive).
+ # Use signal to abort cleanly if cancelled.
+ output = await run_ffmpeg(params.source_path, params.output_path, signal=signal)
+
+ # Commit the job-done marker AFTER the work succeeds.
+ job_file.write_text(json.dumps({"output_path": output}))
+
+ return AgentToolResult(
+ content=[TextContent(text=f"Transcoded to {output}.")],
+ details={"output_path": output},
+ )
+
+
+transcode_tool = AgentTool(
+ name="transcode_video",
+ description="Transcode a video file. Idempotent — safe to retry.",
+ parameters=TranscodeParams,
+ execute=transcode_video,
+ execution_mode="sequential", # one transcode at a time
+)
+```
+
+Now if the process dies during `run_ffmpeg`, the next agent run sees
+`job_file.exists() == False`, redoes the work, and only writes the
+marker on success. If the process dies *after* the marker was
+written, the next run sees the marker, returns the cached result
+immediately, and the agent continues as if it had just finished.
+
+## Resuming the agent
+
+```python title="resume.py"
+import asyncio
+import os
+import sys
+
+from cubepi import Agent, Model
+from cubepi.checkpointer import SQLiteCheckpointer
+from cubepi.providers.anthropic import AnthropicProvider
+
+from tools import transcode_tool # the wrapped AgentTool from above
+
+
+async def main(thread_id: str, initial_prompt: str | None):
+ async with SQLiteCheckpointer("jobs.db") as cp:
+ agent = Agent(
+ provider=AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"]),
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="You orchestrate video transcoding jobs.",
+ tools=[transcode_tool],
+ checkpointer=cp,
+ thread_id=thread_id,
+ )
+ agent.subscribe(lambda e, s=None: None)
+
+ if initial_prompt:
+ # Fresh run. prompt() auto-loads history on first call before
+ # appending the new user message.
+ await agent.prompt(initial_prompt)
+ else:
+ # Resume. agent.resume() does NOT auto-load — only prompt() does.
+ # Hydrate the agent state manually first.
+ data = await cp.load(thread_id)
+ if data is None:
+ raise RuntimeError(f"No saved state for thread {thread_id!r}")
+ agent.state.messages = list(data.messages)
+ # `extra` is restored too; it's private on Agent, so use the
+ # checkpointer's view if your middleware reads it.
+
+ # Resume picks up from the last persisted message:
+ # ToolResultMessage / UserMessage → re-invokes the model
+ # AssistantMessage with no queued steer/follow_up → raises
+ await agent.resume()
+
+
+if __name__ == "__main__":
+ thread_id = sys.argv[1]
+ initial = sys.argv[2] if len(sys.argv) > 2 else None
+ asyncio.run(main(thread_id, initial))
+```
+
+Workflow:
+
+```bash
+# Start a job:
+python resume.py job-1 "Transcode /videos/a.mov to /out/a.mp4 and /videos/b.mov to /out/b.mp4"
+
+# Kill it mid-flight: Ctrl-C.
+
+# Resume — agent picks up from the last persisted message:
+python resume.py job-1
+```
+
+## The three resume scenarios in code
+
+```python
+async def smart_resume(agent, cp, thread_id):
+ # resume() doesn't auto-load — hydrate the agent first if its state is empty.
+ if not agent.state.messages:
+ data = await cp.load(thread_id)
+ if data is None or not data.messages:
+ return False # nothing to resume from
+ agent.state.messages = list(data.messages)
+
+ last = agent.state.messages[-1]
+ last_role = type(last).__name__
+
+ if last_role == "AssistantMessage":
+ # Either the run finished naturally, or it died right after a
+ # turn ended. resume() raises unless there's queued steering.
+ # Easiest path: ask the user what's next.
+ return False
+
+ # Last is UserMessage or ToolResultMessage — safe to resume.
+ await agent.resume()
+ return True
+```
+
+## Persistence + abort
+
+`agent.abort()` triggers a clean teardown that emits `agent_end`. The
+last *fully persisted* message is whatever made it through
+`message_end`. Aborts during a tool's execution don't persist the
+tool result (the tool didn't return), so `resume()` will re-dispatch
+the model with the last `AssistantMessage` containing the unfinished
+`ToolCall`. The model will usually re-issue the call — your
+idempotency guards handle the rest.
+
+## What about persisting partial tool state?
+
+CubePi doesn't expose a "persist a partial tool result" API. The
+intended pattern is: keep partial state in the tool's own
+external store (filesystem, Redis, S3), keyed deterministically by the
+tool args. That's what `transcode_video` above does with `JOB_DIR`.
+
+## Common pitfalls
+
+- **Non-idempotent tools** — Without deterministic keys, retries can
+ charge a credit card twice or send a duplicate email. Always wrap
+ external side-effects in an idempotency key.
+- **Job markers in `/tmp`** — Cleared on reboot. Use a real
+ persistence layer for production jobs.
+- **`resume()` after an assistant message with no queue** — Raises.
+ Either prompt the user for the next message or call `prompt()`
+ fresh.
+- **`resume()` on a fresh agent** — Raises `No messages to continue
+ from`. `resume()` does not auto-load from the checkpointer; only
+ `prompt()` does. Hydrate manually with `agent.state.messages =
+ (await cp.load(thread_id)).messages` first.
+- **Forgetting the signal check inside the tool** — A long
+ `await asyncio.sleep(...)` or a `for ... in stream` that ignores
+ `signal.is_set()` won't honour `abort`. Drop a check inside any
+ hot loop.
+
+## See also
+
+- [Multi-turn → `resume()`](../guides/agents/multi-turn#resume--continue-from-the-last-message)
+ — full semantics.
+- [Persistent Chat](./persistent-chat) — the simpler restartable
+ scenario.
+- [SQLite Checkpointing](../guides/checkpointing/sqlite) — what's
+ persisted, when.
diff --git a/website/versioned_docs/version-0.6/recipes/sandbox-confirm.md b/website/versioned_docs/version-0.6/recipes/sandbox-confirm.md
new file mode 100644
index 0000000..3bd336a
--- /dev/null
+++ b/website/versioned_docs/version-0.6/recipes/sandbox-confirm.md
@@ -0,0 +1,141 @@
+---
+title: Sandbox Confirm with ApprovalPolicyMiddleware
+description: "Implement sandbox tool confirmation with CubePi's ApprovalPolicyMiddleware — auto-allow, deny, or human-confirm."
+---
+
+# Recipe: Sandbox Confirm with `ApprovalPolicyMiddleware`
+
+Use case: a web service where every tool call goes through a rule engine that
+classifies it as auto-allow, hard-deny, or human-confirm.
+
+## Step 1: Define your policy function
+
+The policy receives a `BeforeToolCallContext` and returns an
+`ApprovalDecision` — `Approve()`, `Deny(reason)`, or `AskUser(...)`.
+
+```python
+from cubepi.hitl import Approve, AskUser, Deny
+
+# Mock rule engine — replace with your actual policy catalog.
+def classify_command(cmd: str) -> tuple[str, str | None]:
+ """(tier, reason) — "allow", "block", or "confirm"."""
+ if cmd.startswith(("ls", "cat", "head", "grep", "find")):
+ return ("allow", None)
+ if "rm -rf /" in cmd or cmd.startswith("dd"):
+ return ("block", "destructive I/O")
+ return ("confirm", "needs human review")
+
+
+def sandbox_policy(ctx):
+ cmd = ctx.args.cmd # ctx.args is the validated pydantic model
+ tier, reason = classify_command(cmd)
+
+ if tier == "allow":
+ return Approve()
+ if tier == "block":
+ return Deny(reason=reason or "blocked by policy")
+ return AskUser(
+ timeout_seconds=180,
+ details={"matched_rule": tier, "impact": reason or "unknown"},
+ )
+```
+
+`ctx.args` is the **validated pydantic model**. Access fields as
+attributes (`ctx.args.cmd`). The middleware internally converts it to a
+dict via `_args_to_dict` for the channel's approve payload, but your
+policy receives the typed model.
+
+## Step 2: Wire into the agent
+
+```python
+from cubepi.agent.agent import Agent
+from cubepi.checkpointer.postgres import PostgresCheckpointer
+from cubepi.hitl import ApprovalPolicyMiddleware, CheckpointedChannel
+
+async def main():
+ async with PostgresCheckpointer("postgresql://...") as cp:
+ channel = CheckpointedChannel(checkpointer=cp, thread_id="session-1")
+
+ agent = Agent(
+ provider=anthropic,
+ model=Model(id="claude-sonnet-4-6", provider="anthropic"),
+ system_prompt="You are a helpful assistant with access to a bash shell.",
+ tools=[bash_tool],
+ middleware=[
+ ApprovalPolicyMiddleware(channel, policy=sandbox_policy),
+ ],
+ channel=channel,
+ checkpointer=cp,
+ thread_id="session-1",
+ )
+
+ await agent.prompt("list files then delete temp logs")
+ # Agent runs; when bash is invoked, sandbox_policy decides:
+ # ls → Approve() → runs immediately
+ # rm /tmp/logs → AskUser() → channel suspends, HitlRequestEvent fires
+```
+
+## Step 3: Host handles the pending request
+
+```python
+async def host_loop(channel: CheckpointedChannel):
+ async for req in channel.subscribe():
+ if req.payload.kind == "approve":
+ tool_name = req.payload.tool_name
+ command = req.payload.args.get("cmd", "")
+ details = req.payload.details or {}
+ timeout = req.timeout_seconds # seconds for the frontend countdown
+
+ # Render to the frontend: tool_name, command, details["matched_rule"],
+ # details["impact"], and a countdown based on timeout.
+ human_answer = await my_frontend.show_confirm(
+ tool_name=tool_name,
+ command=command,
+ details=details,
+ timeout=timeout,
+ )
+ # Build an ApproveAnswer from the human's decision.
+ from cubepi.hitl import ApproveAnswer
+ human_answer = ApproveAnswer(
+ decision=ui_response["decision"], # "approve" | "deny" | "edit"
+ reason=ui_response.get("reason"), # only for deny
+ edited_args=ui_response.get("edited_args"), # only for edit
+ )
+ await channel.answer(req.question_id, human_answer)
+ elif req.payload.kind == "ask":
+ await channel.answer(req.question_id, await my_frontend.show_form(req))
+ else: # confirm
+ await channel.answer(req.question_id, await my_frontend.show_confirm(req))
+```
+
+## Decision semantics
+
+| Human chose | Tool outcome | `hitl_trace["decision"]` | Model sees |
+|---|---|---|---|
+| Approve | Runs with original args | unset (passthrough, no HITL details) | Normal `tool_result` |
+| Deny | Blocked | `"human_deny"` | `tool_result.is_error=True` with user's reason |
+| Edit | Runs with edited args | `"edit"` + `original_args` / `edited_args` | Normal `tool_result` (from the edited execution) |
+
+Policy decisions (hard-deny without asking the human) carry
+`hitl_trace["decision"]="policy_deny"`.
+
+## Timeout behaviour
+
+If the human doesn't respond within `timeout_seconds`, the middleware
+translates to `BeforeToolCallResult(block=True, deny_reason="approval_timeout")`.
+The model sees `tool_result.is_error=True` with
+`details.hitl.decision="timed_out"` and naturally produces a follow-up turn
+explaining the timeout.
+
+## Aborting
+
+If the user closes the tab or an admin kills the conversation:
+
+```python
+await agent.abort_pending(reason="user closed tab")
+```
+
+This closes the conversation cleanly: synthetic deny tool_results are
+appended for any unresolved tool calls, a terminal
+`AssistantMessage(stop_reason="aborted")` is persisted, and
+`AgentAbortedEvent` is emitted. The next `agent.prompt(...)` starts fresh.
diff --git a/website/versioned_docs/version-0.6/recipes/weather-agent.md b/website/versioned_docs/version-0.6/recipes/weather-agent.md
new file mode 100644
index 0000000..3253a23
--- /dev/null
+++ b/website/versioned_docs/version-0.6/recipes/weather-agent.md
@@ -0,0 +1,161 @@
+---
+title: Weather Agent
+description: "Build a weather agent that fetches live API data with CubePi tools."
+---
+
+# Recipe: Weather Agent
+
+A complete, runnable agent that calls a real weather API as a tool.
+Demonstrates HTTP-calling tools, error handling, streaming UI, and
+cancellation.
+
+**Time to run:** 5 minutes.
+**Deps:** `cubepi`, `httpx`, an `ANTHROPIC_API_KEY`.
+
+## The script
+
+```python title="weather_agent.py"
+import asyncio
+import os
+
+import httpx
+from pydantic import BaseModel, Field
+
+from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent
+from cubepi.providers.anthropic import AnthropicProvider
+
+
+# --- The tool -----------------------------------------------------------
+
+class GetWeatherParams(BaseModel):
+ city: str = Field(..., description="The city to look up weather for")
+ units: str = Field("metric", pattern="^(metric|imperial)$")
+
+
+async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):
+ # Free Open-Meteo geocoding + forecast. No API key required.
+ async with httpx.AsyncClient(timeout=10) as client:
+ try:
+ geo = await client.get(
+ "https://geocoding-api.open-meteo.com/v1/search",
+ params={"name": params.city, "count": 1, "language": "en"},
+ )
+ geo.raise_for_status()
+ results = geo.json().get("results")
+ if not results:
+ return AgentToolResult(
+ content=[TextContent(text=f"Couldn't find a city named {params.city!r}.")],
+ is_error=True,
+ )
+ lat, lon = results[0]["latitude"], results[0]["longitude"]
+
+ wx = await client.get(
+ "https://api.open-meteo.com/v1/forecast",
+ params={
+ "latitude": lat,
+ "longitude": lon,
+ "current_weather": True,
+ "temperature_unit": "celsius" if params.units == "metric" else "fahrenheit",
+ },
+ )
+ wx.raise_for_status()
+ cw = wx.json()["current_weather"]
+ unit = "°C" if params.units == "metric" else "°F"
+ return AgentToolResult(
+ content=[TextContent(text=f"{cw['temperature']}{unit}, wind {cw['windspeed']} km/h in {params.city}.")],
+ )
+ except httpx.HTTPError as e:
+ return AgentToolResult(
+ content=[TextContent(text=f"Weather API error: {e}")],
+ is_error=True,
+ )
+
+
+weather_tool = AgentTool(
+ name="get_weather",
+ description="Get current weather for a city. Returns a short text summary.",
+ parameters=GetWeatherParams,
+ execute=get_weather,
+)
+
+
+# --- The agent ----------------------------------------------------------
+
+async def main():
+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])
+ agent = Agent(
+ provider=provider,
+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),
+ system_prompt="You are a concise weather assistant. Always use the tool; don't guess.",
+ tools=[weather_tool],
+ )
+
+ def on_event(event, signal=None):
+ if event.type == "message_update" and event.stream_event.type == "text_delta":
+ print(event.stream_event.delta, end="", flush=True)
+ elif event.type == "tool_execution_start":
+ print(f"\n[calling {event.tool_name}({event.args})]")
+ elif event.type == "agent_end":
+ print()
+
+ agent.subscribe(on_event)
+
+ # Wrap prompt() so Ctrl-C cleanly cancels the run.
+ task = asyncio.create_task(agent.prompt("Weather in Tokyo and São Paulo, please."))
+ try:
+ await task
+ except KeyboardInterrupt:
+ agent.abort()
+ await agent.wait_for_idle()
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
+```
+
+Run:
+
+```bash
+pip install cubepi httpx
+export ANTHROPIC_API_KEY=sk-…
+python weather_agent.py
+```
+
+Sample output:
+
+```
+[calling get_weather({'city': 'Tokyo', 'units': 'metric'})]
+[calling get_weather({'city': 'São Paulo', 'units': 'metric'})]
+Tokyo is currently 18°C with a wind speed of 12 km/h. São Paulo is 25°C with winds of 9 km/h.
+```
+
+## What's going on
+
+- **Two tools in parallel.** The model emits two `get_weather` tool
+ calls in the same assistant turn. CubePi runs them concurrently —
+ the second one doesn't wait for the first.
+- **Streaming text + tool events interleave.** The `on_event` filter
+ handles both `text_delta` (for the final answer) and
+ `tool_execution_start` (for the "thinking" indicator).
+- **Errors are tool results, not exceptions.** A bad city or network
+ hiccup returns `is_error=True`; the model gets the error message
+ and usually retries with a different spelling.
+- **Cancellation is clean.** `agent.abort()` propagates through
+ `signal` into in-flight tools and the provider stream.
+
+## Extending this recipe
+
+- **Add caching:** memoize the geocoding lookup by `city` —
+ Open-Meteo's coordinates are stable.
+- **Add retries:** wrap with [`RetryMiddleware`](../guides/middleware/examples#retries-with-backoff)
+ to handle transient API errors.
+- **Persist conversations:** add a
+ [`SQLiteCheckpointer`](../guides/checkpointing/sqlite) so follow-up
+ questions ("and in Osaka?") have history.
+
+## See also
+
+- [Building Your First Agent](../guides/agents/first-agent) — the same
+ pattern with a hard-coded tool.
+- [Tool Use & Parallel Execution](../guides/agents/tool-use) — more on
+ parallel tool calls.
diff --git a/website/versioned_sidebars/version-0.6-sidebars.json b/website/versioned_sidebars/version-0.6-sidebars.json
new file mode 100644
index 0000000..b170864
--- /dev/null
+++ b/website/versioned_sidebars/version-0.6-sidebars.json
@@ -0,0 +1,127 @@
+{
+ "docs": [
+ "intro",
+ {
+ "type": "category",
+ "label": "Getting Started",
+ "collapsed": false,
+ "items": [
+ "getting-started/installation",
+ "getting-started/quick-start",
+ "getting-started/core-concepts"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Guides",
+ "items": [
+ {
+ "type": "category",
+ "label": "Agents",
+ "items": [
+ "guides/agents/first-agent",
+ "guides/agents/tool-use",
+ "guides/agents/multi-turn",
+ "guides/agents/streaming"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Providers",
+ "items": [
+ "guides/providers/anthropic",
+ "guides/providers/openai",
+ "guides/providers/capability-and-presets",
+ "guides/providers/custom"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Checkpointing",
+ "items": [
+ "guides/checkpointing/sqlite",
+ "guides/checkpointing/postgres",
+ "guides/checkpointing/mysql",
+ "guides/checkpointing/custom"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Middleware",
+ "items": [
+ "guides/middleware/hooks",
+ "guides/middleware/composition",
+ "guides/middleware/examples"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Human-in-the-Loop",
+ "items": [
+ "guides/hitl/overview",
+ "guides/hitl/middlewares",
+ "guides/hitl/durable",
+ "guides/hitl/reference"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "MCP",
+ "items": [
+ "guides/mcp/loading",
+ "guides/mcp/auth"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Tracing",
+ "items": [
+ "guides/tracing/overview",
+ "guides/tracing/getting-started",
+ "guides/tracing/cli",
+ "guides/tracing/otlp",
+ "guides/tracing/content-recording",
+ "guides/tracing/metrics"
+ ]
+ }
+ ]
+ },
+ {
+ "type": "category",
+ "label": "API Reference",
+ "link": {
+ "type": "doc",
+ "id": "api/index"
+ },
+ "items": [
+ "api/cubepi-agent",
+ "api/cubepi-providers",
+ "api/cubepi-checkpointer",
+ "api/cubepi-middleware",
+ "api/cubepi-mcp",
+ "api/cubepi-tracing",
+ "api/cubepi-utils"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Recipes",
+ "items": [
+ "recipes/weather-agent",
+ "recipes/multi-provider-failover",
+ "recipes/persistent-chat",
+ "recipes/resumable-tasks",
+ "recipes/postgres-fastapi",
+ "recipes/ask-user-form",
+ "recipes/sandbox-confirm"
+ ]
+ },
+ {
+ "type": "category",
+ "label": "Migration",
+ "items": [
+ "migration/from-langgraph"
+ ]
+ }
+ ]
+}
diff --git a/website/versions.json b/website/versions.json
index 1bd54b5..f9b93e3 100644
--- a/website/versions.json
+++ b/website/versions.json
@@ -1,4 +1,5 @@
[
+ "0.6",
"0.5",
"0.4",
"0.3"