CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
docs: add CHANGELOG + /changelog page; cut 0.5 docs version (#118)
Chrisf27482a20f2f
diff --git a/CHANGELOG.md b/CHANGELOG.mdnew file mode 100644index 0000000..b02c963--- /dev/null+++ b/CHANGELOG.md@@ -0,0 +1,59 @@+# Changelog++All notable changes to CubePi are documented here.++The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).++## [Unreleased]++## [0.5.0] - 2026-05-25++### Added++- **Image generation subsystem** (`cubepi.providers.images`): a pluggable,+ per-vendor model interface for image generation, with a class factory so new+ backends slot in without touching call sites.+- **`CapabilityDescriptor`**: a declarative, per-model description of what a+ model supports — temperature mode (free / fixed / ignored), reasoning-level+ mapping (int budget / effort / enum), and the `max_tokens` field name. It now+ drives the OpenAI, OpenAI Responses, Anthropic, and DeepSeek providers, and is+ exported from the top-level package.+- **`cubepi trace` CLI** (install with the `trace-cli` extra): discover, list,+ view, follow, and aggregate stats over local agent-run traces, with rich+ rendering and run-id prefix matching.+- **Tracing**: an OTLP exporter and a best-effort `trace()` scope helper. The+ tracing package now imports cleanly without `opentelemetry` installed.+- **Self-describing provider errors** that carry provider / model / cause+ context for easier debugging.++### Changed++- Provider reasoning/thinking and temperature handling is now driven by+ `CapabilityDescriptor` instead of per-provider ad-hoc payload quirks, giving+ consistent behavior across OpenAI, Anthropic, and DeepSeek.++### Fixed++- **Anthropic**: merge parallel tool results into a single user message; carry+ parsed tool arguments through the streaming `toolcall_end` event; compute+ `max_tokens` from the actual capability budget; honor per-request+ `thinking_budgets` overrides.+- **Agent loop / steering**: drain steering at the turn boundary;+ `after_model_response` now injects after tool results; backfill tool results+ for tool calls orphaned by a cancel.+- **DeepSeek**: correct reasoning-effort path and temperature range handling.++## Earlier releases++- **[0.4.0]** - 2026-05-19 — see the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.4.0).+- **[0.3.0]** - 2026-05-14 — see the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.3.0).+- **[0.2.0]** - 2026-05-10 — see the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.2.0).+- **[0.1.0]** - 2026-05-09 — initial release. See the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.1.0).++[Unreleased]: https://github.com/cubeplexai/cubepi/compare/v0.5.0...HEAD+[0.5.0]: https://github.com/cubeplexai/cubepi/compare/v0.4.0...v0.5.0+[0.4.0]: https://github.com/cubeplexai/cubepi/compare/v0.3.0...v0.4.0+[0.3.0]: https://github.com/cubeplexai/cubepi/compare/v0.2.0...v0.3.0+[0.2.0]: https://github.com/cubeplexai/cubepi/compare/v0.1.0...v0.2.0+[0.1.0]: https://github.com/cubeplexai/cubepi/releases/tag/v0.1.0diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.tsindex e674d14..2d6bf4d 100644--- a/website/docusaurus.config.ts+++ b/website/docusaurus.config.ts@@ -28,10 +28,11 @@ const classicOptions: ClassicOptions = {docs: {sidebarPath: './sidebars.ts',editUrl: 'https://github.com/cubeplexai/cubepi/edit/main/website/',- lastVersion: '0.4',+ lastVersion: '0.5',versions: {current: { label: 'Next 🚧', path: 'next', banner: 'unreleased' },- '0.4': { label: '0.4 (latest)', path: '' },+ '0.5': { label: '0.5 (latest)', path: '' },+ '0.4': { label: '0.4', path: '0.4' },'0.3': { label: '0.3', path: '0.3' },},},@@ -89,6 +90,7 @@ const config: Config = {{ type: 'doc', docId: 'getting-started/installation', label: 'Docs', position: 'left' },{ type: 'doc', docId: 'api/index', label: 'API', position: 'left' },{ type: 'doc', docId: 'recipes/weather-agent', label: 'Recipes', position: 'left' },+ { to: '/changelog', label: 'Changelog', position: 'left' },{ type: 'docsVersionDropdown', position: 'right' },{ type: 'localeDropdown', position: 'right' },{ href: 'https://github.com/cubeplexai/cubepi', label: 'GitHub', position: 'right' },diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.4.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.4.jsonindex e36f971..f1787c4 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.4.json+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.4.json@@ -1,6 +1,6 @@{"version.label": {- "message": "0.4(最新)",+ "message": "0.4","description": "The label for version 0.4"},"sidebar.docs.category.Getting Started": {diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5.json b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5.jsonnew file mode 100644index 0000000..c6a1140--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5.json@@ -0,0 +1,46 @@+{+ "version.label": {+ "message": "0.5(最新)",+ "description": "The label for version 0.5"+ },+ "sidebar.docs.category.Getting Started": {+ "message": "快速入门",+ "description": "The label for category 'Getting Started' in sidebar 'docs'"+ },+ "sidebar.docs.category.Guides": {+ "message": "指南",+ "description": "The label for category 'Guides' in sidebar 'docs'"+ },+ "sidebar.docs.category.Agents": {+ "message": "Agent",+ "description": "The label for category 'Agents' in sidebar 'docs'"+ },+ "sidebar.docs.category.Providers": {+ "message": "Provider",+ "description": "The label for category 'Providers' in sidebar 'docs'"+ },+ "sidebar.docs.category.Checkpointing": {+ "message": "检查点",+ "description": "The label for category 'Checkpointing' in sidebar 'docs'"+ },+ "sidebar.docs.category.Middleware": {+ "message": "中间件",+ "description": "The label for category 'Middleware' in sidebar 'docs'"+ },+ "sidebar.docs.category.MCP": {+ "message": "MCP",+ "description": "The label for category 'MCP' in sidebar 'docs'"+ },+ "sidebar.docs.category.Tracing": {+ "message": "追踪",+ "description": "The label for category 'Tracing' in sidebar 'docs'"+ },+ "sidebar.docs.category.Recipes": {+ "message": "示例",+ "description": "The label for category 'Recipes' in sidebar 'docs'"+ },+ "sidebar.docs.category.Migration": {+ "message": "迁移指南",+ "description": "The label for category 'Migration' in sidebar 'docs'"+ }+}diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/core-concepts.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/core-concepts.mdnew file mode 100644index 0000000..9f53e06--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/core-concepts.md@@ -0,0 +1,192 @@+---+title: 核心概念+---++# 核心概念++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)。++## Tracer(可选)++`Tracer` 输出符合 [OpenTelemetry GenAI 语义约定](https://opentelemetry.io/docs/specs/semconv/gen-ai/)+的 span,任何 OTLP 后端(Jaeger、Tempo、Honeycomb、Datadog、AWS+X-Ray 等)都能直接接收,无需额外 instrumentation。先装 extra:++```bash+pip install "cubepi[tracing]" # OTel SDK+pip install "cubepi[tracing-otlp]" # + OTLP/HTTP 导出器+```++然后用 `async with` 包住 Agent:++```python+from cubepi.tracing import Tracer+from cubepi.tracing.exporters import JsonlSpanExporter++async with (+ Tracer(+ service_name="my-bot",+ agent_name="assistant",+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ ) as tracer,+ tracer.attached(agent),+):+ await agent.prompt("…")+```++每次 run 会发出一个 `invoke_agent` 根 span,其下每轮 LLM 往返对应+一个 `cubepi.turn`,再嵌套 `chat`(CLIENT)和 `execute_tool` 子+span。**默认不记录任何 prompt 内容或模型输出** —— 需要的话用+`Tracer(record_content=True)` 显式打开,搭配 `redact` 回调脱敏。配+合 `Meter(...)` 还能拿到 token / 时延 / TTFC 直方图。完整指南:+[追踪 → 概览](../guides/tracing/overview)。++## 拼起来++```+用户代码+ │+ ▼+┌──────────────────────────────────────────┐+│ Agent │+│ ├─ AgentState (messages, tools, …) │+│ ├─ Middleware ── compose_middleware() │+│ ├─ Checkpointer ── message_end 时追加 │+│ └─ run_agent_loop ◀──── 真实的循环 │+│ │ │+│ ▼ │+│ Provider.stream() → MessageStream │+│ │ │+│ └─ events → emit → subscribers │+└──────────────────────────────────────────┘+```++这张图就是整个框架。文档站的其余部分,都是细节而已。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/installation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/installation.mdnew file mode 100644index 0000000..d9c721e--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/installation.md@@ -0,0 +1,92 @@+---+title: 安装+---++# 安装++CubePi 需要 **Python 3.11 或以上**。核心运行时只有三个依赖:`pydantic`、+`anthropic`、`openai`。可选功能(SQLite、Postgres、MCP、OpenTelemetry+追踪)通过 extras 按需安装,不用的话不会被拉进来。++## 使用 pip++```bash+pip install cubepi+```++可选 extras:++```bash+pip install "cubepi[sqlite]" # 安装 aiosqlite,启用 SQLiteCheckpointer+pip install "cubepi[postgres]" # 安装 asyncpg + sqlalchemy + msgpack+pip install "cubepi[mcp]" # 安装 MCP SDK,启用 MCP 工具加载器+pip install "cubepi[tracing]" # 安装 opentelemetry-sdk,启用 Tracer / Meter+pip install "cubepi[tracing-otlp]" # 加上 OTLP/HTTP 导出器+pip install "cubepi[sqlite,mcp,tracing]" # 组合+```++## 使用 uv++[`uv`](https://github.com/astral-sh/uv) 比 pip 快很多,是推荐的工作流:++```bash+uv add cubepi+uv add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+```++在已有 uv 项目里,改完 `pyproject.toml` 后 `uv sync` 会重新锁定环境。++## 使用 Poetry++```bash+poetry add cubepi+poetry add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+```++## 验证安装++```bash+python -c "import cubepi; print(cubepi.__doc__)"+# cubepi — Pythonic async-native agent framework.+```++如果报 `ImportError`,大概率是解释器版本低于 3.11——用 `python --version`+确认一下。++## 配置 provider 凭据++CubePi 的 provider 从构造函数参数读取凭据。大多数部署会从环境变量+取出来:++```python+import os+from cubepi.providers.anthropic import AnthropicProvider+from cubepi.providers.openai import OpenAIProvider++anthropic = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])+openai = OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"])+```++你也可以传 `base_url=...` 指向自托管端点或兼容代理(如 Anthropic Bedrock、+LiteLLM、vLLM)。++[FauxProvider](../guides/providers/custom#using-fauxprovider-in-tests)+(用于测试)不需要任何凭据。++## extras 选择指南++| Extra | 拉入什么 | 什么时候装 |+|---|---|---|+| (无) | 仅核心 | 只需要内存里的状态,不用 MCP,不用追踪 |+| `[sqlite]` | `aiosqlite` | 单进程应用需要落盘 |+| `[postgres]` | `asyncpg`、`sqlalchemy`、`msgpack` | 多实例 / 生产环境——见 [Postgres 指南](../guides/checkpointing/postgres) |+| `[mcp]` | `mcp` | 想把 MCP server 工具挂到 Agent 上 |+| `[tracing]` | `opentelemetry-sdk` | 想要 OpenTelemetry 追踪(含可选指标)——见 [追踪指南](../guides/tracing/overview) |+| `[tracing-otlp]` | `opentelemetry-exporter-otlp-proto-http` | 把 trace 发往 OTLP/HTTP 后端(Jaeger ≥1.50、Tempo、Honeycomb、Datadog 等)|+| `[docs]` | `griffe` | 仅文档站构建(贡献者用) |++## 下一步++- [快速开始](./quick-start) —— 五分钟内跑通你的第一个 Agent。+- [核心概念](./core-concepts) —— 在动手前先弄清 `Agent` / `Tool` /+ `Provider` / `Checkpointer` 各自是什么。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/quick-start.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/quick-start.mdnew file mode 100644index 0000000..974721c--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/getting-started/quick-start.md@@ -0,0 +1,122 @@+---+title: 快速开始+---++# 快速开始++五分钟内跑通一个能流式输出、会调用工具的 Agent。我们写一个天气 Agent:+它把一个 Python 函数当工具调用、把 Claude 的回复逐字符流式打出来,+然后干净退出。++## 前置条件++- Python 3.11++- 已安装 `cubepi`(`pip install cubepi`)+- 环境变量中有 `ANTHROPIC_API_KEY`++## 完整脚本++存为 `weather_agent.py`:++```python title="weather_agent.py"+import asyncio+import os+from pydantic import BaseModel++from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent+from cubepi.providers.anthropic import AnthropicProvider+++class GetWeatherParams(BaseModel):+ city: str+++async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):+ # 真实应用里:调一个 HTTP 天气 API。这里直接返回一段假数据。+ return AgentToolResult(+ content=[TextContent(text=f"{params.city} 现在 72°F,晴")]+ )+++async def main():+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])++ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="你是一个简洁的天气助手。",+ tools=[+ AgentTool(+ name="get_weather",+ description="获取一个城市的当前天气",+ parameters=GetWeatherParams,+ execute=get_weather,+ ),+ ],+ )++ # 在 prompt() 之前订阅 —— 这是看到流式事件的关键。+ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "agent_end":+ print() # 末尾换行++ agent.subscribe(on_event)+ await agent.prompt("东京现在天气怎么样?")+++asyncio.run(main())+```++跑起来:++```bash+python weather_agent.py+```++你会看到 Claude 流式输出类似+*"东京当前天气 72°F,晴..."* 的句子,工具结果已经被串进去。++## 刚刚发生了什么++CubePi 跑了一个概念上长这样的循环:++1. `agent.prompt("东京现在天气怎么样?")` 把一条 `UserMessage` 入队,+ 然后调用模型。+2. 模型决定调用 `get_weather(city="Tokyo")`——CubePi 用你的 Pydantic+ 模型解析 JSON 参数,调用你的 `async def`,把结果作为+ `ToolResultMessage` 反馈回去。+3. 模型产生最终的 assistant 回复,以 `text_delta` 事件流的形式回来。+4. 循环发出 `agent_end` 然后返回。++`agent.subscribe(...)` 注册了一个回调,接收运行时发出的每一个事件:+`agent_start`、`turn_start`、`message_start`、`text_delta`、+`tool_execution_start`、`tool_execution_end`、`message_end`、+`turn_end`、`agent_end`。这个脚本只关心 `text_delta`,但你可以基于+任意其他事件渲染 UI。++## 调试之前请先读:常见困惑++- **必须在 prompt 之前订阅。** Listener 只会收到 `subscribe` 之后发出+ 的事件。先 prompt 再 subscribe,早期事件就丢了。+- **`Model(id=..., provider=...)` 是必填的。** Agent 使用 `model.provider`+ 来 clamp 思考等级、给响应打标签。`id` 必须是你的 provider 支持的+ 模型名。+- **`execute` 签名是固定的。** 哪怕你不用 keyword-only 参数,签名也得+ 保留 `(tool_call_id, params, *, signal, on_update)`。CubePi 总是+ 会传它们。+- **`agent.prompt()` 一次只能跑一个 prompt。** 跑的过程中,用+ [`agent.steer()`](../guides/agents/multi-turn) 插入修正,或+ `agent.follow_up()` 把后续消息排队。++## 下一步++- [核心概念](./core-concepts) —— `Agent`、`Tool`、`Provider`、`Stream`、+ `Middleware`、`Checkpointer` 背后的心智模型。+- [构建第一个 Agent](../guides/agents/first-agent) —— 工具、流式、错误+ 处理的完整走查。+- [工具使用与并行执行](../guides/agents/tool-use) —— 让 Agent 同时+ 扇出多个工具。+- [Recipes → Weather Agent](../recipes/weather-agent) —— 上面这个脚本+ 的加强版,真的会发 HTTP 请求。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/first-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/first-agent.mdnew file mode 100644index 0000000..f46e641--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/first-agent.md@@ -0,0 +1,180 @@+---+title: 第一个 Agent+---++# 构建你的第一个 Agent++这是 [快速开始](../../getting-started/quick-start) 的"加长版"。我们+端到端构建一个单工具 Agent,然后逐层加上你后续大概率会想要的东西:+流式 UI、错误处理、取消按钮。++## 第 1 步 —— 配 provider 和 model++provider 是到 LLM API 的连接;`Model` 描述你想调哪个模型 + 一些能力+开关。++```python+import os+from cubepi import Model+from cubepi.providers.anthropic import AnthropicProvider++provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])+model = Model(+ id="claude-sonnet-4-5-20250929",+ provider="anthropic",+ max_tokens=4096, # 回复 token 上限+ context_window=200_000, # 模型硬上限;通常默认就够+ temperature=0.7,+)+```++`Model.provider` 是一个字符串标签(比如 `"anthropic"`、`"openai"`)。+框架内部用来 clamp 思考等级和打 tag —— 在你的代码库里保持稳定即可,+不必和 provider 内部命名一致。++## 第 2 步 —— 声明一个工具++每个工具 = Pydantic 参数模型 + 一个异步 `execute` 函数:++```python+from pydantic import BaseModel+from cubepi import AgentTool, AgentToolResult, TextContent+++class GetWeatherParams(BaseModel):+ city: str+++async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):+ # 真实工作放在这里 —— 调 HTTP API、查 DB 等。+ return AgentToolResult(+ content=[TextContent(text=f"{params.city} 现在 72°F,晴")]+ )+++weather_tool = AgentTool(+ name="get_weather",+ description="获取一个城市的当前天气,返回简短文字。",+ parameters=GetWeatherParams,+ execute=get_weather,+)+```++注意几点:++- Pydantic 模型自动转成 JSON Schema,作为工具定义发给模型。+- `execute` 签名是固定的:`(tool_call_id, params, *, signal, on_update)`。+ 最后两个 keyword-only 参数一定会被传入 —— 哪怕你不用,也得在签名里。+- `signal` 是用户取消时会被 set 的 `asyncio.Event`。在长时间运行的+ 代码里检查它,及时退出。+- `on_update(partial)` 让你流式回报进度(见+ [工具使用](./tool-use))。++## 第 3 步 —— 组装 Agent++```python+from cubepi import Agent++agent = Agent(+ provider=provider,+ model=model,+ system_prompt="你是一个简洁的天气助手。",+ tools=[weather_tool],+)+```++不需要工具时传 `tools=[]`(或干脆省掉)。++## 第 4 步 —— 订阅事件++`agent.subscribe(listener)` 是观察运行过程的入口。Listener 会收到+每一个 `AgentEvent`:++```python+def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "tool_execution_start":+ print(f"\n→ 调用 {event.tool_name}({event.args})")+ elif event.type == "tool_execution_end":+ print(f" ✓ 完成")++agent.subscribe(on_event)+```++可以注册多个 listener,它们都会收到所有事件。**在 `prompt()` 之前+订阅** —— 事件在 run 一开始就会发出。++## 第 5 步 —— prompt 然后跑++```python+import asyncio++async def main():+ await agent.prompt("东京天气怎么样?")++asyncio.run(main())+```++`agent.prompt()` 不返回任何值。结果存在 `agent.state.messages`+(完整历史)和 `agent.state.streaming_message`(当前正在产生的消息,+在两轮之间为 `None`)上。++## 加上错误处理++当 `provider.stream()` 抛异常时,Agent 循环仍然会产出一条+`AssistantMessage`,其 `stop_reason="error"`、`error_message` 已填好。+事件序列是:`message_start` → `message_end` → `turn_end` → `agent_end`。++两种处理方式:++1. 在 subscriber 里捕获 `event.type == "agent_end"`,看最后一条消息+ 的 `stop_reason`:++ ```python+ def on_event(event, signal=None):+ if event.type == "agent_end":+ last = event.messages[-1]+ if getattr(last, "stop_reason", "") == "error":+ print(f"\nerror: {last.error_message}")+ ```++2. 或者在 `await agent.prompt(...)` 返回之后,检查+ `agent.state.error_message`。++## 加一个"取消按钮"++`agent.abort()` 会 set run 级别的 signal。Provider 流短路成+`"aborted"`,正在运行的工具看到 `signal.is_set() == True`,+循环干净地发出 `agent_end`。++```python+async def main():+ task = asyncio.create_task(agent.prompt("搜索…"))+ await asyncio.sleep(0.5)+ agent.abort()+ await task # 一定会 return —— 不会抛异常+ await agent.wait_for_idle()+```++## 常见坑++- **`RuntimeError: Agent is already processing a prompt.`** ——+ 上一次 `prompt()` 没 await 完你又调了一次。用 `await+ agent.wait_for_idle()`,或用 `steer()` / `follow_up()` 排队。+- **没有 `text_delta` 事件** —— 是不是在 `prompt()` 之后才订阅的?+ Listener 只看得到注册之后的事件。+- **Tool not found** —— 模型调了一个 `name` 不在 `tools=[...]` 里的+ 工具。CubePi 把这种情况包装成一个 `is_error=True` 的工具结果,+ 不会崩 —— 在 `tool_execution_end` 事件的 `result` 里能看到。+- **Pydantic ValidationError 被吞掉了** —— 如果模型产出格式错误的+ JSON,CubePi 会把 validation error 也包成工具的 error result 喂+ 回去,模型通常下一轮自动纠正。++## 下一步++- [工具使用与并行执行](./tool-use) —— 同时多个工具、sequential 模式、+ `terminate`、增量进度。+- [流式事件](./streaming) —— 完整的事件分类。+- [多轮会话](./multi-turn) —— 跨轮保留状态、`steer`、`follow_up`、+ `resume`。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/streaming.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/streaming.mdnew file mode 100644index 0000000..bb7d7f1--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/streaming.md@@ -0,0 +1,151 @@+---+title: 流式输出+---++# 流式事件++CubePi 暴露两层流:++1. **Provider 流** —— `provider.stream(...)` 返回的 `MessageStream`,+ 产出 `StreamEvent` 描述原始线缆输出:文本 delta、思考 delta、+ 工具调用 delta,最后是 `done` 或 `error`。+2. **Agent 事件流** —— `agent.subscribe(...)` 注册的 listener 看到的+ 内容。十一种事件覆盖 `prompt()` 调用的完整生命周期,包括把 provider+ 事件包在 `MessageUpdateEvent` 里。++大部分应用代码只需要 Agent 事件流。++## 十一种 Agent 事件++| 事件 | 何时触发 |+|---|---|+| `agent_start` | `prompt()` / `resume()` 一开始 |+| `turn_start` | 每次调模型之前(一次 `prompt` 可能调多次) |+| `message_start` | 一条新消息(user / assistant / tool result)即将加入历史 |+| `message_update` | 每个 provider `StreamEvent`(deltas 等);`event.stream_event` 字段会带原始事件 |+| `message_end` | 一条消息已 finalize |+| `tool_execution_start` | 一个工具调用被派发(在并行 `asyncio.gather` 之前各发一次) |+| `tool_execution_update` | 一个工具通过 `on_update(...)` 报告了局部进度 |+| `tool_execution_end` | 一个工具结束(成功或失败) |+| `turn_end` | 当前批次的工具都尘埃落定,或一条无工具的 assistant 回复结束 |+| `agent_end` | 整个 `prompt()` 调用结束 —— 正常结束、abort、或 error 都会发 |++`MessageStartEvent` 和 `MessageEndEvent` 对 *每种* 消息都触发,不只是+assistant。User 消息和 tool result 消息也有。++## 工具调用一轮的事件顺序++典型 "用户提问 → 模型调一个工具 → 模型回答" 的事件序列:++```+agent_start+turn_start+ message_start (从 prompt 来的 UserMessage)+ message_end (UserMessage)+ message_start (空的 AssistantMessage partial)+ message_update × N (text_delta、toolcall_delta、…)+ message_end (finalize 后的 AssistantMessage)+ tool_execution_start+ tool_execution_end+ message_start (ToolResultMessage)+ message_end (ToolResultMessage)+turn_end+turn_start (循环带着工具结果再进模型)+ message_start+ message_update × N+ message_end+turn_end+agent_end+```++## 订阅++```python+def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)++unsubscribe = agent.subscribe(on_event)+```++`agent.subscribe(...)` 永远不会收到 `event.type == "text_delta"`+的事件 —— 那是 *provider* 事件的 type。Agent 把每个 provider 事件+都包成 `MessageUpdateEvent`,原事件挂在 `event.stream_event` 上。+所以要同时匹配外层和内层。++Listener 可以是同步或异步,异步的会被 await。第二个参数是 run 级别+的 `asyncio.Event`(abort signal)—— 你可以查 `signal.is_set()` 判断+本次运行是否被取消。++要取消订阅,调用 `subscribe` 返回的那个函数。++## 过滤文本增量(最常见的用法)++```python+def on_event(event, signal=None):+ if event.type == "message_update":+ sub = event.stream_event+ if sub.type == "text_delta":+ print(sub.delta, end="", flush=True)+```++CubePi 保证的稳定结构是上面表格里那一种(`message_update.stream_event.delta`)。+代码里对内部类型做防御性判断。++## Provider 的 `StreamEvent` 类型++在 `MessageUpdateEvent.stream_event` 内部,type 字段告诉你模型正在+吐什么:++| `stream_event.type` | 含义 | 关键字段 |+|---|---|---|+| `start` | assistant 消息开始 | `partial` |+| `text_start` | 一个文本块开始 | `content_index` |+| `text_delta` | token 片段 | `delta` |+| `text_end` | 文本块结束 | `content_index` |+| `thinking_start` / `thinking_delta` / `thinking_end` | 扩展思考块 | `delta` |+| `toolcall_start` / `toolcall_delta` / `toolcall_end` | 工具调用的流式 JSON 参数 | `delta`(partial JSON) |+| `done` | 流正常结束 | — |+| `error` | 流出错 | `error_message` |++每个事件的 `partial` 字段是当前 `AssistantMessage` 的深拷贝快照,+方便 UI 不追 delta、每个事件直接重渲染。++## 直接迭代 provider 流++如果你完全跳过 `Agent`(罕见,通常意味着你在写测试或自定义编排),+直接迭代流即可:++```python+stream = await provider.stream(+ model=model,+ messages=[UserMessage(content=[TextContent(text="hello")])],+)+async for event in stream:+ if event.type == "text_delta":+ print(event.delta, end="", flush=True)+final = await stream.result() # 拿最终的 AssistantMessage+```++`stream.result()` 在迭代结束后也能调用 —— 这是拿最终消息的标准+方式。++## 常见坑++- **`prompt()` 之后才订阅** —— 早期事件已经发完了。先 subscribe,+ 再 prompt。+- **Listener 抛异常会让循环崩吗?** —— 不会,但异常会向上传播到下一个+ `await`。把风险代码包在 try/except 里。+- **并行工具的事件顺序** —— `tool_execution_start` 按模型发出顺序,+ `tool_execution_end` 按完成顺序。别依赖事件成对相邻。+- **`message_update` 触发太频繁** —— 高频 token 可能压垮慢消费者+ (比如 websocket)。消费端做批处理。+- **思考块会触发 `text_delta` 吗?** —— 不会,思考块发 `thinking_*`+ 事件。只想看可见文本就过滤 `event.stream_event.type`。++## 另请参阅++- [工具使用](./tool-use) —— 详解 `tool_execution_*` 三联事件。+- [多轮会话](./multi-turn) —— steering 和 resume 周边的事件顺序。+- [API Reference → StreamEvent](../../api/cubepi-providers#streamevent)+ 里有字段级 schema。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/tool-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/tool-use.mdnew file mode 100644index 0000000..378e99f--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/agents/tool-use.md@@ -0,0 +1,175 @@+---+title: 工具调用+---++# 工具使用与并行执行++工具是 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.5/guides/checkpointing/sqlite.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/checkpointing/sqlite.mdnew file mode 100644index 0000000..eab801b--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/checkpointing/sqlite.md@@ -0,0 +1,161 @@+---+title: SQLite+---++# SQLite 检查点++`SQLiteCheckpointer` 是轻量级持久化后端:单个本地文件、无 server、+追加式消息日志。它是个人电脑、单进程应用、桌面工具,以及任何"单+进程独占会话"场景下的默认选择。++安装 extra:++```bash+pip install "cubepi[sqlite]"+```++会拉入 `aiosqlite`。++## 基本用法++```python+import asyncio+from cubepi import Agent, Model+from cubepi.checkpointer import SQLiteCheckpointer+from cubepi.providers.anthropic import AnthropicProvider+++async def main():+ provider = AnthropicProvider(api_key="…")+ async with SQLiteCheckpointer("agent.db") as cp:+ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ checkpointer=cp,+ thread_id="user-42",+ )+ await agent.prompt("记一下:我最爱的颜色是青色。")++ # 之后再次启动脚本 —— 文件还在。+ await agent.prompt("我说过我最爱什么颜色?")+ # → "你说过是青色。"+++asyncio.run(main())+```++两件事必须记住:++1. **`thread_id`** 是会话标识符 —— 一般是用户 id 或 session id。+ 两个 Agent 用同一个 `thread_id` 共享同一段历史。+2. **`async with SQLiteCheckpointer(...)`** 是必需的:context manager+ 在 `__aenter__` 里打开连接、做一次性建表。不用 context manager+ 会抛 `AssertionError`。++## 会持久化什么++`SQLiteCheckpointer` 首次使用时建两张表:++```sql+CREATE TABLE messages (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ thread_id TEXT NOT NULL,+ message_json TEXT NOT NULL,+ created_at REAL NOT NULL DEFAULT (julianday('now'))+);++CREATE TABLE thread_extra (+ thread_id TEXT PRIMARY KEY,+ extra_json TEXT NOT NULL DEFAULT '{}'+);+```++- 每条 `UserMessage`、`AssistantMessage`、`ToolResultMessage` 各占+ `messages` 一行。JSON payload 通过 Pydantic `model_dump()` 生成。+- `AgentContext` 的 `extra` dict 在 `agent_end` 时持久化到 `thread_extra`。+ Middleware 需要持久化线程级状态时,往 `context.extra` 写。++这个 schema 是追加式的。CubePi 从不 update 或 delete 行。++## 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.5/guides/providers/anthropic.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/providers/anthropic.mdnew file mode 100644index 0000000..4e96832--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/guides/providers/anthropic.md@@ -0,0 +1,159 @@+---+title: Anthropic+---++# Anthropic Provider++`AnthropicProvider` 封装了官方 `anthropic` SDK 的 Messages API。+支持流式、扩展思考、prompt caching 和工具调用。++## 构造++```python+from cubepi.providers.anthropic import AnthropicProvider++provider = AnthropicProvider(+ api_key="sk-ant-…", # 也可让 SDK 自己读 ANTHROPIC_API_KEY+ base_url=None, # 指向代理 / Bedrock 兼容端点+ cache_retention="short", # "short"(5 分钟,默认) | "long"(1 小时) | "none"+)+```++`api_key=None` 时 SDK 会从环境变量读取。++## `Model`++```python+from cubepi import Model++model = Model(+ id="claude-sonnet-4-5-20250929",+ provider="anthropic",+ reasoning=True, # 启用思考等级(见下)+ max_tokens=8192, # 回复 token 上限+ context_window=200_000, # 模型硬上限+ temperature=0.7,+)+```++`id` 就是你传给 SDK 的模型名。`provider` 字符串是 CubePi 内部用的+自由标签 —— 保持稳定即可,不必精确匹配 `"anthropic"`。++## 扩展思考++CubePi 把 `ThinkingLevel` 枚举映射到 Anthropic 的 `budget_tokens`:++| Level | 默认 budget |+|---|---|+| `"off"` | 关闭思考 |+| `"minimal"` | 1024 |+| `"low"` | 2048 |+| `"medium"` | 8192 |+| `"high"` | 16384 |+| `"xhigh"` | clamp 到 `"high"` |++在 Agent 上设置:++```python+agent = Agent(provider=provider, model=model, thinking="medium")+```++要自定义 budget,可以通过自己的 `on_payload` hook 传入+`StreamOptions(thinking_budgets=ThinkingBudgets(low=4096, medium=12288))`。++思考打开时,CubePi **会把 `temperature` 字段省掉** —— 因为 Anthropic+API 在扩展思考模式下不接受非默认的 temperature([兼容性文档](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#feature-compatibility))。+关闭思考时再按 `Model.temperature` 走;CubePi 自己处理切换。++思考内容以 `thinking_start` / `thinking_delta` / `thinking_end` 事件+流式产出,最终作为 `ThinkingContent` 块保存在 `AssistantMessage.content`+里 —— 后续轮次也会带着,以保证模型的思路连贯性。++## Prompt caching++默认情况下,provider 在每个请求上插入三个缓存断点:++- **system prompt**(最稳定)。+- **最后一个工具定义**(变化少)。+- **最后一条消息**(每轮往前推,把之前的历史全部缓存)。++缓存保留期默认 `"short"`(5 分钟,免费)。如果你的回合间隔较长,+切到 `"long"`:++```python+AnthropicProvider(api_key=…, cache_retention="long") # 1 小时 TTL+AnthropicProvider(api_key=…, cache_retention="none") # 完全禁用+```++每个 `AssistantMessage` 上的 `Usage` 对象会报告 `cache_read_tokens`+和 `cache_write_tokens`,方便你看命中率。++需要自定义缓存策略(比如换个断点策略)?实现 `CacheMarkerPolicy`+Protocol 然后 `cache_policy=…` 传入。默认策略类位于+`cubepi.providers.anthropic.DefaultCacheMarkerPolicy`。++## 用 `on_payload` 自定义请求++`on_payload` 让你在请求发出前查看 / 替换 request dict:++```python+async def my_payload(payload, model):+ payload.setdefault("metadata", {})["user_id"] = "u-42"+ return payload # 返回 None 或不返回保留原 payload++agent = Agent(provider=provider, model=model, on_payload=my_payload)+```++典型用法:加 `metadata.user_id`(计费)、强制 beta header,或留一份+调试面板用的 payload 副本。++## 用 `on_response` 自定义响应处理++`on_response` 在收到 HTTP 响应(状态、头)后、流式开始前触发:++```python+async def my_response(resp, model):+ if resp.status >= 400:+ logger.warning("bad status %s", resp.status)+ rate = resp.headers.get("anthropic-ratelimit-requests-remaining")+ if rate is not None:+ metrics.gauge("rate_remaining", int(rate))++agent = Agent(provider=provider, model=model, on_response=my_response)+```++两个回调都可以是同步或异步。++## 指向 Bedrock / Vertex / 代理++Anthropic SDK 接受 `base_url`,CubePi 透传:++```python+provider = AnthropicProvider(+ api_key="…",+ base_url="https://my-litellm.internal/v1",+)+```++对于 Bedrock,使用 `anthropic-bedrock` 适配器、通过 [自定义 provider](./custom)+注入。++## 常见坑++- **`temperature` 被忽略** —— 预期之内。思考打开时 CubePi 故意 drop+ 掉,这是 API 约束,不是 bug。+- **`xhigh` 和 `high` 看起来一样** —— Anthropic 没有更高一档的 budget,+ 所以 CubePi 把 `xhigh` clamp 到 `high`,token budget 相同。+- **缓存未命中** —— 缓存按 (内容, ttl) 索引。改 system prompt 会让+ 整块失效;改工具列表则从工具往后失效。要最大化命中,保持这两个+ 跨轮稳定。+- **`anthropic.RateLimitError`** —— 会作为 stream error 事件传出,+ 错误消息来自 SDK 的 `str(exc)`。在 `agent_end` 里捕获,决定是否+ 重试。++## 另请参阅++- [OpenAI Provider](./openai) —— 同 Protocol,不同形态。+- [自定义 Provider](./custom) —— 把不内建的 API 接进来。+- [Recipes → 多 Provider 容错](../../recipes/multi-provider-failover)+ —— Anthropic 故障时切到 OpenAI。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/intro.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/intro.mdxnew file mode 100644index 0000000..3746107--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.5/intro.mdx@@ -0,0 +1,66 @@+---+id: intro+title: CubePi+slug: /+sidebar_position: 0+---++# CubePi++**CubePi** 是一个 Pythonic、原生异步的 Agent 框架——相对于+[langgraph](https://github.com/langchain-ai/langgraph) 等 Agent 运行时,+更精简、更易读的另一种思路。它把 Agent 建模为一个普通的 `async` 函数,+而不是状态图;整个核心循环你五分钟就能读完。++```bash+pip install cubepi+```++然后跳到 [快速开始](./getting-started/quick-start),五分钟内跑通一个+能调用工具的 Agent。++## 你能拿到什么++- **普通 async 函数,不是图节点。** Agent 循环就是一个对消息轮次的+ `while` 循环。你把工具写成 `async def` 函数,框架负责路由调用并并行+ 执行。+- **统一的流式模式。** 所有 provider 都通过 `MessageStream` 产出+ `StreamEvent`。你用 `async for` 迭代它。没有 callback 注册表,也没有+ 为文本和工具单独的 handler 类型。+- **追加式检查点。** 每一轮只写入新消息,而不是整段对话历史。无论+ 会话多长,数据库 I/O 都是 O(1)——SQLite 适合个人开发,Postgres 适合+ 生产环境。+- **原生多 provider。** Anthropic 和 OpenAI 开箱即用,通过 `Provider`+ Protocol 接入。要新增一个 provider 只需要写一个类。+- **五个 Hook 的中间件。** `transform_context`、`convert_to_llm`、+ `before_tool_call`、`after_tool_call`、`should_stop_after_turn`——+ 每一个都有明确的组合规则。没有"节点执行顺序之谜"。+- **MCP 加载器。** 指向任意+ [Model Context Protocol](https://modelcontextprotocol.io) 服务器+ (HTTP 或 stdio),就能拿回一组 `AgentTool`。+- **原生 OpenTelemetry。** 挂一个 `Tracer`,每次 prompt 就产生符合+ GenAI 语义约定的 OTel span 树 —— Jaeger、Tempo、Honeycomb、+ Datadog 等任意 OTLP 后端都能直接接收。默认不记录任何 payload;+ 需要时用 `record_content=True` 配合 `redact` 回调显式开启。++## 接下来去哪儿++| 如果你想… | 从这里开始 |+|---|---|+| 安装并跑通第一个 Agent | [入门 → 安装](./getting-started/installation) |+| 理解骨架 | [入门 → 核心概念](./getting-started/core-concepts) |+| 接入一个真实的工具 Agent | [指南 → 构建第一个 Agent](./guides/agents/first-agent) |+| 跨重启保留对话 | [指南 → SQLite 检查点](./guides/checkpointing/sqlite) |+| 查找某个具体符号 | [API 参考](./api/) |+| 看完整的可运行示例 | [Recipes](./recipes/weather-agent) |+| 从 langgraph Agent 迁移 | [迁移 → 来自 langgraph](./migration/from-langgraph) |++## 状态++你正在浏览的是已发布的 **0.5** 版本文档。+原生 OpenTelemetry 追踪模块([指南 →](./guides/tracing/overview))——+`Tracer`、`Meter`、内容录制、MCP CLIENT span、按 run 打标签的+`tracing_context` —— 已在 0.4 发布。++源代码、Issue 和讨论都在+[GitHub](https://github.com/cubeplexai/cubepi)。diff --git a/website/src/pages/changelog.mdx b/website/src/pages/changelog.mdxnew file mode 100644index 0000000..bb91b31--- /dev/null+++ b/website/src/pages/changelog.mdx@@ -0,0 +1,8 @@+---+title: Changelog+description: Release notes for CubePi.+---++import Changelog from '../../../CHANGELOG.md';++<Changelog />diff --git a/website/versioned_docs/version-0.5/api/cubepi-agent.mdx b/website/versioned_docs/version-0.5/api/cubepi-agent.mdxnew file mode 100644index 0000000..8617ac3--- /dev/null+++ b/website/versioned_docs/version-0.5/api/cubepi-agent.mdx@@ -0,0 +1,525 @@+---+id: cubepi-agent+title: cubepi.agent+sidebar_position: 1+hide_table_of_contents: false+---++# `cubepi.agent`++### Agent {#agent}++_class_++```python+Agent(self, *, provider: Provider, model: Model, system_prompt: str = '', tools: list[AgentTool] | None = None, thinking: ThinkingLevel = 'off', convert_to_llm: Callable[[list[Message]], list[Message]] | None = None, transform_context: Callable | None = None, transform_system_prompt: Callable | None = None, after_model_response: Callable | None = None, before_tool_call: Callable | None = None, after_tool_call: Callable | None = None, should_stop_after_turn: Callable | None = None, on_payload: OnPayloadCallback | None = None, on_response: OnResponseCallback | None = None, steering_mode: str = 'one-at-a-time', follow_up_mode: str = 'one-at-a-time', tool_execution: str = 'parallel', checkpointer: Any = None, thread_id: str | None = None, middleware: list[Middleware] | None = None)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L107)+++**Attributes**++- `convert_to_llm`+- `transform_context`+- `transform_system_prompt`+- `after_model_response`+- `before_tool_call`+- `after_tool_call`+- `should_stop_after_turn`+- `on_payload`+- `on_response`+- `tool_execution`+- `checkpointer`+- `thread_id`+- `state`: `AgentState`+++**Methods**++#### `subscribe` {#agent-subscribe}++```python+subscribe(listener: Callable) -> Callable[[], None]+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L175)+++#### `steer` {#agent-steer}++```python+steer(message: Message) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L181)+++#### `follow_up` {#agent-follow-up}++```python+follow_up(message: Message) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L184)+++#### `abort` {#agent-abort}++```python+abort() -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L187)+++#### `wait_for_idle` {#agent-wait-for-idle}++```python+wait_for_idle() -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L191)+++#### `reset` {#agent-reset}++```python+reset() -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L195)+++#### `prompt` {#agent-prompt}++```python+prompt(message: str | Message | list[Message]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L204)+++#### `resume` {#agent-resume}++```python+resume() -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L230)++++### AgentState {#agentstate}++_class_++```python+AgentState(self, system_prompt: str = '', model: Model = (lambda: Model(id='unknown', provider='unknown'))(), thinking: ThinkingLevel = 'off', is_streaming: bool = False, streaming_message: Message | None = None, error_message: str | None = None, _tools: list[AgentTool] = list(), _messages: list[Message] = list(), _pending_tool_calls: set[str] = set())+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/agent.py#L68)+++**Attributes**++- `system_prompt`: `str`+- `model`: `Model`+- `thinking`: `ThinkingLevel`+- `is_streaming`: `bool`+- `streaming_message`: `Message | None`+- `error_message`: `str | None`+- `tools`: `list[AgentTool]`+- `messages`: `list[Message]`+- `pending_tool_calls`: `set[str]`+++### run_agent_loop {#run-agent-loop}++_function_++```python+run_agent_loop(*, prompts: list[Message], context: AgentContext, provider: Provider, model: Model, convert_to_llm: Callable, emit: Callable, transform_context: Callable | None = None, transform_system_prompt: Callable | None = None, after_model_response: Callable | None = None, before_tool_call: Callable | None = None, after_tool_call: Callable | None = None, should_stop_after_turn: Callable | None = None, get_steering_messages: Callable | None = None, get_follow_up_messages: Callable | None = None, stream_options: StreamOptions | None = None, tool_execution: str = 'parallel', system_prompt: str | None = None) -> list[Message]+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/loop.py#L30)+++### run_agent_loop_continue {#run-agent-loop-continue}++_function_++```python+run_agent_loop_continue(*, context: AgentContext, provider: Provider, model: Model, convert_to_llm: Callable, emit: Callable, transform_context: Callable | None = None, transform_system_prompt: Callable | None = None, after_model_response: Callable | None = None, before_tool_call: Callable | None = None, after_tool_call: Callable | None = None, should_stop_after_turn: Callable | None = None, get_steering_messages: Callable | None = None, get_follow_up_messages: Callable | None = None, stream_options: StreamOptions | None = None, tool_execution: str = 'parallel', system_prompt: str | None = None) -> list[Message]+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/loop.py#L87)+++### execute_tool_calls {#execute-tool-calls}++_function_++```python+execute_tool_calls(context: AgentContext, assistant_message: AssistantMessage, *, tool_execution: str = 'parallel', before_tool_call: Callable | None = None, after_tool_call: Callable | None = None, signal: asyncio.Event | None = None, emit: Callable) -> ToolCallBatch+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/tools.py#L206)+++### AfterToolCallContext {#aftertoolcallcontext}++_class_++```python+AfterToolCallContext(self, assistant_message: AssistantMessage, tool_call: ToolCall, args: Any, result: AgentToolResult, is_error: bool, context: AgentContext)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L79)+++**Attributes**++- `assistant_message`: `AssistantMessage`+- `tool_call`: `ToolCall`+- `args`: `Any`+- `result`: `AgentToolResult`+- `is_error`: `bool`+- `context`: `AgentContext`+++### AfterToolCallResult {#aftertoolcallresult}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L64)+++**Attributes**++- `content`: `list[Content] | None`+- `details`: `Any`+- `is_error`: `bool | None`+- `terminate`: `bool | None`+++### AgentContext {#agentcontext}++_class_++```python+AgentContext(self, system_prompt: str, messages: list[Message], tools: list[AgentTool] | None = None, extra: dict[str, Any] = dict())+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L48)+++**Attributes**++- `system_prompt`: `str`+- `messages`: `list[Message]`+- `tools`: `list[AgentTool] | None`+- `extra`: `dict[str, Any]`+++### AgentEndEvent {#agentendevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L104)+++**Attributes**++- `type`: `Literal['agent_end']`+- `messages`: `list[Message]`+++### AgentEvent {#agentevent}++_attribute_++```python+AgentEvent = AgentStartEvent | AgentEndEvent | TurnStartEvent | TurnEndEvent | MessageStartEvent | MessageUpdateEvent | MessageEndEvent | ToolExecutionStartEvent | ToolExecutionUpdateEvent | ToolExecutionEndEvent+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L170)+++### AgentListener {#agentlistener}++_attribute_++```python+AgentListener = Callable[[AgentEvent, asyncio.Event | None], Awaitable[None] | None]+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L185)+++### AgentStartEvent {#agentstartevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L100)+++**Attributes**++- `type`: `Literal['agent_start']`+++### AgentTool {#agenttool}++_class_++```python+AgentTool(self, name: str, description: str, parameters: type[TParams], execute: Callable[..., Awaitable[AgentToolResult]], label: str = '', execution_mode: Literal['sequential', 'parallel'] | None = None)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L30)+++**Attributes**++- `name`: `str`+- `description`: `str`+- `parameters`: `type[TParams]`+- `execute`: `Callable[..., Awaitable[AgentToolResult]]`+- `label`: `str`+- `execution_mode`: `Literal['sequential', 'parallel'] | None`+++**Methods**++#### `to_definition` {#agenttool-to-definition}++```python+to_definition() -> ToolDefinition+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L39)++++### AgentToolResult {#agenttoolresult}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L23)+++**Attributes**++- `content`: `list[Content]`+- `details`: `Any`+- `is_error`: `bool | None`+- `terminate`: `bool | None`+++### BeforeToolCallContext {#beforetoolcallcontext}++_class_++```python+BeforeToolCallContext(self, assistant_message: AssistantMessage, tool_call: ToolCall, args: Any, context: AgentContext)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L71)+++**Attributes**++- `assistant_message`: `AssistantMessage`+- `tool_call`: `ToolCall`+- `args`: `Any`+- `context`: `AgentContext`+++### BeforeToolCallResult {#beforetoolcallresult}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L59)+++**Attributes**++- `block`: `bool`+- `reason`: `str | None`+++### MessageEndEvent {#messageendevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L130)+++**Attributes**++- `type`: `Literal['message_end']`+- `message`: `Message`+++### MessageStartEvent {#messagestartevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L119)+++**Attributes**++- `type`: `Literal['message_start']`+- `message`: `Message`+++### MessageUpdateEvent {#messageupdateevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L124)+++**Attributes**++- `type`: `Literal['message_update']`+- `message`: `AssistantMessage`+- `stream_event`: `StreamEvent`+++### ShouldStopAfterTurnContext {#shouldstopafterturncontext}++_class_++```python+ShouldStopAfterTurnContext(self, message: AssistantMessage, tool_results: list[ToolResultMessage], context: AgentContext, new_messages: list[Message])+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L89)+++**Attributes**++- `message`: `AssistantMessage`+- `tool_results`: `list[ToolResultMessage]`+- `context`: `AgentContext`+- `new_messages`: `list[Message]`+++### ToolExecutionEndEvent {#toolexecutionendevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L150)+++**Attributes**++- `type`: `Literal['tool_execution_end']`+- `tool_call_id`: `str`+- `tool_name`: `str`+- `result`: `Any`+- `is_error`: `bool`+- `terminate`: `bool` — True iff the tool's AgentToolResult.terminate was True (or the after_tool_call hook set terminate=True). Recorders use this to mark the turn as terminated-by-tool without unwrapping `result`.+- `blocked_by_hook`: `bool` — True iff the tool call was blocked by a `before_tool_call` hook returning `block=True`. Distinguishes hook-blocks from other immediate errors (tool-not-found, arg-validation failure).+- `block_reason`: `str | None` — When `blocked_by_hook` is True, the reason string from `BeforeToolCallResult.reason` (or `None` if the hook supplied no reason).+++### ToolExecutionStartEvent {#toolexecutionstartevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L135)+++**Attributes**++- `type`: `Literal['tool_execution_start']`+- `tool_call_id`: `str`+- `tool_name`: `str`+- `args`: `Any`+++### ToolExecutionUpdateEvent {#toolexecutionupdateevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L142)+++**Attributes**++- `type`: `Literal['tool_execution_update']`+- `tool_call_id`: `str`+- `tool_name`: `str`+- `args`: `Any`+- `partial_result`: `Any`+++### TurnEndEvent {#turnendevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L113)+++**Attributes**++- `type`: `Literal['turn_end']`+- `message`: `AssistantMessage`+- `tool_results`: `list[ToolResultMessage]`+++### TurnStartEvent {#turnstartevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/agent/types.py#L109)+++**Attributes**++- `type`: `Literal['turn_start']`+++### emit_event {#emit-event}++_function_++```python+emit_event(emit_fn: Callable, event: object) -> None+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/utils/emit.py#L7)++++<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->\ No newline at end of filediff --git a/website/versioned_docs/version-0.5/api/cubepi-checkpointer.mdx b/website/versioned_docs/version-0.5/api/cubepi-checkpointer.mdxnew file mode 100644index 0000000..e006b9a--- /dev/null+++ b/website/versioned_docs/version-0.5/api/cubepi-checkpointer.mdx@@ -0,0 +1,208 @@+---+id: cubepi-checkpointer+title: cubepi.checkpointer+sidebar_position: 3+hide_table_of_contents: false+---++# `cubepi.checkpointer`++### Checkpointer {#checkpointer}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/base.py#L13)+++**Methods**++#### `load` {#checkpointer-load}++```python+load(thread_id: str) -> CheckpointData | None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/base.py#L15)+++#### `append` {#checkpointer-append}++```python+append(thread_id: str, messages: list[Any]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/base.py#L16)+++#### `save_extra` {#checkpointer-save-extra}++```python+save_extra(thread_id: str, extra: dict[str, Any]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/base.py#L17)++++### CheckpointData {#checkpointdata}++_class_++```python+CheckpointData(self, messages: list[Any] = list(), extra: dict[str, Any] = dict())+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/base.py#L7)+++**Attributes**++- `messages`: `list[Any]`+- `extra`: `dict[str, Any]`+++### MemoryCheckpointer {#memorycheckpointer}++_class_++```python+MemoryCheckpointer(self)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/memory.py#L8)+++**Methods**++#### `load` {#memorycheckpointer-load}++```python+load(thread_id: str) -> CheckpointData | None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/memory.py#L12)+++#### `append` {#memorycheckpointer-append}++```python+append(thread_id: str, messages: list[Any]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/memory.py#L15)+++#### `save_extra` {#memorycheckpointer-save-extra}++```python+save_extra(thread_id: str, extra: dict[str, Any]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/memory.py#L20)++++### PostgresCheckpointer {#postgrescheckpointer}++_class_++```python+PostgresCheckpointer(self, dsn: str, *, min_pool_size: int = 1, max_pool_size: int = 10)+```++Checkpointer backed by PostgreSQL.+++**Usage**++```python+cp = PostgresCheckpointer(dsn="postgresql://...")+async with cp:+ await cp.append(thread_id, [msg1, msg2])+ data = await cp.load(thread_id)+ await cp.save_extra(thread_id, {"k": "v"})+```++Raises CubepiSchemaUninitialized / CubepiSchemaMismatch at __aenter__+if the DB schema isn't compatible with this cubepi version.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/postgres/checkpointer.py#L46)+++**Methods**++#### `load` {#postgrescheckpointer-load}++```python+load(thread_id: str) -> CheckpointData | None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/postgres/checkpointer.py#L110)+++#### `append` {#postgrescheckpointer-append}++```python+append(thread_id: str, messages: list[Message]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/postgres/checkpointer.py#L152)+++#### `save_extra` {#postgrescheckpointer-save-extra}++```python+save_extra(thread_id: str, extra: dict[str, Any]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/postgres/checkpointer.py#L200)++++### SQLiteCheckpointer {#sqlitecheckpointer}++_class_++```python+SQLiteCheckpointer(self, db_path: str)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/sqlite.py#L12)+++**Methods**++#### `load` {#sqlitecheckpointer-load}++```python+load(thread_id: str) -> CheckpointData | None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/sqlite.py#L42)+++#### `append` {#sqlitecheckpointer-append}++```python+append(thread_id: str, messages: list[Any]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/sqlite.py#L68)+++#### `save_extra` {#sqlitecheckpointer-save-extra}++```python+save_extra(thread_id: str, extra: dict[str, Any]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/checkpointer/sqlite.py#L79)+++++<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->\ No newline at end of filediff --git a/website/versioned_docs/version-0.5/api/cubepi-mcp.mdx b/website/versioned_docs/version-0.5/api/cubepi-mcp.mdxnew file mode 100644index 0000000..ccda701--- /dev/null+++ b/website/versioned_docs/version-0.5/api/cubepi-mcp.mdx@@ -0,0 +1,182 @@+---+id: cubepi-mcp+title: cubepi.mcp+sidebar_position: 5+hide_table_of_contents: false+---++# `cubepi.mcp`++### load_mcp_tools_http {#load-mcp-tools-http}++_function_++```python+load_mcp_tools_http(server_url: str, *, headers: dict[str, str] | None = None, timeout: float = 30.0, transport: Transport = 'sse') -> MCPDiscoveryResult+```++Connect to an HTTP MCP server and discover its tools + metadata.++Returns a [`MCPDiscoveryResult`](./cubepi-mcp#mcpdiscoveryresult) carrying:++- `tools` — executable `AgentTool` per `tools/list` entry.+- `server` — `MCPServerInfo` (name, version, websiteUrl, icons)+ captured from the `initialize` handshake's `serverInfo`. Sourced+ from MCP spec rev 2025-11-25's `Implementation` shape.+- `tool_infos` — per-tool display metadata (currently `icons`)+ captured from each `tools/list` entry, separated from+ `AgentTool` so callers can render visuals without coupling+ core types to display concerns.++`transport` picks the wire format:++- `"sse"` (default) — legacy SSE-over-GET transport (`sse_client`).+- `"streamable_http"` — newer SSE-over-POST transport+ (`streamablehttp_client`).++Each returned tool's execute method invokes `tools/call` against a+fresh session — v1 simplicity, no pooling. The session is opened over+the same transport that was used for discovery, so the call path+cannot accidentally regress to the wrong wire format.++The transport's own timeout bounds the connection; we additionally+wrap initialize/list/call awaits in `asyncio.wait_for` so a server+that accepts the connection but stalls on protocol messages still+aborts.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/mcp/http_loader.py#L112)+++### load_mcp_tools_stdio {#load-mcp-tools-stdio}++_function_++```python+load_mcp_tools_stdio(command: str, args: list[str], *, env: dict[str, str] | None = None, cwd: str | None = None, timeout: float = 30.0) -> MCPDiscoveryResult+```++Spawn a stdio MCP server subprocess and discover its tools + metadata.++Returns a [`MCPDiscoveryResult`](./cubepi-mcp#mcpdiscoveryresult) with the same shape as+[`load_mcp_tools_http`](./cubepi-mcp#load-mcp-tools-http): `tools` (executable AgentTools),+`server` (Implementation info from `initialize`), and `tool_infos`+(per-tool display metadata such as icons).++Each returned tool's execute opens a fresh subprocess per call (v1+simplicity, no process pooling).+++**Args**++- `command` — executable to run (e.g. "npx" or sys.executable)+- `args` — argv for the server process+- `env` — environment variables (passed to subprocess)+- `cwd` — working directory for the subprocess+- `timeout` — per-call wall-clock timeout for initialize/list/call awaits.+ A hung server raises asyncio.TimeoutError instead of blocking forever.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/mcp/stdio_loader.py#L16)+++### MCPDiscoveryResult {#mcpdiscoveryresult}++_class_++```python+MCPDiscoveryResult(self, tools: list[AgentTool], server: MCPServerInfo | None = None, tool_infos: list[MCPToolInfo] = list())+```++Outcome of an MCP discovery handshake.++`tools` is the executable surface (one `AgentTool` per tool the+server exposes). `server` and `tool_infos` are display metadata+captured from the same handshake; both follow MCP spec rev 2025-11-25.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/mcp/types.py#L56)+++**Attributes**++- `tools`: `list[AgentTool]`+- `server`: `MCPServerInfo | None`+- `tool_infos`: `list[MCPToolInfo]`+++### MCPIcon {#mcpicon}++_class_++```python+MCPIcon(self, src: str, mime_type: str | None = None, sizes: tuple[str, ...] | None = None, theme: str | None = None)+```++One icon entry from an MCP `Icon` block.++Mirrors `mcp.types.Icon` with snake_case fields. `src` is either an+HTTP/HTTPS URL or a `data:` URI; `sizes` is a tuple of strings such+as `("48x48", "96x96")`. `theme` is `"light"` or `"dark"` when+the server supplies separate variants — the spec lets clients pick the+variant matching the current UI theme and fall back to the first entry+otherwise.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/mcp/types.py#L10)+++**Attributes**++- `src`: `str`+- `mime_type`: `str | None`+- `sizes`: `tuple[str, ...] | None`+- `theme`: `str | None`+++### MCPServerInfo {#mcpserverinfo}++_class_++```python+MCPServerInfo(self, name: str, version: str, website_url: str | None = None, icons: tuple[MCPIcon, ...] = ())+```++Server-level metadata captured from the `initialize` handshake.++Sourced from `InitializeResult.serverInfo` (an `Implementation`):+the server's display name + version, an optional website URL, and an+optional list of icons that clients can render as the server's logo.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/mcp/types.py#L28)+++**Attributes**++- `name`: `str`+- `version`: `str`+- `website_url`: `str | None`+- `icons`: `tuple[MCPIcon, ...]`+++### MCPToolInfo {#mcptoolinfo}++_class_++```python+MCPToolInfo(self, name: str, icons: tuple[MCPIcon, ...] = ())+```++Per-tool display metadata captured from `tools/list`.++Carries `Tool.icons` separately from the executable `AgentTool` so+consumers can render tool-specific icons without coupling cubepi's+core `AgentTool` type to MCP display concerns.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/mcp/types.py#L43)+++**Attributes**++- `name`: `str`+- `icons`: `tuple[MCPIcon, ...]`++++<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->\ No newline at end of filediff --git a/website/versioned_docs/version-0.5/api/cubepi-middleware.mdx b/website/versioned_docs/version-0.5/api/cubepi-middleware.mdxnew file mode 100644index 0000000..4897138--- /dev/null+++ b/website/versioned_docs/version-0.5/api/cubepi-middleware.mdx@@ -0,0 +1,121 @@+---+id: cubepi-middleware+title: cubepi.middleware+sidebar_position: 4+hide_table_of_contents: false+---++# `cubepi.middleware`++### Middleware {#middleware}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L23)+++**Methods**++#### `transform_context` {#middleware-transform-context}++```python+transform_context(messages: list, *, signal = None) -> list+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L24)+++#### `convert_to_llm` {#middleware-convert-to-llm}++```python+convert_to_llm(messages: list) -> list+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L27)+++#### `before_tool_call` {#middleware-before-tool-call}++```python+before_tool_call(ctx: Any, *, signal = None) -> Any+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L30)+++#### `after_tool_call` {#middleware-after-tool-call}++```python+after_tool_call(ctx: Any, *, signal = None) -> Any+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L33)+++#### `transform_system_prompt` {#middleware-transform-system-prompt}++```python+transform_system_prompt(system_prompt: str, *, signal = None) -> str+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L36)+++#### `should_stop_after_turn` {#middleware-should-stop-after-turn}++```python+should_stop_after_turn(ctx: Any) -> bool+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L44)+++#### `after_model_response` {#middleware-after-model-response}++```python+after_model_response(response: AssistantMessage, ctx: Any, *, signal: Any = None) -> TurnAction | None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L47)++++### TurnAction {#turnaction}++_class_++```python+TurnAction(self, response: AssistantMessage | None = None, inject_messages: list[Message] = list(), decision: Literal['natural', 'stop', 'loop_to_model'] = 'natural')+```++Directs the agent loop's next step after a model response.++Composition (chain): each middleware sees previous middleware's+TurnAction. Last middleware's value wins for response and decision.+inject_messages concatenates across the chain.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L9)+++**Attributes**++- `response`: `AssistantMessage | None`+- `inject_messages`: `list[Message]`+- `decision`: `Literal['natural', 'stop', 'loop_to_model']`+++### compose_middleware {#compose-middleware}++_function_++```python+compose_middleware(middlewares: list[Middleware]) -> dict[str, Callable]+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/middleware/base.py#L63)++++<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->\ No newline at end of filediff --git a/website/versioned_docs/version-0.5/api/cubepi-providers.mdx b/website/versioned_docs/version-0.5/api/cubepi-providers.mdxnew file mode 100644index 0000000..0319317--- /dev/null+++ b/website/versioned_docs/version-0.5/api/cubepi-providers.mdx@@ -0,0 +1,739 @@+---+id: cubepi-providers+title: cubepi.providers+sidebar_position: 2+hide_table_of_contents: false+---++# `cubepi.providers`++### AssistantMessage {#assistantmessage}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L124)+++**Attributes**++- `role`: `Literal['assistant']`+- `content`: `list[Content | ThinkingContent | ToolCall]`+- `stop_reason`: `str`+- `error_message`: `str | None`+- `usage`: `Usage | None`+- `timestamp`: `float | None`+- `provider_id`: `str`+- `model_id`: `str`+- `response_id`: `str | None`+- `metadata`: `dict[str, Any]`+++### BaseProvider {#baseprovider}++_class_++```python+BaseProvider(self)+```++Concrete base class for built-in cubepi providers.++Built-in providers (Anthropic, OpenAI, OpenAI Responses, Faux) inherit+from this class to gain the persistent listener registry used by+`cubepi.tracing` and other observers. User-defined providers may also+inherit from `BaseProvider` to opt in, or remain duck-typed against+the `Provider` Protocol (which only requires `stream()`).++Concrete subclasses must implement `stream()` and call+`_fire_listeners` at three points: after the request payload is+finalized, for each `StreamEvent` pushed onto the stream, and exactly+once in a `finally` block after the stream terminates.++Per-call mutators (`StreamOptions.on_payload`,+`StreamOptions.on_response`) retain their existing single-slot+semantics and fire independently of the persistent listener registry+below.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L581)+++**Methods**++#### `stream` {#baseprovider-stream}++```python+stream(model: Model, messages: list[Message], *, system_prompt: str = '', tools: list[ToolDefinition] | None = None, options: StreamOptions | None = None) -> MessageStream+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L606)+++#### `subscribe_request` {#baseprovider-subscribe-request}++```python+subscribe_request(cb: OnRequestCallback) -> Callable[[], None]+```++Register a persistent observer for request payloads.++Returns a detach callable that removes this specific subscription.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L625)+++#### `subscribe_chunk` {#baseprovider-subscribe-chunk}++```python+subscribe_chunk(cb: OnChunkCallback) -> Callable[[], None]+```++Register a persistent observer for stream chunks.++Returns a detach callable.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L633)+++#### `subscribe_response` {#baseprovider-subscribe-response}++```python+subscribe_response(cb: OnResponseBodyCallback) -> Callable[[], None]+```++Register a persistent observer for assembled responses.++Returns a detach callable.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L641)++++### Content {#content}++_attribute_++```python+Content = TextContent | ImageContent+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L107)+++### ImageContent {#imagecontent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L96)+++**Attributes**++- `type`: `Literal['image']`+- `source`: `str`+- `media_type`: `str`+++### Message {#message}++_attribute_++```python+Message = UserMessage | AssistantMessage | ToolResultMessage+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L148)+++### MessageStream {#messagestream}++_class_++```python+MessageStream(self)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L209)+++**Methods**++#### `attach_task` {#messagestream-attach-task}++```python+attach_task(task: asyncio.Task) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L217)+++#### `push` {#messagestream-push}++```python+push(event: StreamEvent) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L229)+++#### `set_result` {#messagestream-set-result}++```python+set_result(message: AssistantMessage) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L234)+++#### `result` {#messagestream-result}++```python+result() -> AssistantMessage+```++Return the final assistant message.++Blocks not just on the result future, but also on the producer+task's completion — the producer's `finally` block runs+`_fire_response_listeners` (after `set_result`), so+without waiting for the task, callers under `asyncio.run`+teardown could exit before async response listeners have run.+Producer exceptions are NOT re-raised here; they were already+surfaced via the result future or the stream's error events.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L247)++++### Model {#model}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L79)+++**Attributes**++- `id`: `str`+- `provider`: `str`+- `api`: `str`+- `reasoning`: `bool`+- `context_window`: `int`+- `max_tokens`: `int`+- `temperature`: `float`+- `cost`: `ModelCost | None`+- `thinking_level_map`: `dict[str, str | None] | None`+++### ModelCost {#modelcost}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L65)+++**Attributes**++- `input`: `float`+- `output`: `float`+- `cache_read`: `float`+- `cache_write`: `float`+++### OnChunkCallback {#onchunkcallback}++_attribute_++```python+OnChunkCallback = Callable[['StreamEvent', Model], Awaitable[None] | None]+```++Persistent observer. Fires for every StreamEvent pushed onto the stream+(start, text_delta, thinking_delta, toolcall_delta, done, error, ...).+Heavy listeners should early-return on irrelevant event types — this hook+fires hot. Return value is ignored.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L301)+++### OnPayloadCallback {#onpayloadcallback}++_attribute_++```python+OnPayloadCallback = Callable[[dict, Model], Awaitable[dict | None] | dict | None]+```++Optional callback for inspecting/replacing provider payloads before sending.+Return a dict to replace the payload, or None to keep unchanged.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L288)+++### OnRequestCallback {#onrequestcallback}++_attribute_++```python+OnRequestCallback = Callable[[dict, Model], Awaitable[None] | None]+```++Persistent observer. Fires just before HTTP send, after any per-call+`StreamOptions.on_payload` mutation has been applied. Receives the final+wire payload dict and the Model. Return value is ignored.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L296)+++### OnResponseBodyCallback {#onresponsebodycallback}++_attribute_++```python+OnResponseBodyCallback = Callable[[dict | None, Model, BaseException | None], Awaitable[None] | None]+```++Persistent observer. Fires exactly once per `stream()` call, in a+finally block, after the stream terminates.++- body: assembled provider response as a dict (same shape a non-streaming+ call to the provider would have returned), or None if the stream failed+ before a response could be assembled.+- exc: the exception that ended the stream (including+ `asyncio.CancelledError`), or None on normal completion.+Return value is ignored.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L307)+++### OnResponseCallback {#onresponsecallback}++_attribute_++```python+OnResponseCallback = Callable[['ProviderResponse', Model], Awaitable[None] | None]+```++Optional callback invoked after an HTTP response is received.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L292)+++### Provider {#provider}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L568)+++**Methods**++#### `stream` {#provider-stream}++```python+stream(model: Model, messages: list[Message], *, system_prompt: str = '', tools: list[ToolDefinition] | None = None, options: StreamOptions | None = None) -> MessageStream+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L570)++++### ProviderResponse {#providerresponse}++_class_++```python+ProviderResponse(self, status: int, headers: dict[str, str] = dict())+```++HTTP response metadata exposed to on_response callbacks.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L280)+++**Attributes**++- `status`: `int`+- `headers`: `dict[str, str]`+++### StreamEvent {#streamevent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L157)+++**Attributes**++- `type`: `Literal['start', 'text_start', 'text_delta', 'text_end', 'thinking_start', 'thinking_delta', 'thinking_end', 'toolcall_start', 'toolcall_delta', 'toolcall_end', 'done', 'error']`+- `content_index`: `int | None`+- `delta`: `str | None`+- `partial`: `AssistantMessage | None`+- `error_message`: `str | None`+++### StreamOptions {#streamoptions}++_class_++Options bag for Provider.stream(), transparent to the agent loop.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L529)+++**Attributes**++- `model_config`+- `thinking`: `ThinkingLevel`+- `thinking_budgets`: `ThinkingBudgets | None`+- `signal`: `asyncio.Event | None`+- `on_payload`: `OnPayloadCallback | None`+- `on_response`: `OnResponseCallback | None`+++### TextContent {#textcontent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L91)+++**Attributes**++- `type`: `Literal['text']`+- `text`: `str`+++### ThinkingBudgets {#thinkingbudgets}++_class_++Token budgets for each thinking level.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L22)+++**Attributes**++- `minimal`: `int`+- `low`: `int`+- `medium`: `int`+- `high`: `int`+++### ThinkingContent {#thinkingcontent}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L102)+++**Attributes**++- `type`: `Literal['thinking']`+- `thinking`: `str`+++### ThinkingLevel {#thinkinglevel}++_attribute_++```python+ThinkingLevel = Literal['off', 'minimal', 'low', 'medium', 'high', 'xhigh']+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L19)+++### ToolCall {#toolcall}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L110)+++**Attributes**++- `type`: `Literal['tool_call']`+- `id`: `str`+- `name`: `str`+- `arguments`: `dict[str, Any]`+++### ToolDefinition {#tooldefinition}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L151)+++**Attributes**++- `name`: `str`+- `description`: `str`+- `parameters`: `dict[str, Any]`+++### ToolResultMessage {#toolresultmessage}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L137)+++**Attributes**++- `role`: `Literal['tool_result']`+- `tool_call_id`: `str`+- `tool_name`: `str`+- `content`: `list[Content]`+- `details`: `Any`+- `is_error`: `bool`+- `timestamp`: `float | None`+- `metadata`: `dict[str, Any]`+++### Usage {#usage}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L72)+++**Attributes**++- `input_tokens`: `int`+- `output_tokens`: `int`+- `cache_read_tokens`: `int`+- `cache_write_tokens`: `int`+++### UserMessage {#usermessage}++_class_+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L117)+++**Attributes**++- `role`: `Literal['user']`+- `content`: `list[Content]`+- `timestamp`: `float | None`+- `metadata`: `dict[str, Any]`+++### adjust_max_tokens_for_thinking {#adjust-max-tokens-for-thinking}++_function_++```python+adjust_max_tokens_for_thinking(base_max_tokens: int, model_max_tokens: int, reasoning_level: ThinkingLevel, custom_budgets: ThinkingBudgets | None = None) -> tuple[int, int]+```++Adjust max_tokens to reserve space for a thinking budget.++Given a base max_tokens (the desired output capacity), increases it to+accommodate the thinking budget while respecting the model's hard cap.+If the model cap is too small to fit both, the thinking budget is reduced+to leave at least `min_output_tokens` (1024) for output.+++**Returns**++- A `(max_tokens, thinking_budget)` tuple.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/base.py#L31)+++### FauxProvider {#fauxprovider}++_class_++```python+FauxProvider(self, *, tokens_per_second: float | None = None, token_size_min: int = 3, token_size_max: int = 5)+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L155)+++**Attributes**++- `call_count`+- `pending_response_count`: `int`+- `prompt_cache`: `dict[str, str]` — Read-only access to the prompt cache for test assertions.+++**Methods**++#### `set_responses` {#fauxprovider-set-responses}++```python+set_responses(responses: list[FauxResponseStep]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L213)+++#### `append_responses` {#fauxprovider-append-responses}++```python+append_responses(responses: list[FauxResponseStep]) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L216)+++#### `clear_prompt_cache` {#fauxprovider-clear-prompt-cache}++```python+clear_prompt_cache() -> None+```++Clear the prompt cache, useful between test scenarios.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L223)+++#### `stream` {#fauxprovider-stream}++```python+stream(model: Model, messages: list[Message], *, system_prompt: str = '', tools: list[ToolDefinition] | None = None, options: StreamOptions | None = None) -> MessageStream+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L265)++++### faux_assistant_message {#faux-assistant-message}++_function_++```python+faux_assistant_message(content: str | FauxContentBlock | list[FauxContentBlock], *, stop_reason: str = 'stop', error_message: str | None = None) -> AssistantMessage+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L63)+++### faux_text {#faux-text}++_function_++```python+faux_text(text: str) -> TextContent+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L46)+++### faux_thinking {#faux-thinking}++_function_++```python+faux_thinking(thinking: str) -> ThinkingContent+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L50)+++### faux_tool_call {#faux-tool-call}++_function_++```python+faux_tool_call(name: str, arguments: dict[str, Any], *, id: str | None = None) -> ToolCall+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/faux.py#L54)+++### THINKING_LEVELS {#thinking-levels}++_attribute_++```python+THINKING_LEVELS: list[ThinkingLevel] = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh']+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/models.py#L12)+++### clamp_thinking_level {#clamp-thinking-level}++_function_++```python+clamp_thinking_level(model: Model, level: ThinkingLevel) -> ThinkingLevel+```++Clamp *level* to the nearest supported level for *model*.++If *level* is already supported, return it unchanged. Otherwise search+upward first (higher intensity), then downward, through the ordered level+list to find the closest available level.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/models.py#L54)+++### get_supported_thinking_levels {#get-supported-thinking-levels}++_function_++```python+get_supported_thinking_levels(model: Model) -> list[ThinkingLevel]+```++Return the thinking levels supported by *model*.++* Non-reasoning models only support `["off"]`.+* For reasoning models, levels are filtered through the model's+ `thinking_level_map`. A level mapped to `None` is unsupported.+ `"xhigh"` is only included when it has an explicit (non-None) mapping.+ All other levels are included by default when the map omits them.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/models.py#L22)+++### models_are_equal {#models-are-equal}++_function_++```python+models_are_equal(a: Model | None, b: Model | None) -> bool+```++Return `True` if *a* and *b* refer to the same model.++Comparison is by `id` and `provider`. Returns `False` when either+argument is `None`.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/providers/models.py#L87)++++<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->\ No newline at end of filediff --git a/website/versioned_docs/version-0.5/api/cubepi-tracing.mdx b/website/versioned_docs/version-0.5/api/cubepi-tracing.mdxnew file mode 100644index 0000000..5a38c4f--- /dev/null+++ b/website/versioned_docs/version-0.5/api/cubepi-tracing.mdx@@ -0,0 +1,394 @@+---+id: cubepi-tracing+title: cubepi.tracing+sidebar_position: 6+hide_table_of_contents: false+---++# `cubepi.tracing`++### tracing_context {#tracing-context}++_function_++```python+tracing_context(*, tags: list[str] | tuple[str, ...] | None = None, metadata: dict[str, Any] | None = None) -> Iterator[None]+```++Scope tags / metadata onto agent runs started inside this block.++The recorder reads these contextvars on `AgentStartEvent` and+stamps them on the `invoke_agent` span as:++- `cubepi.tags` — tuple of strings (OTel attribute type)+- one attribute per metadata key, namespaced under+ `cubepi.metadata.*` (e.g. `metadata=\{"user_id": "u-42"\}` →+ `cubepi.metadata.user_id = "u-42"`). The dedicated+ sub-namespace keeps recorder-owned schema keys+ (`cubepi.run_id`, `cubepi.turn.index`, …) safe from+ caller-supplied collisions.++The contextvar nature means this works for concurrent agents:+each asyncio task tree gets its own value. Nested blocks merge+additively (tags concatenate; metadata is union with inner+keys winning).+++**Args**++- `tags` — Tags to apply to runs started in this scope. Stored as+ a tuple on the span so it round-trips through OTel's+ attribute serializer.+- `metadata` — Per-run key/value pairs. Values must be types that+ OTel attributes accept (str, bool, int, float, or a+ tuple/list of those); other shapes will be silently+ dropped by the recorder.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/context.py#L51)+++### JsonlSpanExporter {#jsonlspanexporter}++_class_++```python+JsonlSpanExporter(self, directory: str | os.PathLike[str] = './cubepi-traces')+```++Write each ReadableSpan as one JSON line.++Files: `<directory>/<YYYY-MM-DD>/<run_id>.jsonl`. The date used for+the subdirectory is the span's start time (UTC). The `run_id` comes+from the `cubepi.run_id` attribute set by the cubepi Recorder;+spans without that attribute fall back to `"unknown-run"`.++Permissions: files are created mode `0o600` (user-only).++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/exporters/jsonl.py#L23)+++**Methods**++#### `export` {#jsonlspanexporter-export}++```python+export(spans: Sequence[ReadableSpan]) -> SpanExportResult+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/exporters/jsonl.py#L41)+++#### `shutdown` {#jsonlspanexporter-shutdown}++```python+shutdown() -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/exporters/jsonl.py#L68)+++#### `force_flush` {#jsonlspanexporter-force-flush}++```python+force_flush(timeout_millis: int = 30000) -> bool+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/exporters/jsonl.py#L71)++++### Meter {#meter}++_class_++```python+Meter(self, *, resource: Resource | None = None, exporters: list[MetricExporter] | None = None, export_interval_millis: int = 60000)+```++Emit OTel GenAI histograms alongside the cubepi Tracer.++Construct with a list of `MetricExporter` instances (e.g. the+OTLP metric exporter); call `attach` to start emitting.++Example:++```python+from cubepi.tracing import Tracer, Meter+from opentelemetry.exporter.otlp.proto.http.metric_exporter import (+ OTLPMetricExporter,+)++tracer = Tracer(service_name="my-bot", exporters=[...])+meter = Meter(+ resource=tracer.resource,+ exporters=[OTLPMetricExporter(endpoint="http://collector:4318/v1/metrics")],+)+tracer.attach(agent)+meter.attach(agent)+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/meter.py#L71)+++**Attributes**++- `otel_meter`: `Any` — The underlying `opentelemetry.metrics.Meter` — exposed so callers can register their own instruments.+++**Methods**++#### `attach` {#meter-attach}++```python+attach(agent: 'Agent') -> Callable[[], None]+```++Subscribe to `agent` and start emitting metrics.++Each `attach()` call gets its own `_MeterState` so+multiple concurrent agents attached to the same Meter don't+clobber each other's open-ns timestamps and attribute dicts+(codex overall-review MAJOR — previously all state lived on+the Meter instance, so a second agent's `provider_request`+overwrote the first agent's `_chat_open_ns` / `_chat_attrs`+before its response landed).++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/meter.py#L144)+++#### `force_flush` {#meter-force-flush}++```python+force_flush(timeout_seconds: float = 30.0) -> bool+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/meter.py#L194)+++#### `shutdown` {#meter-shutdown}++```python+shutdown(timeout_seconds: float = 30.0) -> None+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/meter.py#L197)+++#### `attached` {#meter-attached}++```python+attached(agent: 'Agent') -> AsyncIterator['Meter']+```++RAII wrapper around `attach`.++`async with` enters by attaching the per-attach state, exits+by calling the detach callable returned from `attach`.+Mirrors [`Tracer.attached`](./cubepi-tracing#tracer-attached) — use both for the cleanest+end-to-end shutdown:++```python+async with (+ Tracer(...) as tracer,+ Meter(resource=tracer.resource, ...) as meter,+ tracer.attached(agent),+ meter.attached(agent),+):+ await agent.prompt("...")+# auto: detach both + shutdown both+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/meter.py#L204)++++### SCHEMA_URL {#schema-url}++_attribute_++```python+SCHEMA_URL = 'https://opentelemetry.io/schemas/1.41.0'+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/schema.py#L13)+++### Tracer {#tracer}++_class_++```python+Tracer(self, *, service_name: str | None = None, service_version: str | None = None, service_namespace: str | None = None, service_instance_id: str | None = None, deployment_environment: str | None = None, agent_name: str | None = None, agent_id: str | None = None, agent_description: str | None = None, agent_version: str | None = None, exporters: list[SpanExporter] | None = None, record_content: bool = False, redact: 'Callable[[str, Any], Any] | None' = None, resource: Resource | None = None, atexit_flush: bool = True, atexit_flush_timeout_seconds: float = 5.0)+```++Attaches OTel-compatible tracing to a cubepi [`Agent`](./cubepi-agent#agent).++Construct once per process (or per service). Each `attach(agent)`+call wires the cubepi recorder to the agent's event stream and+provider listener registry; the returned callable detaches.++**Example**++```python+from cubepi.tracing import Tracer+from cubepi.tracing.exporters import JsonlSpanExporter++tracer = Tracer(+ service_name="my-bot",+ agent_name="coding-agent",+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+)+detach = tracer.attach(agent)+try:+ ...+finally:+ detach()+ await tracer.shutdown()+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/tracer.py#L34)+++**Attributes**++- `resource`: `Resource`+- `otel_tracer`: `Any` — The underlying `opentelemetry.trace.Tracer` instance.+- `redact`: `'Callable[[str, Any], Any] | None'` — Optional `(key, value) -> value` filter applied at every `set_attribute` site for content attributes.+++**Methods**++#### `attach` {#tracer-attach}++```python+attach(agent: 'Agent') -> Callable[[], Any]+```++Wire the cubepi recorder to `agent`.++Returns a `detach()` callable. When invoked:++- Synchronously: unsubscribes every hook, closes any spans+ still open from a cancelled run, sweeps MCP tool-span+ registrations — observable on the next line.+- Schedules a flush on the running event loop and returns the+ resulting `asyncio.Task` so callers can `await detach()`+ to block until buffered spans have been exported. Outside+ an async context returns `None` — call+ `await tracer.shutdown()` separately to flush.++Either `await detach()` or `await tracer.shutdown()` (or+both) must be used in the caller's `finally` block; the+synchronous `detach()` alone does not guarantee that ended+spans have left `BatchSpanProcessor` (codex overall-review+MAJOR).++Also registers this Tracer's private TracerProvider with+`cubepi.mcp._tracing` so MCP CLIENT spans flow through+the same exporters — without this step, the MCP module falls+back to the OTel global default (a no-op provider when the+caller didn't separately call `trace.set_tracer_provider`).+The detach callable unregisters.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/tracer.py#L148)+++#### `force_flush` {#tracer-force-flush}++```python+force_flush(timeout_seconds: float = 30.0) -> bool+```++Block until all currently buffered spans are exported.++Returns `False` on timeout.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/tracer.py#L226)+++#### `shutdown` {#tracer-shutdown}++```python+shutdown(timeout_seconds: float = 30.0) -> None+```++Flush and close all exporters. Tracer is unusable after this.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/tracer.py#L234)+++#### `attached` {#tracer-attached}++```python+attached(agent: 'Agent') -> AsyncIterator['Tracer']+```++RAII wrapper around `attach`.++`async with` enters by attaching the recorder, exits by+running detach and (in an async context) awaiting its returned+flush `Task`. Equivalent to:++```python+detach = tracer.attach(agent)+try:+ ...+finally:+ result = detach()+ if result is not None: # async context: it's a Task+ await result+```++Use this instead of the bare `attach` / `finally: detach()`+pattern when you want the cleanup tied to a single ``async+with`` block. Combines with [`Tracer`](./cubepi-tracing#tracer)'s own context+manager:++```python+async with Tracer(...) as tracer, tracer.attached(agent):+ await agent.prompt("...")+# auto: detach (closes cancelled spans) + shutdown (flush + close)+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/tracer.py#L275)++++### trace {#trace}++_function_++```python+trace(tracer: 'Tracer | None', agent: 'Agent') -> AsyncIterator[None]+```++Best-effort tracing scope for one agent run.++Attaches `tracer` to `agent` on enter and detaches + flushes its+buffered spans on exit. Every tracing fault — a failed attach, detach, or+flush — is logged and swallowed, so tracing can never break or fail the+work inside the `async with` block. Passing `tracer=None` makes the+block a no-op, which lets callers gate tracing on config without branching+at the call site.++This does **not** shut the tracer down: the tracer is reusable across runs,+so build it once (e.g. per process) and call `await tracer.shutdown()`+when the owning process stops.++Unlike [`Tracer.attached`](./cubepi-tracing#tracer-attached), which surfaces flush failures to the caller,+this helper swallows them — use it when tracing is auxiliary to the work and+must never affect its outcome.++**Example**++```python+async with trace(tracer, agent):+ await agent.prompt("...")+```++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/tracing/tracer.py#L389)++++<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->\ No newline at end of filediff --git a/website/versioned_docs/version-0.5/api/cubepi-utils.mdx b/website/versioned_docs/version-0.5/api/cubepi-utils.mdxnew file mode 100644index 0000000..88abcef--- /dev/null+++ b/website/versioned_docs/version-0.5/api/cubepi-utils.mdx@@ -0,0 +1,67 @@+---+id: cubepi-utils+title: cubepi.utils+sidebar_position: 7+hide_table_of_contents: false+---++# `cubepi.utils`++### emit_event {#emit-event}++_function_++```python+emit_event(emit_fn: Callable, event: object) -> None+```+++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/utils/emit.py#L7)+++### parse_streaming_json {#parse-streaming-json}++_function_++```python+parse_streaming_json(text: str | None) -> dict+```++Parse potentially incomplete or malformed JSON from streaming.++Uses a 3-tier fallback:+ 1. `json.loads(text)`+ 2. `json.loads(repair_json(text))`+ 3. Partial-parse: repair + close open braces/brackets/strings+ 4. `\{\}` as last resort++Always returns a *dict* (or at minimum `\{\}`) so callers never need+to handle parse failures.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/utils/json_parse.py#L169)+++### repair_json {#repair-json}++_function_++```python+repair_json(text: str) -> str+```++Repair malformed JSON string literals.++Operates character-by-character, tracking whether the cursor is inside a+JSON string value. Inside strings it:++* Escapes raw control characters (0x00-0x1F) that are not already+ escaped (`\t`, `\n`, `\r` are kept when already escaped).+* Doubles a backslash before an invalid escape character+ (e.g. `\x` becomes `\\x`), making the output parseable.+* Handles truncated backslash at end-of-string.++[source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/cubepi/utils/json_parse.py#L39)++++<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->\ No newline at end of filediff --git a/website/versioned_docs/version-0.5/api/index.mdx b/website/versioned_docs/version-0.5/api/index.mdxnew file mode 100644index 0000000..3da8881--- /dev/null+++ b/website/versioned_docs/version-0.5/api/index.mdx@@ -0,0 +1,17 @@+---+title: API Reference+---++# API Reference++Auto-generated from CubePi's public modules.++- `cubepi.agent`+- `cubepi.providers`+- `cubepi.checkpointer`+- `cubepi.middleware`+- `cubepi.mcp`+- `cubepi.tracing`+- `cubepi.utils`++The module pages above are generated at build time from docstrings and are not editable by hand.diff --git a/website/versioned_docs/version-0.5/getting-started/core-concepts.md b/website/versioned_docs/version-0.5/getting-started/core-concepts.mdnew file mode 100644index 0000000..c4811a6--- /dev/null+++ b/website/versioned_docs/version-0.5/getting-started/core-concepts.md@@ -0,0 +1,205 @@+---+title: Core Concepts+---++# Core Concepts++Six concepts cover everything CubePi does. Read this page once, then+the rest of the docs become a lookup table.++## Agent++`Agent` is the stateful façade: you construct it with a provider, a+model, optional tools, and optional middleware/checkpointer. You drive+it through three methods:++- `await agent.prompt(message)` — start a new turn from a user message.+- `await agent.resume()` — continue from the last persisted message+ (used with a checkpointer).+- `agent.steer(message)` / `agent.follow_up(message)` — queue a+ message mid-flight or after the current run.++The agent owns an `AgentState` (system prompt, tools, model, message+history, pending tool calls, streaming flag) and a list of subscribers:++```python+unsubscribe = agent.subscribe(my_listener)+# ...+unsubscribe()+```++Subscribers receive every `AgentEvent` the loop emits. They can be+sync or async.++## Tool++An `AgentTool` is a name + description + Pydantic parameter model ++async `execute` function:++```python+from pydantic import BaseModel+from cubepi import AgentTool, AgentToolResult, TextContent++class SearchParams(BaseModel):+ query: str+ limit: int = 10++async def execute(tool_call_id, params: SearchParams, *, signal=None, on_update=None):+ # do work; respect `signal` if you can be aborted+ return AgentToolResult(content=[TextContent(text=f"…")])++search = AgentTool(+ name="search",+ description="Search the corpus",+ parameters=SearchParams,+ execute=execute,+)+```++The Pydantic schema is auto-converted to JSON Schema and passed to the+model. Arg parsing, error wrapping, and parallel execution are+handled by the framework. See [Tool Use](../guides/agents/tool-use)+for `execution_mode`, `on_update` (incremental progress), and+`terminate` (end the turn from a tool).++## Provider++A `Provider` is anything matching this Protocol:++```python+class Provider(Protocol):+ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ options: StreamOptions | None = None,+ ) -> MessageStream: ...+```++It returns a `MessageStream` — a single async iterator that yields+`StreamEvent`s and exposes the final `AssistantMessage` via `await+stream.result()`. Built-in providers:++- `AnthropicProvider` — Claude (Messages API, with thinking, caching,+ tool use).+- `OpenAIProvider` — GPT family (Chat Completions API).+- `OpenAIResponsesProvider` — GPT family (Responses API, server-side+ state).+- `FauxProvider` — deterministic test double (no network).++Write your own by implementing one method. See [Providers / Custom](../guides/providers/custom).++## Stream and events++Streams and events are two layers:++- **Provider streams** — `MessageStream` yields *provider* events:+ `start`, `text_start`, `text_delta`, `text_end`, `thinking_*`,+ `toolcall_*`, `done`, `error`. This is the raw token stream.+- **Agent events** — what `agent.subscribe(...)` receives. 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).++## Tracer (optional)++`Tracer` produces OpenTelemetry spans aligned with the+[GenAI Semantic Conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/),+so any OTLP backend (Jaeger, Tempo, Honeycomb, Datadog, AWS X-Ray, …)+can ingest agent runs without custom instrumentation. Install the+extra:++```bash+pip install "cubepi[tracing]" # OTel SDK+pip install "cubepi[tracing-otlp]" # + OTLP/HTTP exporter+```++then wrap your agent in an `async with`:++```python+from cubepi.tracing import Tracer+from cubepi.tracing.exporters import JsonlSpanExporter++async with (+ Tracer(+ service_name="my-bot",+ agent_name="assistant",+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ ) as tracer,+ tracer.attached(agent),+):+ await agent.prompt("…")+```++Each run emits an `invoke_agent` root span containing one+`cubepi.turn` per LLM round-trip, plus `chat` (CLIENT) and+`execute_tool` children. By default **no prompt content or model+output is recorded** — opt in with `Tracer(record_content=True)` and+a `redact` callback for PII. Pair with `Meter(...)` for token /+duration / TTFC histograms. Full guide:+[Tracing → Overview](../guides/tracing/overview).++## Putting it together++```+User code+ │+ ▼+┌──────────────────────────────────────────┐+│ Agent │+│ ├─ AgentState (messages, tools, …) │+│ ├─ Middleware ── compose_middleware() │+│ ├─ Checkpointer ── append on message_end │+│ └─ run_agent_loop ◀──── the actual loop │+│ │ │+│ ▼ │+│ Provider.stream() → MessageStream │+│ │ │+│ └─ events → emit → subscribers │+└──────────────────────────────────────────┘+```++That diagram is the whole framework. The rest of this site is just+the details.diff --git a/website/versioned_docs/version-0.5/getting-started/installation.md b/website/versioned_docs/version-0.5/getting-started/installation.mdnew file mode 100644index 0000000..72c8939--- /dev/null+++ b/website/versioned_docs/version-0.5/getting-started/installation.md@@ -0,0 +1,96 @@+---+title: Installation+---++# Installation++CubePi runs on **Python 3.11+**. The core has three runtime+dependencies: `pydantic`, `anthropic`, `openai`. Optional features+(SQLite, Postgres, MCP, OpenTelemetry tracing) are gated behind extras+so you only install what you use.++## With pip++```bash+pip install cubepi+```++Optional extras:++```bash+pip install "cubepi[sqlite]" # adds aiosqlite for SQLiteCheckpointer+pip install "cubepi[postgres]" # adds asyncpg + sqlalchemy + msgpack+pip install "cubepi[mcp]" # adds the MCP SDK for tool loaders+pip install "cubepi[tracing]" # adds opentelemetry-sdk for Tracer / Meter+pip install "cubepi[tracing-otlp]" # adds the OTLP/HTTP span exporter+pip install "cubepi[sqlite,mcp,tracing]" # combine+```++## With uv++[`uv`](https://github.com/astral-sh/uv) is significantly faster than+pip and is the recommended workflow:++```bash+uv add cubepi+uv add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+```++In an existing uv project, `uv sync` re-locks the environment after+edits to `pyproject.toml`.++## With Poetry++```bash+poetry add cubepi+poetry add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+```++## Verifying the install++```bash+python -c "import cubepi; print(cubepi.__doc__)"+# cubepi — Pythonic async-native agent framework.+```++If you see an `ImportError`, your interpreter is likely \< 3.11 — check+`python --version`.++## Configuring provider credentials++CubePi providers read credentials from constructor arguments. Most+deployments pull them from environment variables:++```python+import os+from cubepi.providers.anthropic import AnthropicProvider+from cubepi.providers.openai import OpenAIProvider++anthropic = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])+openai = OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"])+```++You can also pass `base_url=...` to either provider to point at a+self-hosted endpoint or compatible proxy (e.g. Anthropic Bedrock,+LiteLLM, vLLM).++For the [FauxProvider](../guides/providers/custom#using-fauxprovider-in-tests)+(used in tests), no credentials are required.++## Choosing extras: which to install++| Extra | Pulls in | Install when |+|---|---|---|+| (none) | core only | You only need in-memory state, no MCP, no tracing |+| `[sqlite]` | `aiosqlite` | Single-process app needs disk persistence |+| `[postgres]` | `asyncpg`, `sqlalchemy`, `msgpack` | Multi-instance / production — see [Postgres guide](../guides/checkpointing/postgres) |+| `[mcp]` | `mcp` | You want to mount MCP server tools into your agent |+| `[tracing]` | `opentelemetry-sdk` | You want OpenTelemetry traces (and optionally metrics) — see [Tracing guide](../guides/tracing/overview) |+| `[tracing-otlp]` | `opentelemetry-exporter-otlp-proto-http` | Ship traces to an OTLP/HTTP backend (Jaeger ≥1.50, Tempo, Honeycomb, Datadog, …) |+| `[docs]` | `griffe` | You're building the docs site (contributors only) |++## Next steps++- [Quick Start](./quick-start) — your first agent in five minutes.+- [Core Concepts](./core-concepts) — what `Agent` / `Tool` / `Provider`+ / `Checkpointer` actually mean before you start gluing them.diff --git a/website/versioned_docs/version-0.5/getting-started/quick-start.md b/website/versioned_docs/version-0.5/getting-started/quick-start.mdnew file mode 100644index 0000000..a0ff7de--- /dev/null+++ b/website/versioned_docs/version-0.5/getting-started/quick-start.md@@ -0,0 +1,126 @@+---+title: Quick Start+---++# Quick Start++Ship a streaming, tool-using agent in five minutes. We'll build a+weather agent that calls a Python function as a tool, streams Claude's+response token-by-token, and exits cleanly.++## Prerequisites++- Python 3.11++- `cubepi` installed (`pip install cubepi`)+- An `ANTHROPIC_API_KEY` in your environment++## The full script++Save this as `weather_agent.py`:++```python title="weather_agent.py"+import asyncio+import os+from pydantic import BaseModel++from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent+from cubepi.providers.anthropic import AnthropicProvider+++class GetWeatherParams(BaseModel):+ city: str+++async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):+ # In a real app: call an HTTP weather API. Here we hard-code a reply.+ return AgentToolResult(+ content=[TextContent(text=f"72°F and sunny in {params.city}")]+ )+++async def main():+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])++ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="You are a concise weather assistant.",+ tools=[+ AgentTool(+ name="get_weather",+ description="Get current weather for a city",+ parameters=GetWeatherParams,+ execute=get_weather,+ ),+ ],+ )++ # Subscribe BEFORE prompt() — that's how you see streaming events.+ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "agent_end":+ print() # final newline++ agent.subscribe(on_event)+ await agent.prompt("What's the weather in Tokyo?")+++asyncio.run(main())+```++Run it:++```bash+python weather_agent.py+```++You should see Claude stream a sentence like+*"The weather in Tokyo is currently 72°F and sunny…"*, with the+tool result threaded through.++## What just happened++CubePi ran a loop that looks (conceptually) like this:++1. `agent.prompt("What's the weather in Tokyo?")` enqueued a+ `UserMessage` and called the model.+2. The model decided to invoke `get_weather(city="Tokyo")` — CubePi+ parsed the JSON args with your Pydantic model, called your `async+ def`, and fed the result back as a `ToolResultMessage`.+3. The model produced a final assistant response, streamed back as+ `text_delta` events.+4. The loop emitted `agent_end` and returned.++`agent.subscribe(...)` registered a callback for every event the+runtime emits: `agent_start`, `turn_start`, `message_start`,+`text_delta`, `tool_execution_start`, `tool_execution_end`,+`message_end`, `turn_end`, `agent_end`. The script only cared about+`text_delta`, but you can hang any UI off the rest.++## Sources of confusion (read before you debug)++- **Subscribe before you prompt.** Listeners only receive events+ emitted *after* `subscribe` was called. Calling `prompt` first means+ the early events are gone.+- **`Model(id=…, provider=…)` is required.** The agent uses+ `model.provider` to clamp thinking levels and route metadata. The id+ must match a model the provider supports.+- **The `execute` signature is fixed.** Keep `(tool_call_id, params,+ *, signal, on_update)` even if you don't use the keyword-only+ arguments. CubePi always passes them.+- **`agent.prompt()` can only run one prompt at a time.** While it's+ running, use [`agent.steer()`](../guides/agents/multi-turn) to+ inject a follow-up, or `agent.follow_up()` to queue one for after+ the current run.++## Next steps++- [Core Concepts](./core-concepts) — the mental model behind `Agent`,+ `Tool`, `Provider`, `Stream`, `Middleware`, `Checkpointer`.+- [Building Your First Agent](../guides/agents/first-agent) — full+ walkthrough of tools, streaming, and error handling.+- [Tool Use & Parallel Execution](../guides/agents/tool-use) — make+ the agent fan out across multiple tools at once.+- [Recipes → Weather Agent](../recipes/weather-agent) — a slightly+ beefier version of this script with real HTTP calls.diff --git a/website/versioned_docs/version-0.5/guides/agents/first-agent.md b/website/versioned_docs/version-0.5/guides/agents/first-agent.mdnew file mode 100644index 0000000..0783d05--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/agents/first-agent.md@@ -0,0 +1,189 @@+---+title: Building Your First Agent+---++# Building Your First Agent++This guide is the longer cousin of the [Quick Start](../../getting-started/quick-start).+We'll build a single-tool agent end-to-end, then layer on the things+you'll want next: streaming UI, error handling, and a cancel button.++## Step 1 — set up the provider and model++The provider is the connection to the LLM API; the `Model` describes+which model you want to invoke and a few capabilities.++```python+import os+from cubepi import Model+from cubepi.providers.anthropic import AnthropicProvider++provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])+model = Model(+ id="claude-sonnet-4-5-20250929",+ provider="anthropic",+ max_tokens=4096, # response cap+ context_window=200_000, # hard model limit; defaults are usually fine+ temperature=0.7,+)+```++The `provider` field on `Model` is a string label (e.g. `"anthropic"`,+`"openai"`). It's used by the framework to clamp thinking levels and+tag responses — keep it stable, it doesn't have to match the+provider's internal name.++## Step 2 — declare a tool++Every tool is a Pydantic param model + an async `execute` function:++```python+from pydantic import BaseModel+from cubepi import AgentTool, AgentToolResult, TextContent+++class GetWeatherParams(BaseModel):+ city: str+++async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):+ # do real work here — call an HTTP API, query a DB, etc.+ return AgentToolResult(+ content=[TextContent(text=f"72°F and sunny in {params.city}")]+ )+++weather_tool = AgentTool(+ name="get_weather",+ description="Get current weather for a city. Returns a short text summary.",+ parameters=GetWeatherParams,+ execute=get_weather,+)+```++A few details:++- The Pydantic model is auto-converted to JSON Schema and sent to the+ model as part of the tool definition.+- The `execute` signature is fixed:+ `(tool_call_id, params, *, signal, on_update)`. The two+ keyword-only args are always passed — keep them in your signature+ even if you ignore them.+- `signal` is an `asyncio.Event` that's set when the user cancels.+ Check it inside long-running work and bail out early.+- `on_update(partial)` lets you stream incremental progress (covered+ in [Tool Use](./tool-use#streaming-tool-progress)).++## Step 3 — assemble the agent++```python+from cubepi import Agent++agent = Agent(+ provider=provider,+ model=model,+ system_prompt="You are a concise weather assistant.",+ tools=[weather_tool],+)+```++You can pass `tools=[]` (or omit it) for a plain chat agent.++## Step 4 — subscribe to events++`agent.subscribe(listener)` is how you observe the run. The listener+receives every `AgentEvent`:++```python+def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "tool_execution_start":+ print(f"\n→ calling {event.tool_name}({event.args})")+ elif event.type == "tool_execution_end":+ print(f" ✓ done")++agent.subscribe(on_event)+```++You can register multiple listeners and they all receive every event.+Subscribe **before** `prompt()` — events fire as soon as the run+starts.++## Step 5 — prompt and run++```python+import asyncio++async def main():+ await agent.prompt("What's the weather in Tokyo?")++asyncio.run(main())+```++`agent.prompt()` does not return any value. The result lives on+`agent.state.messages` (the full history) and `agent.state.streaming_message`+(the current in-flight message, or `None` between turns).++## Adding error handling++When `provider.stream()` raises, the agent loop still produces an+`AssistantMessage` with `stop_reason="error"` and `error_message`+filled in. The event sequence is:+`message_start` → `message_end` → `turn_end` → `agent_end`.++You can either:++1. Catch in the subscriber, looking for `event.type == "agent_end"` and+ the last message's `stop_reason`:++ ```python+ def on_event(event, signal=None):+ if event.type == "agent_end":+ last = event.messages[-1]+ if getattr(last, "stop_reason", "") == "error":+ print(f"\nerror: {last.error_message}")+ ```++2. Or inspect `agent.state.error_message` after `await+ agent.prompt(...)` returns.++## Adding a cancel button++`agent.abort()` sets the run-level signal. The provider stream+short-circuits to `"aborted"`, in-flight tools see `signal.is_set()+== True`, and the loop emits `agent_end` cleanly.++```python+async def main():+ task = asyncio.create_task(agent.prompt("Search for…"))+ await asyncio.sleep(0.5)+ agent.abort()+ await task # always completes — never raises+ await agent.wait_for_idle()+```++## Common pitfalls++- **`RuntimeError: Agent is already processing a prompt.`** — You called+ `prompt()` twice without awaiting the first. Use `await+ agent.wait_for_idle()` or queue with `steer()` / `follow_up()`+ instead.+- **No `text_delta` events** — Did you subscribe *before* calling+ `prompt()`? Listeners only see events emitted after registration.+- **Tool not found** — The model invoked a tool whose `name` doesn't+ match any tool in `tools=[...]`. CubePi reports this as a tool result+ with `is_error=True` rather than crashing — check the+ `tool_execution_end` event's `result`.+- **Pydantic ValidationError swallowed** — If the model produces+ malformed JSON, CubePi captures the validation error and feeds it+ back as a tool error result. The model usually corrects itself on+ the next turn.++## Next++- [Tool Use & Parallel Execution](./tool-use) — multiple tools at once,+ sequential mode, `terminate`, incremental progress.+- [Streaming Events](./streaming) — the full event taxonomy.+- [Multi-turn Conversations](./multi-turn) — keeping state across+ turns, `steer`, `follow_up`, `resume`.diff --git a/website/versioned_docs/version-0.5/guides/agents/multi-turn.md b/website/versioned_docs/version-0.5/guides/agents/multi-turn.mdnew file mode 100644index 0000000..d238bfc--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/agents/multi-turn.md@@ -0,0 +1,163 @@+---+title: Multi-turn Conversations+---++# Multi-turn Conversations++A "turn" in CubePi is one round of: user input → model response (and+maybe tools) → optional more model responses to tool results. The+agent's `_messages` list grows across turns; this guide covers how to+drive multi-turn flows correctly and how to inject input while the+agent is mid-thought.++## The basic pattern++Just call `prompt` again after the previous call returns:++```python+await agent.prompt("Hi, my name is Sam.")+await agent.prompt("What's my name?")+# → "Your name is Sam."+```++History lives on `agent.state.messages`. CubePi appends each user+message, each assistant message, and each tool result. The provider+gets the full list every time, so context windows matter (see+[Context Management](#context-management) below).++## In-flight steering: `agent.steer()`++Sometimes the user has a correction or extra context while the model+is still mid-turn. Use `steer()`:++```python+import asyncio++async def main():+ task = asyncio.create_task(agent.prompt("Plan a 5-day trip to Kyoto."))+ await asyncio.sleep(2)+ # User changed their mind:+ agent.steer(UserMessage(content=[TextContent(text="Make it 3 days, not 5.")]))+ await task+```++A steering message is enqueued; the loop picks it up between turns (in+practice, between a tool batch and the next model call). The agent+sees it before its next response — it's not lost.++`steering_mode` on `Agent` controls drain behaviour:++- `"one-at-a-time"` (default) — one queued message per pickup point.+- `"all"` — every queued message is drained at once.++## Queued follow-ups: `agent.follow_up()`++`follow_up` is for *"after the current run, start a new turn with+this."* It's the typical pattern for a chat UI: the user types while+the assistant is still responding.++```python+agent.follow_up(UserMessage(content=[TextContent(text="And what about Osaka?")]))+# When the current prompt() finishes, the loop picks this up+# automatically and starts a new turn.+```++If the agent is idle when you call `follow_up`, you still need to+trigger a run — most apps call `await agent.resume()` once `prompt()`+returns, to drain the queue.++## `resume()` — continue from the last message++`resume()` is the "pick up where we left off" entry point. Two uses:++1. **After loading from a checkpointer.** The state has messages but+ no in-flight prompt. `resume()` looks at the last message and acts:+ - assistant → expects a queued steer/follow_up to convert into a+ new user turn; otherwise raises.+ - tool_result → re-invokes the model with the tool output.+ - user → re-invokes the model on the user message.+2. **After abort.** Once `agent.abort()` has cleanly torn down a run,+ you can resume.++```python+async with SQLiteCheckpointer("conv.db") as cp:+ agent = Agent(provider=…, model=…, checkpointer=cp, thread_id="conv-1")+ await agent.prompt("hello") # loads existing history first+ await agent.prompt("how are you?")+```++The first `prompt()` after instantiation loads any existing thread.+Subsequent calls just append.++## Context management++CubePi does **not** truncate or summarise context on your behalf. The+full message list is sent to the model on every turn. Strategies:++- **Manual truncation** — Implement a+ [`transform_context`](../middleware/hooks#transform_context)+ middleware that returns a sliding window.+- **Summarisation pass** — Periodically inject a summary message and+ drop older ones via `transform_context`.+- **Different `convert_to_llm`** — Reshape the history just before+ serialisation (the last opportunity), without mutating+ `agent.state.messages`. The user-visible history stays full; the+ model sees less.++See [Middleware → Examples](../middleware/examples#sliding-window-truncation)+for a working example.++## Cancellation and idle waits++```python+agent.abort() # signals the current run to stop+await agent.wait_for_idle() # awaits the run-cleanup+```++`wait_for_idle()` is a no-op if the agent is already idle. It's safe+to call anywhere.++## Restoring state from disk++```python+from cubepi.checkpointer import SQLiteCheckpointer++async with SQLiteCheckpointer("conv.db") as cp:+ agent = Agent(+ provider=provider,+ model=model,+ checkpointer=cp,+ thread_id="user-42",+ )+ # First prompt() restores the saved history if any.+ await agent.prompt("continue our chat")+```++The `_extra` slot (an arbitrary `dict[str, Any]`) is also restored.+Middleware that wants to persist per-thread state should write into+`context.extra`; the checkpointer's `save_extra` is called at+`agent_end`.++## Common pitfalls++- **`prompt()` while another `prompt()` is in flight** raises+ `RuntimeError`. Use `steer()` or `follow_up()`, or `wait_for_idle()`+ first.+- **`resume()` with last message = assistant and no queue** raises+ `"Cannot continue from message role: assistant"`. Either queue a+ follow-up first or call `prompt()` instead.+- **History grows unbounded** — without a `transform_context`+ middleware you'll eventually hit context limits. Plan for+ truncation/summarisation early.+- **Concurrent agents on the same `thread_id`** — Append-only is safe+ for ordering but two agents writing the same thread will interleave+ messages. Use one agent instance per thread or coordinate at the+ application layer.++## See also++- [Streaming Events](./streaming) — exact event order around+ steering/follow_up.+- [Checkpointing → SQLite](../checkpointing/sqlite) — persisting history.+- [Recipes → Persistent Chat](../../recipes/persistent-chat) — full+ multi-turn app with history reload.diff --git a/website/versioned_docs/version-0.5/guides/agents/streaming.md b/website/versioned_docs/version-0.5/guides/agents/streaming.mdnew file mode 100644index 0000000..c55baf0--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/agents/streaming.md@@ -0,0 +1,170 @@+---+title: Streaming Events+---++# Streaming Events++CubePi exposes two streams, layered:++1. **Provider stream** — `MessageStream` you get from+ `provider.stream(...)`. Yields `StreamEvent`s describing the raw+ wire output: text deltas, thinking deltas, tool-call deltas, then+ `done` or `error`.+2. **Agent event stream** — what listeners registered with+ `agent.subscribe(...)` see. Eleven event types covering the full+ lifecycle of a `prompt()` call, including provider events wrapped+ inside `MessageUpdateEvent`.++Most app code only needs the agent event stream.++## The eleven agent events++| Event | Fires when |+|---|---|+| `agent_start` | At the very beginning of `prompt()` / `resume()` |+| `turn_start` | Before each model invocation (one or more per `prompt`) |+| `message_start` | Right before a new message (user / assistant / tool result) is added to history |+| `message_update` | On every provider `StreamEvent` (deltas, etc.); has `event.stream_event` attached |+| `message_end` | After a message is finalised |+| `tool_execution_start` | A tool call is dispatched (one per call, before parallel `asyncio.gather`) |+| `tool_execution_update` | A tool reported partial progress via `on_update(...)` |+| `tool_execution_end` | A tool finished (or failed) |+| `turn_end` | After all tools in a batch settled, or after a tool-less assistant response |+| `agent_end` | The whole `prompt()` call has finished — clean exit, abort, or error |++`MessageStartEvent` and `MessageEndEvent` apply to *every* message,+not just assistant ones. User and tool-result messages also get them.++## Event order for a tool-using turn++A typical "user asks question → model calls one tool → model responds"+sequence:++```+agent_start+turn_start+ message_start (UserMessage from prompt)+ message_end (UserMessage)+ message_start (AssistantMessage — empty partial)+ message_update × N (text_delta, toolcall_delta, …)+ message_end (AssistantMessage — finalised)+ tool_execution_start+ tool_execution_end+ message_start (ToolResultMessage)+ message_end (ToolResultMessage)+turn_end+turn_start (loop continues with the tool result in context)+ message_start+ message_update × N+ message_end+turn_end+agent_end+```++## Subscribing++```python+def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)++unsubscribe = agent.subscribe(on_event)+```++`agent.subscribe(...)` never receives an event whose top-level `.type`+equals `"text_delta"` — that's a *provider* event type. The agent+wraps every provider event in a `MessageUpdateEvent` and tucks the+original under `event.stream_event`. Match on both fields, as above.++Listeners can be sync or async; async ones are awaited. The second+argument is the run-level `asyncio.Event` (the abort signal) — you can+inspect `signal.is_set()` to know if the run was cancelled.++To stop receiving events, call the function returned by `subscribe`.++## Filtering for text deltas (the common case)++```python+def on_event(event, signal=None):+ if event.type == "message_update":+ sub = event.stream_event+ if sub.type == "text_delta":+ print(sub.delta, end="", flush=True)+```++Equivalent defensive form using `getattr`, since only+`MessageUpdateEvent` carries a `stream_event` attribute:++```python+def on_event(event, signal=None):+ if getattr(event, "stream_event", None) and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+```++The shape that CubePi guarantees is the one in the table above+(`MessageUpdateEvent.stream_event.delta`). Always match the outer+event's `type == "message_update"` (or check `stream_event` exists)+before reaching into `stream_event.type`.++## Provider `StreamEvent` types++Inside a `MessageUpdateEvent.stream_event`, the type tells you what+the model is emitting:++| `stream_event.type` | Meaning | Useful fields |+|---|---|---|+| `start` | Start of an assistant message | `partial` |+| `text_start` | Beginning of a text block | `content_index` |+| `text_delta` | Token chunk | `delta` |+| `text_end` | End of a text block | `content_index` |+| `thinking_start` / `thinking_delta` / `thinking_end` | Extended thinking blocks | `delta` |+| `toolcall_start` / `toolcall_delta` / `toolcall_end` | Streaming JSON args for a tool call | `delta` (partial JSON) |+| `done` | Stream finished normally | — |+| `error` | Stream errored | `error_message` |++The `partial` field on every event is a deep-copied snapshot of the+in-progress `AssistantMessage` — handy for UIs that re-render+on every event without tracking deltas themselves.++## Iterating a raw provider stream++If you're skipping `Agent` entirely (rare — usually means you're+writing a test or a custom orchestrator), iterate the stream+directly:++```python+stream = await provider.stream(+ model=model,+ messages=[UserMessage(content=[TextContent(text="hello")])],+)+async for event in stream:+ if event.type == "text_delta":+ print(event.delta, end="", flush=True)+final = await stream.result() # waits for the AssistantMessage+```++`stream.result()` returns even after iteration ends; it's the+canonical way to get the final message.++## Common pitfalls++- **Subscribing after `prompt()`** — Early events are gone.+ `agent.subscribe(...)` first, always.+- **Listener exceptions crash the loop?** — They don't, but they+ propagate up to the next `await`. Wrap risky work in `try/except`.+- **Order on parallel tools** — `tool_execution_start` events come in+ the model's emit order; `tool_execution_end` events come in+ completion order. Don't rely on pairs being adjacent.+- **`message_update` fires for every delta** — High-frequency tokens+ can flood a slow listener (e.g. a websocket). Batch on the consumer+ side if needed.+- **`text_delta` for thinking?** — No. Thinking blocks emit+ `thinking_*` events. Filter on `event.stream_event.type` if you only+ want visible text.++## See also++- [Tool Use](./tool-use) — the `tool_execution_*` triplet in detail.+- [Multi-turn](./multi-turn) — event order around steering and resume.+- [API Reference → StreamEvent](../../api/cubepi-providers#streamevent)+ for the field-level schema.diff --git a/website/versioned_docs/version-0.5/guides/agents/tool-use.md b/website/versioned_docs/version-0.5/guides/agents/tool-use.mdnew file mode 100644index 0000000..ed722bc--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/agents/tool-use.md@@ -0,0 +1,190 @@+---+title: Tool Use & Parallel Execution+---++# Tool Use & Parallel Execution++Tools are how an agent acts on the world. CubePi turns each `AgentTool`+into a JSON Schema for the model, validates arguments with Pydantic,+runs the work, and feeds the result back as a `ToolResultMessage`. By+default tools run in parallel when the model calls more than one in a+single turn.++## Anatomy of a tool++```python+from pydantic import BaseModel, Field+from cubepi import AgentTool, AgentToolResult, TextContent+++class SearchParams(BaseModel):+ query: str = Field(..., description="The natural-language query")+ limit: int = Field(10, ge=1, le=100)+++async def search(tool_call_id, params: SearchParams, *, signal=None, on_update=None):+ results = await my_search_backend(params.query, params.limit)+ return AgentToolResult(+ content=[TextContent(text="\n".join(results))],+ details={"raw_results": results}, # passes through to ToolResultMessage.details+ )+++search_tool = AgentTool(+ name="search",+ description="Search the internal knowledge base.",+ parameters=SearchParams,+ execute=search,+)+```++The `description` is shown to the model verbatim — write it for the+model, not for humans. Pydantic `Field(description=...)` propagates+into the JSON Schema and helps the model understand each parameter.++## Parallel by default++When the model emits multiple tool calls in one assistant message,+CubePi schedules them on `asyncio.create_task()` and gathers them.+That's almost always what you want.++```python+agent = Agent(+ provider=provider,+ model=model,+ tools=[search_tool, fetch_url_tool, summarise_tool],+)+```++The event stream emits `tool_execution_start` for all of them up+front, interleaved `tool_execution_update` events as each tool reports+progress, then `tool_execution_end` per tool in completion order.++## Forcing sequential execution++There are two ways to opt out of parallel mode:++1. **Per agent** — `Agent(tool_execution="sequential")`. All tool+ batches run one-by-one in the order the model emitted them.++2. **Per tool** — set `execution_mode="sequential"` on the+ `AgentTool`. If *any* tool in the current batch is sequential, the+ whole batch falls back to sequential.++ ```python+ write_db_tool = AgentTool(+ name="write_db",+ description="Persist a record.",+ parameters=WriteDbParams,+ execute=write_db,+ execution_mode="sequential", # opt out of parallelism for safety+ )+ ```++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.5/guides/checkpointing/custom.md b/website/versioned_docs/version-0.5/guides/checkpointing/custom.mdnew file mode 100644index 0000000..1d7bd49--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/checkpointing/custom.md@@ -0,0 +1,201 @@+---+title: Custom Backends+---++# Custom Checkpointing Backends++The `Checkpointer` protocol is three async methods:++```python+class Checkpointer(Protocol):+ async def load(self, thread_id: str) -> CheckpointData | None: ...+ async def append(self, thread_id: str, messages: list[Message]) -> None: ...+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None: ...+```++That's the whole contract. Implement it for Redis, DynamoDB, S3, a+filesystem, an in-memory dict — anything that can append-and-list.++## When the agent calls each method++| Method | Called when |+|---|---|+| `load(thread_id)` | Once, on the first `prompt()` after agent construction |+| `append(thread_id, messages)` | Inside `message_end`, every time a message is finalised |+| `save_extra(thread_id, extra)` | At `agent_end`, with the current `_extra` dict |++`load` returns `None` for unknown threads. `append` and `save_extra`+do nothing useful if you don't already have a thread; create the row+on first call.++## A minimal Redis example++```python+import json+from typing import Any+import redis.asyncio as aredis+from cubepi.checkpointer.base import CheckpointData+from cubepi.providers.base import AssistantMessage, Message, ToolResultMessage, UserMessage+++_ROLE_TO_CLS: dict[str, type[Message]] = {+ "user": UserMessage,+ "assistant": AssistantMessage,+ "tool_result": ToolResultMessage,+}+++class RedisCheckpointer:+ def __init__(self, redis_url: str, prefix: str = "cubepi:") -> None:+ self._url = redis_url+ self._prefix = prefix+ self._r: aredis.Redis | None = None++ async def __aenter__(self):+ self._r = aredis.from_url(self._url)+ return self++ async def __aexit__(self, *args):+ if self._r is not None:+ await self._r.aclose()+ self._r = None++ def _msgs_key(self, thread_id: str) -> str:+ return f"{self._prefix}msgs:{thread_id}"++ def _extra_key(self, thread_id: str) -> str:+ return f"{self._prefix}extra:{thread_id}"++ async def load(self, thread_id: str) -> CheckpointData | None:+ raw_msgs = await self._r.lrange(self._msgs_key(thread_id), 0, -1)+ raw_extra = await self._r.get(self._extra_key(thread_id))++ if not raw_msgs and raw_extra is None:+ return None++ messages: list[Message] = []+ for item in raw_msgs:+ data = json.loads(item)+ cls = _ROLE_TO_CLS.get(data.get("role"))+ if cls is not None:+ messages.append(cls.model_validate(data))++ extra: dict[str, Any] = json.loads(raw_extra) if raw_extra else {}+ return CheckpointData(messages=messages, extra=extra)++ async def append(self, thread_id: str, messages: list[Message]) -> None:+ if not messages:+ return+ pipe = self._r.pipeline()+ for m in messages:+ pipe.rpush(self._msgs_key(thread_id), json.dumps(m.model_dump(mode="json")))+ await pipe.execute()++ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:+ # Merge-style: load existing, update, write back.+ raw = await self._r.get(self._extra_key(thread_id))+ existing = json.loads(raw) if raw else {}+ existing.update(extra)+ await self._r.set(self._extra_key(thread_id), json.dumps(existing))+```++Usage:++```python+async with RedisCheckpointer("redis://localhost:6379") as cp:+ agent = Agent(provider=…, model=…, checkpointer=cp, thread_id="user-42")+ await agent.prompt("hi")+```++## Invariants worth holding++1. **Append-only.** Don't update past messages. The agent assumes the+ history it appended is what you'll return on `load`.+2. **Order preserved.** `load` returns messages in the order they were+ appended. Use a list, a sorted key, or a sequence column.+3. **Idempotent re-`load`.** Calling `load` twice on the same thread+ should yield identical results. (CubePi calls it once, but tools+ often need to too.)+4. **`extra` is a merge.** `save_extra({"a": 1})` followed by+ `save_extra({"b": 2})` should leave `{"a": 1, "b": 2}` — not just+ `{"b": 2}`. The agent calls this with the full dict, but middleware+ composes its writes.+5. **Reconstruct messages with `model_validate`.** Use the role+ discriminator (`UserMessage` / `AssistantMessage` /+ `ToolResultMessage`) to pick the right class.++## Custom backend without async context manager++The `Checkpointer` Protocol doesn't require `__aenter__` /+`__aexit__`. Built-in checkpointers use it because they manage+network resources, but a pure in-memory or local-file backend can+skip it:++```python+class FileCheckpointer:+ def __init__(self, dir_path: str) -> None:+ self._dir = pathlib.Path(dir_path)+ self._dir.mkdir(parents=True, exist_ok=True)++ async def load(self, thread_id: str) -> CheckpointData | None:+ ...+ async def append(self, thread_id: str, messages: list[Message]) -> None:+ ...+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:+ ...++# Pass directly:+agent = Agent(provider=…, model=…, checkpointer=FileCheckpointer("/tmp/cp"), thread_id="x")+```++## Testing your backend++Drop-in test pattern using `FauxProvider`:++```python+from cubepi import Agent, Model+from cubepi.providers import FauxProvider, faux_assistant_message++async def test_roundtrip():+ cp = MyCheckpointer(…)+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("hello")])++ agent1 = Agent(provider=provider, model=Model(id="t", provider="faux"),+ checkpointer=cp, thread_id="t1")+ agent1.subscribe(lambda e, s=None: None)+ await agent1.prompt("hi")++ # Fresh agent, same thread — should restore history.+ provider2 = FauxProvider()+ provider2.set_responses([faux_assistant_message("hello again")])+ agent2 = Agent(provider=provider2, model=Model(id="t", provider="faux"),+ checkpointer=cp, thread_id="t1")+ agent2.subscribe(lambda e, s=None: None)+ await agent2.prompt("hi again")++ assert len(agent2.state.messages) == 4 # 2 user + 2 assistant+```++## Common pitfalls++- **Mutating returned `CheckpointData`** — Either deep-copy on the way+ in, or document that the agent owns the list. CubePi's built-ins+ copy.+- **Losing `metadata`** — `model_dump(mode="json")` preserves+ `metadata`. If you serialise via `__dict__` you'll drop it.+- **Race on `save_extra` merge** — A read-modify-write pattern can+ lose concurrent writes. Use a SQL `JSONB ||` or a Redis Lua script+ if you have concurrent writers per thread.+- **Forgetting to register the role for tool results** — Easy to map+ `"user"` and `"assistant"` and forget `"tool_result"`. All three are+ needed.++## See also++- [`Checkpointer` Protocol API](../../api/cubepi-checkpointer) — full+ signature.+- [SQLiteCheckpointer source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/sqlite.py)+ — a complete reference implementation.+- [PostgresCheckpointer source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/postgres/checkpointer.py)+ — production-grade reference.diff --git a/website/versioned_docs/version-0.5/guides/checkpointing/postgres.md b/website/versioned_docs/version-0.5/guides/checkpointing/postgres.mdnew file mode 100644index 0000000..1e07e35--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/checkpointing/postgres.md@@ -0,0 +1,195 @@+---+title: Postgres Checkpointing+---++# Postgres Checkpointing++`PostgresCheckpointer` is the production-grade persistence backend.+It uses `asyncpg` with a connection pool, `msgpack` for payloads, and+a per-thread Postgres advisory lock so multiple processes can write+the same `thread_id` without trampling each other.++Install the extra:++```bash+pip install "cubepi[postgres]"+```++This pulls in `asyncpg`, `sqlalchemy`, and `msgpack`.++## Basic usage++```python+import asyncio+from cubepi import Agent, Model+from cubepi.checkpointer import PostgresCheckpointer+from cubepi.providers.anthropic import AnthropicProvider+++async def main():+ provider = AnthropicProvider(api_key="…")+ async with PostgresCheckpointer("postgresql://user:pass@host/dbname") as cp:+ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ checkpointer=cp,+ thread_id="user-42",+ )+ await agent.prompt("hello")+++asyncio.run(main())+```++The DSN is whatever `asyncpg.create_pool(...)` accepts. Pool sizing:++```python+async with PostgresCheckpointer(+ "postgresql://…",+ min_pool_size=2,+ max_pool_size=20,+) as cp:+ …+```++## Schema++The checkpointer expects three tables: `cubepi_threads`,+`cubepi_messages`, and `cubepi_schema_version`. Unlike SQLite, CubePi+**does not create these for you** — it verifies on `__aenter__` that+they exist with the expected `schema_version`.++If they're missing, you get `CubepiSchemaUninitialized`. If the+version doesn't match this cubepi release, you get+`CubepiSchemaMismatch`.++The reason: a production database belongs to the host application's+migration system (Alembic, Atlas, …), not to a third-party library+that might fight your existing migrations.++### Bootstrapping via Alembic++CubePi exposes the SQLAlchemy `MetaData` so your migrations can adopt+the schema:++```python+# alembic/env.py+from cubepi.checkpointer.postgres import cubepi_metadata, EXPECTED_SCHEMA_VERSION++target_metadata = [my_app_metadata, cubepi_metadata]+```++Then 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 (+ create_message_partitions_op,+ write_schema_version_op,+)++def upgrade():+ op.create_table(...) # auto-generated from cubepi_metadata+ op.execute(create_message_partitions_op()) # creates the 64 hash partitions+ op.execute(write_schema_version_op()) # records EXPECTED_SCHEMA_VERSION+```++Both helpers return a SQL string — you pass them to `op.execute(...)`.+`write_schema_version_op()` is idempotent: it deletes any rows from a+prior cubepi version and inserts the current one.++When CubePi later upgrades and bumps `EXPECTED_SCHEMA_VERSION`, you+generate a new revision and call `op.execute(write_schema_version_op())`+again.++## Data model++```+cubepi_threads+ thread_id (PK)+ parent_thread_id -- for forks+ forked_at_seq -- seq number at fork point+ extra -- JSONB+ created_at / updated_at++cubepi_messages+ thread_id, seq -- composite PK; partitioned by HASH(thread_id) into 64+ role -- "user" | "assistant" | "tool"+ metadata -- JSONB (indexed via GIN)+ payload -- bytea (msgpack)+ created_at++cubepi_schema_version+ version (PK)+```++Important properties:++- **`(thread_id, seq)` is the message identity.** `seq` is monotonic+ per thread, allocated under a `pg_advisory_xact_lock(hashtext(thread_id))`.+ Two concurrent writers on the same thread serialize cleanly.+- **`payload` is msgpack-encoded `model.model_dump(mode="json")`.**+ CubePi reconstructs the Pydantic model on read.+- **`metadata` is JSONB, queryable.** The full message also has+ `metadata` inside the payload, but the column is the canonical view+ for SQL queries.+- **Tables are partitioned by `HASH(thread_id)` into 64 partitions.**+ Even distribution across partitions, no per-thread bottleneck.++## Concurrency++The advisory lock makes append-on-the-same-thread safe across+processes:++```python+# Process A and Process B both append to thread "user-42" at the same time.+# They serialize through pg_advisory_xact_lock and each gets a consecutive seq.+```++Reads (`load`) take no lock — they're snapshot-consistent within the+transaction.++The pool default of `min=1, max=10` is fine for most apps; bump+`max_pool_size` if you have many concurrent agents.++## `save_extra` semantics++`save_extra` does a JSONB merge, not a replace:++```sql+extra = cubepi_threads.extra || EXCLUDED.extra+```++So writing `{"foo": 1}` then `{"bar": 2}` leaves `{"foo": 1, "bar":+2}`. Middleware can safely write partial dicts without losing prior+keys.++## Forks++The `parent_thread_id` + `forked_at_seq` columns exist for future fork+support. CubePi v0.3 doesn't expose a fork API yet — they're written+to so the schema is forward-compatible.++## Common pitfalls++- **`CubepiSchemaUninitialized`** — Your DB is empty or your+ migrations didn't run. Apply the host alembic upgrade first.+- **`CubepiSchemaMismatch`** — You upgraded cubepi but didn't generate+ a new migration. Generate one, apply it, and CubePi will start.+- **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.5/guides/checkpointing/sqlite.md b/website/versioned_docs/version-0.5/guides/checkpointing/sqlite.mdnew file mode 100644index 0000000..f6af8d5--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/checkpointing/sqlite.md@@ -0,0 +1,174 @@+---+title: SQLite Checkpointing+---++# SQLite Checkpointing++`SQLiteCheckpointer` is the lightweight persistence backend: a single+local file, no server, append-only message log. It's the default+choice for laptops, single-process apps, desktop tools, and any+environment where one Python process owns the conversation.++Install the extra:++```bash+pip install "cubepi[sqlite]"+```++This pulls in `aiosqlite`.++## Basic usage++```python+import asyncio+from cubepi import Agent, Model+from cubepi.checkpointer import SQLiteCheckpointer+from cubepi.providers.anthropic import AnthropicProvider+++async def main():+ provider = AnthropicProvider(api_key="…")+ async with SQLiteCheckpointer("agent.db") as cp:+ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ checkpointer=cp,+ thread_id="user-42",+ )+ await agent.prompt("Remember: my favourite colour is teal.")++ # Restart the script later — the file persists.+ await agent.prompt("What did I say my favourite colour was?")+ # → "You said teal."+++asyncio.run(main())+```++Two things to internalise:++1. **`thread_id`** is your conversation identifier — usually a user id+ or a session id. Two agents on the same `thread_id` share the same+ history.+2. **`async with SQLiteCheckpointer(...)`** is required: the context+ manager opens the connection and runs the one-time table creation+ on `__aenter__`. Using it without the context manager will raise+ `AssertionError`.++## What gets persisted++`SQLiteCheckpointer` writes two tables on first use:++```sql+CREATE TABLE messages (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ thread_id TEXT NOT NULL,+ message_json TEXT NOT NULL,+ created_at REAL NOT NULL DEFAULT (julianday('now'))+);++CREATE TABLE thread_extra (+ thread_id TEXT PRIMARY KEY,+ extra_json TEXT NOT NULL DEFAULT '{}'+);+```++- Every `UserMessage`, `AssistantMessage`, and `ToolResultMessage`+ becomes one row in `messages`. Pydantic `model_dump()` is used for+ the JSON payload.+- The `extra` dict on `AgentContext` is persisted on `agent_end` into+ `thread_extra`. Middleware that wants thread-scoped state should+ write into `context.extra`.++This schema is append-only. CubePi never updates or deletes rows.++## 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.5/guides/mcp/auth.md b/website/versioned_docs/version-0.5/guides/mcp/auth.mdnew file mode 100644index 0000000..0dc729c--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/mcp/auth.md@@ -0,0 +1,212 @@+---+title: MCP Server Authentication+---++# MCP Server Authentication++The MCP transport layer doesn't dictate an auth scheme — servers+decide. In practice, three patterns cover almost every case:++1. **Bearer token in `Authorization` header** (HTTP transport).+2. **Arbitrary custom headers** (HTTP transport).+3. **Environment variables** (stdio transport — server reads them+ from its own process env).++This page walks through each.++## HTTP: bearer tokens++The dominant pattern for hosted MCP servers (GitHub, Sentry,+internal). Pass an `Authorization` header to `load_mcp_tools_http`:++```python+import os+from cubepi.mcp import load_mcp_tools_http++tools = await load_mcp_tools_http(+ server_url="https://mcp.example.com/sse",+ headers={"Authorization": f"Bearer {os.environ['MCP_TOKEN']}"},+)+```++`headers` is forwarded to *every* request the transport makes,+including subsequent `tools/call` invocations. There's no separate+"login then call" step — the token rides every connection.++## HTTP: custom headers++Some servers use API-key headers instead:++```python+tools = await load_mcp_tools_http(+ server_url="https://mcp.internal/sse",+ headers={+ "X-API-Key": os.environ["MCP_API_KEY"],+ "X-Tenant-Id": "acme-corp",+ },+)+```++Combine as needed:++```python+headers = {+ "Authorization": f"Bearer {token}",+ "X-Trace-Id": str(uuid.uuid4()),+}+```++## HTTP: short-lived tokens / refresh++CubePi's loaders take a static `headers` dict at load time. For tokens+that expire (OAuth, JWT with short TTL), you have two options:++### Option A — Re-load on expiry++Catch the error, re-fetch the token, re-load the tools:++```python+async def load_with_fresh_token():+ token = await fetch_token()+ return await load_mcp_tools_http(+ server_url="…",+ headers={"Authorization": f"Bearer {token}"},+ )++tools = await load_with_fresh_token()+```++Practical for tokens that live longer than a single agent run.++### Option B — Wrap and refresh inside the tool++Build the `AgentTool` yourself with a closure that knows how to+refresh:++```python+from cubepi.mcp._adapter import make_mcp_agent_tool+from cubepi.mcp import load_mcp_tools_http++async def call_remote_with_refresh(tool_name, args):+ headers = {"Authorization": f"Bearer {await fetch_token()}"}+ # Re-implement the http_loader's call_remote with fresh headers each time+ from mcp.client.sse import sse_client+ from mcp import ClientSession+ async with sse_client(server_url, headers=headers, timeout=30) as streams:+ async with ClientSession(*streams) as session:+ await session.initialize()+ resp = await session.call_tool(tool_name, args)+ return _serialize_call_tool_response(resp)++# Use the adapter directly:+my_tool = make_mcp_agent_tool(+ name="…",+ description="…",+ input_schema={…},+ call_remote=call_remote_with_refresh,+)+```++Only worth it for tokens with very short TTLs. For anything longer,+Option A is simpler.++## stdio: environment variables++stdio servers read credentials from their own process environment.+Pass an `env` dict:++```python+import os+from cubepi.mcp import load_mcp_tools_stdio++tools = await load_mcp_tools_stdio(+ command="npx",+ args=["-y", "@modelcontextprotocol/server-github"],+ env={+ "GITHUB_PERSONAL_ACCESS_TOKEN": os.environ["GH_TOKEN"],+ **os.environ, # inherit the rest+ },+)+```++If you omit `env`, the subprocess inherits **all** parent env vars+(standard subprocess behaviour). For a clean slate, pass an explicit+dict:++```python+env = {+ "PATH": os.environ["PATH"],+ "HOME": os.environ["HOME"],+ "GITHUB_PERSONAL_ACCESS_TOKEN": token,+}+```++## stdio: file-based credentials++When a server reads credentials from `~/.config/...`, pass `cwd` to+ensure consistent path resolution, and rely on the inherited+environment:++```python+tools = await load_mcp_tools_stdio(+ command="/usr/local/bin/my-mcp",+ args=["--config", "config.yaml"],+ cwd="/etc/myapp",+)+```++## Per-user / per-tenant credentials++In a multi-tenant service, each agent invocation needs different+credentials. **Load tools per-request**:++```python+async def build_agent_for_user(user_id: str) -> Agent:+ token = await fetch_user_token(user_id)+ tools = await load_mcp_tools_http(+ server_url="https://mcp.example.com/sse",+ headers={"Authorization": f"Bearer {token}"},+ )+ return Agent(provider=provider, model=model, tools=tools)+```++Don't cache a single `tools` list across users — the closures retain+the auth headers from load time.++## Auditing / observability++Log MCP calls inside a [`before_tool_call`](../middleware/hooks#before_tool_call)+middleware. Tools loaded from MCP look identical to hand-written+tools in event streams, so existing logging middleware Just Works.++To tag MCP tools specifically, check for the synthesised parameter+model's name (prefix `MCP_`):++```python+class MCPAuditMiddleware(Middleware):+ async def before_tool_call(self, ctx, *, signal=None):+ param_name = type(ctx.args).__name__+ if param_name.startswith("MCP_"):+ log.info("mcp_call", extra={"tool": ctx.tool_call.name})+ return None+```++## Common pitfalls++- **`401 Unauthorized` only on call, not on `list_tools`** — Some+ servers gate per-tool. Ensure the token has scopes for every tool+ you intend the agent to use.+- **Tokens leaking into logs** — Don't log the `headers` dict.+ Especially watch out for exception messages that include URLs with+ query-string credentials.+- **stdio server fails silently** — Server prints auth errors to its+ own stderr. Add `stdout`/`stderr` redirection or use the MCP SDK's+ diagnostic logging.+- **Re-loading every request is slow** — Cache the loaded tools per+ `(user_id, token)` pair. Just remember tokens have TTLs.++## See also++- [Loading MCP Tools](./loading) — the basic loader API.+- [Middleware → Examples → Logging](../middleware/examples#structured-logging)+ — pairs naturally with MCP audit needs.diff --git a/website/versioned_docs/version-0.5/guides/mcp/loading.md b/website/versioned_docs/version-0.5/guides/mcp/loading.mdnew file mode 100644index 0000000..2cf6f27--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/mcp/loading.md@@ -0,0 +1,169 @@+---+title: Loading MCP Tools+---++# Loading MCP Tools++The [Model Context Protocol](https://modelcontextprotocol.io) defines+a standard way for tool servers to expose capabilities to agents.+CubePi ships two loaders that connect to an MCP server, enumerate its+tools, and turn each one into a regular `AgentTool` you can hand to+`Agent(tools=…)`.++Install the extra:++```bash+pip install "cubepi[mcp]"+```++This pulls in the `mcp` SDK.++## stdio transport: local subprocess++For tools that run as a local process (e.g. npm-published servers, a+Python module, an internal CLI):++```python+import asyncio+import sys+from cubepi import Agent, Model+from cubepi.mcp import load_mcp_tools_stdio+from cubepi.providers.anthropic import AnthropicProvider+++async def main():+ # Spawn a stdio MCP server and discover its tools.+ tools = await load_mcp_tools_stdio(+ command="npx",+ args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp/sandbox"],+ timeout=30.0,+ )++ agent = Agent(+ provider=AnthropicProvider(api_key="…"),+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ tools=tools, # all server tools, ready to use+ )+ agent.subscribe(lambda e, s=None: None)+ await agent.prompt("List files in /tmp/sandbox.")+++asyncio.run(main())+```++`load_mcp_tools_stdio` connects, calls `list_tools`, disconnects, and+returns the `AgentTool` list. **Each tool call spawns a fresh+subprocess** — v0.3 keeps things simple, no process pool.++Arguments:++| Parameter | Purpose |+|---|---|+| `command` | The executable (e.g. `"npx"`, `sys.executable`, `/usr/bin/uvx`) |+| `args` | argv for the server |+| `env` | Environment variables (optional) |+| `cwd` | Working directory (optional) |+| `timeout` | Per-call wall-clock timeout for `initialize` / `list` / `call` |++## HTTP/SSE transport: remote server++For hosted MCP servers (Sentry, GitHub, internal services):++```python+from cubepi.mcp import load_mcp_tools_http++tools = await load_mcp_tools_http(+ server_url="https://mcp.example.com/sse",+ headers={"Authorization": "Bearer <token>"},+ timeout=30.0,+)+```++`load_mcp_tools_http` uses the MCP SDK's SSE client. Same model as+stdio: one connection to enumerate, then a fresh connection per tool+call.++See [MCP Auth](./auth) for the auth patterns you'll likely need with+HTTP servers.++## What you get back++Each entry in the returned list is an `AgentTool`:++- `name` — the MCP tool name.+- `description` — straight from the server (no rewrites).+- `parameters` — a Pydantic model synthesised from the MCP+ `inputSchema` (JSON Schema → Pydantic via `pydantic.create_model`).+- `execute` — closure that calls `tools/call` over the same transport.++The synthesised Pydantic model covers: `string`, `integer`, `number`,+`boolean`, `array`, `object` (as `dict[str, Any]`), and enum (via+`Literal`). Top-level constraints are preserved: `description`,+`pattern`, `minLength`/`maxLength`, `minimum`/`maximum` (incl.+exclusive variants), `minItems`/`maxItems`.++## Mixing MCP tools with hand-written tools++They're the same type. Just concatenate the lists:++```python+mcp_tools = await load_mcp_tools_stdio(command="…", args=[…])+my_tools = [weather_tool, search_tool]++agent = Agent(+ provider=provider,+ model=model,+ tools=my_tools + mcp_tools,+)+```++The model sees one combined JSON Schema; the loop dispatches each+call to the right implementation.++## Per-call vs reusable connections++CubePi opens a new transport per `execute` call. That's:++- ✅ Simple — no pool lifecycle to manage.+- ✅ Robust — a hung connection can't poison other tools.+- ⚠️ Slower for stdio servers with heavy startup (a `npx` server can+ add seconds per call).++For high-throughput stdio servers, run the server as a persistent+HTTP service instead and use `load_mcp_tools_http`.++## Image and structured content++If an MCP tool returns image content blocks, CubePi maps them to+`ImageContent` and includes them in the `AgentToolResult.content`.+Anthropic provider relays these as image blocks in tool results;+OpenAI providers currently strip them (the wire format doesn't+support image-bearing tool results).++If the server returns `structuredContent`, it's exposed under+`AgentToolResult.details["structuredContent"]` — useful for+downstream programmatic access, but not shown to the model.++## Common pitfalls++- **`asyncio.TimeoutError` immediately on first call** — Server didn't+ finish `initialize` within `timeout`. Bump `timeout=60` or higher;+ some servers do heavy setup.+- **Each tool call is slow** — stdio subprocess spawn overhead. Run+ the server as HTTP, or write a custom adapter that keeps the+ subprocess alive.+- **Tools missing from the list** — Server failed to advertise them.+ Run the server in isolation and call `list_tools` manually with the+ MCP CLI to inspect.+- **Pydantic validation rejects model output** — The MCP `inputSchema`+ has constraints the model isn't honouring. Either loosen the schema+ on the server side or add a `before_tool_call` middleware that+ coerces.++## See also++- [MCP Auth](./auth) — bearer tokens, headers, env-based credentials.+- [Tool Use](../agents/tool-use) — how tools (MCP or otherwise) are+ dispatched.+- [`make_mcp_agent_tool` source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/mcp/_adapter.py)+ — the schema → Pydantic adapter, if you need to customise.diff --git a/website/versioned_docs/version-0.5/guides/middleware/composition.md b/website/versioned_docs/version-0.5/guides/middleware/composition.mdnew file mode 100644index 0000000..c40adb6--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/middleware/composition.md@@ -0,0 +1,168 @@+---+title: Composition Rules+---++# Composition Rules++When you pass multiple middlewares — `Agent(middleware=[m1, m2,+m3])` — CubePi composes them according to **per-hook rules** that+differ on purpose. The right way to think about it is: each hook has+the composition rule that makes sense for its job, and you don't have+to remember "before" or "after" precedence guesses.++## The rules at a glance++| Hook | Rule | Order matters? |+|---|---|---|+| `transform_context` | **Chain** — each sees previous output | Yes |+| `convert_to_llm` | **Last wins** | Only the last one runs |+| `transform_system_prompt` | **Chain** | Yes |+| `before_tool_call` | **First block stops** | 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.5/guides/middleware/examples.md b/website/versioned_docs/version-0.5/guides/middleware/examples.mdnew file mode 100644index 0000000..dbdf15f--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/middleware/examples.md@@ -0,0 +1,245 @@+---+title: Examples+---++# Middleware Examples++Working middleware for the four most common needs: rate limiting,+retries, structured logging, and context truncation.++## Rate limiting++Block tool calls when a user exceeds quota. Combine+`before_tool_call` with an external rate-limiter (a token bucket, a+Redis INCR, …).++```python+import time+from cubepi import Middleware+from cubepi.agent.types import BeforeToolCallResult+++class RateLimitMiddleware(Middleware):+ def __init__(self, max_calls_per_min: int) -> None:+ self.max = max_calls_per_min+ self._timestamps: list[float] = []++ async def before_tool_call(self, ctx, *, signal=None):+ now = time.monotonic()+ # Drop entries older than 60 s.+ self._timestamps = [t for t in self._timestamps if now - t < 60]+ if len(self._timestamps) >= self.max:+ return BeforeToolCallResult(+ block=True,+ reason=f"Rate limit: {self.max} tool calls/min exceeded. Try again shortly.",+ )+ self._timestamps.append(now)+ return None+```++Use:++```python+agent = Agent(provider=…, model=…, middleware=[RateLimitMiddleware(max_calls_per_min=30)])+```++When the limit hits, the model sees a tool result that says "Rate+limit exceeded…" and usually waits or asks the user.++## Retries with backoff++Retry failed tool calls inside `after_tool_call`. Up to N times, with+exponential backoff, only for transient errors.++```python+import asyncio+from cubepi import Middleware+from cubepi.agent.types import AfterToolCallResult+++class RetryMiddleware(Middleware):+ def __init__(self, max_retries: int = 3, base_delay: float = 0.5) -> None:+ self.max_retries = max_retries+ self.base_delay = base_delay++ async def after_tool_call(self, ctx, *, signal=None):+ if not ctx.is_error:+ return None++ # Find the tool by name and re-execute up to max_retries times.+ tool = next(+ (t for t in (ctx.context.tools or []) if t.name == ctx.tool_call.name),+ None,+ )+ if tool is None:+ return None++ for attempt in range(1, self.max_retries + 1):+ await asyncio.sleep(self.base_delay * (2 ** (attempt - 1)))+ try:+ new_result = await tool.execute(+ ctx.tool_call.id,+ ctx.args,+ signal=signal,+ on_update=None,+ )+ return AfterToolCallResult(+ content=new_result.content,+ details={"retried": attempt, "original_error": ctx.result.content},+ is_error=False,+ )+ except Exception:+ continue++ return None # give up — original error stays+```++Combine with caution: retrying non-idempotent tools (writes, sends,+deletes) can cause real damage. Mark such tools `execution_mode="sequential"`+and skip them here based on `ctx.tool_call.name`.++## Structured logging++Log every tool call with its arguments, duration, and outcome.+Pairs `before_tool_call` (to record start time) with `after_tool_call`+(to record the result). Stash the start time in `ctx.context.extra`.++```python+import time, logging+from cubepi import Middleware++log = logging.getLogger("cubepi.tools")+++class ToolLoggingMiddleware(Middleware):+ async def before_tool_call(self, ctx, *, signal=None):+ ctx.context.extra.setdefault("_tool_starts", {})[ctx.tool_call.id] = time.monotonic()+ return None++ async def after_tool_call(self, ctx, *, signal=None):+ started = ctx.context.extra.get("_tool_starts", {}).pop(ctx.tool_call.id, None)+ duration_ms = int((time.monotonic() - started) * 1000) if started else None+ log.info(+ "tool_call",+ extra={+ "tool_name": ctx.tool_call.name,+ "args": ctx.args.model_dump() if hasattr(ctx.args, "model_dump") else ctx.args,+ "is_error": ctx.is_error,+ "duration_ms": duration_ms,+ },+ )+ return None+```++`ctx.context.extra` is the right place to stash per-run state because+it's:++- Visible to other middleware via the same `ctx.context`.+- Persisted by checkpointers via `save_extra` at `agent_end`.+- Reset when a new conversation starts (a new `thread_id`).++## Sliding-window truncation++Keep the model's context bounded by retaining only the most recent N+messages, plus the system prompt:++```python+from cubepi import Middleware+++class SlidingWindow(Middleware):+ def __init__(self, max_messages: int = 20) -> None:+ self.max_messages = max_messages++ async def transform_context(self, messages, *, signal=None):+ if len(messages) <= self.max_messages:+ return messages+ return messages[-self.max_messages:]+```++`transform_context` doesn't touch `agent.state.messages` — the user+keeps seeing the full history. The model just sees the last N.++Pairs well with a `transform_system_prompt` that injects a summary of+what was dropped:++```python+class SummaryInjector(Middleware):+ async def transform_system_prompt(self, system_prompt, *, signal=None):+ summary = "Earlier in this conversation we discussed: …"+ return f"{system_prompt}\n\nContext: {summary}".strip()+```++## Max turns / budget cap++Hard-stop the agent after a maximum number of turns or a cost cap:++```python+class MaxTurns(Middleware):+ def __init__(self, max_turns: int) -> None:+ self.max_turns = max_turns+ self.turns = 0++ async def should_stop_after_turn(self, ctx):+ self.turns += 1+ return self.turns >= self.max_turns+++class BudgetCap(Middleware):+ def __init__(self, usd: float, model_cost) -> None:+ self.cap = usd+ self.cost = model_cost # cubepi.providers.ModelCost or similar+ self.spent = 0.0++ async def should_stop_after_turn(self, ctx):+ m = ctx.message+ if m.usage:+ self.spent += (+ (m.usage.input_tokens / 1_000_000) * self.cost.input+ + (m.usage.output_tokens / 1_000_000) * self.cost.output+ )+ return self.spent >= self.cap+```++## Structured output with `after_model_response`++Validate JSON output and re-prompt if it doesn't parse:++```python+import json+from cubepi import Middleware+from cubepi.middleware.base import TurnAction+from cubepi.providers.base import TextContent, UserMessage+++class JSONOutputValidator(Middleware):+ def __init__(self, schema_cls) -> None:+ self.schema = schema_cls++ async def after_model_response(self, response, ctx, *, signal=None):+ text = "".join(+ c.text for c in response.content if isinstance(c, TextContent)+ )+ try:+ obj = json.loads(text)+ self.schema.model_validate(obj)+ return None # valid — proceed naturally+ except Exception as e:+ return TurnAction(+ inject_messages=[+ UserMessage(content=[TextContent(text=f"Invalid output: {e}. Return valid JSON.")]),+ ],+ decision="loop_to_model",+ )+```++The agent will skip tool execution and immediately re-prompt the+model with the feedback message in context.++## 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.5/guides/middleware/hooks.md b/website/versioned_docs/version-0.5/guides/middleware/hooks.mdnew file mode 100644index 0000000..36f2019--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/middleware/hooks.md@@ -0,0 +1,205 @@+---+title: The 7 Hooks+---++# The 7 Hooks++`Middleware` is a class with up to seven optional async methods. Each+hook fires at a precise point in the agent loop. Implement only the+ones you need — CubePi only wires in the ones you override.++```python+from cubepi import Middleware++class MyMiddleware(Middleware):+ async def transform_context(self, messages, *, signal=None):+ ...+```++Pass instances to `Agent(middleware=[MyMiddleware(), …])`.++## `transform_context`++```python+async def transform_context(self, messages: list[Message], *, signal=None) -> list[Message]:+ ...+```++Fires **before each model call**, on the full message list. Use to:++- Truncate or summarise to fit context windows.+- Inject system reminders (better: use `transform_system_prompt`).+- Add or remove specific messages dynamically.++Return the (possibly new) list. **Don't mutate the input** — return a+new list so other code that holds the original isn't surprised.++Composition: chained — each middleware sees the previous one's+output.++## `convert_to_llm`++```python+async def convert_to_llm(self, messages: list[Message]) -> list[Message]:+ ...+```++Fires **right before serialisation** to the provider. This is the last+chance to reshape what the LLM sees. Use for:++- Stripping tool results to text-only.+- Replacing image content with text descriptions for non-multimodal+ providers.+- Compacting long tool outputs.++Composition: **last implementation wins** (not chained). Use this when+multiple middlewares would conflict and you want a single owner.++## `transform_system_prompt`++```python+async def transform_system_prompt(self, system_prompt: str, *, signal=None) -> str:+ ...+```++Fires **before each model call**, on the system prompt string. Use to:++- Inject runtime info (current time, user role).+- Compose modular system-prompt fragments.+- A/B test prompt variants.++Composition: chained.++## `before_tool_call`++```python+async def before_tool_call(self, ctx: BeforeToolCallContext, *, signal=None) -> BeforeToolCallResult | None:+ ...+```++Fires **per tool call**, after argument validation, before+`tool.execute`. The context provides:++- `ctx.assistant_message` — the message that initiated the call.+- `ctx.tool_call` — the `ToolCall` block.+- `ctx.args` — the *validated* Pydantic instance.+- `ctx.context` — the full `AgentContext`.++Return `BeforeToolCallResult(block=True, reason="…")` to short-circuit+— CubePi feeds the reason back as the tool result with+`is_error=True`. Return `None` (or no return) to proceed.++Use for: permissions, rate limiting, dry-run modes, sandboxing.++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.5/guides/providers/anthropic.md b/website/versioned_docs/version-0.5/guides/providers/anthropic.mdnew file mode 100644index 0000000..be42c2a--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/providers/anthropic.md@@ -0,0 +1,202 @@+---+title: Anthropic+---++# Anthropic Provider++`AnthropicProvider` wraps the official `anthropic` SDK against the+Messages API. It supports streaming, extended thinking, prompt+caching, and tool use.++## Construction++```python+from cubepi.providers.anthropic import AnthropicProvider++provider = AnthropicProvider(+ api_key="sk-ant-…", # or read from os.environ["ANTHROPIC_API_KEY"]+ base_url=None, # set to point at a proxy / Bedrock-compatible endpoint+ cache_retention="short", # "short" (5 min, default) | "long" (1 h) | "none"+)+```++`api_key=None` lets the underlying SDK read `ANTHROPIC_API_KEY` from+the environment.++## The `Model`++```python+from cubepi import Model++model = Model(+ id="claude-sonnet-4-5-20250929",+ provider="anthropic",+ reasoning=True, # enables thinking levels (see below)+ max_tokens=8192, # response cap+ context_window=200_000, # hard model limit+ temperature=0.7,+)+```++The `id` is the model name exactly as you'd pass it to the SDK. The+`provider` string is a free-form label used by CubePi internals — keep+it stable across your codebase but it doesn't have to match+`"anthropic"` literally.++## Extended thinking++CubePi maps a `ThinkingLevel` enum onto Anthropic's `budget_tokens`:++| Level | Default budget |+|---|---|+| `"off"` | thinking disabled |+| `"minimal"` | 1024 |+| `"low"` | 2048 |+| `"medium"` | 8192 |+| `"high"` | 16384 |+| `"xhigh"` | clamped to `"high"` |++Set it per-agent:++```python+agent = Agent(provider=provider, model=model, thinking="medium")+```++To change the per-level budgets, supply a+[`CapabilityDescriptor`](./capability-and-presets) with a+`reasoning_level` of `kind="int_budget"` at construction — its+`level_budgets` map is the single source of truth for budget values.++```python+from cubepi import CapabilityDescriptor, ReasoningLevelSpec+from cubepi.providers.anthropic import AnthropicProvider++provider = AnthropicProvider(+ api_key="sk-ant-…",+ capability=CapabilityDescriptor(+ reasoning_off_payload={"thinking": {"type": "disabled"}},+ reasoning_on_payload={"thinking": {"type": "enabled"}},+ reasoning_level=ReasoningLevelSpec(+ path="thinking.budget_tokens",+ kind="int_budget",+ level_budgets={"off": 0, "minimal": 1024, "low": 4096,+ "medium": 12288, "high": 16384, "xhigh": 16384},+ ),+ ),+)+```++:::note Changed in 0.5+`AnthropicProvider` no longer honors+`StreamOptions(thinking_budgets=…)` — the capability descriptor's+`level_budgets` is now the only way to override budgets.+:::++When thinking is on, CubePi **omits `temperature`** because the+Anthropic API rejects non-default temperatures alongside extended+thinking ([feature compatibility](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#feature-compatibility)).+Set `Model.temperature` to the value you want when thinking is off;+CubePi handles the rest.++Thinking content streams as `thinking_start` / `thinking_delta` /+`thinking_end` events and ends up in `AssistantMessage.content` as+`ThinkingContent` blocks, preserved on subsequent turns so the model+keeps continuity.++## Prompt caching++By default the provider marks three cache breakpoints on each request:++- The **system prompt** (most stable).+- The **last tool definition** (changes rarely).+- The **last message** (the cache moves forward each turn so prior+ history stays warm).++Cache retention is `"short"` (5 minutes, free). Bump to `"long"` if+your turns are slower than that:++```python+AnthropicProvider(api_key=…, cache_retention="long") # 1-hour TTL+AnthropicProvider(api_key=…, cache_retention="none") # disable entirely+```++The `Usage` object on each `AssistantMessage` reports+`cache_read_tokens` and `cache_write_tokens` so you can see your hit+rate.++For custom cache strategies (a different breakpoint policy), implement+the `CacheMarkerPolicy` Protocol and pass `cache_policy=…`. The+default policy lives at `cubepi.providers.anthropic.DefaultCacheMarkerPolicy`.++## Custom payloads with `on_payload`++`on_payload` lets you inspect or replace the request dict right before+it's sent:++```python+async def my_payload(payload, model):+ payload.setdefault("metadata", {})["user_id"] = "u-42"+ return payload # return None or no return to keep the original++agent = Agent(provider=provider, model=model, on_payload=my_payload)+```++Use this for: adding `metadata.user_id` (for billing), forcing+beta-header flags, or tracking the exact payloads you sent for a+debug pane.++## Custom response handling with `on_response`++`on_response` fires after the HTTP response is received (status,+headers), before streaming begins:++```python+async def my_response(resp, model):+ if resp.status >= 400:+ logger.warning("bad status %s", resp.status)+ rate = resp.headers.get("anthropic-ratelimit-requests-remaining")+ if rate is not None:+ metrics.gauge("rate_remaining", int(rate))++agent = Agent(provider=provider, model=model, on_response=my_response)+```++Both callbacks may be sync or async.++## Pointing at Bedrock / Vertex / proxies++The Anthropic SDK accepts a `base_url`; CubePi forwards it:++```python+provider = AnthropicProvider(+ api_key="…",+ base_url="https://my-litellm.internal/v1",+)+```++For Bedrock specifically, use the `anthropic-bedrock` adapter directly+and inject it via a [custom provider](./custom).++## Common pitfalls++- **`temperature` ignored** — Expected. CubePi drops it when thinking+ is on; that's an API constraint, not a bug.+- **`xhigh` looks the same as `high`** — Anthropic doesn't expose a+ budget tier above `high`, so CubePi clamps `xhigh` down. The token+ budget is the same.+- **Cache misses you didn't expect** — Caches are keyed by content ++ ttl. Changing the system prompt invalidates everything; changing the+ tool list invalidates from the tools onward. Make those two stable+ across turns to maximise hits.+- **`anthropic.RateLimitError`** — Propagates as a stream error event+ with the SDK's `str(exc)`. Catch in `agent_end` and decide whether+ to retry.++## See also++- [OpenAI Provider](./openai) — same protocol, different shape.+- [Capabilities & Preset Catalog](./capability-and-presets) — tune+ reasoning budgets and temperature handling as data.+- [Custom Provider](./custom) — wrap a non-built-in API.+- [Recipes → Multi-Provider Failover](../../recipes/multi-provider-failover)+ — fall back to OpenAI when Anthropic is down.diff --git a/website/versioned_docs/version-0.5/guides/providers/capability-and-presets.md b/website/versioned_docs/version-0.5/guides/providers/capability-and-presets.mdnew file mode 100644index 0000000..3c1085c--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/providers/capability-and-presets.md@@ -0,0 +1,192 @@+---+title: Capability Descriptors+---++# Capability Descriptors++_Capability descriptors added in cubepi `0.5`._++This page is about reaching **any** model — the big SaaS APIs, a regional+endpoint, a coding-plan tier, or your own vLLM box — without writing+per-vendor glue. The progression is deliberate:++1. **The default is zero config.** For Anthropic and OpenAI you write a+ provider and a model. Nothing on this page is required.+2. **For an off-default endpoint, describe the quirks as data.** A+ `CapabilityDescriptor` captures the differences declaratively — no+ subclassing, no forking.++:::note Preset catalogs live in the host application+cubepi ships the **mechanism** (the `CapabilityDescriptor` and the wire+runtime that applies it), not a catalog of vendors. A ready-made list of+providers — base URLs, auth, regional/coding-plan endpoints, model lists —+is product data and belongs to the application embedding cubepi (for+example, cubebox maintains its own provider catalog). To reach a specific+vendor, build the provider with the right `base_url` + `CapabilityDescriptor`+as shown below.+:::++## 1. The simple case — no config at all++Most users never touch capabilities. The built-in providers ship with+sensible defaults:++```python+import cubepi+from cubepi import Agent, Model+from cubepi.providers.anthropic import AnthropicProvider++agent = Agent(+ provider=AnthropicProvider(), # reads ANTHROPIC_API_KEY+ model=Model(id="claude-sonnet-4-6", provider="anthropic"),+)+await agent.prompt("Hello!")+```++That's the whole setup. A provider built without `capability=` produces+byte-identical output to cubepi `0.4` — the machinery below only kicks in+when you ask for it.++## 2. Off-default endpoints — the CapabilityDescriptor++When you want a model that isn't OpenAI or Anthropic — DeepSeek, Qwen,+Doubao, an OpenRouter route, a local server — the awkward part is each+one's wire dialect (does it want `max_tokens` or `max_completion_tokens`?+how is reasoning toggled?). You don't subclass a provider; you describe the+quirks as a [`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html)+and pass it in, along with the right `base_url` and provider class for the+endpoint's wire shape:++```python+import os+from cubepi import CapabilityDescriptor+from cubepi.providers.openai import OpenAIProvider++provider = OpenAIProvider(+ api_key=os.environ["DEEPSEEK_API_KEY"],+ base_url="https://api.deepseek.com",+ capability=CapabilityDescriptor(+ reasoning_off_payload={"extra_body": {"reasoning": {"exclude": True}}},+ reasoning_on_payload={"extra_body": {"reasoning": {"exclude": False}}},+ ),+)+```++Pick the provider class by the endpoint's wire dialect:++| Wire dialect | Provider class |+| --- | --- |+| `anthropic-messages` | `AnthropicProvider` |+| `openai-completions` | `OpenAIProvider` |+| `openai-responses` | `OpenAIResponsesProvider` |++Each field maps to one wire behavior, and an unset field does nothing — so+you only declare what's actually different.++### `max_tokens_field`++`"max_tokens"` (default) or `"max_completion_tokens"`. Some+OpenAI-compatible servers accept only one spelling; this renames the key+on the way out. **Effect:** wrong choice → the server ignores your output+cap or 400s.++### `temperature`++A `TemperatureSpec` controlling how the caller's temperature is treated:++```python+from cubepi import TemperatureSpec++TemperatureSpec(mode="free", min=0.0, max=2.0, default=1.0) # clamp into [min, max]+TemperatureSpec(mode="fixed", fixed_value=1.0) # always overwrite+TemperatureSpec(mode="ignored") # drop the key+```++- **`free`** — the caller's value is clamped into `[min, max]`; if none was+ sent, nothing is written. **Effect:** protects against an out-of-range+ value the backend would reject.+- **`fixed`** — `fixed_value` always wins. **Effect:** use for models that+ permit only one temperature (e.g. some o-series reasoning models).+- **`ignored`** — the key is stripped entirely. **Effect:** for backends+ that 400 on any `temperature` while reasoning.++### Reasoning toggle: `reasoning_off_payload` / `reasoning_on_payload`++When thinking is off, `reasoning_off_payload` is deep-merged into the+request; when it's on, `reasoning_on_payload` is. **Effect:** this is how+"turn reasoning on/off" becomes whatever field the vendor expects:++```python+CapabilityDescriptor(+ reasoning_off_payload={"extra_body": {"enable_thinking": False}},+ reasoning_on_payload={"extra_body": {"enable_thinking": True}},+)+```++The merge recurses into nested dicts; arrays are atomic; on a collision+the capability value wins.++### Reasoning level: `reasoning_level` (three shapes)++Beyond on/off, cubepi maps a `ThinkingLevel`+(`off`/`minimal`/`low`/`medium`/`high`/`xhigh`) onto a concrete wire value+written at a dotted `path`. `kind` picks the shape:++```python+from cubepi import ReasoningLevelSpec++# int_budget — a token budget (Anthropic).+ReasoningLevelSpec(+ path="thinking.budget_tokens", kind="int_budget",+ level_budgets={"off": 0, "minimal": 1024, "low": 2048,+ "medium": 8192, "high": 16384, "xhigh": 16384},+)++# effort — an effort string (OpenAI Responses).+ReasoningLevelSpec(+ path="reasoning.effort", kind="effort",+ level_to_effort={"minimal": "minimal", "low": "low",+ "medium": "medium", "high": "high", "xhigh": "high"},+)++# enum — a vendor-specific state (Doubao's 3-state thinking).+ReasoningLevelSpec(+ path="thinking.type", kind="enum",+ level_to_enum={"off": "disabled", "low": "enabled", "high": "enabled"},+)+```++**Effect:** a level missing from the map is simply not written, so the+endpoint keeps its own default for that level.++### `supports_tools` / `supports_images` / `supports_streaming`++Declarative flags read by host applications and frontends (for example, to+grey out image upload). The providers themselves don't gate on them.++### Per-model overrides on a shared endpoint++One gateway (OpenRouter, LiteLLM, an internal proxy) often serves both+reasoning and non-reasoning models. `model_capability_overrides` maps a+`model_id` to a descriptor that **replaces** the base one for that model:++```python+provider = OpenAIProvider(+ api_key="…",+ base_url="https://openrouter.ai/api/v1",+ capability=base_cap, # default for unlisted models+ model_capability_overrides={+ "deepseek/deepseek-r1": reasoning_cap, # this model only+ },+)+```++Resolution is exact-match on `model_id`; anything not listed falls back to+`capability`.++## See also++- [OpenAI Provider](./openai) — concrete OpenAI / OpenAI-compatible setup.+- [Anthropic Provider](./anthropic) — the `int_budget` reasoning shape in practice.+- [Writing a Custom Provider](./custom) — when the endpoint isn't even OpenAI/Anthropic-shaped.+- [API Reference → `cubepi.providers`](../../api/cubepi-providers).diff --git a/website/versioned_docs/version-0.5/guides/providers/custom.md b/website/versioned_docs/version-0.5/guides/providers/custom.mdnew file mode 100644index 0000000..3bfd97d--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/providers/custom.md@@ -0,0 +1,239 @@+---+title: Writing a Custom Provider+---++# Writing a Custom Provider++A provider is any class with one method:++```python+class Provider(Protocol):+ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ options: StreamOptions | None = None,+ ) -> MessageStream: ...+```++That's the whole interface. Implement it and `Agent(provider=…)`+accepts your class.++This page covers two scenarios:++1. **A new real provider** — Bedrock, Vertex, Replicate, an internal+ LLM gateway, …+2. **`FauxProvider`** — the built-in deterministic provider that's+ essential for unit tests.++## A minimal real provider++The pattern: create a `MessageStream`, kick off a producer task that+pushes events into it, return the stream immediately.++```python+import asyncio+import time+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ MessageStream,+ Model,+ StreamEvent,+ StreamOptions,+ TextContent,+ ToolDefinition,+ Usage,+)+++class MyProvider:+ def __init__(self, *, api_key: str) -> None:+ self._api_key = api_key++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ options: StreamOptions | None = None,+ ) -> MessageStream:+ opts = options or StreamOptions()+ ms = MessageStream()++ async def _produce():+ try:+ partial = AssistantMessage(+ content=[TextContent(text="")],+ usage=Usage(),+ timestamp=time.time(),+ provider_id=model.provider,+ model_id=model.id,+ )+ ms.push(StreamEvent(type="start", partial=partial.model_copy(deep=True)))++ # Call your backend. Stream tokens:+ async for token in call_my_backend(messages, model.id, signal=opts.signal):+ if opts.signal and opts.signal.is_set():+ ms.push(StreamEvent(type="error", error_message="aborted"))+ ms.set_result(partial.model_copy(update={"stop_reason": "aborted"}))+ return+ partial.content[-1] = TextContent(text=partial.content[-1].text + token)+ ms.push(StreamEvent(+ type="text_delta",+ delta=token,+ partial=partial.model_copy(deep=True),+ ))++ ms.push(StreamEvent(type="done"))+ ms.set_result(partial)++ except Exception as exc:+ error_msg = AssistantMessage(+ content=[],+ stop_reason="error",+ error_message=str(exc),+ usage=Usage(),+ timestamp=time.time(),+ )+ ms.push(StreamEvent(type="error", error_message=str(exc)))+ ms.set_result(error_msg)++ ms.attach_task(asyncio.create_task(_produce()))+ return ms+```++Things to get right:++1. **Always push `start` first.** Subscribers count on it for UI+ bootstrapping.+2. **Always end with `done` or `error`.** The agent loop waits on the+ `MessageStream` until one of those arrives.+3. **Always call `ms.set_result(...)`** so `await stream.result()` can+ complete. Even on error.+4. **`ms.attach_task(...)` is required** if the producer is its own+ task — it wires the task's exception state into the stream so a+ crash surfaces as `error`, not a hang.+5. **Respect `opts.signal`.** Check it inside your read loop; emit an+ `aborted` stop_reason so the agent can shut down cleanly.++## Supporting tool calls++If your model emits tool calls, append `ToolCall` blocks to+`partial.content` as they stream in and emit `toolcall_start` /+`toolcall_delta` / `toolcall_end`:++```python+from cubepi.providers.base import ToolCall++tc = ToolCall(id=block_id, name=tool_name, arguments={})+partial.content.append(tc)+ms.push(StreamEvent(type="toolcall_start", content_index=len(partial.content)-1,+ partial=partial.model_copy(deep=True)))+# ... as JSON args arrive:+ms.push(StreamEvent(type="toolcall_delta", delta=partial_json_chunk, …))+# ... on completion:+# replace tc.arguments with the parsed dict, push toolcall_end+```++CubePi's agent loop will dispatch the tool calls automatically once+`done` is emitted.++## Hooking `on_payload` / `on_response`++If your provider sends an HTTP request, call the helpers in+`cubepi.providers.base`:++```python+from cubepi.providers.base import (+ ProviderResponse,+ invoke_on_payload,+ invoke_on_response,+)++payload = await invoke_on_payload(opts.on_payload, payload, model)+http_resp = await self._client.post(..., json=payload)+await invoke_on_response(+ opts.on_response,+ ProviderResponse(status=http_resp.status_code, headers=dict(http_resp.headers)),+ model,+)+```++This mirrors what built-in providers do; your users get the same+inspection points for free.++## Using `FauxProvider` in tests++CubePi ships `FauxProvider` for deterministic tests — no network, no+flakiness, real streaming events:++```python+from cubepi import Agent, Model+from cubepi.providers import FauxProvider, faux_assistant_message, faux_text, faux_tool_call+++def test_my_agent():+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message([+ faux_tool_call("search", {"query": "python"}),+ ]),+ faux_assistant_message("Here are the results: …"),+ ])++ agent = Agent(+ provider=provider,+ model=Model(id="test", provider="faux"),+ tools=[my_search_tool],+ )+ events = []+ agent.subscribe(lambda e, signal=None: events.append(e))+ await agent.prompt("Search for python")++ assert any(e.type == "tool_execution_start" for e in events)+ assert events[-1].type == "agent_end"+```++`set_responses` is a FIFO queue: each model call pops one. The faux+provider replays it with realistic deltas (token-by-token), so your+streaming code paths actually exercise.++Helpers:++- `faux_text("Hello!")` — wraps a string into a `TextContent` block.+- `faux_thinking("Pondering…")` — a `ThinkingContent` block.+- `faux_tool_call("name", {"arg": …})` — a `ToolCall` block.+- `faux_assistant_message(content_or_text)` — builds a complete+ `AssistantMessage`.++## Common pitfalls++- **Missing `start` event** — Subscribers don't see the partial+ message. Always push it first.+- **Forgot `ms.set_result(...)`** — `await agent.prompt()` hangs+ forever. Set the result on both happy and error paths.+- **Synchronous `produce`** — `stream()` must return *immediately* —+ do the work inside the task. If you `await` your backend before+ `return ms`, you've blocked the caller.+- **Modifying `partial` after pushing** — Push `deep=True` copies; the+ caller iterates events asynchronously, and a mutation during+ iteration creates very hard-to-debug aliasing.++## See also++- [Capabilities & Preset Catalog](./capability-and-presets) — before+ writing a class from scratch, check whether your backend is just an+ OpenAI/Anthropic-compatible endpoint a `CapabilityDescriptor` or+ bundled preset already covers.+- [API Reference → providers/base](../../api/cubepi-providers) — the+ full type list.+- [Anthropic Provider source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/anthropic.py)+ — a real, complete example.+- [`FauxProvider` source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/faux.py)+ — the testing primitive, including stream-realism details.diff --git a/website/versioned_docs/version-0.5/guides/providers/openai.md b/website/versioned_docs/version-0.5/guides/providers/openai.mdnew file mode 100644index 0000000..06bb3bd--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/providers/openai.md@@ -0,0 +1,187 @@+---+title: OpenAI+---++# OpenAI Provider++CubePi ships two OpenAI providers covering the two API surfaces:++- **`OpenAIProvider`** — Chat Completions API+ (`/v1/chat/completions`). Use this for the GPT-4/5 family and most+ OpenAI-compatible servers (vLLM, LiteLLM, DeepSeek, Qwen, MiniMax,+ DouBao, …).+- **`OpenAIResponsesProvider`** — Responses API+ (`/v1/responses`). Use this when you want server-side state and+ reasoning summaries.++Both implement the same `Provider` protocol; pick one per agent.++## Chat Completions: `OpenAIProvider`++```python+from cubepi import Model+from cubepi.providers.openai import OpenAIProvider++provider = OpenAIProvider(+ api_key="sk-…", # or reads OPENAI_API_KEY+ base_url=None, # set for OpenAI-compatible servers+ extra_body=None, # merged into every request+ extra_headers=None,+)++model = Model(+ id="gpt-5",+ provider="openai",+ reasoning=True, # enables thinking level mapping+ max_tokens=8192,+ context_window=128_000,+)+```++### Thinking on Chat Completions++OpenAI exposes reasoning content through `delta.reasoning_content` on+o-series and gpt-5 models. CubePi captures it as `ThinkingContent` and+emits `thinking_*` events identically to Anthropic. The same+`ThinkingLevel` enum (`"off"` → `"high"`) works.++Many OpenAI-compatible OSS backends emit reasoning under different+fields. CubePi understands three in priority order:++1. `delta.reasoning_content` (DeepSeek, Qwen, DouBao)+2. `delta.reasoning` (vLLM)+3. `delta.reasoning_details` (MiniMax)++No configuration needed — the provider picks whichever field is+present.++### `extra_body` for OSS quirks++Most OpenAI-compatible servers accept extensions through the request+body. Set them once at construction:++```python+provider = OpenAIProvider(+ api_key="…",+ base_url="https://api.deepseek.com/v1",+ extra_body={"enable_thinking": True, "stream_options": {"include_usage": True}},+)+```++If you need per-request mutation, use `on_payload` (see below).++### Capability descriptor++Wire-shape differences between OpenAI and OpenAI-compatible backends+(e.g. `max_tokens` vs `max_completion_tokens`, reasoning field names,+temperature handling) are configured through a+[`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html)+passed at construction. For example, `max_tokens_field="max_completion_tokens"`+renames the key on the way out. See+[Capability Descriptors](./capability-and-presets) for the full set of+knobs (cubepi `0.5+`).++### Pointing at vLLM / LiteLLM / DeepSeek++```python+provider = OpenAIProvider(+ api_key="dummy", # vLLM ignores it+ base_url="http://localhost:8000/v1",+ extra_headers={"Authorization": "Bearer dummy"},+)+```++For LiteLLM:++```python+provider = OpenAIProvider(+ api_key=os.environ["LITELLM_KEY"],+ base_url="https://litellm.internal/v1",+)+```++For the wire quirks of these backends (reasoning toggles, token-field+renames, …), see [Capability Descriptors](./capability-and-presets).++## Responses API: `OpenAIResponsesProvider`++```python+from cubepi.providers.openai_responses import OpenAIResponsesProvider++provider = OpenAIResponsesProvider(api_key="sk-…")+model = Model(id="gpt-5", provider="openai_responses", reasoning=True)+```++The Responses API keeps state server-side (referenced by+`previous_response_id`). CubePi tracks `AssistantMessage.response_id`+and feeds it back automatically — your code looks identical to the+Chat Completions path.++Use the Responses provider when:++- You want reasoning **summaries** (not just text) surfaced as+ thinking blocks.+- You're using the `o`-series and want the server to hold the+ reasoning chain across turns (smaller payloads, faster reuse).++Stay on `OpenAIProvider` when you want full control over the message+list and prompt caching strategy.++## `on_payload` / `on_response`++Same shape as the [Anthropic](./anthropic) provider. The payload dict+differs (`messages` instead of `messages` + `system` separately,+OpenAI-style `tools` schema), so inspect it once before mutating.++```python+async def add_user_metadata(payload, model):+ payload["user"] = "u-42" # billable user attribution+ return payload++agent = Agent(provider=provider, model=model, on_payload=add_user_metadata)+```++## Tool calling++Tool definitions are auto-converted to OpenAI's+`{"type": "function", "function": {...}}` shape. The streaming format+emits incremental JSON arguments under `toolcall_delta`; CubePi+buffers and parses them through+[`cubepi.utils.json_parse.parse_streaming_json`](../../api/cubepi-utils)+so partials always validate to the closest well-formed object.++Multiple parallel tool calls in one assistant message just work —+they're routed through the same parallel executor as the Anthropic+provider.++## Common pitfalls++- **`stream_options.include_usage` rejected** — Some compatibles+ reject the whole `stream_options` field. **`on_payload` cannot fix+ this**: cubepi 0.3 calls `kwargs.setdefault("stream_options", {})`+ *after* your callback runs, so deleting the key in `on_payload` is+ silently undone. Workarounds:+ - Subclass `OpenAIProvider` and override `stream()` to skip the+ `setdefault` for your backend.+ - Set `include_usage=False` in `on_payload` (the field still goes+ out, but is usually accepted as a no-op even by strict+ backends).+ - Use a [`CapabilityDescriptor`](./capability-and-presets) (cubepi+ `0.5+`) to describe your backend's reasoning wiring declaratively.+- **Thinking events but no `thinking_*` events** — Your backend+ surfaces reasoning under a non-standard field. Either add a fourth+ branch via PR or transcode it with `on_payload`.+- **Mixed providers in one process** — Each provider holds its own+ HTTP client. Reuse a single instance per `(base_url, api_key)`+ pair instead of creating one per agent.+- **Usage shows 0 input tokens** — Most compatibles omit usage+ entirely or only emit it on the final chunk. Inspect the trailing+ chunk in `on_payload` for a hint, or treat token counts as+ best-effort on those backends.++## See also++- [Anthropic Provider](./anthropic) — the other built-in.+- [Custom Provider](./custom) — write your own from scratch.+- [Recipes → Multi-Provider Failover](../../recipes/multi-provider-failover)+ — combine both providers for resilience.diff --git a/website/versioned_docs/version-0.5/guides/tracing/content-recording.md b/website/versioned_docs/version-0.5/guides/tracing/content-recording.mdnew file mode 100644index 0000000..220102d--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/tracing/content-recording.md@@ -0,0 +1,128 @@+---+title: Content & Redaction+sidebar_position: 4+---++# Recording Prompts, Responses, and Tool Payloads++By default cubepi's tracing emits structural attributes only — operation+names, models, token counts, finish reasons, durations. **No prompt content,+no model output, no tool arguments or results leave the process.** This is+deliberate: many agent setups handle PII, customer data, or trade-secret+prompts that don't belong in a third-party observability backend.++When you _do_ want content captured — for offline evaluation, debugging a+flaky tool call, or building a labelled dataset — opt in explicitly with+`record_content=True`, and combine it with a `redact` callback to strip the+sensitive parts before they leave the process.++## Turning content recording on++```python+tracer = Tracer(+ service_name="my-bot",+ agent_name="assistant",+ record_content=True, # ← opt-in+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+)+```++With `record_content=True`, each span layer carries the relevant content+attributes per the OTel GenAI semconv:++| Span | Content attributes added |+|---|---|+| `invoke_agent` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.output.messages` |+| `cubepi.turn` | `gen_ai.input.messages` (per-turn slice), `gen_ai.output.messages` (per-turn slice) |+| `chat <model>` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.tool.definitions`, `cubepi.llm.raw_request`, `cubepi.llm.raw_response` |+| `execute_tool <tool_name>` | `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result` |++The `chat` span's `gen_ai.input.messages` contains the **full chronological+context** the provider request actually carried — including prior assistant+turns and tool results — not just the new user prompt. This matters for+multi-turn tool-using runs: trace consumers can reconstruct exactly what+the model saw at each call.++## Redacting before export++`redact` is a `(key, value) -> value | None` callback invoked at every+content-attribute set site. Return:++- The original value unchanged → keep as-is+- A modified value of the same shape → substitute+- `None` → drop the attribute entirely++```python+def redact(key: str, value):+ # Strip secrets from prompts before they leave the process.+ if key in ("gen_ai.input.messages", "gen_ai.output.messages"):+ return _scrub_messages(value)+ # Don't ship raw bodies at all in prod — keep only the normalised shape.+ if key in ("cubepi.llm.raw_request", "cubepi.llm.raw_response"):+ return None+ return value+++tracer = Tracer(+ service_name="my-bot",+ record_content=True,+ redact=redact,+ exporters=[…],+)+```++`redact` is the single chokepoint for content — the recorder calls it once+per attribute before serializing into the OTel attribute, so anything the+function returns is what hits the wire. Exceptions inside `redact` are+swallowed (the attribute is dropped in that case), so a buggy redactor+fails closed rather than leaking.++### Common patterns++Drop everything but per-message length so dashboards still work without+shipping content:++```python+def redact(key, value):+ if key in ("gen_ai.input.messages", "gen_ai.output.messages"):+ return [{"role": m["role"], "parts": [{"type": "text", "content": "<redacted>",+ "length": sum(len(p.get("content", "")) for p in m["parts"])}]}+ for m in value]+ return value+```++Tag-based selective recording — strip everything unless a thread is opted in:++```python+import contextvars+RECORD = contextvars.ContextVar("trace.record_content", default=False)++def redact(key, value):+ return value if RECORD.get() else None+```++then `RECORD.set(True)` for the runs you want captured.++## Size budgets++OTel attribute values are JSON-serialized inside the recorder. Most backends+truncate or reject attributes over a few hundred KB. If you're recording+the raw provider response on every chat span, multi-turn agentic runs can+get large fast. Drop or summarise via `redact` for any field over your+budget.++## Auditing what's recorded++The recorder always sets `service.name`, `gen_ai.agent.name`, and+`cubepi.run_id` on every span — regardless of `record_content`. Use these+to filter the trace backend to a single run and visually confirm what+landed.++For deeper audits, `JsonlSpanExporter` writes one line per span, so you can+grep / `jq` the local files before pointing the same exporter at a remote+backend:++```bash+jq -r 'select(.attributes["gen_ai.input.messages"]) | .attributes["gen_ai.input.messages"]' \+ cubepi-traces/2026-05-19/*.jsonl+```diff --git a/website/versioned_docs/version-0.5/guides/tracing/getting-started.md b/website/versioned_docs/version-0.5/guides/tracing/getting-started.mdnew file mode 100644index 0000000..a68387a--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/tracing/getting-started.md@@ -0,0 +1,227 @@+---+title: Getting Started+sidebar_position: 2+---++# Getting Started with Tracing++## Install the extra++CubePi keeps OpenTelemetry an optional dependency:++```bash+pip install "cubepi[tracing]"+```++This pulls in `opentelemetry-sdk` and friends. Without the extra, the+`cubepi.tracing` import raises a clear error so you find out at import time+rather than mid-run.++## Attach a Tracer++The minimal end-to-end setup — local JSONL export, idiomatic RAII:++```python+import asyncio+from cubepi import Agent, Model+from cubepi.providers.anthropic import AnthropicProvider+from cubepi.tracing import Tracer+from cubepi.tracing.exporters import JsonlSpanExporter+++async def main() -> None:+ agent = Agent(+ provider=AnthropicProvider(api_key="…"),+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="Be helpful.",+ )++ async with (+ Tracer(+ service_name="my-bot",+ agent_name="assistant",+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ ) as tracer,+ tracer.attached(agent),+ ):+ await agent.prompt("Say hello.")+ await agent.wait_for_idle()+ # On exit: auto-detach (closes any cancelled-run spans, awaits the+ # flush) + tracer shutdown (flushes + closes exporters). No+ # try/finally needed.+++asyncio.run(main())+```++If you can't restructure into an `async with` (e.g. long-lived web+handler that hands the agent around), the explicit pattern still+works and is fully equivalent:++```python+detach = tracer.attach(agent)+try:+ await agent.prompt("…")+finally:+ # Either is enough on its own:+ # await detach() # awaits the scheduled flush+ # await tracer.shutdown() # flushes + closes exporters+ detach()+ await tracer.shutdown()+```++Even if you forget the cleanup entirely, `Tracer` registers an+`atexit` hook by default that sync-flushes buffered spans at process+exit — pass `atexit_flush=False` to opt out, or rely on it as a+safety net while you're still building. (Doesn't run on `SIGKILL` or+`os._exit`; for guaranteed delivery there, use the synchronous+`SimpleSpanProcessor` from OTel.)++The run produces one JSONL file per agent run:++```text+./cubepi-traces/+ 2026-05-19/+ 8e1c…-…-…-….jsonl ← one run, one file, one span per line+```++Open it with any tool that reads OTLP/JSON or with `jq` directly:++```bash+jq -r '"\(.name) \(.attributes."gen_ai.operation.name" // "")"' \+ cubepi-traces/2026-05-19/*.jsonl+# invoke_agent invoke_agent+# cubepi.turn+# chat claude-sonnet-4-5-20250929 chat+```++## Span hierarchy++For a single prompt with one LLM round-trip, the recorder produces three spans:++```text+invoke_agent assistant [INTERNAL] gen_ai.operation.name=invoke_agent+└── cubepi.turn [INTERNAL] cubepi.turn.index=0+ └── chat <model> [CLIENT] gen_ai.operation.name=chat+```++When the model calls a tool, you get an extra layer per tool:++```text+invoke_agent assistant+└── cubepi.turn ← turn index 0+ ├── chat <model> ← first round trip+ └── execute_tool <tool_name> ← gen_ai.tool.name, gen_ai.tool.call.id+└── cubepi.turn ← turn index 1 (response after tool result)+ └── chat <model>+```++For MCP tools the `execute_tool` span gets a CLIENT child:++```text+execute_tool <tool_name> [INTERNAL] cubepi-side wrapper+└── tools/call <tool_name> [CLIENT] gen_ai.operation.name=execute_tool+ mcp.method.name=tools/call+ mcp.session.id=…+ server.address / server.port+```++The CLIENT span injects W3C `traceparent` into outgoing HTTP headers, so an+instrumented MCP server can continue the trace.++## Cancellation, errors, aborts++The recorder treats cancellation as a control signal, not a failure:++- `agent.abort()` mid-stream → spans close with `cubepi.aborted=true` and+ `error.type=cubepi.aborted`, **status UNSET** (per OTel guidance — cancellation+ isn't an error).+- A provider raising → chat/turn/root close with **status ERROR**, an+ `exception` event on the chat span, and `error.type` derived from the+ exception class (`timeout`, `connection_error`, fully-qualified class name, …).+- An MCP `tools/call` returning `isError=true` → CLIENT span closes+ ERROR + `error.type=mcp.is_error`.++Either way, `detach()` and `tracer.shutdown()` always close any span the run+left open, so cancelled runs are still visible in your backend rather than+silently disappearing.++## What's on each span++Defaults (no opt-in needed):++- `invoke_agent` (root) — `gen_ai.operation.name`, `gen_ai.provider.name`,+ `gen_ai.agent.name`, `cubepi.run_id`, `cubepi.agent.system_prompt.sha256`,+ `cubepi.agent.tools` (names list), `cubepi.input_messages.count`,+ `cubepi.output_messages.count`+- `cubepi.turn` — `cubepi.turn.index`, `cubepi.turn.stop_reason`,+ `cubepi.turn.tool_calls.count`, `cubepi.turn.terminated_by_tool`,+ `cubepi.run_id`+- `chat <model>` — `gen_ai.operation.name`, `gen_ai.provider.name`,+ `gen_ai.request.model`, `gen_ai.request.max_tokens` / `temperature` /+ `top_p`, `gen_ai.request.stream`, `gen_ai.usage.input_tokens` /+ `output_tokens` / `cache_read_input_tokens` / `cache_creation_input_tokens` /+ `reasoning_output_tokens`, `gen_ai.response.model` /+ `finish_reasons` / `id`, `gen_ai.response.time_to_first_chunk`, plus+ OpenAI-specific extras (`openai.api.type`, service tier, system fingerprint)+- `execute_tool <tool_name>` — `gen_ai.operation.name=execute_tool`,+ `gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.description`,+ `gen_ai.tool.type`, `cubepi.tool.is_error`, `cubepi.tool.execution_mode`+- `tools/call <tool_name>` (MCP only) — `mcp.method.name`, `mcp.session.id`,+ `mcp.protocol.version`, `server.address`, `server.port`, `gen_ai.tool.name`++Optional, opt-in via `Tracer(record_content=True)`:+`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`,+`gen_ai.tool.definitions`, `gen_ai.tool.call.arguments`,+`gen_ai.tool.call.result`, `cubepi.llm.raw_request`,+`cubepi.llm.raw_response`. See [Content & Redaction](./content-recording).++## Multiple agents, one process++Both `Tracer` and `Meter` are fine to share across agents — call+`attach(agent)` multiple times. Each attach gets its own recorder /+metric state so concurrent agents don't share span or histogram state,+and MCP CLIENT spans route through the right Tracer based on which+agent's `execute_tool` span is the parent.++With the RAII helper, stacking them is one `async with`:++```python+async with (+ Tracer(...) as tracer,+ tracer.attached(agent_a),+ tracer.attached(agent_b),+):+ await asyncio.gather(agent_a.prompt("…"), agent_b.prompt("…"))+```++## Tagging individual runs++`cubepi.tracing.tracing_context` scopes per-run tags / metadata onto+the `invoke_agent` span — perfect for `user_id`, `session_id`,+A/B-test arm, anything you'd want to filter by in the backend later:++```python+from cubepi.tracing import tracing_context++async with tracer.attached(agent):+ with tracing_context(tags=["beta-arm"], metadata={"user_id": "u-42"}):+ await agent.prompt("Hello.")+```++Attributes on the span:++- `cubepi.tags = ("beta-arm",)`+- `cubepi.metadata.user_id = "u-42"`++The `cubepi.metadata.*` prefix keeps user keys from clobbering+recorder-owned schema (e.g. `cubepi.run_id`). Tags and metadata+contextvars are per-asyncio-task, so concurrent agents see+independent values, and nested `tracing_context` blocks merge+(tags concatenate, metadata keys union with inner winning).++## Next++- [OTLP & Backends](./otlp) — Jaeger, Tempo, Honeycomb, Datadog, …+- [Content Recording & Redaction](./content-recording)+- [Metrics](./metrics)diff --git a/website/versioned_docs/version-0.5/guides/tracing/metrics.md b/website/versioned_docs/version-0.5/guides/tracing/metrics.mdnew file mode 100644index 0000000..948e811--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/tracing/metrics.md@@ -0,0 +1,152 @@+---+title: Metrics+sidebar_position: 5+---++# Metrics with `Meter`++Spans tell you the shape of one run; histograms tell you the shape of the+fleet. `cubepi.tracing.Meter` mirrors `Tracer` and emits the OTel GenAI+metric set so dashboards work out of the box.++## What it emits++| Instrument | Description |+|---|---|+| `gen_ai.client.operation.duration` | Histogram (seconds) — recorded for `chat`, `execute_tool`, and `invoke_agent` on close |+| `gen_ai.client.operation.time_to_first_chunk` | Histogram (seconds) — recorded for `chat` when at least one content chunk arrived |+| `gen_ai.client.token.usage` | Histogram (`{token}`) — one observation per `gen_ai.token.type` (`input`, `output`) per chat response |++Each point carries the operation, provider, and request model attributes+so failed / cancelled requests (where no response body / response model+landed) are still groupable by what was asked for:++- `gen_ai.operation.name` — `chat` / `execute_tool` / `invoke_agent`+- `gen_ai.provider.name` — `anthropic`, `openai`, `openai_responses`, …+- `gen_ai.request.model` — e.g. `claude-sonnet-4-5-20250929`+- `gen_ai.response.model` — e.g. `claude-sonnet-4-5-20250929` (success only)+- `gen_ai.token.type` — `input` or `output` (token usage only)++## Attaching a Meter++The idiomatic RAII form — `async with` everything, no manual cleanup:++```python+from opentelemetry.exporter.otlp.proto.http.metric_exporter import (+ OTLPMetricExporter,+)+from cubepi.tracing import Tracer, Meter+from cubepi.tracing.exporters import JsonlSpanExporter++async with (+ Tracer(+ service_name="my-bot",+ agent_name="assistant",+ exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ ) as tracer,+ Meter(+ resource=tracer.resource, # share Resource so service.* matches spans+ exporters=[+ OTLPMetricExporter(endpoint="http://otel-collector:4318/v1/metrics"),+ ],+ ) as meter,+ tracer.attached(agent),+ meter.attached(agent),+):+ await agent.prompt("...")+# Exit order auto: detach both (closes any cancelled-run spans, flushes+# the trace pipeline) → shutdown both (flush + close exporters).+```++`Meter.attach()` is independent from `Tracer.attach()`. You can run+either on its own; the recommended setup is both, sharing one+`Resource` so the backend treats them as the same service.++If you need the explicit, non-RAII form (e.g. attaching agents+dynamically over the lifetime of a long-running server):++```python+tracer_detach = tracer.attach(agent)+meter_detach = meter.attach(agent)+try:+ ...+finally:+ tracer_detach() # closes any cancelled-run spans+ meter_detach() # unsubscribes the meter's listeners+ await tracer.shutdown()+ await meter.shutdown()+```++## Bucket boundaries++The duration histograms ship with the OTel GenAI semconv's recommended+boundaries (in seconds):++```text+0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300+```++OTel exposes these as the `_advisory` boundaries; backends are free to use+them as-is or override.++## Concurrent agents on one Meter++Like `Tracer`, one `Meter` instance is safe to attach to multiple agents+in the same process. Each `attach()` call gets its own internal+`_MeterState` holding the open-ns timestamps and attribute dicts, so+overlapping runs from two agents never share or overwrite each other's+metric state.++```python+meter = Meter(resource=tracer.resource, exporters=[exporter])+meter.attach(agent_a)+meter.attach(agent_b)+```++Both agents emit independent duration / token / TTFC observations,+filterable by `gen_ai.agent.name` (set at the `Resource` level when+`Tracer(agent_name=…)` is used) or by `gen_ai.request.model`.++## Shutting down++The RAII form (`async with … as tracer, … as meter, tracer.attached(agent),+meter.attached(agent):` from above) handles the shutdown ordering for you:+detach inner first → outer `Tracer/Meter` `__aexit__` runs `shutdown()`.++For the manual pattern, order matters — `tracer_detach()` must run before+`tracer.shutdown()` so any spans an in-flight cancellation left open get+closed and exported in the same flush:++```python+finally:+ tracer_detach()+ meter_detach()+ await tracer.shutdown()+ await meter.shutdown()+```++`Meter.shutdown()` awaits a flush of the metric reader, then closes it.+`PeriodicExportingMetricReader` exports on a fixed interval (60 s by+default) — `shutdown` is the only way to guarantee the final window lands+before the process exits.++## Querying example (Honeycomb)++p95 chat latency by provider over the last hour:++```text+VISUALIZE P95(duration_s)+GROUP BY gen_ai.provider.name+WHERE gen_ai.operation.name = "chat"+TIME last 1 hour+```++Token usage by model:++```text+VISUALIZE SUM(token_count)+GROUP BY gen_ai.request.model, gen_ai.token.type+WHERE gen_ai.operation.name = "chat"+```++Substitute your backend's query DSL — same attributes, same aggregations.diff --git a/website/versioned_docs/version-0.5/guides/tracing/otlp.md b/website/versioned_docs/version-0.5/guides/tracing/otlp.mdnew file mode 100644index 0000000..c93dd75--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/tracing/otlp.md@@ -0,0 +1,174 @@+---+title: OTLP & Backends+sidebar_position: 3+---++# Exporting to OTLP Backends++`cubepi.tracing.Tracer` accepts any `opentelemetry.sdk.trace.export.SpanExporter`,+so anything in the OpenTelemetry ecosystem works. Pick the wire format+(HTTP or gRPC), point it at your collector, hand the exporter to the Tracer.++## HTTP (OTLP/HTTP)++```bash+pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-http+```++```python+from opentelemetry.exporter.otlp.proto.http.trace_exporter import (+ OTLPSpanExporter,+)+from cubepi.tracing import Tracer++tracer = Tracer(+ service_name="my-bot",+ service_version="1.4.2",+ deployment_environment="prod",+ agent_name="assistant",+ exporters=[+ OTLPSpanExporter(+ endpoint="http://otel-collector:4318/v1/traces",+ headers={"x-api-key": "…"}, # backend-specific+ ),+ ],+)+```++`service_name`, `service_version`, `deployment_environment`, and `agent_name`+flow through as OTel Resource attributes (`service.*`, `gen_ai.agent.name`,+`deployment.environment.name`) so backends can group runs without further+config.++## gRPC (OTLP/gRPC)++```bash+pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-grpc+```++```python+from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (+ OTLPSpanExporter,+)++exporter = OTLPSpanExporter(endpoint="otel-collector:4317", insecure=True)+tracer = Tracer(service_name="my-bot", exporters=[exporter])+```++## Backend recipes++These all consume OTLP — the only thing that differs is the endpoint and+auth header.++### Jaeger (>=1.50)++Jaeger natively accepts OTLP/HTTP on port 4318:++```python+OTLPSpanExporter(endpoint="http://jaeger:4318/v1/traces")+```++### Grafana Tempo++Send to your collector, or directly to Tempo's OTLP endpoint:++```python+OTLPSpanExporter(endpoint="http://tempo:4318/v1/traces")+```++### Honeycomb++```python+OTLPSpanExporter(+ endpoint="https://api.honeycomb.io/v1/traces",+ headers={"x-honeycomb-team": HONEYCOMB_API_KEY},+)+```++### Datadog (via the OTel collector)++Configure the collector with the Datadog exporter, then ship to it:++```python+OTLPSpanExporter(endpoint="http://otel-collector:4318/v1/traces")+```++Datadog also accepts native OTLP HTTP directly — same shape, different URL.++### AWS X-Ray (via collector)++The OTel collector includes the AWS X-Ray exporter; treat it like any other+OTLP target.++## Continuing an upstream trace++`Tracer.attach(agent)` currently roots every agent run in its own trace —+there is no public API yet for passing an inbound `traceparent` so that+spans nest under a caller's HTTP handler trace. The internal hook+(`Tracer._make_parent_context`) exists for a future `run_scope` feature;+until that ships, agent runs and the surrounding service trace are linked+only by their resource attributes (`service.name`, `gen_ai.agent.name`,+`cubepi.run_id`).++If you need the upstream trace to continue into cubepi today, the+workaround is to set the OTel current span yourself before calling+`agent.prompt(...)` and let the agent's spans inherit it via OTel's+ambient context — cubepi never overrides an active parent.++On the way out, MCP `tools/call` does inject W3C `traceparent` as an HTTP+header automatically, so an instrumented MCP server downstream of the+agent can continue the trace through to its own backend.++## Combining exporters++You can pass multiple exporters and they'll receive every span. Common+pattern — JSONL for local debugging plus OTLP for the production backend:++```python+tracer = Tracer(+ service_name="my-bot",+ exporters=[+ JsonlSpanExporter(directory="./cubepi-traces"),+ OTLPSpanExporter(endpoint="https://api.honeycomb.io/v1/traces", headers={…}),+ ],+)+```++## Flushing++`Tracer` uses `BatchSpanProcessor` under the hood, so spans are exported in+the background. The recommended pattern — and the one that exercises all+the cleanup paths automatically — is the `async with` form:++```python+async with Tracer(...) as tracer, tracer.attached(agent):+ await agent.prompt("...")+# On exit:+# - detach() runs synchronously: closes any spans a cancelled run left+# open, then schedules the flush as an asyncio.Task and awaits it.+# - tracer.shutdown() flushes again (idempotent) and closes exporters.+```++If you've stored `detach` from a manual `tracer.attach(agent)` call, it+returns the scheduled flush `Task`. Two valid manual patterns:++```python+# (a) Belt-and-braces — safest, both run.+finally:+ detach() # closes cancelled-run spans, schedules flush+ await tracer.shutdown() # awaits force_flush, then shuts the SDK down++# (b) Awaited detach — single call when you're not also shutting down.+finally:+ await detach() # awaits the scheduled flush+```++Outside an async context (no running loop) `detach()` returns `None` — the+sync part has run, but the flush is the caller's responsibility via+`await tracer.shutdown()`.++If even that gets missed — say a script raises before reaching `finally` —+`Tracer(atexit_flush=True)` (the default) registers a process-exit handler+that sync-flushes buffered spans through `BatchSpanProcessor`. Doesn't run+on `SIGKILL` / `os._exit`; for guaranteed delivery there, use+`SimpleSpanProcessor` (sync export per span).diff --git a/website/versioned_docs/version-0.5/guides/tracing/overview.md b/website/versioned_docs/version-0.5/guides/tracing/overview.mdnew file mode 100644index 0000000..09e8a97--- /dev/null+++ b/website/versioned_docs/version-0.5/guides/tracing/overview.md@@ -0,0 +1,88 @@+---+title: Tracing Overview+sidebar_position: 1+---++# Tracing Overview++CubePi emits [OpenTelemetry](https://opentelemetry.io/) spans that follow the+[GenAI Semantic Conventions v1.41](https://opentelemetry.io/docs/specs/semconv/gen-ai/)+so any OTel-compatible backend (Jaeger, Tempo, Honeycomb, Datadog, AWS X-Ray,+Azure Monitor, …) can ingest agent runs without custom instrumentation.++Attach a `Tracer` to an `Agent` and every prompt produces a tree of spans you+can pivot, query, and join with the rest of your service traces:++```text+invoke_agent <agent_name> [INTERNAL] one per agent.prompt()+└── cubepi.turn [INTERNAL] one per LLM round-trip+ ├── chat <model> [CLIENT] the LLM call itself+ └── execute_tool <tool_name> [INTERNAL] each tool invocation+ └── tools/call <tool_name> [CLIENT] (MCP tools only)+```++Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,+`gen_ai.request.model`, `gen_ai.provider.name`, `gen_ai.usage.input_tokens`,+`gen_ai.usage.output_tokens`, `gen_ai.response.finish_reasons`, …++## What ships out of the box++- **Tracer** — builds an SDK `TracerProvider`, attaches one+ `BatchSpanProcessor` per exporter, wires the cubepi event stream into spans.+- **Meter** — sibling for OTel histograms:+ `gen_ai.client.operation.duration`, `gen_ai.client.operation.time_to_first_chunk`,+ `gen_ai.client.token.usage`.+- **JsonlSpanExporter** — write one JSON line per span to+ `./cubepi-traces/<date>/<run_id>.jsonl`. Useful for local dev and offline+ debugging; works with any OTel viewer that reads JSONL.+- **OTLP** — bring your own exporter via `opentelemetry-exporter-otlp-proto-http`+ (HTTP) or `…-grpc` and hand it to `Tracer(exporters=[…])`.+- **W3C trace context propagation** — outgoing MCP calls inject the active+ `traceparent` as an HTTP header so an instrumented MCP server can continue+ the trace.+- **`tracer.attached(agent)` / `meter.attached(agent)`** — async context+ managers that RAII-wrap attach/detach, so cleanup is one `async with`+ block instead of an explicit `try/finally`.+- **`atexit` flush hook** — `Tracer(atexit_flush=True)` (default) registers+ a process-exit handler that sync-flushes any buffered spans, so callers+ who forget `await tracer.shutdown()` still get their spans exported on+ normal exit / Ctrl-C / unhandled exception.+- **`tracing_context()`** — set per-run tags and metadata+ (`cubepi.tags = ("beta-arm",)`, `cubepi.metadata.user_id = "u-42"`)+ via a contextvar-scoped block. Concurrent agents each see their own+ values.++## What it costs++- One pure-Python recorder per agent run subscribing to the agent's event+ stream and the provider's listener registry — no monkey-patching, no extra+ threads.+- One OTel SDK span per layer above. `BatchSpanProcessor` batches export off+ the hot path.+- **No payloads are recorded by default.** `gen_ai.input.messages`,+ `gen_ai.output.messages`, raw request/response, and tool args/results all+ require explicit opt-in via `record_content=True` so you don't accidentally+ ship PII to your backend. See [Content & Redaction](./content-recording).++## When to use each piece++| You want | Use |+|---|---|+| Trace one local agent run and inspect a JSONL file | `Tracer` + `JsonlSpanExporter` |+| Ship to Jaeger / Tempo / Honeycomb / Datadog | `Tracer` + OTLP exporter |+| Latency + token histograms next to the spans | `Meter` alongside `Tracer` |+| Record prompts / model outputs for evaluation | `Tracer(record_content=True)` |+| Redact PII before it leaves the process | `Tracer(redact=…)` |+| Tag runs with `user_id` / `session_id` / A-B arm | `tracing_context(tags=…, metadata=…)` |+| One-liner cleanup, no try/finally | `async with tracer.attached(agent): …` |+| Forget to call `shutdown()` and not lose spans | `Tracer(atexit_flush=True)` (default) |+| Continue a trace from an upstream service | `Tracer(resource=…)` + W3C `traceparent` (auto for MCP, manual for HTTP) |++## Where to go next++- [Getting Started](./getting-started) — install the extra and emit your+ first spans+- [OTLP & Backends](./otlp) — point cubepi at Jaeger, Tempo, Honeycomb, …+- [Content Recording & Redaction](./content-recording) — record prompts and+ responses safely+- [Metrics](./metrics) — histograms via `Meter`diff --git a/website/versioned_docs/version-0.5/intro.mdx b/website/versioned_docs/version-0.5/intro.mdxnew file mode 100644index 0000000..13056e4--- /dev/null+++ b/website/versioned_docs/version-0.5/intro.mdx@@ -0,0 +1,69 @@+---+id: intro+title: CubePi+slug: /+sidebar_position: 0+---++# CubePi++**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.++```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.+- **OpenTelemetry built in.** Attach a `Tracer` and every prompt+ produces a tree of OTel spans aligned with the GenAI Semantic+ Conventions — works with Jaeger, Tempo, Honeycomb, Datadog, or any+ OTLP-compatible backend. No payloads recorded by default; opt in+ with `record_content=True` and a `redact` callback.++## Where to go next++| If you want to… | Start here |+|---|---|+| Install and run your first agent | [Getting Started → Installation](./getting-started/installation) |+| Understand the building blocks | [Getting Started → Core Concepts](./getting-started/core-concepts) |+| Wire a real tool-using agent | [Guides → Building Your First Agent](./guides/agents/first-agent) |+| Persist a conversation across restarts | [Guides → SQLite Checkpointing](./guides/checkpointing/sqlite) |+| Ship traces to Jaeger / Tempo / Honeycomb | [Guides → Tracing](./guides/tracing/overview) |+| Look up a specific symbol | [API Reference](./api/) |+| See full working examples | [Recipes](./recipes/weather-agent) |+| Port an existing langgraph agent | [Migration → From langgraph](./migration/from-langgraph) |++## Status++You are reading the docs for the released **0.5** version. The native+OpenTelemetry tracing module ([guide →](./guides/tracing/overview))+— `Tracer`, `Meter`, content recording, MCP CLIENT spans, per-run+`tracing_context` tags — landed in 0.4.++Source, issues, and discussion live on+[GitHub](https://github.com/cubeplexai/cubepi).diff --git a/website/versioned_docs/version-0.5/migration/from-langgraph.md b/website/versioned_docs/version-0.5/migration/from-langgraph.mdnew file mode 100644index 0000000..e4e6c21--- /dev/null+++ b/website/versioned_docs/version-0.5/migration/from-langgraph.md@@ -0,0 +1,243 @@+---+title: From langgraph+---++# Migrating from langgraph++CubePi and [langgraph](https://github.com/langchain-ai/langgraph) both+build tool-using LLM agents, but they have different mental models.+This page maps langgraph concepts onto CubePi so you can port code+without having to re-learn from scratch.++## Mental-model shift++| langgraph | CubePi | Why |+|---|---|---|+| **State graph** with nodes, edges, channels | **Agent loop** that's a plain `while` loop you can read | A linear loop is easier to reason about than a graph; CubePi never branches at runtime — control flow lives in middleware |+| **Channels** (typed state slots) | **`AgentContext.extra`** + `AgentState.messages` | A single dict + a single message list cover every state shape we've seen |+| **`StateGraph.add_node(name, fn)`** | A middleware hook or a tool | Functions in langgraph nodes split into two roles in CubePi: tool execution (when the model decides) vs. middleware (always-on transforms) |+| **`add_edge(a, b)`** / `add_conditional_edges` | Built-in: tools → next turn → tools → … | The conditional shape (tool calls → re-prompt) is the loop; you don't reify it |+| **`MemorySaver` / `SqliteSaver` / `PostgresSaver`** | `MemoryCheckpointer` / `SQLiteCheckpointer` / `PostgresCheckpointer` | Same idea, append-only schema instead of full snapshots |+| **`config: {"configurable": {"thread_id": …}}`** | `Agent(thread_id=…)` | First-class agent parameter |+| **`stream_mode="messages"` / `"values"` / `"updates"`** | `agent.subscribe(listener)` — one event stream | One pattern, eleven event types |+| **Tools as `@tool` decorated functions** | `AgentTool` with Pydantic params + async execute | Closer to OpenAI/Anthropic native shape |+| **`HumanMessage`, `AIMessage`** | `UserMessage`, `AssistantMessage` | Same role-tagged messages, just renamed |+| **Interrupts via `interrupt_before` / `interrupt_after`** | `agent.steer(...)`, `agent.follow_up(...)`, `agent.abort()` | Imperative control instead of declarative interrupt points |+| **`config_schema`** | Constructor parameters on `Agent` | No separate schema layer |++## Side-by-side: a tool-using agent++### langgraph++```python+from typing import TypedDict+from langchain_anthropic import ChatAnthropic+from langgraph.graph import StateGraph, END+from langgraph.prebuilt import ToolNode+from langchain_core.tools import tool+++@tool+def get_weather(city: str) -> str:+ """Get current weather for a city."""+ return f"72°F and sunny in {city}"+++llm = ChatAnthropic(model="claude-sonnet-4-5-20250929").bind_tools([get_weather])++class State(TypedDict):+ messages: list++def call_model(state: State):+ return {"messages": [llm.invoke(state["messages"])]}++def should_continue(state: State):+ last = state["messages"][-1]+ return "tools" if last.tool_calls else END++graph = StateGraph(State)+graph.add_node("llm", call_model)+graph.add_node("tools", ToolNode([get_weather]))+graph.add_edge("__start__", "llm")+graph.add_conditional_edges("llm", should_continue)+graph.add_edge("tools", "llm")+app = graph.compile()++for chunk in app.stream({"messages": [("user", "Weather in Tokyo?")]}):+ print(chunk)+```++### CubePi++```python+import asyncio+from pydantic import BaseModel+from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent+from cubepi.providers.anthropic import AnthropicProvider+++class GetWeatherParams(BaseModel):+ city: str+++async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text=f"72°F and sunny in {params.city}")])+++agent = Agent(+ provider=AnthropicProvider(api_key="…"),+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ tools=[AgentTool(+ name="get_weather",+ description="Get current weather for a city.",+ parameters=GetWeatherParams,+ execute=get_weather,+ )],+)+agent.subscribe(lambda e, s=None: print(e.type))+asyncio.run(agent.prompt("Weather in Tokyo?"))+```++CubePi version removes:++- The `StateGraph`, edges, nodes, `END` sentinel, conditional edges.+- The `ToolNode` registry — tools go directly to the `Agent`.+- The `should_continue` function — the loop knows when there are tool+ calls.+- The `State` TypedDict — state lives on the agent.++## Mapping common patterns++### Checkpointing++```python+# langgraph+from langgraph.checkpoint.sqlite import SqliteSaver+graph.compile(checkpointer=SqliteSaver.from_conn_string(":memory:"))++# CubePi+from cubepi.checkpointer import SQLiteCheckpointer+async with SQLiteCheckpointer("agent.db") as cp:+ agent = Agent(..., checkpointer=cp, thread_id="conv-1")+```++CubePi's append-only model is O(1) per message, regardless of+conversation length. langgraph saves full snapshots, which scales+linearly with history.++### Streaming++```python+# langgraph+for chunk in app.stream(state, stream_mode="messages"):+ if chunk["event"] == "on_chat_model_stream":+ print(chunk["data"]["chunk"].content, end="")++# CubePi+def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="")++agent.subscribe(on_event)+await agent.prompt("…")+```++One subscriber, one stream — no mode flag.++### Interrupting / human-in-the-loop++```python+# langgraph+graph.compile(interrupt_before=["tools"])++# CubePi+class HumanApproval(Middleware):+ async def before_tool_call(self, ctx, *, signal=None):+ approved = await ask_human(f"Run {ctx.tool_call.name}({ctx.args})?")+ if not approved:+ return BeforeToolCallResult(block=True, reason="rejected")+ return None+```++Imperative interrupts via middleware. You decide per call instead of+configuring graph-level interrupt points.++### Branching++```python+# langgraph+graph.add_conditional_edges("llm", lambda s: "tools" if s["messages"][-1].tool_calls else "summary")+graph.add_node("summary", summarize)+graph.add_edge("summary", END)+```++```python+# CubePi+class SummariseAtEnd(Middleware):+ async def should_stop_after_turn(self, ctx) -> bool:+ msg = ctx.message+ if not any(isinstance(c, ToolCall) for c in msg.content):+ # No more tool calls; we're done. Inject a summary turn first.+ ...+ return True+ return False+```++There's no built-in branching primitive; flow control happens through+`should_stop_after_turn` and `after_model_response`.++## What langgraph does that CubePi doesn't (yet)++- **Multi-agent supervisor patterns.** No first-class "agents+ spawning agents" abstraction. You can build it by running multiple+ `Agent` instances with shared tools.+- **Visual graph rendering.** No `app.get_graph().draw_mermaid()`+ equivalent. CubePi's flow is linear so the picture would be a single+ line anyway.+- **Time travel / fork** at arbitrary checkpoints. The Postgres schema+ has fork columns but no API surface in v0.4.+- **First-party UI for traces.** CubePi doesn't render its own trace+ visualizer the way LangSmith / Langfuse do; instead it emits+ vendor-neutral OpenTelemetry — point any OTLP backend+ (LangSmith's OTel endpoint, Langfuse v3, Jaeger, Tempo,+ Honeycomb, Datadog, …) at it via+ `Tracer(exporters=[OTLPSpanExporter(...)])`. See+ [Tracing → OTLP & Backends](../guides/tracing/otlp).++## What CubePi does that langgraph doesn't++- **Native OpenTelemetry tracing** — `Tracer` + `Meter` emit OTel+ spans + GenAI-semconv attributes out of the box, ingestible by+ any OTLP backend. See [Tracing → Overview](../guides/tracing/overview).+- **Native async-first** — every entry point is async. No+ `app.invoke` vs. `app.ainvoke` split.+- **Append-only persistence** — O(1) DB writes, JSONB-queryable+ messages.+- **3 core deps** vs. langchain-core + langgraph-sdk + transitives.+- **Streaming-realistic test provider** (`FauxProvider`) ships in the+ box.+- **MCP loaders** for HTTP + stdio transports.++## Porting checklist++1. Replace `StateGraph` construction with a single `Agent(...)` call.+2. Move `@tool`-decorated functions to `AgentTool` instances (Pydantic+ models for params, async execute).+3. Replace `MemorySaver` / `SqliteSaver` / `PostgresSaver` with+ `MemoryCheckpointer` / `SQLiteCheckpointer` / `PostgresCheckpointer`.+4. Replace `stream_mode` callbacks with `agent.subscribe(...)`.+5. Convert custom nodes that did message transforms → `Middleware`+ hooks.+6. Convert `interrupt_before/after` → `before_tool_call` /+ `after_model_response` middleware.+7. If you had a `summary` or `route` node — fold it into+ `after_model_response` with `decision="stop"` or `"loop_to_model"`.++## See also++- [Core Concepts](../getting-started/core-concepts) — the building+ blocks you're mapping to.+- [Middleware → Composition](../guides/middleware/composition) — where+ flow-control logic lives.+- [Checkpointing](../guides/checkpointing/sqlite) — the new+ persistence story.diff --git a/website/versioned_docs/version-0.5/recipes/multi-provider-failover.md b/website/versioned_docs/version-0.5/recipes/multi-provider-failover.mdnew file mode 100644index 0000000..58e7210--- /dev/null+++ b/website/versioned_docs/version-0.5/recipes/multi-provider-failover.md@@ -0,0 +1,258 @@+---+title: Multi-Provider Failover+---++# Recipe: Multi-Provider Failover++When Anthropic is rate-limited or down, fail over to OpenAI without+crashing the agent. We'll wrap both providers behind a single+`Provider` adapter that does its own retry/failover logic.++**Time to run:** 10 minutes.+**Deps:** `cubepi`, `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`.++## The wrapper provider++```python title="failover.py"+import asyncio+import logging+import time+from typing import Sequence++from cubepi.providers.base import (+ AssistantMessage,+ Message,+ MessageStream,+ Model,+ Provider,+ StreamEvent,+ StreamOptions,+ ToolDefinition,+ Usage,+)+from cubepi.providers.anthropic import AnthropicProvider+from cubepi.providers.openai import OpenAIProvider++log = logging.getLogger(__name__)+++class FailoverProvider:+ """Try providers in order; fall over on construction or first-event errors.++ Built-in providers swallow API/network errors and surface them as+ `StreamEvent(type="error")` on the returned stream — never as exceptions+ out of `provider.stream()`. So we peek at the first event from each+ inner stream and only commit to it once we see a non-error event.++ Limitation: errors that arrive *after* the first event (e.g. mid-stream+ rate limit, server disconnect) are forwarded to the agent as-is.+ Fully replaying a half-streamed turn against a fallback provider would+ require buffering the whole turn — out of scope here.+ """++ def __init__(self, primary_pair: tuple[Provider, Model], *fallbacks: tuple[Provider, Model]) -> None:+ self._chain: list[tuple[Provider, Model]] = [primary_pair, *fallbacks]++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ options: StreamOptions | None = None,+ ) -> MessageStream:+ last_error: str | None = None++ for provider, mapped_model in self._chain:+ # Construction-time failures (rare — most stay inside the producer task).+ try:+ inner = await provider.stream(+ mapped_model,+ messages,+ system_prompt=system_prompt,+ tools=tools,+ options=options,+ )+ except Exception as e:+ log.warning("provider %s failed at construction: %s", mapped_model.provider, e)+ last_error = repr(e)+ continue++ # Peek at the first event to learn whether the stream is healthy.+ iterator = inner.__aiter__()+ try:+ first = await iterator.__anext__()+ except StopAsyncIteration:+ last_error = "stream ended before producing any events"+ continue++ if first.type == "error":+ log.warning("provider %s errored on first event: %s",+ mapped_model.provider, first.error_message)+ last_error = first.error_message or "stream error"+ continue++ # Healthy — commit to this provider. Forward `first` plus the rest+ # through a fresh outer MessageStream so the caller sees a complete+ # stream starting at the start event.+ outer = MessageStream()++ async def _forward(first_event=first, src=iterator, src_stream=inner):+ try:+ outer.push(first_event)+ async for ev in src:+ outer.push(ev)+ final = await src_stream.result()+ outer.set_result(final)+ except Exception as exc:+ fallback_msg = AssistantMessage(+ content=[],+ stop_reason="error",+ error_message=str(exc),+ usage=Usage(),+ timestamp=time.time(),+ )+ outer.push(StreamEvent(type="error", error_message=str(exc)))+ outer.set_result(fallback_msg)++ outer.attach_task(asyncio.create_task(_forward()))+ return outer++ raise RuntimeError(f"all providers exhausted; last error: {last_error!r}")+```++## Use it++```python title="main.py"+import asyncio+import os++from cubepi import Agent, Model+from cubepi.providers.anthropic import AnthropicProvider+from cubepi.providers.openai import OpenAIProvider+from failover import FailoverProvider+++async def main():+ failover = FailoverProvider(+ (+ AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"]),+ Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ ),+ (+ OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"]),+ Model(id="gpt-5", provider="openai"),+ ),+ )++ # The model passed here is overridden inside FailoverProvider; pass any+ # placeholder. We use the primary's so usage tracking labels match the+ # happy path.+ agent = Agent(+ provider=failover,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="You answer concisely.",+ )+ agent.subscribe(lambda e, s=None: None)+ await agent.prompt("Capital of Mongolia?")+ last = agent.state.messages[-1]+ print(last.content[0].text)+++asyncio.run(main())+```++## What about smarter failover policies?++The example above falls back on **any** error event. That's fine for+`RateLimitError`, `APIConnectionError`, or 5xx — but arguably wrong for+`BadRequestError` (your code is wrong; the next provider will fail the+same way).++The first-event `error_message` comes from `str(exc)` on the+underlying SDK exception. Filter on substrings, or — better — wrap each+provider's `_produce` to tag the error category:++```python+NON_RETRYABLE_HINTS = ("bad request", "invalid_request_error", "401", "403")++if first.type == "error":+ msg = (first.error_message or "").lower()+ if any(h in msg for h in NON_RETRYABLE_HINTS):+ raise RuntimeError(f"non-retryable error from {mapped_model.provider}: {msg}")+ last_error = first.error_message+ continue+```++A more robust approach is to fork the built-in providers and re-raise+specific SDK exceptions from `_produce` so they reach `provider.stream()`+as real Python exceptions — but that's a larger change against+cubepi itself.++## Adding circuit breaking++Don't keep retrying a provider that's clearly down. A simple counter:++```python+import time++class CircuitBreaker:+ def __init__(self, failure_threshold: int = 3, recovery_seconds: float = 60) -> None:+ self._failures = 0+ self._opened_at: float | None = None+ self._threshold = failure_threshold+ self._recovery = recovery_seconds++ def can_attempt(self) -> bool:+ if self._opened_at and time.monotonic() - self._opened_at < self._recovery:+ return False+ if self._opened_at:+ self._opened_at = None # half-open+ return True++ def record_failure(self) -> None:+ self._failures += 1+ if self._failures >= self._threshold:+ self._opened_at = time.monotonic()+ self._failures = 0++ def record_success(self) -> None:+ self._failures = 0+```++Hold one `CircuitBreaker` per provider in the `FailoverProvider`,+skip if `can_attempt()` is False.++## Per-tool failover doesn't apply++This recipe handles **provider** failures. Tool failures are different+— see [Middleware → Retries](../guides/middleware/examples#retries-with-backoff)+for that pattern.++## Common pitfalls++- **Different tool schemas across providers** — Both built-in+ providers accept the same `ToolDefinition`, but extra-body+ customisations (e.g. OpenAI `parallel_tool_calls=False`) won't carry+ to Anthropic. Keep cross-provider behaviour in+ [`transform_context`](../guides/middleware/hooks#transform_context),+ not in `extra_body`.+- **Different cost** — Failover from Anthropic to OpenAI changes+ per-token cost. Track which provider answered (via `on_response` or+ `AssistantMessage.provider_id`) and bill accordingly.+- **Streaming consistency** — The wrapper forwards events through a+ fresh `MessageStream`, so consumers see the same `StreamEvent` shape+ regardless of which provider answered. The original `start` event+ comes from the inner provider unchanged.+- **Mid-stream errors aren't recovered** — Once we've seen a healthy+ first event, the wrapper commits to that provider. If it errors+ halfway through a long response, the agent sees the error. Full+ mid-stream replay would require buffering — out of scope here.++## See also++- [Providers / Anthropic](../guides/providers/anthropic) and+ [OpenAI](../guides/providers/openai) — provider-specific details.+- [Writing a Custom Provider](../guides/providers/custom) — the same+ Protocol used by this wrapper.diff --git a/website/versioned_docs/version-0.5/recipes/persistent-chat.md b/website/versioned_docs/version-0.5/recipes/persistent-chat.mdnew file mode 100644index 0000000..df822e0--- /dev/null+++ b/website/versioned_docs/version-0.5/recipes/persistent-chat.md@@ -0,0 +1,177 @@+---+title: Persistent Chat+---++# Recipe: Persistent Chat (SQLite)++A REPL chat that survives restarts. Conversation history is kept in a+SQLite file; each user gets a `thread_id`.++**Time to run:** 5 minutes.+**Deps:** `cubepi[sqlite]`, an `ANTHROPIC_API_KEY`.++## The script++```python title="chat.py"+import asyncio+import os+import sys++from cubepi import Agent, Model+from cubepi.checkpointer import SQLiteCheckpointer+from cubepi.providers.anthropic import AnthropicProvider+++async def main(thread_id: str):+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])++ async with SQLiteCheckpointer("chat.db") as cp:+ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="You are a concise, friendly assistant.",+ checkpointer=cp,+ thread_id=thread_id,+ )++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "agent_end":+ print()++ agent.subscribe(on_event)++ print(f"chatting on thread {thread_id!r}. Ctrl-D to quit.\n")+ loop = asyncio.get_event_loop()+ while True:+ try:+ user_input = await loop.run_in_executor(None, input, "you> ")+ except EOFError:+ print()+ return+ if not user_input.strip():+ continue+ print("ai > ", end="", flush=True)+ await agent.prompt(user_input)+++if __name__ == "__main__":+ asyncio.run(main(thread_id=sys.argv[1] if len(sys.argv) > 1 else "default"))+```++Run:++```bash+pip install "cubepi[sqlite]"+export ANTHROPIC_API_KEY=sk-…+python chat.py alice+# Have a chat, then Ctrl-D.++python chat.py alice+# History is restored. Ask "what did I just tell you?" — the model+# remembers the previous session.++python chat.py bob+# Different thread, clean slate.+```++## What's going on++- **First `prompt()` per process loads history.** CubePi checks the+ checkpointer once at the start of the first prompt, restores+ `agent.state.messages`, and proceeds.+- **Each `message_end` appends to the database.** No batching, no+ lossy buffering. If the process crashes mid-stream, the next run+ picks up at the last committed message.+- **The system prompt isn't persisted** — it's part of agent+ construction, not state. Keep it in your code (or in env config).++## Multi-user routing++In a web service, derive `thread_id` from the authenticated user:++```python+agent = Agent(+ provider=provider,+ model=model,+ checkpointer=cp,+ thread_id=f"user-{user_id}",+)+```++You can serve thousands of users from one `SQLiteCheckpointer` —+threads are isolated by `thread_id`.++## Pruning a thread++There's no built-in "delete thread" API by design — checkpointers are+append-only. To prune, drop rows by `thread_id` directly:++```bash+sqlite3 chat.db "DELETE FROM messages WHERE thread_id='alice'; DELETE FROM thread_extra WHERE thread_id='alice'"+```++Or implement a small admin tool that does the SQL on demand.++## Sliding the context window++After a long conversation, the model's context gets expensive. Add a+[`SlidingWindow`](../guides/middleware/examples#sliding-window-truncation)+middleware:++```python+from cubepi import Middleware++class SlidingWindow(Middleware):+ def __init__(self, n: int) -> None:+ self.n = n++ async def transform_context(self, messages, *, signal=None):+ return messages[-self.n:] if len(messages) > self.n else messages+++agent = Agent(+ provider=provider,+ model=model,+ checkpointer=cp,+ thread_id=thread_id,+ middleware=[SlidingWindow(40)],+)+```++The DB keeps every message; the model only sees the last 40. The+user-visible history (e.g. for a chat UI rendering past turns) stays+complete.++## Switching to Postgres++Same code, different checkpointer:++```python+from cubepi.checkpointer import PostgresCheckpointer++async with PostgresCheckpointer("postgresql://…") as cp:+ agent = Agent(provider=…, model=…, checkpointer=cp, thread_id=…)+```++Postgres is the right choice for multi-instance services or many+concurrent users — see [Postgres + FastAPI](./postgres-fastapi).++## Common pitfalls++- **`async with` forgotten** — Without it, the SQLite connection is+ never opened. You get `AssertionError`. Wrap.+- **Multiple processes writing the same `thread_id`** — Interleaved+ history. One agent per thread, or move to Postgres.+- **`chat.db` in `/tmp`** — Some OSes wipe `/tmp` on reboot. Use+ `~/.local/share/myapp/chat.db` or similar for user data.++## See also++- [Multi-turn Conversations](../guides/agents/multi-turn) — `steer`,+ `follow_up`, `resume`.+- [SQLite Checkpointing](../guides/checkpointing/sqlite) — the backend+ in detail.+- [Resumable Long Tasks](./resumable-tasks) — when crashes happen+ mid-tool, not just between turns.diff --git a/website/versioned_docs/version-0.5/recipes/postgres-fastapi.md b/website/versioned_docs/version-0.5/recipes/postgres-fastapi.mdnew file mode 100644index 0000000..d6c0421--- /dev/null+++ b/website/versioned_docs/version-0.5/recipes/postgres-fastapi.md@@ -0,0 +1,255 @@+---+title: Postgres + FastAPI Service+---++# Recipe: Postgres + FastAPI Service++A production-shaped HTTP service that fronts a CubePi agent: FastAPI+for routing, server-sent events for streaming, a shared+`PostgresCheckpointer` for persistence, and `thread_id` derived from+the authenticated user.++**Time to run:** 30 minutes.+**Deps:** `cubepi[postgres]`, `fastapi`, `uvicorn[standard]`,+`sse-starlette`, a running Postgres with the cubepi schema applied.++## Schema first++Before the service starts, run the cubepi schema migration. The+quickest way for this recipe:++```bash+psql "$DATABASE_URL" <<'SQL'+CREATE TABLE cubepi_threads (+ thread_id TEXT PRIMARY KEY,+ parent_thread_id TEXT REFERENCES cubepi_threads(thread_id),+ forked_at_seq BIGINT,+ extra JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+);++CREATE TABLE cubepi_messages (+ thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) ON DELETE CASCADE,+ seq BIGINT NOT NULL,+ role TEXT NOT NULL,+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,+ payload BYTEA NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (thread_id, seq)+) PARTITION BY HASH (thread_id);++-- 64 hash partitions+DO $$+BEGIN+ FOR i IN 0..63 LOOP+ EXECUTE format(+ 'CREATE TABLE cubepi_messages_p%s PARTITION OF cubepi_messages FOR VALUES WITH (MODULUS 64, REMAINDER %s)',+ i, i+ );+ END LOOP;+END$$;++CREATE INDEX ix_cubepi_messages_metadata_gin+ON cubepi_messages USING gin (metadata jsonb_path_ops);++CREATE TABLE cubepi_schema_version (version INT PRIMARY KEY);+INSERT INTO cubepi_schema_version VALUES (1);+SQL+```++For a real deployment, generate this via Alembic — see+[Postgres Checkpointing → Bootstrapping via Alembic](../guides/checkpointing/postgres#bootstrapping-via-alembic).++## The service++```python title="service.py"+import asyncio+import os+from contextlib import asynccontextmanager+from typing import AsyncIterator++from fastapi import FastAPI, Depends, HTTPException+from pydantic import BaseModel+from sse_starlette.sse import EventSourceResponse++from cubepi import Agent, Model+from cubepi.checkpointer import PostgresCheckpointer+from cubepi.providers.anthropic import AnthropicProvider+++# --- App lifecycle ------------------------------------------------------++_provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])+_checkpointer: PostgresCheckpointer | None = None+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _checkpointer+ _checkpointer = await PostgresCheckpointer(+ os.environ["DATABASE_URL"],+ min_pool_size=2,+ max_pool_size=20,+ ).__aenter__()+ yield+ await _checkpointer.__aexit__(None, None, None)+++app = FastAPI(lifespan=lifespan)+++# --- Auth (stub — replace with your real auth) -------------------------++async def current_user_id() -> str:+ # In production: decode JWT, look up session, etc.+ return "demo-user"+++# --- Routes -------------------------------------------------------------++class PromptBody(BaseModel):+ text: str++[email protected]("/chat/{conversation_id}/messages")+async def post_message(+ conversation_id: str,+ body: PromptBody,+ user_id: str = Depends(current_user_id),+):+ thread_id = f"{user_id}:{conversation_id}"++ async def event_generator() -> AsyncIterator[dict]:+ agent = Agent(+ provider=_provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="You are a helpful assistant.",+ checkpointer=_checkpointer,+ thread_id=thread_id,+ )++ queue: asyncio.Queue = asyncio.Queue()+ agent.subscribe(lambda e, s=None: queue.put_nowait(e))++ async def run():+ try:+ await agent.prompt(body.text)+ finally:+ queue.put_nowait(None) # sentinel++ task = asyncio.create_task(run())++ try:+ while True:+ event = await queue.get()+ if event is None:+ break+ # Emit a small subset to the client.+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ yield {"event": "delta", "data": event.stream_event.delta}+ elif event.type == "tool_execution_start":+ yield {"event": "tool_start", "data": event.tool_name}+ elif event.type == "agent_end":+ yield {"event": "done", "data": ""}+ finally:+ await task++ return EventSourceResponse(event_generator())++[email protected]("/chat/{conversation_id}/history")+async def get_history(+ conversation_id: str,+ user_id: str = Depends(current_user_id),+):+ thread_id = f"{user_id}:{conversation_id}"+ data = await _checkpointer.load(thread_id)+ if data is None:+ return {"messages": []}+ return {+ "messages": [m.model_dump(mode="json") for m in data.messages],+ }+```++Run:++```bash+pip install "cubepi[postgres]" fastapi "uvicorn[standard]" sse-starlette+export DATABASE_URL=postgresql://user:pass@localhost/cubepi+export ANTHROPIC_API_KEY=sk-…+uvicorn service:app --reload --port 8000+```++Test:++```bash+curl -N -X POST http://localhost:8000/chat/conv1/messages \+ -H "content-type: application/json" \+ -d '{"text":"hi"}'+# event: delta+# data: Hello+# event: delta+# data: !+# event: done+```++## Design notes++- **One `PostgresCheckpointer` per process, shared across requests.**+ It holds a connection pool; opening one per request would defeat+ the pool.+- **One `Agent` per request.** Agents own per-conversation state+ (steering queues, listeners). Don't reuse them.+- **`thread_id = f"{user_id}:{conversation_id}"`** — user isolation by+ prefix. The agent reads/writes only its own thread.+- **SSE for streaming.** Each text delta goes to the client as a+ separate event. Tool starts get their own event type — clients can+ render a "thinking" indicator without rebuilding event handling.+- **No load balancer affinity needed.** Because state is in Postgres,+ any service instance can pick up any conversation.++## Concurrency on the same thread++If a user double-clicks send, two `POST` requests arrive simultaneously.+Both create an `Agent` bound to the same `thread_id`. The Postgres+advisory lock serialises their appends, but the **in-memory** states+diverge — the second request's agent might not see the first's+in-progress message in its `agent.state.messages`.++For most chat UIs this is fine (the client controls send timing).+If you need strict ordering, add an application-layer mutex+(`asyncio.Lock` keyed by `thread_id`) or queue.++## Production hardening checklist++- **Auth:** Replace `current_user_id()` with real JWT / session+ validation.+- **Rate limiting:** Add a [`RateLimitMiddleware`](../guides/middleware/examples#rate-limiting)+ to the agent constructor, keyed by `user_id`.+- **Cost tracking:** Subscribe to `agent_end`, sum `usage` on each+ `AssistantMessage`, write to a billing table.+- **Observability:** Use `on_response` to capture `anthropic-*` rate+ headers; export to Prometheus.+- **Backups:** Postgres native — `pg_dump`, point-in-time recovery.+- **Graceful shutdown:** uvicorn's lifespan handler closes the pool;+ add `signal.signal(SIGTERM, ...)` if you have other resources.++## Common pitfalls++- **CubepiSchemaUninitialized at startup** — Your migrations didn't+ run. Apply the schema first.+- **Connection pool exhaustion** — Default `max_pool_size=10`. Bump+ it if your service has more concurrent agents than that.+- **SSE behind a load balancer** — Some LBs buffer SSE. Disable+ buffering (`X-Accel-Buffering: no` for nginx).+- **Long requests timing out** — Tool-heavy agents can run minutes.+ Set generous proxy timeouts and uvicorn `--timeout-keep-alive 600`.++## See also++- [Postgres Checkpointing](../guides/checkpointing/postgres) — the+ backend in depth.+- [Persistent Chat](./persistent-chat) — the same flow with SQLite.+- [Multi-Provider Failover](./multi-provider-failover) — combine with+ this service for resilience.diff --git a/website/versioned_docs/version-0.5/recipes/resumable-tasks.md b/website/versioned_docs/version-0.5/recipes/resumable-tasks.mdnew file mode 100644index 0000000..5a03f23--- /dev/null+++ b/website/versioned_docs/version-0.5/recipes/resumable-tasks.md@@ -0,0 +1,229 @@+---+title: Resumable Long Tasks+---++# Recipe: Resumable Long Tasks++When an agent is mid-flight through a long-running operation (a series+of tool calls, a multi-turn reasoning session) and the process dies,+you want to come back and pick up where it left off — not start over.+CubePi's append-only checkpointing plus `agent.resume()` makes this+trivial *between turns*; for resumption *mid-tool*, you need a little+more care.++**Time to run:** 15 minutes.+**Deps:** `cubepi[sqlite]`, an `ANTHROPIC_API_KEY`.++## The pattern++There are three crash points to think about:++1. **Between turns** — The model has answered, no tools to run, the+ loop is between iterations. `resume()` re-invokes the model. *Free+ with the checkpointer.*+2. **After tool results, before model call** — Tool results are+ persisted. `resume()` sees the last message is a `ToolResultMessage`+ and re-invokes the model. *Free with the checkpointer.*+3. **Mid-tool** — The tool started but didn't finish. Nothing is+ persisted yet (CubePi only persists messages). You need+ tool-internal idempotency. *Requires care.*++This recipe focuses on case 3.++## Idempotent tools with external state++The pattern: each tool action has a deterministic, idempotent key.+Before doing the work, check whether it's been done.++```python title="tools.py"+import os+import json+from pathlib import Path++from pydantic import BaseModel+from cubepi import AgentTool, AgentToolResult, TextContent+++# Simple file-backed job store; replace with Redis / Postgres in prod.+JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubepi-jobs"))+JOB_DIR.mkdir(parents=True, exist_ok=True)+++class TranscodeParams(BaseModel):+ source_path: str+ output_path: str+++async def transcode_video(tool_call_id, params: TranscodeParams, *, signal=None, on_update=None):+ job_key = f"transcode:{params.source_path}->{params.output_path}"+ job_file = JOB_DIR / f"{job_key.replace('/', '_')}.json"++ if job_file.exists():+ # Already done in a previous run.+ state = json.loads(job_file.read_text())+ return AgentToolResult(+ content=[TextContent(text=f"Already transcoded to {state['output_path']}.")],+ details=state,+ )++ # Do the actual work (long-running, expensive).+ # Use signal to abort cleanly if cancelled.+ output = await run_ffmpeg(params.source_path, params.output_path, signal=signal)++ # Commit the job-done marker AFTER the work succeeds.+ job_file.write_text(json.dumps({"output_path": output}))++ return AgentToolResult(+ content=[TextContent(text=f"Transcoded to {output}.")],+ details={"output_path": output},+ )+++transcode_tool = AgentTool(+ name="transcode_video",+ description="Transcode a video file. Idempotent — safe to retry.",+ parameters=TranscodeParams,+ execute=transcode_video,+ execution_mode="sequential", # one transcode at a time+)+```++Now if the process dies during `run_ffmpeg`, the next agent run sees+`job_file.exists() == False`, redoes the work, and only writes the+marker on success. If the process dies *after* the marker was+written, the next run sees the marker, returns the cached result+immediately, and the agent continues as if it had just finished.++## Resuming the agent++```python title="resume.py"+import asyncio+import os+import sys++from cubepi import Agent, Model+from cubepi.checkpointer import SQLiteCheckpointer+from cubepi.providers.anthropic import AnthropicProvider++from tools import transcode_tool # the wrapped AgentTool from above+++async def main(thread_id: str, initial_prompt: str | None):+ async with SQLiteCheckpointer("jobs.db") as cp:+ agent = Agent(+ provider=AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"]),+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="You orchestrate video transcoding jobs.",+ tools=[transcode_tool],+ checkpointer=cp,+ thread_id=thread_id,+ )+ agent.subscribe(lambda e, s=None: None)++ if initial_prompt:+ # Fresh run. prompt() auto-loads history on first call before+ # appending the new user message.+ await agent.prompt(initial_prompt)+ else:+ # Resume. agent.resume() does NOT auto-load — only prompt() does.+ # Hydrate the agent state manually first.+ data = await cp.load(thread_id)+ if data is None:+ raise RuntimeError(f"No saved state for thread {thread_id!r}")+ agent.state.messages = list(data.messages)+ # `extra` is restored too; it's private on Agent, so use the+ # checkpointer's view if your middleware reads it.++ # Resume picks up from the last persisted message:+ # ToolResultMessage / UserMessage → re-invokes the model+ # AssistantMessage with no queued steer/follow_up → raises+ await agent.resume()+++if __name__ == "__main__":+ thread_id = sys.argv[1]+ initial = sys.argv[2] if len(sys.argv) > 2 else None+ asyncio.run(main(thread_id, initial))+```++Workflow:++```bash+# Start a job:+python resume.py job-1 "Transcode /videos/a.mov to /out/a.mp4 and /videos/b.mov to /out/b.mp4"++# Kill it mid-flight: Ctrl-C.++# Resume — agent picks up from the last persisted message:+python resume.py job-1+```++## The three resume scenarios in code++```python+async def smart_resume(agent, cp, thread_id):+ # resume() doesn't auto-load — hydrate the agent first if its state is empty.+ if not agent.state.messages:+ data = await cp.load(thread_id)+ if data is None or not data.messages:+ return False # nothing to resume from+ agent.state.messages = list(data.messages)++ last = agent.state.messages[-1]+ last_role = type(last).__name__++ if last_role == "AssistantMessage":+ # Either the run finished naturally, or it died right after a+ # turn ended. resume() raises unless there's queued steering.+ # Easiest path: ask the user what's next.+ return False++ # Last is UserMessage or ToolResultMessage — safe to resume.+ await agent.resume()+ return True+```++## Persistence + abort++`agent.abort()` triggers a clean teardown that emits `agent_end`. The+last *fully persisted* message is whatever made it through+`message_end`. Aborts during a tool's execution don't persist the+tool result (the tool didn't return), so `resume()` will re-dispatch+the model with the last `AssistantMessage` containing the unfinished+`ToolCall`. The model will usually re-issue the call — your+idempotency guards handle the rest.++## What about persisting partial tool state?++CubePi doesn't expose a "persist a partial tool result" API. The+intended pattern is: keep partial state in the tool's own+external store (filesystem, Redis, S3), keyed deterministically by the+tool args. That's what `transcode_video` above does with `JOB_DIR`.++## Common pitfalls++- **Non-idempotent tools** — Without deterministic keys, retries can+ charge a credit card twice or send a duplicate email. Always wrap+ external side-effects in an idempotency key.+- **Job markers in `/tmp`** — Cleared on reboot. Use a real+ persistence layer for production jobs.+- **`resume()` after an assistant message with no queue** — Raises.+ Either prompt the user for the next message or call `prompt()`+ fresh.+- **`resume()` on a fresh agent** — Raises `No messages to continue+ from`. `resume()` does not auto-load from the checkpointer; only+ `prompt()` does. Hydrate manually with `agent.state.messages =+ (await cp.load(thread_id)).messages` first.+- **Forgetting the signal check inside the tool** — A long+ `await asyncio.sleep(...)` or a `for ... in stream` that ignores+ `signal.is_set()` won't honour `abort`. Drop a check inside any+ hot loop.++## See also++- [Multi-turn → `resume()`](../guides/agents/multi-turn#resume--continue-from-the-last-message)+ — full semantics.+- [Persistent Chat](./persistent-chat) — the simpler restartable+ scenario.+- [SQLite Checkpointing](../guides/checkpointing/sqlite) — what's+ persisted, when.diff --git a/website/versioned_docs/version-0.5/recipes/weather-agent.md b/website/versioned_docs/version-0.5/recipes/weather-agent.mdnew file mode 100644index 0000000..96cc4d6--- /dev/null+++ b/website/versioned_docs/version-0.5/recipes/weather-agent.md@@ -0,0 +1,160 @@+---+title: Weather Agent+---++# Recipe: Weather Agent++A complete, runnable agent that calls a real weather API as a tool.+Demonstrates HTTP-calling tools, error handling, streaming UI, and+cancellation.++**Time to run:** 5 minutes.+**Deps:** `cubepi`, `httpx`, an `ANTHROPIC_API_KEY`.++## The script++```python title="weather_agent.py"+import asyncio+import os++import httpx+from pydantic import BaseModel, Field++from cubepi import Agent, AgentTool, AgentToolResult, Model, TextContent+from cubepi.providers.anthropic import AnthropicProvider+++# --- The tool -----------------------------------------------------------++class GetWeatherParams(BaseModel):+ city: str = Field(..., description="The city to look up weather for")+ units: str = Field("metric", pattern="^(metric|imperial)$")+++async def get_weather(tool_call_id, params: GetWeatherParams, *, signal=None, on_update=None):+ # Free Open-Meteo geocoding + forecast. No API key required.+ async with httpx.AsyncClient(timeout=10) as client:+ try:+ geo = await client.get(+ "https://geocoding-api.open-meteo.com/v1/search",+ params={"name": params.city, "count": 1, "language": "en"},+ )+ geo.raise_for_status()+ results = geo.json().get("results")+ if not results:+ return AgentToolResult(+ content=[TextContent(text=f"Couldn't find a city named {params.city!r}.")],+ is_error=True,+ )+ lat, lon = results[0]["latitude"], results[0]["longitude"]++ wx = await client.get(+ "https://api.open-meteo.com/v1/forecast",+ params={+ "latitude": lat,+ "longitude": lon,+ "current_weather": True,+ "temperature_unit": "celsius" if params.units == "metric" else "fahrenheit",+ },+ )+ wx.raise_for_status()+ cw = wx.json()["current_weather"]+ unit = "°C" if params.units == "metric" else "°F"+ return AgentToolResult(+ content=[TextContent(text=f"{cw['temperature']}{unit}, wind {cw['windspeed']} km/h in {params.city}.")],+ )+ except httpx.HTTPError as e:+ return AgentToolResult(+ content=[TextContent(text=f"Weather API error: {e}")],+ is_error=True,+ )+++weather_tool = AgentTool(+ name="get_weather",+ description="Get current weather for a city. Returns a short text summary.",+ parameters=GetWeatherParams,+ execute=get_weather,+)+++# --- The agent ----------------------------------------------------------++async def main():+ provider = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])+ agent = Agent(+ provider=provider,+ model=Model(id="claude-sonnet-4-5-20250929", provider="anthropic"),+ system_prompt="You are a concise weather assistant. Always use the tool; don't guess.",+ tools=[weather_tool],+ )++ def on_event(event, signal=None):+ if event.type == "message_update" and event.stream_event.type == "text_delta":+ print(event.stream_event.delta, end="", flush=True)+ elif event.type == "tool_execution_start":+ print(f"\n[calling {event.tool_name}({event.args})]")+ elif event.type == "agent_end":+ print()++ agent.subscribe(on_event)++ # Wrap prompt() so Ctrl-C cleanly cancels the run.+ task = asyncio.create_task(agent.prompt("Weather in Tokyo and São Paulo, please."))+ try:+ await task+ except KeyboardInterrupt:+ agent.abort()+ await agent.wait_for_idle()+++if __name__ == "__main__":+ asyncio.run(main())+```++Run:++```bash+pip install cubepi httpx+export ANTHROPIC_API_KEY=sk-…+python weather_agent.py+```++Sample output:++```+[calling get_weather({'city': 'Tokyo', 'units': 'metric'})]+[calling get_weather({'city': 'São Paulo', 'units': 'metric'})]+Tokyo is currently 18°C with a wind speed of 12 km/h. São Paulo is 25°C with winds of 9 km/h.+```++## What's going on++- **Two tools in parallel.** The model emits two `get_weather` tool+ calls in the same assistant turn. CubePi runs them concurrently —+ the second one doesn't wait for the first.+- **Streaming text + tool events interleave.** The `on_event` filter+ handles both `text_delta` (for the final answer) and+ `tool_execution_start` (for the "thinking" indicator).+- **Errors are tool results, not exceptions.** A bad city or network+ hiccup returns `is_error=True`; the model gets the error message+ and usually retries with a different spelling.+- **Cancellation is clean.** `agent.abort()` propagates through+ `signal` into in-flight tools and the provider stream.++## Extending this recipe++- **Add caching:** memoize the geocoding lookup by `city` —+ Open-Meteo's coordinates are stable.+- **Add retries:** wrap with [`RetryMiddleware`](../guides/middleware/examples#retries-with-backoff)+ to handle transient API errors.+- **Persist conversations:** add a+ [`SQLiteCheckpointer`](../guides/checkpointing/sqlite) so follow-up+ questions ("and in Osaka?") have history.++## See also++- [Building Your First Agent](../guides/agents/first-agent) — the same+ pattern with a hard-coded tool.+- [Tool Use & Parallel Execution](../guides/agents/tool-use) — more on+ parallel tool calls.diff --git a/website/versioned_sidebars/version-0.5-sidebars.json b/website/versioned_sidebars/version-0.5-sidebars.jsonnew file mode 100644index 0000000..79ab136--- /dev/null+++ b/website/versioned_sidebars/version-0.5-sidebars.json@@ -0,0 +1,113 @@+{+ "docs": [+ "intro",+ {+ "type": "category",+ "label": "Getting Started",+ "collapsed": false,+ "items": [+ "getting-started/installation",+ "getting-started/quick-start",+ "getting-started/core-concepts"+ ]+ },+ {+ "type": "category",+ "label": "Guides",+ "items": [+ {+ "type": "category",+ "label": "Agents",+ "items": [+ "guides/agents/first-agent",+ "guides/agents/tool-use",+ "guides/agents/multi-turn",+ "guides/agents/streaming"+ ]+ },+ {+ "type": "category",+ "label": "Providers",+ "items": [+ "guides/providers/anthropic",+ "guides/providers/openai",+ "guides/providers/capability-and-presets",+ "guides/providers/custom"+ ]+ },+ {+ "type": "category",+ "label": "Checkpointing",+ "items": [+ "guides/checkpointing/sqlite",+ "guides/checkpointing/postgres",+ "guides/checkpointing/custom"+ ]+ },+ {+ "type": "category",+ "label": "Middleware",+ "items": [+ "guides/middleware/hooks",+ "guides/middleware/composition",+ "guides/middleware/examples"+ ]+ },+ {+ "type": "category",+ "label": "MCP",+ "items": [+ "guides/mcp/loading",+ "guides/mcp/auth"+ ]+ },+ {+ "type": "category",+ "label": "Tracing",+ "items": [+ "guides/tracing/overview",+ "guides/tracing/getting-started",+ "guides/tracing/otlp",+ "guides/tracing/content-recording",+ "guides/tracing/metrics"+ ]+ }+ ]+ },+ {+ "type": "category",+ "label": "API Reference",+ "link": {+ "type": "doc",+ "id": "api/index"+ },+ "items": [+ "api/cubepi-agent",+ "api/cubepi-providers",+ "api/cubepi-checkpointer",+ "api/cubepi-middleware",+ "api/cubepi-mcp",+ "api/cubepi-tracing",+ "api/cubepi-utils"+ ]+ },+ {+ "type": "category",+ "label": "Recipes",+ "items": [+ "recipes/weather-agent",+ "recipes/multi-provider-failover",+ "recipes/persistent-chat",+ "recipes/resumable-tasks",+ "recipes/postgres-fastapi"+ ]+ },+ {+ "type": "category",+ "label": "Migration",+ "items": [+ "migration/from-langgraph"+ ]+ }+ ]+}diff --git a/website/versions.json b/website/versions.jsonindex 9635242..1bd54b5 100644--- a/website/versions.json+++ b/website/versions.json@@ -1,4 +1,5 @@[+ "0.5","0.4","0.3"]