Skip to content

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

docs(website): replace placeholders with full content for 35 pages

xf gongb2dfb6009720
diff --git a/website/docs/getting-started/core-concepts.md b/website/docs/getting-started/core-concepts.md
index fc28a3e..6215183 100644
--- a/website/docs/getting-started/core-concepts.md
+++ b/website/docs/getting-started/core-concepts.md
@@ -4,4 +4,164 @@ title: Core Concepts
# Core Concepts
-_Placeholder. Content arrives in a follow-up content PR._
+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. Eleven
+ types covering the entire loop: `agent_start`, `agent_end`,
+ `turn_start`, `turn_end`, `message_start`, `message_update`,
+ `message_end`, `tool_execution_start`, `tool_execution_update`,
+ `tool_execution_end`. `message_update` wraps the provider event
+ inside `event.stream_event`.
+
+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`. See
+[Checkpointing → SQLite](../guides/checkpointing/sqlite).
+
+## 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/docs/getting-started/installation.md b/website/docs/getting-started/installation.md
index 27827b7..62b2b08 100644
--- a/website/docs/getting-started/installation.md
+++ b/website/docs/getting-started/installation.md
@@ -4,4 +4,89 @@ title: Installation
# Installation
-_Placeholder. Content arrives in a follow-up content PR._
+CubePi runs on **Python 3.11+**. The core has three runtime
+dependencies: `pydantic`, `anthropic`, `openai`. Optional features
+(SQLite, Postgres, MCP) 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[sqlite,mcp]" # 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]"
+```
+
+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]"
+```
+
+## 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 |
+| `[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 |
+| `[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/docs/getting-started/quick-start.md b/website/docs/getting-started/quick-start.md
index b1171f1..a421747 100644
--- a/website/docs/getting-started/quick-start.md
+++ b/website/docs/getting-started/quick-start.md
@@ -4,4 +4,123 @@ title: Quick Start
# Quick Start
-_Placeholder. Content arrives in a follow-up content PR._
+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 == "text_delta":
+ print(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/docs/guides/agents/first-agent.md b/website/docs/guides/agents/first-agent.md
index 7982610..2c33250 100644
--- a/website/docs/guides/agents/first-agent.md
+++ b/website/docs/guides/agents/first-agent.md
@@ -1,7 +1,189 @@
---
-title: First Agent
+title: Building Your First Agent
---
-# First Agent
+# Building Your First Agent
-_Placeholder. Content arrives in a follow-up content PR._
+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 == "text_delta":
+ print(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/docs/guides/agents/multi-turn.md b/website/docs/guides/agents/multi-turn.md
index 85ff92b..d238bfc 100644
--- a/website/docs/guides/agents/multi-turn.md
+++ b/website/docs/guides/agents/multi-turn.md
@@ -1,7 +1,163 @@
---
-title: Multi Turn
+title: Multi-turn Conversations
---
-# Multi Turn
+# Multi-turn Conversations
-_Placeholder. Content arrives in a follow-up content PR._
+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/docs/guides/agents/streaming.md b/website/docs/guides/agents/streaming.md
index a590c9c..70a7b9d 100644
--- a/website/docs/guides/agents/streaming.md
+++ b/website/docs/guides/agents/streaming.md
@@ -1,7 +1,166 @@
---
-title: Streaming
+title: Streaming Events
---
-# Streaming
+# Streaming Events
-_Placeholder. Content arrives in a follow-up content PR._
+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 == "text_delta":
+ print(event.delta, end="", flush=True)
+
+unsubscribe = agent.subscribe(on_event)
+```
+
+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 shorter form, since `text_delta` is the inner provider
+event type and CubePi exposes the same `.type` and `.delta` on the
+event itself:
+
+```python
+def on_event(event, signal=None):
+ # message_update unwraps the inner stream_event onto the wrapper:
+ 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
+(`message_update.stream_event.delta`). Code defensively against the
+inner 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/docs/guides/agents/tool-use.md b/website/docs/guides/agents/tool-use.md
index 013c139..ed722bc 100644
--- a/website/docs/guides/agents/tool-use.md
+++ b/website/docs/guides/agents/tool-use.md
@@ -1,7 +1,190 @@
---
-title: Tool Use
+title: Tool Use & Parallel Execution
---
-# Tool Use
+# Tool Use & Parallel Execution
-_Placeholder. Content arrives in a follow-up content PR._
+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
+ )
+ ```
+
+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/docs/guides/checkpointing/custom.md b/website/docs/guides/checkpointing/custom.md
index cae226e..1d7bd49 100644
--- a/website/docs/guides/checkpointing/custom.md
+++ b/website/docs/guides/checkpointing/custom.md
@@ -1,7 +1,201 @@
---
-title: Custom
+title: Custom Backends
---
-# Custom
+# Custom Checkpointing Backends
-_Placeholder. Content arrives in a follow-up content PR._
+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/docs/guides/checkpointing/postgres.md b/website/docs/guides/checkpointing/postgres.md
index 3d0d01c..b2c5dfa 100644
--- a/website/docs/guides/checkpointing/postgres.md
+++ b/website/docs/guides/checkpointing/postgres.md
@@ -1,7 +1,186 @@
---
-title: Postgres
+title: Postgres Checkpointing
---
-# Postgres
+# Postgres Checkpointing
-_Placeholder. Content arrives in a follow-up content PR._
+`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 generate a revision and apply it. The migration must also
+INSERT the schema version. Use the helper:
+
+```python
+# In a migration's upgrade():
+from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op
+
+def upgrade():
+ op.create_table(...) # auto-generated by Alembic from cubepi_metadata
+ write_schema_version_op(op) # records EXPECTED_SCHEMA_VERSION
+```
+
+When CubePi later upgrades and bumps `EXPECTED_SCHEMA_VERSION`, you
+generate a new revision and call `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.
+- **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.
diff --git a/website/docs/guides/checkpointing/sqlite.md b/website/docs/guides/checkpointing/sqlite.md
index 354d68c..f6af8d5 100644
--- a/website/docs/guides/checkpointing/sqlite.md
+++ b/website/docs/guides/checkpointing/sqlite.md
@@ -1,7 +1,174 @@
---
-title: Sqlite
+title: SQLite Checkpointing
---
-# Sqlite
+# SQLite Checkpointing
-_Placeholder. Content arrives in a follow-up content PR._
+`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.
+
+## 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/docs/guides/mcp/auth.md b/website/docs/guides/mcp/auth.md
index f1a1384..0dc729c 100644
--- a/website/docs/guides/mcp/auth.md
+++ b/website/docs/guides/mcp/auth.md
@@ -1,7 +1,212 @@
---
-title: Auth
+title: MCP Server Authentication
---
-# Auth
+# MCP Server Authentication
-_Placeholder. Content arrives in a follow-up content PR._
+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/docs/guides/mcp/loading.md b/website/docs/guides/mcp/loading.md
index 838b911..2cf6f27 100644
--- a/website/docs/guides/mcp/loading.md
+++ b/website/docs/guides/mcp/loading.md
@@ -1,7 +1,169 @@
---
-title: Loading
+title: Loading MCP Tools
---
-# Loading
+# Loading MCP Tools
-_Placeholder. Content arrives in a follow-up content PR._
+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/docs/guides/middleware/composition.md b/website/docs/guides/middleware/composition.md
index fd95377..c40adb6 100644
--- a/website/docs/guides/middleware/composition.md
+++ b/website/docs/guides/middleware/composition.md
@@ -1,7 +1,168 @@
---
-title: Composition
+title: Composition Rules
---
-# Composition
+# Composition Rules
-_Placeholder. Content arrives in a follow-up content PR._
+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** | First in list wins blocks |
+| `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. Use to chain policy
+layers from most-restrictive to least:
+
+```python
+agent = Agent(
+ middleware=[
+ RateLimiter(), # blocks on rate quota
+ SafetyFilter(), # blocks on dangerous args
+ AuditLogger(), # never blocks; just records
+ ],
+)
+```
+
+If `RateLimiter` returns `block=True`, `SafetyFilter` and
+`AuditLogger`'s `before_tool_call` don't run. `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/docs/guides/middleware/examples.md b/website/docs/guides/middleware/examples.md
index 5f00489..dbdf15f 100644
--- a/website/docs/guides/middleware/examples.md
+++ b/website/docs/guides/middleware/examples.md
@@ -2,6 +2,244 @@
title: Examples
---
-# Examples
+# Middleware Examples
-_Placeholder. Content arrives in a follow-up content PR._
+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.
+
+## 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/docs/guides/middleware/hooks.md b/website/docs/guides/middleware/hooks.md
index a16c78d..36f2019 100644
--- a/website/docs/guides/middleware/hooks.md
+++ b/website/docs/guides/middleware/hooks.md
@@ -1,7 +1,205 @@
---
-title: Hooks
+title: The 7 Hooks
---
-# Hooks
+# The 7 Hooks
-_Placeholder. Content arrives in a follow-up content PR._
+`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.
+
+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/docs/guides/providers/anthropic.md b/website/docs/guides/providers/anthropic.md
index 3098230..78402cb 100644
--- a/website/docs/guides/providers/anthropic.md
+++ b/website/docs/guides/providers/anthropic.md
@@ -2,6 +2,172 @@
title: Anthropic
---
-# Anthropic
+# Anthropic Provider
-_Placeholder. Content arrives in a follow-up content PR._
+`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")
+```
+
+Custom budgets are also possible by passing `StreamOptions(thinking_budgets=ThinkingBudgets(low=4096, medium=12288))`
+through your own `on_payload` hook.
+
+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.
+- [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/docs/guides/providers/custom.md b/website/docs/guides/providers/custom.md
index cae226e..15a56ac 100644
--- a/website/docs/guides/providers/custom.md
+++ b/website/docs/guides/providers/custom.md
@@ -1,7 +1,235 @@
---
-title: Custom
+title: Writing a Custom Provider
---
-# Custom
+# Writing a Custom Provider
-_Placeholder. Content arrives in a follow-up content PR._
+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
+
+- [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/docs/guides/providers/openai.md b/website/docs/guides/providers/openai.md
index f572161..71185ee 100644
--- a/website/docs/guides/providers/openai.md
+++ b/website/docs/guides/providers/openai.md
@@ -1,7 +1,178 @@
---
-title: Openai
+title: OpenAI
---
-# Openai
+# OpenAI Provider
-_Placeholder. Content arrives in a follow-up content PR._
+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,
+ payload_quirks=None, # ["max_completion_tokens_alias", …]
+)
+
+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).
+
+### `payload_quirks`
+
+Some servers require `max_tokens` instead of `max_completion_tokens`:
+
+```python
+provider = OpenAIProvider(
+ api_key="…",
+ payload_quirks=["max_completion_tokens_alias"],
+)
+```
+
+CubePi renames the key on the way out.
+
+### 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",
+)
+```
+
+## 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. Override via `on_payload`
+ to delete it before send.
+- **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/docs/intro.md b/website/docs/intro.md
index 3ad0a6d..ce3f9a7 100644
--- a/website/docs/intro.md
+++ b/website/docs/intro.md
@@ -7,6 +7,56 @@ sidebar_position: 0
# CubePi
-A Pythonic, async-native agent framework.
+**CubePi** is a Pythonic, async-native agent framework — a leaner, more
+readable take on agent runtimes like
+[langgraph](https://github.com/langchain-ai/langgraph). It models an
+agent as a plain `async` function instead of a state graph; you can read
+the entire core loop in five minutes.
-Start with the [Quick Start](./getting-started/quick-start) or browse the [API Reference](./api/).
+```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.
+- **Five-hook middleware.** `transform_context`, `convert_to_llm`,
+ `before_tool_call`, `after_tool_call`, `should_stop_after_turn` —
+ 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.
+
+## 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) |
+| 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
+
+CubePi is at `v0.3.0` — alpha. The public API surface is stable for
+v0.3 and frozen in the [`0.3` docs snapshot](pathname:///). The `next`
+channel (toggle in the top-right) tracks the unreleased main branch.
+
+Source, issues, and discussion live on
+[GitHub](https://github.com/cubeplexai/cubepi).
diff --git a/website/docs/migration/from-langgraph.md b/website/docs/migration/from-langgraph.md
index 78be141..3b15ce4 100644
--- a/website/docs/migration/from-langgraph.md
+++ b/website/docs/migration/from-langgraph.md
@@ -1,7 +1,235 @@
---
-title: From Langgraph
+title: From langgraph
---
-# From Langgraph
+# Migrating from langgraph
-_Placeholder. Content arrives in a follow-up content PR._
+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.3.
+- **LangSmith / Langfuse integrations.** Bring your own tracing via
+ middleware + `on_response`.
+
+## What CubePi does that langgraph doesn't
+
+- **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/docs/recipes/multi-provider-failover.md b/website/docs/recipes/multi-provider-failover.md
index d254f8f..456a9da 100644
--- a/website/docs/recipes/multi-provider-failover.md
+++ b/website/docs/recipes/multi-provider-failover.md
@@ -1,7 +1,199 @@
---
-title: Multi Provider Failover
+title: Multi-Provider Failover
---
-# Multi Provider Failover
+# Recipe: Multi-Provider Failover
-_Placeholder. Content arrives in a follow-up content PR._
+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
+from typing import Sequence
+
+from cubepi.providers.base import (
+ Message,
+ MessageStream,
+ Model,
+ Provider,
+ StreamOptions,
+ ToolDefinition,
+)
+from cubepi.providers.anthropic import AnthropicProvider
+from cubepi.providers.openai import OpenAIProvider
+
+log = logging.getLogger(__name__)
+
+
+class FailoverProvider:
+ """Try a primary provider; fall back to others on retryable errors."""
+
+ 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:
+ # `model` is the agent's selected Model — we ignore it and use the
+ # one paired with each provider in the chain.
+ last_exc: BaseException | None = None
+ for provider, mapped_model in self._chain:
+ try:
+ stream = await provider.stream(
+ mapped_model,
+ messages,
+ system_prompt=system_prompt,
+ tools=tools,
+ options=options,
+ )
+ # Peek at the first event to validate the stream actually started.
+ # If the provider produces a stream object but errors on first chunk,
+ # we want to fall through.
+ return stream
+ except Exception as e:
+ log.warning("provider %s failed: %s — trying fallback", mapped_model.provider, e)
+ last_exc = e
+ continue
+
+ raise RuntimeError(f"all providers exhausted; last error: {last_exc!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** exception. That's the right
+behaviour for `RateLimitError`, `APIConnectionError`, or 5xx — but
+arguably wrong for `BadRequestError` (your code is wrong; the next
+provider will fail the same way).
+
+Tighten the catch:
+
+```python
+import anthropic, openai
+
+RETRYABLE = (
+ anthropic.RateLimitError, anthropic.APIConnectionError, anthropic.APIStatusError,
+ openai.RateLimitError, openai.APIConnectionError, openai.APIStatusError,
+)
+
+# Inside the loop:
+except RETRYABLE as e:
+ ...
+except Exception:
+ raise # not retryable
+```
+
+## 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 passes streams through
+ unchanged, so consumers see the same `StreamEvent` shape regardless
+ of which provider answered.
+
+## 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/docs/recipes/persistent-chat.md b/website/docs/recipes/persistent-chat.md
index 6965c93..df822e0 100644
--- a/website/docs/recipes/persistent-chat.md
+++ b/website/docs/recipes/persistent-chat.md
@@ -2,6 +2,176 @@
title: Persistent Chat
---
-# Persistent Chat
+# Recipe: Persistent Chat (SQLite)
-_Placeholder. Content arrives in a follow-up content PR._
+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/docs/recipes/postgres-fastapi.md b/website/docs/recipes/postgres-fastapi.md
index 4d63e59..d6c0421 100644
--- a/website/docs/recipes/postgres-fastapi.md
+++ b/website/docs/recipes/postgres-fastapi.md
@@ -1,7 +1,255 @@
---
-title: Postgres Fastapi
+title: Postgres + FastAPI Service
---
-# Postgres Fastapi
+# Recipe: Postgres + FastAPI Service
-_Placeholder. Content arrives in a follow-up content PR._
+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/docs/recipes/resumable-tasks.md b/website/docs/recipes/resumable-tasks.md
index 03d6901..c4c4518 100644
--- a/website/docs/recipes/resumable-tasks.md
+++ b/website/docs/recipes/resumable-tasks.md
@@ -1,7 +1,203 @@
---
-title: Resumable Tasks
+title: Resumable Long Tasks
---
-# Resumable Tasks
+# Recipe: Resumable Long Tasks
-_Placeholder. Content arrives in a follow-up content PR._
+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},
+ )
+```
+
+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_video # the idempotent tool 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_video],
+ checkpointer=cp,
+ thread_id=thread_id,
+ )
+ agent.subscribe(lambda e, s=None: None)
+
+ if initial_prompt:
+ # Fresh run.
+ await agent.prompt(initial_prompt)
+ else:
+ # Resume. If the last message is an assistant message with no
+ # follow-up queued, this will raise; otherwise it picks up.
+ 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):
+ msgs = agent.state.messages
+ if not msgs:
+ # Brand-new conversation. Caller must prompt.
+ return False
+
+ last = msgs[-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.
+- **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/docs/recipes/weather-agent.md b/website/docs/recipes/weather-agent.md
index 8946608..96cc4d6 100644
--- a/website/docs/recipes/weather-agent.md
+++ b/website/docs/recipes/weather-agent.md
@@ -2,6 +2,159 @@
title: Weather Agent
---
-# Weather Agent
+# Recipe: Weather Agent
-_Placeholder. Content arrives in a follow-up content PR._
+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/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md
index 660d64f..23e59df 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md
@@ -4,4 +4,154 @@ title: 核心概念
# 核心概念
-_占位。内容将在后续内容 PR 中补充。_
+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(...)` 收到的内容。十一种类型
+ 覆盖整个循环:`agent_start`、`agent_end`、`turn_start`、`turn_end`、
+ `message_start`、`message_update`、`message_end`、
+ `tool_execution_start`、`tool_execution_update`、
+ `tool_execution_end`。`message_update` 把 provider 事件嵌套在
+ `event.stream_event` 里。
+
+做 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`。
+见 [Checkpointing → SQLite](../guides/checkpointing/sqlite)。
+
+## 拼起来
+
+```
+用户代码
+ │
+ ▼
+┌──────────────────────────────────────────┐
+│ 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/current/getting-started/installation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md
index f82b755..66f66ae 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md
@@ -4,4 +4,85 @@ title: 安装
# 安装
-_占位。内容将在后续内容 PR 中补充。_
+CubePi 需要 **Python 3.11 或以上**。核心运行时只有三个依赖:`pydantic`、
+`anthropic`、`openai`。可选功能(SQLite、Postgres、MCP)通过 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[sqlite,mcp]" # 组合
+```
+
+## 使用 uv
+
+[`uv`](https://github.com/astral-sh/uv) 比 pip 快很多,是推荐的工作流:
+
+```bash
+uv add cubepi
+uv add "cubepi[sqlite,postgres,mcp]"
+```
+
+在已有 uv 项目里,改完 `pyproject.toml` 后 `uv sync` 会重新锁定环境。
+
+## 使用 Poetry
+
+```bash
+poetry add cubepi
+poetry add "cubepi[sqlite,postgres,mcp]"
+```
+
+## 验证安装
+
+```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 上 |
+| `[docs]` | `griffe` | 仅文档站构建(贡献者用) |
+
+## 下一步
+
+- [快速开始](./quick-start) —— 五分钟内跑通你的第一个 Agent。
+- [核心概念](./core-concepts) —— 在动手前先弄清 `Agent` / `Tool` /
+ `Provider` / `Checkpointer` 各自是什么。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md
index 9e7bfd9..6b35709 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md
@@ -4,4 +4,119 @@ title: 快速开始
# 快速开始
-_占位。内容将在后续内容 PR 中补充。_
+五分钟内跑通一个能流式输出、会调用工具的 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 == "text_delta":
+ print(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/current/guides/agents/first-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md
index 148fb0b..b40f822 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md
@@ -2,6 +2,179 @@
title: 第一个 Agent
---
-# 第一个 Agent
+# 构建你的第一个 Agent
-_占位。内容将在后续内容 PR 中补充。_
+这是 [快速开始](../../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 == "text_delta":
+ print(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/current/guides/agents/streaming.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md
index 77cc598..eb22294 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md
@@ -2,6 +2,145 @@
title: 流式输出
---
-# 流式输出
+# 流式事件
-_占位。内容将在后续内容 PR 中补充。_
+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 == "text_delta":
+ print(event.delta, end="", flush=True)
+
+unsubscribe = agent.subscribe(on_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/current/guides/agents/tool-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md
index d862904..378e99f 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md
@@ -2,6 +2,174 @@
title: 工具调用
---
-# 工具调用
+# 工具使用与并行执行
-_占位。内容将在后续内容 PR 中补充。_
+工具是 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", # 出于安全考虑放弃并行
+ )
+ ```
+
+工具会修改共享状态(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/current/guides/checkpointing/sqlite.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md
index f9835eb..eab801b 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md
@@ -2,6 +2,160 @@
title: SQLite
---
-# SQLite
+# SQLite 检查点
-_占位。内容将在后续内容 PR 中补充。_
+`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 行。
+
+## 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/current/guides/providers/anthropic.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md
index d19499c..4e96832 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md
@@ -2,6 +2,158 @@
title: Anthropic
---
-# Anthropic
+# Anthropic Provider
-_占位。内容将在后续内容 PR 中补充。_
+`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/current/intro.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.md
index a2042c3..382d5ad 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.md
@@ -7,6 +7,55 @@ sidebar_position: 0
# CubePi
-一个 Pythonic、原生异步的 Agent 框架。
+**CubePi** 是一个 Pythonic、原生异步的 Agent 框架——相对于
+[langgraph](https://github.com/langchain-ai/langgraph) 等 Agent 运行时,
+更精简、更易读的另一种思路。它把 Agent 建模为一个普通的 `async` 函数,
+而不是状态图;整个核心循环你五分钟就能读完。
-从 [快速开始](./getting-started/quick-start) 开始,或浏览 [API 参考](./api/) 。
+```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`。
+
+## 接下来去哪儿
+
+| 如果你想… | 从这里开始 |
+|---|---|
+| 安装并跑通第一个 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) |
+
+## 状态
+
+CubePi 当前版本是 `v0.3.0` —— alpha。v0.3 的公开 API 已稳定,并冻结
+在 [`0.3` 文档快照](pathname:///) 中。右上角的 `next` 频道跟踪未发布
+的 main 分支。
+
+源代码、Issue 和讨论都在
+[GitHub](https://github.com/cubeplexai/cubepi)。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/core-concepts.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/core-concepts.md
index 660d64f..23e59df 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/core-concepts.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/core-concepts.md
@@ -4,4 +4,154 @@ title: 核心概念
# 核心概念
-_占位。内容将在后续内容 PR 中补充。_
+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(...)` 收到的内容。十一种类型
+ 覆盖整个循环:`agent_start`、`agent_end`、`turn_start`、`turn_end`、
+ `message_start`、`message_update`、`message_end`、
+ `tool_execution_start`、`tool_execution_update`、
+ `tool_execution_end`。`message_update` 把 provider 事件嵌套在
+ `event.stream_event` 里。
+
+做 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`。
+见 [Checkpointing → SQLite](../guides/checkpointing/sqlite)。
+
+## 拼起来
+
+```
+用户代码
+ │
+ ▼
+┌──────────────────────────────────────────┐
+│ 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.3/getting-started/installation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/installation.md
index f82b755..66f66ae 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/installation.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/installation.md
@@ -4,4 +4,85 @@ title: 安装
# 安装
-_占位。内容将在后续内容 PR 中补充。_
+CubePi 需要 **Python 3.11 或以上**。核心运行时只有三个依赖:`pydantic`、
+`anthropic`、`openai`。可选功能(SQLite、Postgres、MCP)通过 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[sqlite,mcp]" # 组合
+```
+
+## 使用 uv
+
+[`uv`](https://github.com/astral-sh/uv) 比 pip 快很多,是推荐的工作流:
+
+```bash
+uv add cubepi
+uv add "cubepi[sqlite,postgres,mcp]"
+```
+
+在已有 uv 项目里,改完 `pyproject.toml` 后 `uv sync` 会重新锁定环境。
+
+## 使用 Poetry
+
+```bash
+poetry add cubepi
+poetry add "cubepi[sqlite,postgres,mcp]"
+```
+
+## 验证安装
+
+```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 上 |
+| `[docs]` | `griffe` | 仅文档站构建(贡献者用) |
+
+## 下一步
+
+- [快速开始](./quick-start) —— 五分钟内跑通你的第一个 Agent。
+- [核心概念](./core-concepts) —— 在动手前先弄清 `Agent` / `Tool` /
+ `Provider` / `Checkpointer` 各自是什么。
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/quick-start.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/quick-start.md
index 9e7bfd9..6b35709 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/quick-start.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/getting-started/quick-start.md
@@ -4,4 +4,119 @@ title: 快速开始
# 快速开始
-_占位。内容将在后续内容 PR 中补充。_
+五分钟内跑通一个能流式输出、会调用工具的 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 == "text_delta":
+ print(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.3/guides/agents/first-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/first-agent.md
index 148fb0b..b40f822 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/first-agent.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/first-agent.md
@@ -2,6 +2,179 @@
title: 第一个 Agent
---
-# 第一个 Agent
+# 构建你的第一个 Agent
-_占位。内容将在后续内容 PR 中补充。_
+这是 [快速开始](../../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 == "text_delta":
+ print(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.3/guides/agents/streaming.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/streaming.md
index 77cc598..eb22294 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/streaming.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/streaming.md
@@ -2,6 +2,145 @@
title: 流式输出
---
-# 流式输出
+# 流式事件
-_占位。内容将在后续内容 PR 中补充。_
+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 == "text_delta":
+ print(event.delta, end="", flush=True)
+
+unsubscribe = agent.subscribe(on_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.3/guides/agents/tool-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/tool-use.md
index d862904..378e99f 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/tool-use.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/agents/tool-use.md
@@ -2,6 +2,174 @@
title: 工具调用
---
-# 工具调用
+# 工具使用与并行执行
-_占位。内容将在后续内容 PR 中补充。_
+工具是 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", # 出于安全考虑放弃并行
+ )
+ ```
+
+工具会修改共享状态(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.3/guides/checkpointing/sqlite.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/checkpointing/sqlite.md
index f9835eb..eab801b 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/checkpointing/sqlite.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/checkpointing/sqlite.md
@@ -2,6 +2,160 @@
title: SQLite
---
-# SQLite
+# SQLite 检查点
-_占位。内容将在后续内容 PR 中补充。_
+`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 行。
+
+## 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.3/guides/providers/anthropic.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/providers/anthropic.md
index d19499c..4e96832 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/providers/anthropic.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/guides/providers/anthropic.md
@@ -2,6 +2,158 @@
title: Anthropic
---
-# Anthropic
+# Anthropic Provider
-_占位。内容将在后续内容 PR 中补充。_
+`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.3/intro.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/intro.md
index a2042c3..382d5ad 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/intro.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/intro.md
@@ -7,6 +7,55 @@ sidebar_position: 0
# CubePi
-一个 Pythonic、原生异步的 Agent 框架。
+**CubePi** 是一个 Pythonic、原生异步的 Agent 框架——相对于
+[langgraph](https://github.com/langchain-ai/langgraph) 等 Agent 运行时,
+更精简、更易读的另一种思路。它把 Agent 建模为一个普通的 `async` 函数,
+而不是状态图;整个核心循环你五分钟就能读完。
-从 [快速开始](./getting-started/quick-start) 开始,或浏览 [API 参考](./api/) 。
+```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`。
+
+## 接下来去哪儿
+
+| 如果你想… | 从这里开始 |
+|---|---|
+| 安装并跑通第一个 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) |
+
+## 状态
+
+CubePi 当前版本是 `v0.3.0` —— alpha。v0.3 的公开 API 已稳定,并冻结
+在 [`0.3` 文档快照](pathname:///) 中。右上角的 `next` 频道跟踪未发布
+的 main 分支。
+
+源代码、Issue 和讨论都在
+[GitHub](https://github.com/cubeplexai/cubepi)。
diff --git a/website/versioned_docs/version-0.3/getting-started/core-concepts.md b/website/versioned_docs/version-0.3/getting-started/core-concepts.md
index fc28a3e..6215183 100644
--- a/website/versioned_docs/version-0.3/getting-started/core-concepts.md
+++ b/website/versioned_docs/version-0.3/getting-started/core-concepts.md
@@ -4,4 +4,164 @@ title: Core Concepts
# Core Concepts
-_Placeholder. Content arrives in a follow-up content PR._
+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. Eleven
+ types covering the entire loop: `agent_start`, `agent_end`,
+ `turn_start`, `turn_end`, `message_start`, `message_update`,
+ `message_end`, `tool_execution_start`, `tool_execution_update`,
+ `tool_execution_end`. `message_update` wraps the provider event
+ inside `event.stream_event`.
+
+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`. See
+[Checkpointing → SQLite](../guides/checkpointing/sqlite).
+
+## 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.3/getting-started/installation.md b/website/versioned_docs/version-0.3/getting-started/installation.md
index 27827b7..62b2b08 100644
--- a/website/versioned_docs/version-0.3/getting-started/installation.md
+++ b/website/versioned_docs/version-0.3/getting-started/installation.md
@@ -4,4 +4,89 @@ title: Installation
# Installation
-_Placeholder. Content arrives in a follow-up content PR._
+CubePi runs on **Python 3.11+**. The core has three runtime
+dependencies: `pydantic`, `anthropic`, `openai`. Optional features
+(SQLite, Postgres, MCP) 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[sqlite,mcp]" # 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]"
+```
+
+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]"
+```
+
+## 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 |
+| `[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 |
+| `[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.3/getting-started/quick-start.md b/website/versioned_docs/version-0.3/getting-started/quick-start.md
index b1171f1..a421747 100644
--- a/website/versioned_docs/version-0.3/getting-started/quick-start.md
+++ b/website/versioned_docs/version-0.3/getting-started/quick-start.md
@@ -4,4 +4,123 @@ title: Quick Start
# Quick Start
-_Placeholder. Content arrives in a follow-up content PR._
+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 == "text_delta":
+ print(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.3/guides/agents/first-agent.md b/website/versioned_docs/version-0.3/guides/agents/first-agent.md
index 7982610..2c33250 100644
--- a/website/versioned_docs/version-0.3/guides/agents/first-agent.md
+++ b/website/versioned_docs/version-0.3/guides/agents/first-agent.md
@@ -1,7 +1,189 @@
---
-title: First Agent
+title: Building Your First Agent
---
-# First Agent
+# Building Your First Agent
-_Placeholder. Content arrives in a follow-up content PR._
+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 == "text_delta":
+ print(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.3/guides/agents/multi-turn.md b/website/versioned_docs/version-0.3/guides/agents/multi-turn.md
index 85ff92b..d238bfc 100644
--- a/website/versioned_docs/version-0.3/guides/agents/multi-turn.md
+++ b/website/versioned_docs/version-0.3/guides/agents/multi-turn.md
@@ -1,7 +1,163 @@
---
-title: Multi Turn
+title: Multi-turn Conversations
---
-# Multi Turn
+# Multi-turn Conversations
-_Placeholder. Content arrives in a follow-up content PR._
+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.3/guides/agents/streaming.md b/website/versioned_docs/version-0.3/guides/agents/streaming.md
index a590c9c..70a7b9d 100644
--- a/website/versioned_docs/version-0.3/guides/agents/streaming.md
+++ b/website/versioned_docs/version-0.3/guides/agents/streaming.md
@@ -1,7 +1,166 @@
---
-title: Streaming
+title: Streaming Events
---
-# Streaming
+# Streaming Events
-_Placeholder. Content arrives in a follow-up content PR._
+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 == "text_delta":
+ print(event.delta, end="", flush=True)
+
+unsubscribe = agent.subscribe(on_event)
+```
+
+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 shorter form, since `text_delta` is the inner provider
+event type and CubePi exposes the same `.type` and `.delta` on the
+event itself:
+
+```python
+def on_event(event, signal=None):
+ # message_update unwraps the inner stream_event onto the wrapper:
+ 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
+(`message_update.stream_event.delta`). Code defensively against the
+inner 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.3/guides/agents/tool-use.md b/website/versioned_docs/version-0.3/guides/agents/tool-use.md
index 013c139..ed722bc 100644
--- a/website/versioned_docs/version-0.3/guides/agents/tool-use.md
+++ b/website/versioned_docs/version-0.3/guides/agents/tool-use.md
@@ -1,7 +1,190 @@
---
-title: Tool Use
+title: Tool Use & Parallel Execution
---
-# Tool Use
+# Tool Use & Parallel Execution
-_Placeholder. Content arrives in a follow-up content PR._
+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
+ )
+ ```
+
+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.3/guides/checkpointing/custom.md b/website/versioned_docs/version-0.3/guides/checkpointing/custom.md
index cae226e..1d7bd49 100644
--- a/website/versioned_docs/version-0.3/guides/checkpointing/custom.md
+++ b/website/versioned_docs/version-0.3/guides/checkpointing/custom.md
@@ -1,7 +1,201 @@
---
-title: Custom
+title: Custom Backends
---
-# Custom
+# Custom Checkpointing Backends
-_Placeholder. Content arrives in a follow-up content PR._
+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.3/guides/checkpointing/postgres.md b/website/versioned_docs/version-0.3/guides/checkpointing/postgres.md
index 3d0d01c..b2c5dfa 100644
--- a/website/versioned_docs/version-0.3/guides/checkpointing/postgres.md
+++ b/website/versioned_docs/version-0.3/guides/checkpointing/postgres.md
@@ -1,7 +1,186 @@
---
-title: Postgres
+title: Postgres Checkpointing
---
-# Postgres
+# Postgres Checkpointing
-_Placeholder. Content arrives in a follow-up content PR._
+`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 generate a revision and apply it. The migration must also
+INSERT the schema version. Use the helper:
+
+```python
+# In a migration's upgrade():
+from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op
+
+def upgrade():
+ op.create_table(...) # auto-generated by Alembic from cubepi_metadata
+ write_schema_version_op(op) # records EXPECTED_SCHEMA_VERSION
+```
+
+When CubePi later upgrades and bumps `EXPECTED_SCHEMA_VERSION`, you
+generate a new revision and call `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.
+- **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.
diff --git a/website/versioned_docs/version-0.3/guides/checkpointing/sqlite.md b/website/versioned_docs/version-0.3/guides/checkpointing/sqlite.md
index 354d68c..f6af8d5 100644
--- a/website/versioned_docs/version-0.3/guides/checkpointing/sqlite.md
+++ b/website/versioned_docs/version-0.3/guides/checkpointing/sqlite.md
@@ -1,7 +1,174 @@
---
-title: Sqlite
+title: SQLite Checkpointing
---
-# Sqlite
+# SQLite Checkpointing
-_Placeholder. Content arrives in a follow-up content PR._
+`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.
+
+## 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.3/guides/mcp/auth.md b/website/versioned_docs/version-0.3/guides/mcp/auth.md
index f1a1384..0dc729c 100644
--- a/website/versioned_docs/version-0.3/guides/mcp/auth.md
+++ b/website/versioned_docs/version-0.3/guides/mcp/auth.md
@@ -1,7 +1,212 @@
---
-title: Auth
+title: MCP Server Authentication
---
-# Auth
+# MCP Server Authentication
-_Placeholder. Content arrives in a follow-up content PR._
+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.3/guides/mcp/loading.md b/website/versioned_docs/version-0.3/guides/mcp/loading.md
index 838b911..2cf6f27 100644
--- a/website/versioned_docs/version-0.3/guides/mcp/loading.md
+++ b/website/versioned_docs/version-0.3/guides/mcp/loading.md
@@ -1,7 +1,169 @@
---
-title: Loading
+title: Loading MCP Tools
---
-# Loading
+# Loading MCP Tools
-_Placeholder. Content arrives in a follow-up content PR._
+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.3/guides/middleware/composition.md b/website/versioned_docs/version-0.3/guides/middleware/composition.md
index fd95377..c40adb6 100644
--- a/website/versioned_docs/version-0.3/guides/middleware/composition.md
+++ b/website/versioned_docs/version-0.3/guides/middleware/composition.md
@@ -1,7 +1,168 @@
---
-title: Composition
+title: Composition Rules
---
-# Composition
+# Composition Rules
-_Placeholder. Content arrives in a follow-up content PR._
+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** | First in list wins blocks |
+| `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. Use to chain policy
+layers from most-restrictive to least:
+
+```python
+agent = Agent(
+ middleware=[
+ RateLimiter(), # blocks on rate quota
+ SafetyFilter(), # blocks on dangerous args
+ AuditLogger(), # never blocks; just records
+ ],
+)
+```
+
+If `RateLimiter` returns `block=True`, `SafetyFilter` and
+`AuditLogger`'s `before_tool_call` don't run. `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.3/guides/middleware/examples.md b/website/versioned_docs/version-0.3/guides/middleware/examples.md
index 5f00489..dbdf15f 100644
--- a/website/versioned_docs/version-0.3/guides/middleware/examples.md
+++ b/website/versioned_docs/version-0.3/guides/middleware/examples.md
@@ -2,6 +2,244 @@
title: Examples
---
-# Examples
+# Middleware Examples
-_Placeholder. Content arrives in a follow-up content PR._
+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.
+
+## 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.3/guides/middleware/hooks.md b/website/versioned_docs/version-0.3/guides/middleware/hooks.md
index a16c78d..36f2019 100644
--- a/website/versioned_docs/version-0.3/guides/middleware/hooks.md
+++ b/website/versioned_docs/version-0.3/guides/middleware/hooks.md
@@ -1,7 +1,205 @@
---
-title: Hooks
+title: The 7 Hooks
---
-# Hooks
+# The 7 Hooks
-_Placeholder. Content arrives in a follow-up content PR._
+`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.
+
+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.3/guides/providers/anthropic.md b/website/versioned_docs/version-0.3/guides/providers/anthropic.md
index 3098230..78402cb 100644
--- a/website/versioned_docs/version-0.3/guides/providers/anthropic.md
+++ b/website/versioned_docs/version-0.3/guides/providers/anthropic.md
@@ -2,6 +2,172 @@
title: Anthropic
---
-# Anthropic
+# Anthropic Provider
-_Placeholder. Content arrives in a follow-up content PR._
+`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")
+```
+
+Custom budgets are also possible by passing `StreamOptions(thinking_budgets=ThinkingBudgets(low=4096, medium=12288))`
+through your own `on_payload` hook.
+
+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.
+- [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.3/guides/providers/custom.md b/website/versioned_docs/version-0.3/guides/providers/custom.md
index cae226e..15a56ac 100644
--- a/website/versioned_docs/version-0.3/guides/providers/custom.md
+++ b/website/versioned_docs/version-0.3/guides/providers/custom.md
@@ -1,7 +1,235 @@
---
-title: Custom
+title: Writing a Custom Provider
---
-# Custom
+# Writing a Custom Provider
-_Placeholder. Content arrives in a follow-up content PR._
+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
+
+- [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.3/guides/providers/openai.md b/website/versioned_docs/version-0.3/guides/providers/openai.md
index f572161..71185ee 100644
--- a/website/versioned_docs/version-0.3/guides/providers/openai.md
+++ b/website/versioned_docs/version-0.3/guides/providers/openai.md
@@ -1,7 +1,178 @@
---
-title: Openai
+title: OpenAI
---
-# Openai
+# OpenAI Provider
-_Placeholder. Content arrives in a follow-up content PR._
+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,
+ payload_quirks=None, # ["max_completion_tokens_alias", …]
+)
+
+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).
+
+### `payload_quirks`
+
+Some servers require `max_tokens` instead of `max_completion_tokens`:
+
+```python
+provider = OpenAIProvider(
+ api_key="…",
+ payload_quirks=["max_completion_tokens_alias"],
+)
+```
+
+CubePi renames the key on the way out.
+
+### 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",
+)
+```
+
+## 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. Override via `on_payload`
+ to delete it before send.
+- **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.3/intro.md b/website/versioned_docs/version-0.3/intro.md
index 3ad0a6d..ce3f9a7 100644
--- a/website/versioned_docs/version-0.3/intro.md
+++ b/website/versioned_docs/version-0.3/intro.md
@@ -7,6 +7,56 @@ sidebar_position: 0
# CubePi
-A Pythonic, async-native agent framework.
+**CubePi** is a Pythonic, async-native agent framework — a leaner, more
+readable take on agent runtimes like
+[langgraph](https://github.com/langchain-ai/langgraph). It models an
+agent as a plain `async` function instead of a state graph; you can read
+the entire core loop in five minutes.
-Start with the [Quick Start](./getting-started/quick-start) or browse the [API Reference](./api/).
+```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.
+- **Five-hook middleware.** `transform_context`, `convert_to_llm`,
+ `before_tool_call`, `after_tool_call`, `should_stop_after_turn` —
+ 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.
+
+## 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) |
+| 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
+
+CubePi is at `v0.3.0` — alpha. The public API surface is stable for
+v0.3 and frozen in the [`0.3` docs snapshot](pathname:///). The `next`
+channel (toggle in the top-right) tracks the unreleased main branch.
+
+Source, issues, and discussion live on
+[GitHub](https://github.com/cubeplexai/cubepi).
diff --git a/website/versioned_docs/version-0.3/migration/from-langgraph.md b/website/versioned_docs/version-0.3/migration/from-langgraph.md
index 78be141..3b15ce4 100644
--- a/website/versioned_docs/version-0.3/migration/from-langgraph.md
+++ b/website/versioned_docs/version-0.3/migration/from-langgraph.md
@@ -1,7 +1,235 @@
---
-title: From Langgraph
+title: From langgraph
---
-# From Langgraph
+# Migrating from langgraph
-_Placeholder. Content arrives in a follow-up content PR._
+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.3.
+- **LangSmith / Langfuse integrations.** Bring your own tracing via
+ middleware + `on_response`.
+
+## What CubePi does that langgraph doesn't
+
+- **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.3/recipes/multi-provider-failover.md b/website/versioned_docs/version-0.3/recipes/multi-provider-failover.md
index d254f8f..456a9da 100644
--- a/website/versioned_docs/version-0.3/recipes/multi-provider-failover.md
+++ b/website/versioned_docs/version-0.3/recipes/multi-provider-failover.md
@@ -1,7 +1,199 @@
---
-title: Multi Provider Failover
+title: Multi-Provider Failover
---
-# Multi Provider Failover
+# Recipe: Multi-Provider Failover
-_Placeholder. Content arrives in a follow-up content PR._
+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
+from typing import Sequence
+
+from cubepi.providers.base import (
+ Message,
+ MessageStream,
+ Model,
+ Provider,
+ StreamOptions,
+ ToolDefinition,
+)
+from cubepi.providers.anthropic import AnthropicProvider
+from cubepi.providers.openai import OpenAIProvider
+
+log = logging.getLogger(__name__)
+
+
+class FailoverProvider:
+ """Try a primary provider; fall back to others on retryable errors."""
+
+ 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:
+ # `model` is the agent's selected Model — we ignore it and use the
+ # one paired with each provider in the chain.
+ last_exc: BaseException | None = None
+ for provider, mapped_model in self._chain:
+ try:
+ stream = await provider.stream(
+ mapped_model,
+ messages,
+ system_prompt=system_prompt,
+ tools=tools,
+ options=options,
+ )
+ # Peek at the first event to validate the stream actually started.
+ # If the provider produces a stream object but errors on first chunk,
+ # we want to fall through.
+ return stream
+ except Exception as e:
+ log.warning("provider %s failed: %s — trying fallback", mapped_model.provider, e)
+ last_exc = e
+ continue
+
+ raise RuntimeError(f"all providers exhausted; last error: {last_exc!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** exception. That's the right
+behaviour for `RateLimitError`, `APIConnectionError`, or 5xx — but
+arguably wrong for `BadRequestError` (your code is wrong; the next
+provider will fail the same way).
+
+Tighten the catch:
+
+```python
+import anthropic, openai
+
+RETRYABLE = (
+ anthropic.RateLimitError, anthropic.APIConnectionError, anthropic.APIStatusError,
+ openai.RateLimitError, openai.APIConnectionError, openai.APIStatusError,
+)
+
+# Inside the loop:
+except RETRYABLE as e:
+ ...
+except Exception:
+ raise # not retryable
+```
+
+## 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 passes streams through
+ unchanged, so consumers see the same `StreamEvent` shape regardless
+ of which provider answered.
+
+## 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.3/recipes/persistent-chat.md b/website/versioned_docs/version-0.3/recipes/persistent-chat.md
index 6965c93..df822e0 100644
--- a/website/versioned_docs/version-0.3/recipes/persistent-chat.md
+++ b/website/versioned_docs/version-0.3/recipes/persistent-chat.md
@@ -2,6 +2,176 @@
title: Persistent Chat
---
-# Persistent Chat
+# Recipe: Persistent Chat (SQLite)
-_Placeholder. Content arrives in a follow-up content PR._
+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.3/recipes/postgres-fastapi.md b/website/versioned_docs/version-0.3/recipes/postgres-fastapi.md
index 4d63e59..d6c0421 100644
--- a/website/versioned_docs/version-0.3/recipes/postgres-fastapi.md
+++ b/website/versioned_docs/version-0.3/recipes/postgres-fastapi.md
@@ -1,7 +1,255 @@
---
-title: Postgres Fastapi
+title: Postgres + FastAPI Service
---
-# Postgres Fastapi
+# Recipe: Postgres + FastAPI Service
-_Placeholder. Content arrives in a follow-up content PR._
+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.3/recipes/resumable-tasks.md b/website/versioned_docs/version-0.3/recipes/resumable-tasks.md
index 03d6901..c4c4518 100644
--- a/website/versioned_docs/version-0.3/recipes/resumable-tasks.md
+++ b/website/versioned_docs/version-0.3/recipes/resumable-tasks.md
@@ -1,7 +1,203 @@
---
-title: Resumable Tasks
+title: Resumable Long Tasks
---
-# Resumable Tasks
+# Recipe: Resumable Long Tasks
-_Placeholder. Content arrives in a follow-up content PR._
+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},
+ )
+```
+
+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_video # the idempotent tool 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_video],
+ checkpointer=cp,
+ thread_id=thread_id,
+ )
+ agent.subscribe(lambda e, s=None: None)
+
+ if initial_prompt:
+ # Fresh run.
+ await agent.prompt(initial_prompt)
+ else:
+ # Resume. If the last message is an assistant message with no
+ # follow-up queued, this will raise; otherwise it picks up.
+ 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):
+ msgs = agent.state.messages
+ if not msgs:
+ # Brand-new conversation. Caller must prompt.
+ return False
+
+ last = msgs[-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.
+- **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.3/recipes/weather-agent.md b/website/versioned_docs/version-0.3/recipes/weather-agent.md
index 8946608..96cc4d6 100644
--- a/website/versioned_docs/version-0.3/recipes/weather-agent.md
+++ b/website/versioned_docs/version-0.3/recipes/weather-agent.md
@@ -2,6 +2,159 @@
title: Weather Agent
---
-# Weather Agent
+# Recipe: Weather Agent
-_Placeholder. Content arrives in a follow-up content PR._
+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.