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 AGENTS.md with project context and dev workflow (#105)
Chrisb36083e7bdc8
diff --git a/.gitignore b/.gitignoreindex a2b60ea..1f79959 100644--- a/.gitignore+++ b/.gitignore@@ -1,6 +1,3 @@-docs/specs-docs/plans-# Python__pycache__/*.pycdiff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..54abcd2--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,85 @@+# cubepi++Pythonic async-native agent framework (an alternative to langgraph). Async-first,+strongly typed, deliberately few dependencies.++## Commands (always via `uv`)++```bash+uv sync --all-extras --dev # install everything+uv run pytest tests/ # run tests (asyncio_mode=auto)+uv run pytest tests/path/test.py::test -v # single test+uv run ruff check cubepi/ tests/+uv run ruff format --check cubepi/ tests/ # CI checks formatting, doesn't fix+```++CI runs pytest + ruff only. **There is no mypy step** — ignore the stale+`.mypy_cache/`. Tests run on Python 3.11–3.14 (3.14 is `continue-on-error`);+local default is 3.13 (`.python-version`).++## Architecture++`cubepi/` modules: `providers/` (LLM abstraction — `Provider` protocol returning+`MessageStream`; anthropic / openai / openai_responses / faux), `agent/`+(`agent.py` stateful class, `loop.py` stateless core algorithm, `tools.py`+execution engine), `middleware/`, `checkpointer/` (memory / sqlite / postgres),+`mcp/`, `tracing/` (OTel, optional), `cli/` (`cubepi trace`). See the README+"Architecture" section for the full annotated tree.++## Conventions & gotchas++- **Lean deps**: core deps are anthropic, openai, pydantic, pyyaml only.+ Everything else (sqlite, postgres, mcp, tracing, trace-cli) is an optional+ extra in `pyproject.toml`. Don't add a hard dependency without strong reason.+- **`cubepi.tracing` is lazily importable** (PEP 562 `__getattr__`): schema+ constants import without the opentelemetry SDK, so the trace CLI works on a+ `cubepi[trace-cli]`-only install. Don't add eager OTel imports to its+ `__init__.py`.+- **Tests use `FauxProvider`** for deterministic, no-API-call runs with realistic+ streaming. Prefer it over mocking providers.+- **`cubepi/cli/**` is excluded from codecov** (`codecov.yml` ignore).+- Packaged data: `cubepi/providers/catalog/data/*.yaml` ships in the wheel.++## Development workflow++This project follows a deliberate spec → plan → code pipeline. Honor it for any+non-trivial work.++**1. Set up an isolated worktree first.** When a new requirement comes in, before+doing any work create a **date-prefixed worktree on a date-prefixed branch**+(e.g. `.worktrees/YYYY-MM-DD-<topic>` on branch `YYYY-MM-DD-<topic>`). Never work+directly on `main`. Subagents that write code must also use `isolation:+"worktree"`.++**2. Spec — collaborate, don't go autonomous.** The spec stage is interactive:+talk through and confirm requirements with the user before writing the spec.+While forming it, research prior art — **pi-agent-core, langgraph, claude code** —+to find best practices, but let our own requirements and design philosophy drive+the result. Call out notable divergences ("library does X, cubepi does Y because+Z") so they can be reviewed. Specs go in `dev/specs/` (dated+`YYYY-MM-DD-<topic>.md`), plans in `dev/plans/`.++Codex reviews happen in **two distinct phases** — local (step 3) and on the PR+(step 5).++**3. Local codex review loop — ask before entering it.** Once spec/plan/code are+ready, **check with the user before starting the local codex review loop.** If+they say go: run it autonomously without stopping to ask mid-flow — write the spec+→ codex review; write the plan → codex review; write the code → codex review and+iterate until codex is OK. Use the `codex:rescue` subagent for these reviews.++**4. Document the feature, then open the PR.** Every completed feature **must**+ship with its user-facing docs — add or update the relevant page under+`website/docs/` (e.g. `guides/`, `getting-started/`, `recipes/`) in the same PR.+A feature without docs is not done. Then open a PR from the worktree branch+(never commit to `main` directly — it's a protected branch).++**5. PR codex review loop.** Opening the PR triggers an automatic codex review.+After that it is **not** automatic — drive it manually:++- Poll for feedback every **~2 minutes** (check the PR's review comments).+- Resolve every piece of feedback, pushing fixes to the branch.+- Once resolved, **reply `@codex` on the PR to request another review pass.**+- Repeat poll → fix → `@codex` until codex reports no remaining issues.++Merge only after the PR codex review is clean and CI passes.diff --git a/CLAUDE.md b/CLAUDE.mdnew file mode 120000index 0000000..47dc3e3--- /dev/null+++ b/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/dev/plans/2026-05-09-cubepi-implementation.md b/dev/plans/2026-05-09-cubepi-implementation.mdnew file mode 100644index 0000000..ff8d3e6--- /dev/null+++ b/dev/plans/2026-05-09-cubepi-implementation.md@@ -0,0 +1,5153 @@+# cubepi Framework Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Implement cubepi, a Pythonic async-native agent framework with multi-provider LLM streaming, hook/middleware extensibility, and optional checkpointing.++**Architecture:** Bottom-up build order — provider types first, then streaming, then FauxProvider (enables all later tests), then agent loop, Agent class, middleware, and checkpointers. Each task produces working, tested code.++**Tech Stack:** Python 3.11+, Pydantic v2, pytest + pytest-asyncio, anthropic SDK, openai SDK, aiosqlite++**Spec:** `docs/specs/2026-05-09-cubepi-framework-design.md`++**Pi source reference:** `$HOME/pi/packages/agent/src/` (agent-loop.ts, agent.ts, types.ts) and `$HOME/pi/packages/ai/src/providers/faux.ts`++---++## File Structure++```+cubepi/+├── __init__.py # Public re-exports+├── py.typed # PEP 561 marker+├── providers/+│ ├── __init__.py # Re-exports: Provider, MessageStream, types+│ ├── base.py # Provider Protocol, MessageStream, StreamEvent, all message/content types+│ ├── faux.py # FauxProvider (public test utility)+│ ├── anthropic.py # AnthropicProvider+│ └── openai.py # OpenAIProvider+├── agent/+│ ├── __init__.py # Re-exports: Agent, run_agent_loop, AgentTool, etc.+│ ├── types.py # AgentEvent, AgentContext, AgentTool, hook types, AgentState+│ ├── loop.py # run_agent_loop, run_agent_loop_continue, internal runLoop+│ ├── tools.py # Tool execution engine (sequential/parallel)+│ └── agent.py # Agent class (stateful wrapper)+├── middleware/+│ ├── __init__.py # Re-exports: Middleware, compose_middleware+│ └── base.py # Middleware Protocol + compose_middleware()+├── checkpointer/+│ ├── __init__.py # Re-exports: Checkpointer, CheckpointData+│ ├── base.py # Checkpointer Protocol, CheckpointData+│ ├── memory.py # MemoryCheckpointer+│ └── sqlite.py # SQLiteCheckpointer+tests/+├── conftest.py # Shared fixtures (faux provider helpers)+├── providers/+│ ├── test_base.py # Message type tests+│ ├── test_faux.py # FauxProvider tests+│ ├── test_anthropic.py # AnthropicProvider unit tests+│ └── test_openai.py # OpenAIProvider unit tests+├── agent/+│ ├── test_types.py # AgentTool, event type tests+│ ├── test_loop.py # Agent loop tests (ported from pi)+│ ├── test_tools.py # Tool execution engine tests+│ ├── test_agent.py # Agent class tests (ported from pi)+│ └── test_e2e.py # E2E tests (ported from pi)+├── middleware/+│ └── test_base.py # Middleware composition tests+└── checkpointer/+ ├── test_memory.py # MemoryCheckpointer tests+ └── test_sqlite.py # SQLiteCheckpointer tests+pyproject.toml # Project config, dependencies, pytest config+```++---++### Task 1: Project Scaffolding++**Files:**+- Create: `pyproject.toml`+- Create: `cubepi/__init__.py`+- Create: `cubepi/py.typed`+- Create: `cubepi/providers/__init__.py`+- Create: `cubepi/agent/__init__.py`+- Create: `cubepi/middleware/__init__.py`+- Create: `cubepi/checkpointer/__init__.py`+- Create: `tests/__init__.py`+- Create: `tests/conftest.py`+- Create: `tests/providers/__init__.py`+- Create: `tests/agent/__init__.py`+- Create: `tests/middleware/__init__.py`+- Create: `tests/checkpointer/__init__.py`++- [ ] **Step 1: Initialize project with uv and add dependencies**++```bash+cd /home/chris/cubepi+uv init --name cubepi --python ">=3.11"+uv add pydantic anthropic openai+uv add --optional sqlite aiosqlite+uv add --dev pytest pytest-asyncio pytest-cov+```++Then edit pyproject.toml to add pytest config and build target:++```toml+[tool.pytest.ini_options]+asyncio_mode = "auto"+testpaths = ["tests"]++[tool.hatch.build.targets.wheel]+packages = ["cubepi"]+```++- [ ] **Step 2: Create empty package init files and py.typed marker**++Create `cubepi/__init__.py` (empty for now, will add re-exports as modules are built):+```python+"""cubepi — Pythonic async-native agent framework."""+```++Create `cubepi/py.typed` (empty file — PEP 561 marker).++Create empty `__init__.py` files in:+- `cubepi/providers/__init__.py`+- `cubepi/agent/__init__.py`+- `cubepi/middleware/__init__.py`+- `cubepi/checkpointer/__init__.py`+- `tests/__init__.py`+- `tests/conftest.py` (empty for now)+- `tests/providers/__init__.py`+- `tests/agent/__init__.py`+- `tests/middleware/__init__.py`+- `tests/checkpointer/__init__.py`++- [ ] **Step 3: Verify pytest runs**++```bash+uv run pytest --co # Should collect 0 tests, no errors+```++- [ ] **Step 4: Commit**++```bash+git add pyproject.toml cubepi/ tests/+git commit -m "chore: scaffold cubepi project structure"+```++---++### Task 2: Provider Base Types++**Files:**+- Create: `cubepi/providers/base.py`+- Create: `tests/providers/test_base.py`++This is the foundation — all other modules depend on these types. Matches pi-ai's type system with Pydantic models.++- [ ] **Step 1: Write tests for message types**++Create `tests/providers/test_base.py`:++```python+import asyncio+from typing import Any++from cubepi.providers.base import (+ AssistantMessage,+ Content,+ ImageContent,+ MessageStream,+ Model,+ ModelCost,+ StreamEvent,+ TextContent,+ ThinkingContent,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ Usage,+ UserMessage,+)+++class TestMessageTypes:+ def test_text_content_defaults(self):+ tc = TextContent()+ assert tc.type == "text"+ assert tc.text == ""++ def test_text_content_with_value(self):+ tc = TextContent(text="hello")+ assert tc.text == "hello"++ def test_image_content(self):+ ic = ImageContent(source="base64data", media_type="image/png")+ assert ic.type == "image"+ assert ic.source == "base64data"+ assert ic.media_type == "image/png"++ def test_thinking_content(self):+ tc = ThinkingContent(thinking="step by step")+ assert tc.type == "thinking"+ assert tc.thinking == "step by step"++ def test_tool_call(self):+ tc = ToolCall(id="tc-1", name="search", arguments={"query": "hello"})+ assert tc.type == "tool_call"+ assert tc.id == "tc-1"+ assert tc.name == "search"+ assert tc.arguments == {"query": "hello"}++ def test_user_message(self):+ msg = UserMessage(content=[TextContent(text="hi")])+ assert msg.role == "user"+ assert msg.timestamp is None++ def test_assistant_message_defaults(self):+ msg = AssistantMessage(content=[TextContent(text="hello")])+ assert msg.role == "assistant"+ assert msg.stop_reason == "stop"+ assert msg.error_message is None+ assert msg.usage is None++ def test_assistant_message_with_tool_calls(self):+ msg = AssistantMessage(+ content=[+ TextContent(text="Let me search."),+ ToolCall(id="tc-1", name="search", arguments={"q": "test"}),+ ],+ stop_reason="tool_use",+ )+ assert len(msg.content) == 2+ assert msg.content[1].type == "tool_call"++ def test_tool_result_message(self):+ msg = ToolResultMessage(+ tool_call_id="tc-1",+ tool_name="search",+ content=[TextContent(text="result")],+ )+ assert msg.role == "tool_result"+ assert msg.is_error is False++ def test_model_defaults(self):+ m = Model(id="gpt-4o", provider="openai")+ assert m.context_window == 200_000+ assert m.max_tokens == 8192+ assert m.reasoning is False+ assert m.cost is None++ def test_usage(self):+ u = Usage()+ assert u.input_tokens == 0+ assert u.output_tokens == 0++ def test_model_cost(self):+ c = ModelCost(input=3.0, output=15.0)+ assert c.cache_read == 0++ def test_tool_definition(self):+ td = ToolDefinition(+ name="search",+ description="Search the web",+ parameters={"type": "object", "properties": {"q": {"type": "string"}}},+ )+ assert td.name == "search"+++class TestMessageStream:+ async def test_stream_iteration_and_result(self):+ stream = MessageStream()+ msg = AssistantMessage(content=[TextContent(text="hello")])++ async def produce():+ await asyncio.sleep(0)+ stream.push(StreamEvent(type="text_delta", delta="hello"))+ stream.push(StreamEvent(type="done"))+ stream.set_result(msg)++ asyncio.create_task(produce())++ events = []+ async for event in stream:+ events.append(event)++ assert len(events) == 2+ assert events[0].type == "text_delta"+ assert events[1].type == "done"++ result = await stream.result()+ assert result.content[0].text == "hello"++ async def test_stream_error_event(self):+ stream = MessageStream()+ error_msg = AssistantMessage(+ content=[],+ stop_reason="error",+ error_message="API error",+ )++ async def produce():+ await asyncio.sleep(0)+ stream.push(StreamEvent(type="error", error_message="API error"))+ stream.set_result(error_msg)++ asyncio.create_task(produce())++ events = []+ async for event in stream:+ events.append(event)++ result = await stream.result()+ assert result.stop_reason == "error"+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/providers/test_base.py -v+```++Expected: ImportError — `cubepi.providers.base` module does not exist yet.++- [ ] **Step 3: Implement provider base types**++Create `cubepi/providers/base.py`:++```python+from __future__ import annotations++import asyncio+from typing import Any, AsyncIterator, Literal, Protocol, runtime_checkable++from pydantic import BaseModel++ThinkingLevel = Literal["off", "minimal", "low", "medium", "high", "xhigh"]+++class ModelCost(BaseModel):+ input: float = 0+ output: float = 0+ cache_read: float = 0+ cache_write: float = 0+++class Usage(BaseModel):+ input_tokens: int = 0+ output_tokens: int = 0+ cache_read_tokens: int = 0+ cache_write_tokens: int = 0+++class Model(BaseModel):+ id: str+ provider: str+ api: str = ""+ reasoning: bool = False+ context_window: int = 200_000+ max_tokens: int = 8192+ cost: ModelCost | None = None+++class TextContent(BaseModel):+ type: Literal["text"] = "text"+ text: str = ""+++class ImageContent(BaseModel):+ type: Literal["image"] = "image"+ source: str = ""+ media_type: str = ""+++class ThinkingContent(BaseModel):+ type: Literal["thinking"] = "thinking"+ thinking: str = ""+++Content = TextContent | ImageContent+++class ToolCall(BaseModel):+ type: Literal["tool_call"] = "tool_call"+ id: str+ name: str+ arguments: dict[str, Any]+++class UserMessage(BaseModel):+ role: Literal["user"] = "user"+ content: list[Content]+ timestamp: float | None = None+++class AssistantMessage(BaseModel):+ role: Literal["assistant"] = "assistant"+ content: list[Content | ThinkingContent | ToolCall]+ stop_reason: str = "stop"+ error_message: str | None = None+ usage: Usage | None = None+ timestamp: float | None = None+++class ToolResultMessage(BaseModel):+ role: Literal["tool_result"] = "tool_result"+ tool_call_id: str+ tool_name: str+ content: list[Content]+ is_error: bool = False+ timestamp: float | None = None+++Message = UserMessage | AssistantMessage | ToolResultMessage+++class ToolDefinition(BaseModel):+ name: str+ description: str+ parameters: dict[str, Any]+++class StreamEvent(BaseModel):+ type: Literal[+ "start",+ "text_start", "text_delta", "text_end",+ "thinking_start", "thinking_delta", "thinking_end",+ "toolcall_start", "toolcall_delta", "toolcall_end",+ "done", "error",+ ]+ delta: str | None = None+ partial: AssistantMessage | None = None+ error_message: str | None = None+++class MessageStream:+ def __init__(self) -> None:+ self._queue: asyncio.Queue[StreamEvent | None] = asyncio.Queue()+ self._result_future: asyncio.Future[AssistantMessage] = asyncio.get_event_loop().create_future()++ def push(self, event: StreamEvent) -> None:+ self._queue.put_nowait(event)+ if event.type in ("done", "error"):+ self._queue.put_nowait(None)++ def set_result(self, message: AssistantMessage) -> None:+ if not self._result_future.done():+ self._result_future.set_result(message)++ def __aiter__(self) -> AsyncIterator[StreamEvent]:+ return self++ async def __anext__(self) -> StreamEvent:+ item = await self._queue.get()+ if item is None:+ raise StopAsyncIteration+ return item++ async def result(self) -> AssistantMessage:+ return await self._result_future+++@runtime_checkable+class Provider(Protocol):+ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ thinking: ThinkingLevel = "off",+ signal: asyncio.Event | None = None,+ ) -> MessageStream: ...+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/providers/test_base.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Update providers `__init__.py` with re-exports**++Update `cubepi/providers/__init__.py`:++```python+from cubepi.providers.base import (+ AssistantMessage,+ Content,+ ImageContent,+ Message,+ MessageStream,+ Model,+ ModelCost,+ Provider,+ StreamEvent,+ TextContent,+ ThinkingContent,+ ThinkingLevel,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ Usage,+ UserMessage,+)++__all__ = [+ "AssistantMessage",+ "Content",+ "ImageContent",+ "Message",+ "MessageStream",+ "Model",+ "ModelCost",+ "Provider",+ "StreamEvent",+ "TextContent",+ "ThinkingContent",+ "ThinkingLevel",+ "ToolCall",+ "ToolDefinition",+ "ToolResultMessage",+ "Usage",+ "UserMessage",+]+```++- [ ] **Step 6: Commit**++```bash+git add cubepi/providers/ tests/providers/+git commit -m "feat: add provider base types and message stream"+```++---++### Task 3: FauxProvider++**Files:**+- Create: `cubepi/providers/faux.py`+- Create: `tests/providers/test_faux.py`++Port pi's `faux.ts`. This is the test infrastructure everything else depends on. The cubepi version is simpler — it implements the `Provider` protocol directly instead of using pi's global API registry.++- [ ] **Step 1: Write FauxProvider tests**++Create `tests/providers/test_faux.py`:++```python+import asyncio++from cubepi.providers.base import (+ AssistantMessage,+ StreamEvent,+ TextContent,+ ThinkingContent,+ ToolCall,+)+from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_text, faux_thinking, faux_tool_call+++class TestFauxHelpers:+ def test_faux_text(self):+ block = faux_text("hello")+ assert block.type == "text"+ assert block.text == "hello"++ def test_faux_thinking(self):+ block = faux_thinking("step by step")+ assert block.type == "thinking"+ assert block.thinking == "step by step"++ def test_faux_tool_call(self):+ block = faux_tool_call("search", {"q": "test"}, id="tc-1")+ assert block.type == "tool_call"+ assert block.id == "tc-1"+ assert block.name == "search"++ def test_faux_tool_call_auto_id(self):+ block = faux_tool_call("search", {"q": "test"})+ assert block.id.startswith("tool:")++ def test_faux_assistant_message_string(self):+ msg = faux_assistant_message("hello")+ assert msg.role == "assistant"+ assert len(msg.content) == 1+ assert msg.content[0].type == "text"+ assert msg.content[0].text == "hello"+ assert msg.stop_reason == "stop"++ def test_faux_assistant_message_blocks(self):+ msg = faux_assistant_message([faux_text("hi"), faux_tool_call("search", {"q": "x"}, id="t1")])+ assert len(msg.content) == 2+ assert msg.content[0].type == "text"+ assert msg.content[1].type == "tool_call"++ def test_faux_assistant_message_tool_use_stop_reason(self):+ msg = faux_assistant_message(+ [faux_tool_call("search", {"q": "x"}, id="t1")],+ stop_reason="tool_use",+ )+ assert msg.stop_reason == "tool_use"+++class TestFauxProvider:+ def _make_model(self):+ from cubepi.providers.base import Model+ return Model(id="faux-1", provider="faux")++ async def test_basic_text_response(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("hello world")])+ model = self._make_model()++ stream = await provider.stream(model, [])+ events = [e async for e in stream]+ result = await stream.result()++ assert result.content[0].text == "hello world"+ assert result.stop_reason == "stop"+ assert any(e.type == "done" for e in events)++ async def test_responses_consumed_in_order(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message("first"),+ faux_assistant_message("second"),+ ])+ model = self._make_model()++ stream1 = await provider.stream(model, [])+ _ = [e async for e in stream1]+ r1 = await stream1.result()++ stream2 = await provider.stream(model, [])+ _ = [e async for e in stream2]+ r2 = await stream2.result()++ assert r1.content[0].text == "first"+ assert r2.content[0].text == "second"++ async def test_error_when_queue_exhausted(self):+ provider = FauxProvider()+ model = self._make_model()++ stream = await provider.stream(model, [])+ _ = [e async for e in stream]+ result = await stream.result()++ assert result.stop_reason == "error"+ assert "No more faux responses" in (result.error_message or "")++ async def test_set_responses_replaces_queue(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("old")])+ provider.set_responses([faux_assistant_message("new")])+ model = self._make_model()++ stream = await provider.stream(model, [])+ _ = [e async for e in stream]+ result = await stream.result()++ assert result.content[0].text == "new"++ async def test_append_responses(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("first")])+ provider.append_responses([faux_assistant_message("second")])+ model = self._make_model()++ assert provider.pending_response_count == 2++ async def test_async_response_factory(self):+ async def factory(context, model):+ return faux_assistant_message("dynamic response")++ provider = FauxProvider()+ provider.set_responses([factory])+ model = self._make_model()++ stream = await provider.stream(model, [])+ _ = [e async for e in stream]+ result = await stream.result()++ assert result.content[0].text == "dynamic response"++ async def test_streams_text_deltas(self):+ provider = FauxProvider(token_size_min=1, token_size_max=1)+ provider.set_responses([faux_assistant_message("AB")])+ model = self._make_model()++ stream = await provider.stream(model, [])+ events = [e async for e in stream]+ event_types = [e.type for e in events]++ assert "start" in event_types+ assert "text_start" in event_types+ assert "text_delta" in event_types+ assert "text_end" in event_types+ assert "done" in event_types++ async def test_streams_thinking_deltas(self):+ provider = FauxProvider(token_size_min=1, token_size_max=1)+ provider.set_responses([faux_assistant_message([faux_thinking("think"), faux_text("ok")])])+ model = self._make_model()++ stream = await provider.stream(model, [])+ events = [e async for e in stream]+ event_types = [e.type for e in events]++ assert "thinking_start" in event_types+ assert "thinking_delta" in event_types+ assert "thinking_end" in event_types++ async def test_streams_tool_call_deltas(self):+ provider = FauxProvider(token_size_min=1, token_size_max=1)+ provider.set_responses([+ faux_assistant_message(+ [faux_tool_call("search", {"q": "test"}, id="t1")],+ stop_reason="tool_use",+ ),+ ])+ model = self._make_model()++ stream = await provider.stream(model, [])+ events = [e async for e in stream]+ event_types = [e.type for e in events]++ assert "toolcall_start" in event_types+ assert "toolcall_delta" in event_types+ assert "toolcall_end" in event_types++ async def test_abort_before_start(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("hello")])+ model = self._make_model()+ signal = asyncio.Event()+ signal.set()++ stream = await provider.stream(model, [], signal=signal)+ events = [e async for e in stream]+ result = await stream.result()++ assert result.stop_reason == "aborted"++ async def test_abort_mid_stream(self):+ provider = FauxProvider(tokens_per_second=20, token_size_min=2, token_size_max=2)+ provider.set_responses([+ faux_assistant_message("one two three four five six seven eight nine ten"),+ ])+ model = self._make_model()+ signal = asyncio.Event()++ stream = await provider.stream(model, [], signal=signal)++ events = []+ count = 0+ async for event in stream:+ events.append(event)+ count += 1+ if count >= 3:+ signal.set()++ result = await stream.result()+ assert result.stop_reason == "aborted"++ async def test_error_message_passthrough(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message("", stop_reason="error", error_message="API rate limit"),+ ])+ model = self._make_model()++ stream = await provider.stream(model, [])+ events = [e async for e in stream]+ result = await stream.result()++ assert result.stop_reason == "error"+ assert any(e.type == "error" for e in events)++ async def test_multiple_tool_calls_in_one_message(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message(+ [+ faux_tool_call("search", {"q": "a"}, id="t1"),+ faux_tool_call("search", {"q": "b"}, id="t2"),+ ],+ stop_reason="tool_use",+ ),+ ])+ model = self._make_model()++ stream = await provider.stream(model, [])+ events = [e async for e in stream]+ result = await stream.result()++ toolcall_starts = [e for e in events if e.type == "toolcall_start"]+ assert len(toolcall_starts) == 2++ async def test_call_count_tracking(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("a"), faux_assistant_message("b")])+ model = self._make_model()++ assert provider.call_count == 0++ s1 = await provider.stream(model, [])+ _ = [e async for e in s1]+ assert provider.call_count == 1++ s2 = await provider.stream(model, [])+ _ = [e async for e in s2]+ assert provider.call_count == 2+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/providers/test_faux.py -v+```++Expected: ImportError — `cubepi.providers.faux` does not exist yet.++- [ ] **Step 3: Implement FauxProvider**++Create `cubepi/providers/faux.py`:++```python+from __future__ import annotations++import asyncio+import json+import math+import time+from typing import Any, Awaitable, Callable++from cubepi.providers.base import (+ AssistantMessage,+ Message,+ MessageStream,+ Model,+ StreamEvent,+ TextContent,+ ThinkingContent,+ ToolCall,+ ToolDefinition,+ ThinkingLevel,+ Usage,+)++FauxContentBlock = TextContent | ThinkingContent | ToolCall++FauxResponseFactory = Callable[+ [list[Message], Model],+ AssistantMessage | Awaitable[AssistantMessage],+]++FauxResponseStep = AssistantMessage | FauxResponseFactory+++def _random_id(prefix: str) -> str:+ import random+ return f"{prefix}:{int(time.time() * 1000)}:{random.randbytes(6).hex()}"+++def faux_text(text: str) -> TextContent:+ return TextContent(text=text)+++def faux_thinking(thinking: str) -> ThinkingContent:+ return ThinkingContent(thinking=thinking)+++def faux_tool_call(+ name: str,+ arguments: dict[str, Any],+ *,+ id: str | None = None,+) -> ToolCall:+ return ToolCall(id=id or _random_id("tool"), name=name, arguments=arguments)+++def faux_assistant_message(+ content: str | FauxContentBlock | list[FauxContentBlock],+ *,+ stop_reason: str = "stop",+ error_message: str | None = None,+) -> AssistantMessage:+ if isinstance(content, str):+ blocks: list[FauxContentBlock] = [faux_text(content)]+ elif isinstance(content, list):+ blocks = content+ else:+ blocks = [content]+ return AssistantMessage(+ content=blocks,+ stop_reason=stop_reason,+ error_message=error_message,+ usage=Usage(),+ timestamp=time.time(),+ )+++def _split_by_token_size(text: str, min_size: int, max_size: int) -> list[str]:+ import random+ chunks: list[str] = []+ i = 0+ while i < len(text):+ token_size = random.randint(min_size, max_size)+ char_size = max(1, token_size * 4)+ chunks.append(text[i : i + char_size])+ i += char_size+ return chunks or [""]+++class FauxProvider:+ def __init__(+ self,+ *,+ tokens_per_second: float | None = None,+ token_size_min: int = 3,+ token_size_max: int = 5,+ ) -> None:+ self._responses: list[FauxResponseStep] = []+ self._tokens_per_second = tokens_per_second+ self._min = max(1, min(token_size_min, token_size_max))+ self._max = max(self._min, token_size_max)+ self.call_count = 0++ def set_responses(self, responses: list[FauxResponseStep]) -> None:+ self._responses = list(responses)++ def append_responses(self, responses: list[FauxResponseStep]) -> None:+ self._responses.extend(responses)++ @property+ def pending_response_count(self) -> int:+ return len(self._responses)++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ thinking: ThinkingLevel = "off",+ signal: asyncio.Event | None = None,+ ) -> MessageStream:+ ms = MessageStream()+ self.call_count += 1++ step = self._responses.pop(0) if self._responses else None++ async def _produce() -> None:+ try:+ if step is None:+ error_msg = AssistantMessage(+ content=[],+ stop_reason="error",+ error_message="No more faux responses queued",+ usage=Usage(),+ timestamp=time.time(),+ )+ ms.push(StreamEvent(type="error", error_message=error_msg.error_message))+ ms.set_result(error_msg)+ return++ if callable(step):+ import inspect+ if inspect.iscoroutinefunction(step):+ resolved = await step(messages, model)+ else:+ resolved = step(messages, model)+ else:+ resolved = step++ await self._stream_with_deltas(ms, resolved, signal)+ 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)++ asyncio.create_task(_produce())+ return ms++ async def _stream_with_deltas(+ self,+ stream: MessageStream,+ message: AssistantMessage,+ signal: asyncio.Event | None,+ ) -> None:+ partial = AssistantMessage(+ content=[],+ stop_reason=message.stop_reason,+ usage=message.usage,+ timestamp=message.timestamp,+ )++ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(StreamEvent(type="error", error_message="Request was aborted"))+ stream.set_result(aborted)+ return++ stream.push(StreamEvent(type="start", partial=partial.model_copy(deep=True)))++ for block in message.content:+ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(StreamEvent(type="error", error_message="Request was aborted"))+ stream.set_result(aborted)+ return++ if isinstance(block, ThinkingContent):+ partial.content.append(ThinkingContent(thinking=""))+ stream.push(StreamEvent(type="thinking_start", partial=partial.model_copy(deep=True)))+ for chunk in _split_by_token_size(block.thinking, self._min, self._max):+ await self._schedule_chunk(chunk)+ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(StreamEvent(type="error", error_message="Request was aborted"))+ stream.set_result(aborted)+ return+ last = partial.content[-1]+ if isinstance(last, ThinkingContent):+ partial.content[-1] = ThinkingContent(thinking=last.thinking + chunk)+ stream.push(StreamEvent(type="thinking_delta", delta=chunk, partial=partial.model_copy(deep=True)))+ stream.push(StreamEvent(type="thinking_end", partial=partial.model_copy(deep=True)))++ elif isinstance(block, TextContent):+ partial.content.append(TextContent(text=""))+ stream.push(StreamEvent(type="text_start", partial=partial.model_copy(deep=True)))+ for chunk in _split_by_token_size(block.text, self._min, self._max):+ await self._schedule_chunk(chunk)+ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(StreamEvent(type="error", error_message="Request was aborted"))+ stream.set_result(aborted)+ return+ last = partial.content[-1]+ if isinstance(last, TextContent):+ partial.content[-1] = TextContent(text=last.text + chunk)+ stream.push(StreamEvent(type="text_delta", delta=chunk, partial=partial.model_copy(deep=True)))+ stream.push(StreamEvent(type="text_end", partial=partial.model_copy(deep=True)))++ elif isinstance(block, ToolCall):+ partial.content.append(ToolCall(id=block.id, name=block.name, arguments={}))+ stream.push(StreamEvent(type="toolcall_start", partial=partial.model_copy(deep=True)))+ json_str = json.dumps(block.arguments)+ for chunk in _split_by_token_size(json_str, self._min, self._max):+ await self._schedule_chunk(chunk)+ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(StreamEvent(type="error", error_message="Request was aborted"))+ stream.set_result(aborted)+ return+ stream.push(StreamEvent(type="toolcall_delta", delta=chunk, partial=partial.model_copy(deep=True)))+ last = partial.content[-1]+ if isinstance(last, ToolCall):+ partial.content[-1] = ToolCall(id=block.id, name=block.name, arguments=block.arguments)+ stream.push(StreamEvent(type="toolcall_end", partial=partial.model_copy(deep=True)))++ if message.stop_reason in ("error", "aborted"):+ stream.push(StreamEvent(type="error", error_message=message.error_message))+ stream.set_result(message)+ return++ stream.push(StreamEvent(type="done"))+ stream.set_result(message)++ async def _schedule_chunk(self, chunk: str) -> None:+ if not self._tokens_per_second or self._tokens_per_second <= 0:+ await asyncio.sleep(0)+ return+ tokens = max(1, math.ceil(len(chunk) / 4))+ delay = tokens / self._tokens_per_second+ await asyncio.sleep(delay)++ @staticmethod+ def _make_aborted(partial: AssistantMessage) -> AssistantMessage:+ return partial.model_copy(update={+ "stop_reason": "aborted",+ "error_message": "Request was aborted",+ "timestamp": time.time(),+ })+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/providers/test_faux.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Commit**++```bash+git add cubepi/providers/faux.py tests/providers/test_faux.py+git commit -m "feat: add FauxProvider test utility"+```++---++### Task 4: Agent Types++**Files:**+- Create: `cubepi/agent/types.py`+- Create: `tests/agent/test_types.py`++Defines AgentEvent (11 types), AgentContext, AgentTool, hook type aliases, and AgentState. These correspond to pi's `types.ts`.++- [ ] **Step 1: Write tests for agent types**++Create `tests/agent/test_types.py`:++```python+from typing import Any++from pydantic import BaseModel++from cubepi.agent.types import (+ AgentContext,+ AgentEndEvent,+ AgentStartEvent,+ AgentTool,+ AgentToolResult,+ BeforeToolCallContext,+ BeforeToolCallResult,+ AfterToolCallContext,+ AfterToolCallResult,+ MessageEndEvent,+ MessageStartEvent,+ MessageUpdateEvent,+ ShouldStopAfterTurnContext,+ ToolExecutionEndEvent,+ ToolExecutionStartEvent,+ ToolExecutionUpdateEvent,+ TurnEndEvent,+ TurnStartEvent,+)+from cubepi.providers.base import (+ AssistantMessage,+ StreamEvent,+ TextContent,+ ToolCall,+ ToolResultMessage,+ UserMessage,+)+++class TestAgentEvents:+ def test_agent_start_event(self):+ e = AgentStartEvent()+ assert e.type == "agent_start"++ def test_agent_end_event(self):+ msg = UserMessage(content=[TextContent(text="hi")])+ e = AgentEndEvent(messages=[msg])+ assert e.type == "agent_end"+ assert len(e.messages) == 1++ def test_turn_start_event(self):+ e = TurnStartEvent()+ assert e.type == "turn_start"++ def test_turn_end_event(self):+ msg = AssistantMessage(content=[TextContent(text="hi")])+ e = TurnEndEvent(message=msg, tool_results=[])+ assert e.type == "turn_end"++ def test_message_start_event(self):+ msg = UserMessage(content=[TextContent(text="hi")])+ e = MessageStartEvent(message=msg)+ assert e.type == "message_start"++ def test_message_update_event(self):+ msg = AssistantMessage(content=[TextContent(text="h")])+ se = StreamEvent(type="text_delta", delta="h")+ e = MessageUpdateEvent(message=msg, stream_event=se)+ assert e.type == "message_update"++ def test_message_end_event(self):+ msg = AssistantMessage(content=[TextContent(text="hello")])+ e = MessageEndEvent(message=msg)+ assert e.type == "message_end"++ def test_tool_execution_events(self):+ start = ToolExecutionStartEvent(tool_call_id="t1", tool_name="search", args={"q": "test"})+ assert start.type == "tool_execution_start"++ update = ToolExecutionUpdateEvent(+ tool_call_id="t1", tool_name="search", args={"q": "test"},+ partial_result=AgentToolResult(content=[TextContent(text="partial")]),+ )+ assert update.type == "tool_execution_update"++ end = ToolExecutionEndEvent(+ tool_call_id="t1", tool_name="search",+ result=AgentToolResult(content=[TextContent(text="done")]),+ is_error=False,+ )+ assert end.type == "tool_execution_end"+++class TestAgentTool:+ async def test_tool_definition_generation(self):+ class SearchParams(BaseModel):+ query: str+ limit: int = 10++ async def execute(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text=f"found: {params.query}")])++ tool = AgentTool(+ name="search",+ description="Search the web",+ parameters=SearchParams,+ execute=execute,+ )++ defn = tool.to_definition()+ assert defn.name == "search"+ assert defn.description == "Search the web"+ assert "query" in defn.parameters.get("properties", {})+ assert "limit" in defn.parameters.get("properties", {})++ async def test_tool_execution(self):+ class EchoParams(BaseModel):+ text: str++ async def execute(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text=params.text)])++ tool = AgentTool(+ name="echo",+ description="Echo text",+ parameters=EchoParams,+ execute=execute,+ )++ result = await tool.execute("t1", EchoParams(text="hello"))+ assert result.content[0].text == "hello"+++class TestAgentContext:+ def test_context_creation(self):+ ctx = AgentContext(system_prompt="You are helpful.", messages=[], tools=[])+ assert ctx.system_prompt == "You are helpful."+ assert ctx.messages == []+++class TestHookTypes:+ def test_before_tool_call_result_defaults(self):+ r = BeforeToolCallResult()+ assert r.block is False+ assert r.reason is None++ def test_before_tool_call_result_block(self):+ r = BeforeToolCallResult(block=True, reason="Not allowed")+ assert r.block is True+ assert r.reason == "Not allowed"++ def test_after_tool_call_result_partial_override(self):+ r = AfterToolCallResult(terminate=True)+ assert r.terminate is True+ assert r.content is None+ assert r.is_error is None+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/agent/test_types.py -v+```++Expected: ImportError.++- [ ] **Step 3: Implement agent types**++Create `cubepi/agent/types.py`:++```python+from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+from typing import Any, Awaitable, Callable, Generic, Literal, TypeVar++from pydantic import BaseModel++from cubepi.providers.base import (+ AssistantMessage,+ Content,+ Message,+ Model,+ StreamEvent,+ TextContent,+ ThinkingLevel,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+)++TParams = TypeVar("TParams", bound=BaseModel)+TMessage = TypeVar("TMessage")+++class AgentToolResult(BaseModel):+ content: list[Content]+ details: Any = None+ terminate: bool | None = None+++@dataclass+class AgentTool(Generic[TParams]):+ name: str+ description: str+ parameters: type[TParams]+ execute: Callable[..., Awaitable[AgentToolResult]]+ label: str = ""+ execution_mode: Literal["sequential", "parallel"] | None = None++ def to_definition(self) -> ToolDefinition:+ schema = self.parameters.model_json_schema()+ return ToolDefinition(+ name=self.name,+ description=self.description,+ parameters=schema,+ )+++@dataclass+class AgentContext:+ system_prompt: str+ messages: list[Any]+ tools: list[AgentTool] | None = None+++# --- Hook context types ---++class BeforeToolCallResult(BaseModel):+ block: bool = False+ reason: str | None = None+++class AfterToolCallResult(BaseModel):+ content: list[Content] | None = None+ details: Any = None+ is_error: bool | None = None+ terminate: bool | None = None+++@dataclass+class BeforeToolCallContext:+ assistant_message: AssistantMessage+ tool_call: ToolCall+ args: Any+ context: AgentContext+++@dataclass+class AfterToolCallContext:+ assistant_message: AssistantMessage+ tool_call: ToolCall+ args: Any+ result: AgentToolResult+ is_error: bool+ context: AgentContext+++@dataclass+class ShouldStopAfterTurnContext:+ message: AssistantMessage+ tool_results: list[ToolResultMessage]+ context: AgentContext+ new_messages: list[Any]+++# --- Event types (11 total, matching pi) ---++class AgentStartEvent(BaseModel):+ type: Literal["agent_start"] = "agent_start"+++class AgentEndEvent(BaseModel):+ type: Literal["agent_end"] = "agent_end"+ messages: list[Any]+++class TurnStartEvent(BaseModel):+ type: Literal["turn_start"] = "turn_start"+++class TurnEndEvent(BaseModel):+ type: Literal["turn_end"] = "turn_end"+ message: Any+ tool_results: list[ToolResultMessage]+++class MessageStartEvent(BaseModel):+ type: Literal["message_start"] = "message_start"+ message: Any+++class MessageUpdateEvent(BaseModel):+ type: Literal["message_update"] = "message_update"+ message: Any+ stream_event: StreamEvent+++class MessageEndEvent(BaseModel):+ type: Literal["message_end"] = "message_end"+ message: Any+++class ToolExecutionStartEvent(BaseModel):+ type: Literal["tool_execution_start"] = "tool_execution_start"+ tool_call_id: str+ tool_name: str+ args: Any+++class ToolExecutionUpdateEvent(BaseModel):+ type: Literal["tool_execution_update"] = "tool_execution_update"+ tool_call_id: str+ tool_name: str+ args: Any = None+ partial_result: Any = None+++class ToolExecutionEndEvent(BaseModel):+ type: Literal["tool_execution_end"] = "tool_execution_end"+ tool_call_id: str+ tool_name: str+ result: Any = None+ is_error: bool = False+++AgentEvent = (+ AgentStartEvent | AgentEndEvent+ | TurnStartEvent | TurnEndEvent+ | MessageStartEvent | MessageUpdateEvent | MessageEndEvent+ | ToolExecutionStartEvent | ToolExecutionUpdateEvent | ToolExecutionEndEvent+)++AgentEventSink = Callable[[AgentEvent], Awaitable[None]]++AgentListener = Callable[[AgentEvent, asyncio.Event | None], Awaitable[None] | None]+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/agent/test_types.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Commit**++```bash+git add cubepi/agent/types.py tests/agent/test_types.py+git commit -m "feat: add agent event types, AgentTool, and hook context types"+```++---++### Task 5: Tool Execution Engine++**Files:**+- Create: `cubepi/agent/tools.py`+- Create: `tests/agent/test_tools.py`++Port pi's tool execution pipeline: `prepareToolCall` → `executePreparedToolCall` → `finalizeExecutedToolCall`, with sequential and parallel modes.++- [ ] **Step 1: Write tests for tool execution**++Create `tests/agent/test_tools.py`:++```python+import asyncio++from pydantic import BaseModel++from cubepi.agent.tools import execute_tool_calls+from cubepi.agent.types import (+ AfterToolCallResult,+ AgentContext,+ AgentTool,+ AgentToolResult,+ BeforeToolCallResult,+)+from cubepi.providers.base import AssistantMessage, TextContent, ToolCall+++class EchoParams(BaseModel):+ value: str+++def make_echo_tool(+ *,+ name: str = "echo",+ execution_mode=None,+ execute_fn=None,+) -> AgentTool:+ async def default_execute(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])++ return AgentTool(+ name=name,+ description="Echo tool",+ parameters=EchoParams,+ execute=execute_fn or default_execute,+ execution_mode=execution_mode,+ )+++def make_assistant_msg(tool_calls: list[ToolCall]) -> AssistantMessage:+ return AssistantMessage(content=tool_calls, stop_reason="tool_use")+++def make_context(tools: list[AgentTool]) -> AgentContext:+ return AgentContext(system_prompt="", messages=[], tools=tools)+++class TestSequentialExecution:+ async def test_single_tool_call(self):+ tool = make_echo_tool()+ ctx = make_context([tool])+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])++ events = []+ batch = await execute_tool_calls(+ ctx, msg, tool_execution="sequential",+ emit=lambda e: events.append(e),+ )++ assert len(batch.messages) == 1+ assert batch.messages[0].tool_call_id == "t1"+ assert not batch.messages[0].is_error+ assert batch.terminate is False++ async def test_multiple_tool_calls_run_sequentially(self):+ order = []++ async def tracked_execute(tool_call_id, params, *, signal=None, on_update=None):+ order.append(f"start:{params.value}")+ await asyncio.sleep(0.01)+ order.append(f"end:{params.value}")+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])++ tool = make_echo_tool(execute_fn=tracked_execute)+ ctx = make_context([tool])+ msg = make_assistant_msg([+ ToolCall(id="t1", name="echo", arguments={"value": "first"}),+ ToolCall(id="t2", name="echo", arguments={"value": "second"}),+ ])++ batch = await execute_tool_calls(ctx, msg, tool_execution="sequential", emit=lambda e: None)++ assert order == ["start:first", "end:first", "start:second", "end:second"]++ async def test_unknown_tool_returns_error(self):+ ctx = make_context([])+ msg = make_assistant_msg([ToolCall(id="t1", name="unknown", arguments={})])++ batch = await execute_tool_calls(ctx, msg, tool_execution="sequential", emit=lambda e: None)++ assert len(batch.messages) == 1+ assert batch.messages[0].is_error+ assert "not found" in batch.messages[0].content[0].text.lower()+++class TestParallelExecution:+ async def test_tools_run_concurrently(self):+ first_resolved = False+ parallel_observed = False+ release = asyncio.Event()++ async def slow_execute(tool_call_id, params, *, signal=None, on_update=None):+ nonlocal first_resolved, parallel_observed+ if params.value == "first":+ await release.wait()+ first_resolved = True+ if params.value == "second" and not first_resolved:+ parallel_observed = True+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])++ tool = make_echo_tool(execute_fn=slow_execute)+ ctx = make_context([tool])+ msg = make_assistant_msg([+ ToolCall(id="t1", name="echo", arguments={"value": "first"}),+ ToolCall(id="t2", name="echo", arguments={"value": "second"}),+ ])++ async def run():+ await asyncio.sleep(0.02)+ release.set()++ asyncio.create_task(run())+ batch = await execute_tool_calls(ctx, msg, tool_execution="parallel", emit=lambda e: None)++ assert parallel_observed+ assert len(batch.messages) == 2+ assert batch.messages[0].tool_call_id == "t1"+ assert batch.messages[1].tool_call_id == "t2"++ async def test_sequential_tool_forces_sequential_mode(self):+ order = []++ async def tracked(tool_call_id, params, *, signal=None, on_update=None):+ order.append(f"start:{params.value}")+ await asyncio.sleep(0.01)+ order.append(f"end:{params.value}")+ return AgentToolResult(content=[TextContent(text="ok")])++ tool = make_echo_tool(execute_fn=tracked, execution_mode="sequential")+ ctx = make_context([tool])+ msg = make_assistant_msg([+ ToolCall(id="t1", name="echo", arguments={"value": "a"}),+ ToolCall(id="t2", name="echo", arguments={"value": "b"}),+ ])++ batch = await execute_tool_calls(ctx, msg, tool_execution="parallel", emit=lambda e: None)++ assert order[0] == "start:a"+ assert order[1] == "end:a"+++class TestBeforeToolCall:+ async def test_block_prevents_execution(self):+ tool = make_echo_tool()+ ctx = make_context([tool])+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])++ async def before(ctx_arg, *, signal=None):+ return BeforeToolCallResult(block=True, reason="Blocked by test")++ batch = await execute_tool_calls(+ ctx, msg, tool_execution="sequential",+ before_tool_call=before, emit=lambda e: None,+ )++ assert len(batch.messages) == 1+ assert batch.messages[0].is_error+ assert "Blocked by test" in batch.messages[0].content[0].text+++class TestAfterToolCall:+ async def test_override_result(self):+ tool = make_echo_tool()+ ctx = make_context([tool])+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])++ async def after(ctx_arg, *, signal=None):+ return AfterToolCallResult(+ content=[TextContent(text="overridden")],+ terminate=True,+ )++ batch = await execute_tool_calls(+ ctx, msg, tool_execution="sequential",+ after_tool_call=after, emit=lambda e: None,+ )++ assert batch.messages[0].content[0].text == "overridden"+ assert batch.terminate is True+++class TestTermination:+ async def test_all_terminate_stops_loop(self):+ async def term_execute(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text="done")], terminate=True)++ tool = make_echo_tool(execute_fn=term_execute)+ ctx = make_context([tool])+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "a"})])++ batch = await execute_tool_calls(ctx, msg, tool_execution="sequential", emit=lambda e: None)+ assert batch.terminate is True++ async def test_partial_terminate_continues(self):+ async def maybe_term(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(+ content=[TextContent(text="done")],+ terminate=(params.value == "first"),+ )++ tool = make_echo_tool(execute_fn=maybe_term)+ ctx = make_context([tool])+ msg = make_assistant_msg([+ ToolCall(id="t1", name="echo", arguments={"value": "first"}),+ ToolCall(id="t2", name="echo", arguments={"value": "second"}),+ ])++ batch = await execute_tool_calls(ctx, msg, tool_execution="parallel", emit=lambda e: None)+ assert batch.terminate is False+++class TestToolEvents:+ async def test_emits_execution_lifecycle_events(self):+ tool = make_echo_tool()+ ctx = make_context([tool])+ msg = make_assistant_msg([ToolCall(id="t1", name="echo", arguments={"value": "hi"})])++ events = []+ batch = await execute_tool_calls(+ ctx, msg, tool_execution="sequential",+ emit=lambda e: events.append(e),+ )++ types = [e.type for e in events]+ assert "tool_execution_start" in types+ assert "tool_execution_end" in types+ start_idx = types.index("tool_execution_start")+ end_idx = types.index("tool_execution_end")+ assert start_idx < end_idx+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/agent/test_tools.py -v+```++Expected: ImportError.++- [ ] **Step 3: Implement tool execution engine**++Create `cubepi/agent/tools.py`:++```python+from __future__ import annotations++import asyncio+import time+from dataclasses import dataclass, field+from typing import Any, Awaitable, Callable++from pydantic import ValidationError++from cubepi.agent.types import (+ AfterToolCallContext,+ AfterToolCallResult,+ AgentContext,+ AgentEvent,+ AgentTool,+ AgentToolResult,+ BeforeToolCallContext,+ BeforeToolCallResult,+ MessageEndEvent,+ MessageStartEvent,+ ToolExecutionEndEvent,+ ToolExecutionStartEvent,+ ToolExecutionUpdateEvent,+)+from cubepi.providers.base import (+ Content,+ TextContent,+ ToolCall,+ ToolResultMessage,+ AssistantMessage,+)+++@dataclass+class ToolCallBatch:+ messages: list[ToolResultMessage]+ terminate: bool+++@dataclass+class _PreparedToolCall:+ tool_call: ToolCall+ tool: AgentTool+ args: Any+++@dataclass+class _ImmediateOutcome:+ result: AgentToolResult+ is_error: bool+++@dataclass+class _FinalizedOutcome:+ tool_call: ToolCall+ result: AgentToolResult+ is_error: bool+++def _error_result(message: str) -> AgentToolResult:+ return AgentToolResult(content=[TextContent(text=message)])+++def _make_tool_result_message(finalized: _FinalizedOutcome) -> ToolResultMessage:+ return ToolResultMessage(+ tool_call_id=finalized.tool_call.id,+ tool_name=finalized.tool_call.name,+ content=finalized.result.content,+ is_error=finalized.is_error,+ timestamp=time.time(),+ )+++async def _prepare_tool_call(+ context: AgentContext,+ assistant_message: AssistantMessage,+ tool_call: ToolCall,+ before_tool_call: Callable | None,+ signal: asyncio.Event | None,+) -> _PreparedToolCall | _ImmediateOutcome:+ tool = None+ if context.tools:+ for t in context.tools:+ if t.name == tool_call.name:+ tool = t+ break++ if tool is None:+ return _ImmediateOutcome(+ result=_error_result(f"Tool {tool_call.name} not found"),+ is_error=True,+ )++ try:+ validated_args = tool.parameters.model_validate(tool_call.arguments)+ except (ValidationError, Exception) as exc:+ return _ImmediateOutcome(result=_error_result(str(exc)), is_error=True)++ if before_tool_call:+ try:+ before_ctx = BeforeToolCallContext(+ assistant_message=assistant_message,+ tool_call=tool_call,+ args=validated_args,+ context=context,+ )+ before_result = await before_tool_call(before_ctx, signal=signal)+ if before_result and before_result.block:+ return _ImmediateOutcome(+ result=_error_result(before_result.reason or "Tool execution was blocked"),+ is_error=True,+ )+ except Exception as exc:+ return _ImmediateOutcome(result=_error_result(str(exc)), is_error=True)++ return _PreparedToolCall(tool_call=tool_call, tool=tool, args=validated_args)+++async def _execute_prepared(+ prepared: _PreparedToolCall,+ signal: asyncio.Event | None,+ emit: Callable,+) -> tuple[AgentToolResult, bool]:+ try:+ result = await prepared.tool.execute(+ prepared.tool_call.id,+ prepared.args,+ signal=signal,+ on_update=lambda partial: emit(ToolExecutionUpdateEvent(+ tool_call_id=prepared.tool_call.id,+ tool_name=prepared.tool_call.name,+ args=prepared.tool_call.arguments,+ partial_result=partial,+ )),+ )+ return result, False+ except Exception as exc:+ return _error_result(str(exc)), True+++async def _finalize(+ context: AgentContext,+ assistant_message: AssistantMessage,+ prepared: _PreparedToolCall,+ result: AgentToolResult,+ is_error: bool,+ after_tool_call: Callable | None,+ signal: asyncio.Event | None,+) -> _FinalizedOutcome:+ if after_tool_call:+ try:+ after_ctx = AfterToolCallContext(+ assistant_message=assistant_message,+ tool_call=prepared.tool_call,+ args=prepared.args,+ result=result,+ is_error=is_error,+ context=context,+ )+ after_result = await after_tool_call(after_ctx, signal=signal)+ if after_result:+ result = AgentToolResult(+ content=after_result.content if after_result.content is not None else result.content,+ details=after_result.details if after_result.details is not None else result.details,+ terminate=after_result.terminate if after_result.terminate is not None else result.terminate,+ )+ is_error = after_result.is_error if after_result.is_error is not None else is_error+ except Exception as exc:+ result = _error_result(str(exc))+ is_error = True++ return _FinalizedOutcome(tool_call=prepared.tool_call, result=result, is_error=is_error)+++def _should_terminate(finalized: list[_FinalizedOutcome]) -> bool:+ return len(finalized) > 0 and all(f.result.terminate is True for f in finalized)+++async def 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:+ tool_calls = [c for c in assistant_message.content if isinstance(c, ToolCall)]++ has_sequential = any(+ t.execution_mode == "sequential"+ for tc in tool_calls+ if context.tools+ for t in context.tools+ if t.name == tc.name+ )++ if tool_execution == "sequential" or has_sequential:+ return await _execute_sequential(+ context, assistant_message, tool_calls,+ before_tool_call, after_tool_call, signal, emit,+ )+ return await _execute_parallel(+ context, assistant_message, tool_calls,+ before_tool_call, after_tool_call, signal, emit,+ )+++async def _execute_sequential(+ context: AgentContext,+ assistant_message: AssistantMessage,+ tool_calls: list[ToolCall],+ before_tool_call: Callable | None,+ after_tool_call: Callable | None,+ signal: asyncio.Event | None,+ emit: Callable,+) -> ToolCallBatch:+ finalized_list: list[_FinalizedOutcome] = []+ messages: list[ToolResultMessage] = []++ for tc in tool_calls:+ await emit(ToolExecutionStartEvent(+ tool_call_id=tc.id, tool_name=tc.name, args=tc.arguments,+ ))++ preparation = await _prepare_tool_call(+ context, assistant_message, tc, before_tool_call, signal,+ )++ if isinstance(preparation, _ImmediateOutcome):+ finalized = _FinalizedOutcome(+ tool_call=tc, result=preparation.result, is_error=preparation.is_error,+ )+ else:+ result, is_error = await _execute_prepared(preparation, signal, emit)+ finalized = await _finalize(+ context, assistant_message, preparation,+ result, is_error, after_tool_call, signal,+ )++ await emit(ToolExecutionEndEvent(+ tool_call_id=tc.id, tool_name=tc.name,+ result=finalized.result, is_error=finalized.is_error,+ ))+ tool_msg = _make_tool_result_message(finalized)+ await emit(MessageStartEvent(message=tool_msg))+ await emit(MessageEndEvent(message=tool_msg))+ finalized_list.append(finalized)+ messages.append(tool_msg)++ return ToolCallBatch(messages=messages, terminate=_should_terminate(finalized_list))+++async def _execute_parallel(+ context: AgentContext,+ assistant_message: AssistantMessage,+ tool_calls: list[ToolCall],+ before_tool_call: Callable | None,+ after_tool_call: Callable | None,+ signal: asyncio.Event | None,+ emit: Callable,+) -> ToolCallBatch:+ entries: list[_FinalizedOutcome | asyncio.Task] = []++ for tc in tool_calls:+ await emit(ToolExecutionStartEvent(+ tool_call_id=tc.id, tool_name=tc.name, args=tc.arguments,+ ))++ preparation = await _prepare_tool_call(+ context, assistant_message, tc, before_tool_call, signal,+ )++ if isinstance(preparation, _ImmediateOutcome):+ finalized = _FinalizedOutcome(+ tool_call=tc, result=preparation.result, is_error=preparation.is_error,+ )+ await emit(ToolExecutionEndEvent(+ tool_call_id=tc.id, tool_name=tc.name,+ result=finalized.result, is_error=finalized.is_error,+ ))+ entries.append(finalized)+ else:+ async def _run(prep=preparation):+ result, is_error = await _execute_prepared(prep, signal, emit)+ fin = await _finalize(+ context, assistant_message, prep,+ result, is_error, after_tool_call, signal,+ )+ await emit(ToolExecutionEndEvent(+ tool_call_id=prep.tool_call.id, tool_name=prep.tool_call.name,+ result=fin.result, is_error=fin.is_error,+ ))+ return fin++ entries.append(asyncio.create_task(_run()))++ finalized_list: list[_FinalizedOutcome] = []+ for entry in entries:+ if isinstance(entry, asyncio.Task):+ finalized_list.append(await entry)+ else:+ finalized_list.append(entry)++ messages: list[ToolResultMessage] = []+ for finalized in finalized_list:+ tool_msg = _make_tool_result_message(finalized)+ await emit(MessageStartEvent(message=tool_msg))+ await emit(MessageEndEvent(message=tool_msg))+ messages.append(tool_msg)++ return ToolCallBatch(messages=messages, terminate=_should_terminate(finalized_list))+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/agent/test_tools.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Commit**++```bash+git add cubepi/agent/tools.py tests/agent/test_tools.py+git commit -m "feat: add tool execution engine with sequential/parallel modes"+```++---++### Task 6: Agent Loop++**Files:**+- Create: `cubepi/agent/loop.py`+- Create: `tests/agent/test_loop.py`++Port pi's `agent-loop.ts` — the stateless core loop with nested structure: outer (follow-up) → inner (tool calls + steering).++- [ ] **Step 1: Write agent loop tests**++Create `tests/agent/test_loop.py`. This file ports all tests from pi's `agent-loop.test.ts`. Due to the length, the test file should contain the following test classes and methods:++```python+import asyncio+from typing import Any++from pydantic import BaseModel++from cubepi.agent.loop import run_agent_loop, run_agent_loop_continue+from cubepi.agent.types import (+ AgentContext,+ AgentEvent,+ AgentTool,+ AgentToolResult,+)+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ MessageStream,+ Model,+ StreamEvent,+ TextContent,+ ToolCall,+ ToolResultMessage,+ UserMessage,+ Usage,+)+from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_text, faux_tool_call+++def make_model() -> Model:+ return Model(id="faux-1", provider="faux")+++def make_user_message(text: str) -> UserMessage:+ return UserMessage(content=[TextContent(text=text)])+++def identity_converter(messages: list[Any]) -> list[Message]:+ return [m for m in messages if hasattr(m, "role") and m.role in ("user", "assistant", "tool_result")]+++class EchoParams(BaseModel):+ value: str+++def make_echo_tool(*, execution_mode=None, execute_fn=None) -> AgentTool:+ async def default_execute(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])++ return AgentTool(+ name="echo",+ description="Echo tool",+ parameters=EchoParams,+ execute=execute_fn or default_execute,+ execution_mode=execution_mode,+ )+++class TestAgentLoop:+ async def test_emit_events_with_agent_message_types(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("Hi there!")])+ context = AgentContext(system_prompt="You are helpful.", messages=[], tools=[])+ user_prompt = make_user_message("Hello")++ events: list[AgentEvent] = []+ messages = await run_agent_loop(+ prompts=[user_prompt],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ emit=lambda e: events.append(e),+ )++ assert len(messages) == 2+ assert messages[0].role == "user"+ assert messages[1].role == "assistant"++ event_types = [e.type for e in events]+ assert "agent_start" in event_types+ assert "turn_start" in event_types+ assert "message_start" in event_types+ assert "message_end" in event_types+ assert "turn_end" in event_types+ assert "agent_end" in event_types++ async def test_custom_message_types_via_convert_to_llm(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("Response")])++ notification = {"role": "notification", "text": "info"}+ context = AgentContext(+ system_prompt="You are helpful.",+ messages=[notification],+ tools=[],+ )+ user_prompt = make_user_message("Hello")++ converted: list[Message] = []++ def converter(messages):+ result = [m for m in messages if hasattr(m, "role") and m.role in ("user", "assistant", "tool_result")]+ converted.extend(result)+ return result++ await run_agent_loop(+ prompts=[user_prompt],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=converter,+ emit=lambda e: None,+ )++ assert len(converted) == 1+ assert converted[0].role == "user"++ async def test_transform_context_before_convert_to_llm(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("Response")])++ context = AgentContext(+ system_prompt="You are helpful.",+ messages=[+ make_user_message("old 1"),+ faux_assistant_message("old resp 1"),+ make_user_message("old 2"),+ faux_assistant_message("old resp 2"),+ ],+ tools=[],+ )++ transformed_len = []+ converted_len = []++ async def transform(messages, *, signal=None):+ result = messages[-2:]+ transformed_len.append(len(result))+ return result++ def converter(messages):+ converted_len.append(len(messages))+ return identity_converter(messages)++ await run_agent_loop(+ prompts=[make_user_message("new")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=converter,+ transform_context=transform,+ emit=lambda e: None,+ )++ assert transformed_len[0] == 2+ assert converted_len[0] == 2++ async def test_tool_calls_and_results(self):+ executed = []++ async def echo_execute(tool_call_id, params, *, signal=None, on_update=None):+ executed.append(params.value)+ return AgentToolResult(content=[TextContent(text=f"echoed: {params.value}")])++ tool = make_echo_tool(execute_fn=echo_execute)+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message(+ [faux_tool_call("echo", {"value": "hello"}, id="tool-1")],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ])++ context = AgentContext(system_prompt="", messages=[], tools=[tool])+ events: list[AgentEvent] = []++ await run_agent_loop(+ prompts=[make_user_message("echo something")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ emit=lambda e: events.append(e),+ )++ assert executed == ["hello"]+ event_types = [e.type for e in events]+ assert "tool_execution_start" in event_types+ assert "tool_execution_end" in event_types++ async def test_should_stop_after_turn(self):+ tool = make_echo_tool()+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message(+ [faux_tool_call("echo", {"value": "hello"}, id="tool-1")],+ stop_reason="tool_use",+ ),+ faux_assistant_message("should not run"),+ ])++ context = AgentContext(system_prompt="", messages=[], tools=[tool])+ stop_called = []++ async def should_stop(ctx):+ stop_called.append(True)+ return True++ events: list[AgentEvent] = []+ messages = await run_agent_loop(+ prompts=[make_user_message("echo something")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ should_stop_after_turn=should_stop,+ emit=lambda e: events.append(e),+ )++ assert len(stop_called) == 1+ assert provider.call_count == 1+ roles = [m.role for m in messages]+ assert roles == ["user", "assistant", "tool_result"]++ async def test_steering_messages_injected_after_tool_calls(self):+ executed = []++ async def echo_execute(tool_call_id, params, *, signal=None, on_update=None):+ executed.append(params.value)+ return AgentToolResult(content=[TextContent(text=f"ok:{params.value}")])++ tool = make_echo_tool(execute_fn=echo_execute)+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message(+ [+ faux_tool_call("echo", {"value": "first"}, id="tool-1"),+ faux_tool_call("echo", {"value": "second"}, id="tool-2"),+ ],+ stop_reason="tool_use",+ ),+ faux_assistant_message("done"),+ ])++ context = AgentContext(system_prompt="", messages=[], tools=[tool])+ steering_delivered = False++ async def get_steering():+ nonlocal steering_delivered+ if len(executed) >= 1 and not steering_delivered:+ steering_delivered = True+ return [make_user_message("interrupt")]+ return []++ events: list[AgentEvent] = []+ await run_agent_loop(+ prompts=[make_user_message("start")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ get_steering_messages=get_steering,+ tool_execution="sequential",+ emit=lambda e: events.append(e),+ )++ assert executed == ["first", "second"]++ async def test_terminate_when_all_tool_results_terminate(self):+ async def term_execute(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(content=[TextContent(text="done")], terminate=True)++ tool = make_echo_tool(execute_fn=term_execute)+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message(+ [faux_tool_call("echo", {"value": "hello"}, id="tool-1")],+ stop_reason="tool_use",+ ),+ ])++ context = AgentContext(system_prompt="", messages=[], tools=[tool])+ messages = await run_agent_loop(+ prompts=[make_user_message("echo something")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ emit=lambda e: None,+ )++ assert provider.call_count == 1+ roles = [m.role for m in messages]+ assert roles == ["user", "assistant", "tool_result"]++ async def test_error_stop_reason_ends_loop(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message("", stop_reason="error", error_message="API error"),+ ])++ context = AgentContext(system_prompt="", messages=[], tools=[])+ events: list[AgentEvent] = []++ messages = await run_agent_loop(+ prompts=[make_user_message("hello")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ emit=lambda e: events.append(e),+ )++ event_types = [e.type for e in events]+ assert "agent_end" in event_types+ assert messages[-1].role == "assistant"+ assert messages[-1].stop_reason == "error"+++class TestAgentLoopContinue:+ async def test_raises_when_no_messages(self):+ provider = FauxProvider()+ context = AgentContext(system_prompt="", messages=[], tools=[])++ try:+ await run_agent_loop_continue(+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ emit=lambda e: None,+ )+ assert False, "Should have raised"+ except ValueError as e:+ assert "no messages" in str(e).lower()++ async def test_continue_without_user_message_events(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("Response")])++ context = AgentContext(+ system_prompt="",+ messages=[make_user_message("Hello")],+ tools=[],+ )++ events: list[AgentEvent] = []+ messages = await run_agent_loop_continue(+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ emit=lambda e: events.append(e),+ )++ assert len(messages) == 1+ assert messages[0].role == "assistant"++ message_ends = [e for e in events if e.type == "message_end"]+ assert len(message_ends) == 1+ assert message_ends[0].message.role == "assistant"+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/agent/test_loop.py -v+```++Expected: ImportError.++- [ ] **Step 3: Implement agent loop**++Create `cubepi/agent/loop.py`:++```python+from __future__ import annotations++import asyncio+from typing import Any, Awaitable, Callable++from cubepi.agent.tools import ToolCallBatch, execute_tool_calls+from cubepi.agent.types import (+ AgentContext,+ AgentEndEvent,+ AgentEvent,+ AgentEventSink,+ AgentStartEvent,+ AgentTool,+ BeforeToolCallResult,+ MessageEndEvent,+ MessageStartEvent,+ MessageUpdateEvent,+ ShouldStopAfterTurnContext,+ TurnEndEvent,+ TurnStartEvent,+)+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ MessageStream,+ Model,+ Provider,+ StreamEvent,+ ThinkingLevel,+ ToolCall,+ ToolResultMessage,+)+++async def run_agent_loop(+ *,+ prompts: list[Any],+ context: AgentContext,+ provider: Provider,+ model: Model,+ convert_to_llm: Callable,+ emit: Callable,+ transform_context: 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,+ thinking: ThinkingLevel = "off",+ tool_execution: str = "parallel",+ signal: asyncio.Event | None = None,+ system_prompt: str | None = None,+) -> list[Any]:+ new_messages: list[Any] = list(prompts)+ current_context = AgentContext(+ system_prompt=system_prompt if system_prompt is not None else context.system_prompt,+ messages=list(context.messages) + list(prompts),+ tools=context.tools,+ )++ await emit(AgentStartEvent())+ await emit(TurnStartEvent())+ for prompt in prompts:+ await emit(MessageStartEvent(message=prompt))+ await emit(MessageEndEvent(message=prompt))++ await _run_loop(+ current_context=current_context,+ new_messages=new_messages,+ provider=provider,+ model=model,+ convert_to_llm=convert_to_llm,+ transform_context=transform_context,+ before_tool_call=before_tool_call,+ after_tool_call=after_tool_call,+ should_stop_after_turn=should_stop_after_turn,+ get_steering_messages=get_steering_messages,+ get_follow_up_messages=get_follow_up_messages,+ thinking=thinking,+ tool_execution=tool_execution,+ signal=signal,+ emit=emit,+ )+ return new_messages+++async def run_agent_loop_continue(+ *,+ context: AgentContext,+ provider: Provider,+ model: Model,+ convert_to_llm: Callable,+ emit: Callable,+ transform_context: 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,+ thinking: ThinkingLevel = "off",+ tool_execution: str = "parallel",+ signal: asyncio.Event | None = None,+ system_prompt: str | None = None,+) -> list[Any]:+ if not context.messages:+ raise ValueError("Cannot continue: no messages in context")++ last = context.messages[-1]+ if hasattr(last, "role") and last.role == "assistant":+ raise ValueError("Cannot continue from message role: assistant")++ new_messages: list[Any] = []+ current_context = AgentContext(+ system_prompt=system_prompt if system_prompt is not None else context.system_prompt,+ messages=list(context.messages),+ tools=context.tools,+ )++ await emit(AgentStartEvent())+ await emit(TurnStartEvent())++ await _run_loop(+ current_context=current_context,+ new_messages=new_messages,+ provider=provider,+ model=model,+ convert_to_llm=convert_to_llm,+ transform_context=transform_context,+ before_tool_call=before_tool_call,+ after_tool_call=after_tool_call,+ should_stop_after_turn=should_stop_after_turn,+ get_steering_messages=get_steering_messages,+ get_follow_up_messages=get_follow_up_messages,+ thinking=thinking,+ tool_execution=tool_execution,+ signal=signal,+ emit=emit,+ )+ return new_messages+++async def _run_loop(+ *,+ current_context: AgentContext,+ new_messages: list[Any],+ provider: Provider,+ model: Model,+ convert_to_llm: Callable,+ transform_context: Callable | None,+ before_tool_call: Callable | None,+ after_tool_call: Callable | None,+ should_stop_after_turn: Callable | None,+ get_steering_messages: Callable | None,+ get_follow_up_messages: Callable | None,+ thinking: ThinkingLevel,+ tool_execution: str,+ signal: asyncio.Event | None,+ emit: Callable,+) -> None:+ first_turn = True+ pending_messages: list[Any] = []+ if get_steering_messages:+ pending_messages = await get_steering_messages() or []++ while True:+ has_more_tool_calls = True++ while has_more_tool_calls or pending_messages:+ if not first_turn:+ await emit(TurnStartEvent())+ else:+ first_turn = False++ if pending_messages:+ for msg in pending_messages:+ await emit(MessageStartEvent(message=msg))+ await emit(MessageEndEvent(message=msg))+ current_context.messages.append(msg)+ new_messages.append(msg)+ pending_messages = []++ message = await _stream_assistant_response(+ current_context, provider, model, convert_to_llm,+ transform_context, thinking, signal, emit,+ )+ new_messages.append(message)++ if message.stop_reason in ("error", "aborted"):+ await emit(TurnEndEvent(message=message, tool_results=[]))+ await emit(AgentEndEvent(messages=new_messages))+ return++ tool_calls = [c for c in message.content if isinstance(c, ToolCall)]+ tool_results: list[ToolResultMessage] = []+ has_more_tool_calls = False++ if tool_calls:+ batch = await execute_tool_calls(+ current_context, message,+ tool_execution=tool_execution,+ before_tool_call=before_tool_call,+ after_tool_call=after_tool_call,+ signal=signal,+ emit=emit,+ )+ tool_results = batch.messages+ has_more_tool_calls = not batch.terminate++ for result in tool_results:+ current_context.messages.append(result)+ new_messages.append(result)++ await emit(TurnEndEvent(message=message, tool_results=tool_results))++ if should_stop_after_turn:+ stop_ctx = ShouldStopAfterTurnContext(+ message=message,+ tool_results=tool_results,+ context=current_context,+ new_messages=new_messages,+ )+ if await should_stop_after_turn(stop_ctx):+ await emit(AgentEndEvent(messages=new_messages))+ return++ if get_steering_messages:+ pending_messages = await get_steering_messages() or []++ if get_follow_up_messages:+ follow_ups = await get_follow_up_messages() or []+ if follow_ups:+ pending_messages = follow_ups+ continue++ break++ await emit(AgentEndEvent(messages=new_messages))+++async def _stream_assistant_response(+ context: AgentContext,+ provider: Provider,+ model: Model,+ convert_to_llm: Callable,+ transform_context: Callable | None,+ thinking: ThinkingLevel,+ signal: asyncio.Event | None,+ emit: Callable,+) -> AssistantMessage:+ messages = context.messages+ if transform_context:+ messages = await transform_context(messages, signal=signal)++ llm_messages = convert_to_llm(messages)+ if asyncio.iscoroutine(llm_messages):+ llm_messages = await llm_messages++ tools_defs = None+ if context.tools:+ tools_defs = [t.to_definition() for t in context.tools]++ stream = await provider.stream(+ model, llm_messages,+ system_prompt=context.system_prompt,+ tools=tools_defs,+ thinking=thinking,+ signal=signal,+ )++ partial_message: AssistantMessage | None = None+ added_partial = False++ async for event in stream:+ if event.type == "start":+ partial_message = event.partial+ if partial_message:+ context.messages.append(partial_message)+ added_partial = True+ await emit(MessageStartEvent(message=partial_message.model_copy(deep=True)))++ elif event.type in (+ "text_start", "text_delta", "text_end",+ "thinking_start", "thinking_delta", "thinking_end",+ "toolcall_start", "toolcall_delta", "toolcall_end",+ ):+ if partial_message and event.partial:+ partial_message = event.partial+ context.messages[-1] = partial_message+ await emit(MessageUpdateEvent(+ message=partial_message.model_copy(deep=True),+ stream_event=event,+ ))++ elif event.type in ("done", "error"):+ final_message = await stream.result()+ if added_partial:+ context.messages[-1] = final_message+ else:+ context.messages.append(final_message)+ if not added_partial:+ await emit(MessageStartEvent(message=final_message))+ await emit(MessageEndEvent(message=final_message))+ return final_message++ final_message = await stream.result()+ if added_partial:+ context.messages[-1] = final_message+ else:+ context.messages.append(final_message)+ await emit(MessageStartEvent(message=final_message))+ await emit(MessageEndEvent(message=final_message))+ return final_message+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/agent/test_loop.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Commit**++```bash+git add cubepi/agent/loop.py tests/agent/test_loop.py+git commit -m "feat: add agent loop with nested loop structure"+```++---++### Task 7: Agent Class++**Files:**+- Create: `cubepi/agent/agent.py`+- Create: `tests/agent/test_agent.py`+- Create: `tests/agent/test_e2e.py`++Port pi's `Agent` class — stateful wrapper with message queues, subscribe/prompt/resume/abort/reset. Also port all e2e tests.++- [ ] **Step 1: Write Agent class tests**++Create `tests/agent/test_agent.py` porting all tests from pi's `agent.test.ts`. The test file should contain these test classes and methods:++```python+import asyncio++from cubepi.agent.agent import Agent+from cubepi.agent.types import AgentEvent, AgentTool, AgentToolResult+from cubepi.providers.base import (+ AssistantMessage,+ Model,+ TextContent,+ UserMessage,+)+from cubepi.providers.faux import FauxProvider, faux_assistant_message+++def make_model() -> Model:+ return Model(id="faux-1", provider="faux")+++class TestAgentInit:+ def test_default_state(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())++ assert agent.state.system_prompt == ""+ assert agent.state.thinking == "off"+ assert agent.state.tools == []+ assert agent.state.messages == []+ assert agent.state.is_streaming is False+ assert agent.state.streaming_message is None+ assert agent.state.pending_tool_calls == set()+ assert agent.state.error_message is None++ def test_custom_initial_state(self):+ provider = FauxProvider()+ agent = Agent(+ provider=provider,+ model=make_model(),+ system_prompt="You are a helpful assistant.",+ thinking="low",+ )++ assert agent.state.system_prompt == "You are a helpful assistant."+ assert agent.state.thinking == "low"+++class TestAgentSubscribe:+ def test_subscribe_and_unsubscribe(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())++ count = 0++ def listener(event, signal=None):+ nonlocal count+ count += 1++ unsub = agent.subscribe(listener)+ assert count == 0++ unsub()++ async def test_events_emitted_on_prompt(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("ok")])+ agent = Agent(provider=provider, model=make_model())++ events = []+ agent.subscribe(lambda e, s=None: events.append(e.type))++ await agent.prompt("hello")++ assert "agent_start" in events+ assert "message_start" in events+ assert "message_end" in events+ assert "agent_end" in events++ async def test_full_lifecycle_events_for_thrown_run_failures(self):+ async def bad_stream(*args, **kwargs):+ raise RuntimeError("provider exploded")++ provider = FauxProvider()+ provider.stream = bad_stream+ agent = Agent(provider=provider, model=make_model())++ events = []+ agent.subscribe(lambda e, s=None: events.append(e.type))++ await agent.prompt("hello")++ assert events == [+ "agent_start", "turn_start",+ "message_start", "message_end",+ "message_start", "message_end",+ "turn_end", "agent_end",+ ]+ last_msg = agent.state.messages[-1]+ assert last_msg.role == "assistant"+ assert last_msg.stop_reason == "error"+ assert last_msg.error_message == "provider exploded"+ assert agent.state.error_message == "provider exploded"++ async def test_await_async_subscribers_before_prompt_resolves(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("ok")])+ agent = Agent(provider=provider, model=make_model())++ barrier = asyncio.Event()+ listener_finished = False++ async def listener(event, signal=None):+ nonlocal listener_finished+ if event.type == "agent_end":+ await barrier.wait()+ listener_finished = True++ agent.subscribe(listener)++ prompt_resolved = False++ async def run_prompt():+ nonlocal prompt_resolved+ await agent.prompt("hello")+ prompt_resolved = True++ task = asyncio.create_task(run_prompt())+ await asyncio.sleep(0.05)++ assert not prompt_resolved+ assert not listener_finished+ assert agent.state.is_streaming is True++ barrier.set()+ await task++ assert listener_finished+ assert prompt_resolved+ assert agent.state.is_streaming is False+++class TestAgentState:+ def test_tools_are_copied(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())++ tools = [AgentTool(name="t", description="t", parameters=type("P", (object,), {"model_json_schema": classmethod(lambda cls: {})}), execute=lambda *a, **k: None)]+ agent.state.tools = tools+ assert agent.state.tools is not tools++ def test_messages_are_copied(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())++ messages = [UserMessage(content=[TextContent(text="hi")])]+ agent.state.messages = messages+ assert agent.state.messages is not messages+++class TestAgentQueues:+ def test_steer_queues_message(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())++ msg = UserMessage(content=[TextContent(text="steering")])+ agent.steer(msg)+ assert msg not in agent.state.messages++ def test_follow_up_queues_message(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())++ msg = UserMessage(content=[TextContent(text="follow-up")])+ agent.follow_up(msg)+ assert msg not in agent.state.messages+++class TestAgentAbort:+ def test_abort_without_active_run_does_not_throw(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())+ agent.abort()+++class TestAgentPromptGuards:+ async def test_raises_when_prompt_called_while_streaming(self):+ barrier = asyncio.Event()+ provider = FauxProvider()++ async def slow_stream(*args, **kwargs):+ from cubepi.providers.base import MessageStream, StreamEvent+ ms = MessageStream()++ async def produce():+ await barrier.wait()+ msg = faux_assistant_message("ok")+ ms.push(StreamEvent(type="done"))+ ms.set_result(msg)++ asyncio.create_task(produce())+ return ms++ provider.stream = slow_stream+ agent = Agent(provider=provider, model=make_model())++ task = asyncio.create_task(agent.prompt("first"))+ await asyncio.sleep(0.02)+ assert agent.state.is_streaming is True++ try:+ await agent.prompt("second")+ assert False, "Should have raised"+ except RuntimeError as e:+ assert "already processing" in str(e).lower()++ barrier.set()+ await task++ async def test_raises_when_resume_called_while_streaming(self):+ barrier = asyncio.Event()+ provider = FauxProvider()++ async def slow_stream(*args, **kwargs):+ from cubepi.providers.base import MessageStream, StreamEvent+ ms = MessageStream()++ async def produce():+ await barrier.wait()+ msg = faux_assistant_message("ok")+ ms.push(StreamEvent(type="done"))+ ms.set_result(msg)++ asyncio.create_task(produce())+ return ms++ provider.stream = slow_stream+ agent = Agent(provider=provider, model=make_model())++ task = asyncio.create_task(agent.prompt("first"))+ await asyncio.sleep(0.02)++ try:+ await agent.resume()+ assert False, "Should have raised"+ except RuntimeError as e:+ assert "already processing" in str(e).lower()++ barrier.set()+ await task+++class TestAgentResume:+ async def test_resume_processes_follow_up_messages(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message("Initial response"),+ faux_assistant_message("Processed"),+ ])+ agent = Agent(provider=provider, model=make_model())++ await agent.prompt("Initial")+ agent.follow_up(UserMessage(content=[TextContent(text="follow-up")]))+ await agent.resume()++ has_follow_up = any(+ hasattr(m, "content") and hasattr(m, "role") and m.role == "user"+ and any(+ hasattr(c, "text") and c.text == "follow-up"+ for c in (m.content if isinstance(m.content, list) else [])+ )+ for m in agent.state.messages+ )+ assert has_follow_up+ assert agent.state.messages[-1].role == "assistant"+```++- [ ] **Step 2: Write E2E tests**++Create `tests/agent/test_e2e.py` porting pi's `e2e.test.ts`:++```python+import asyncio++from pydantic import BaseModel++from cubepi.agent.agent import Agent+from cubepi.agent.types import AgentEvent, AgentTool, AgentToolResult+from cubepi.providers.base import (+ AssistantMessage,+ Model,+ TextContent,+ ToolCall,+ ToolResultMessage,+ UserMessage,+)+from cubepi.providers.faux import (+ FauxProvider,+ faux_assistant_message,+ faux_text,+ faux_thinking,+ faux_tool_call,+)+++def make_model() -> Model:+ return Model(id="faux-1", provider="faux")+++class CalculateParams(BaseModel):+ expression: str+++def make_calculate_tool() -> AgentTool:+ async def execute(tool_call_id, params, *, signal=None, on_update=None):+ try:+ result = eval(params.expression)+ return AgentToolResult(+ content=[TextContent(text=f"{params.expression} = {result}")]+ )+ except Exception as e:+ raise RuntimeError(str(e))++ return AgentTool(+ name="calculate",+ description="Calculate a math expression",+ parameters=CalculateParams,+ execute=execute,+ )+++class TestE2EBasic:+ async def test_basic_text_prompt(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("4")])+ agent = Agent(+ provider=provider,+ model=make_model(),+ system_prompt="You are a helpful assistant.",+ )++ await agent.prompt("What is 2+2?")++ assert agent.state.is_streaming is False+ assert len(agent.state.messages) == 2+ assert agent.state.messages[0].role == "user"+ assert agent.state.messages[1].role == "assistant"+ assert "4" in agent.state.messages[1].content[0].text++ async def test_tool_execution_with_pending_tracking(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message(+ [+ faux_text("Let me calculate that."),+ faux_tool_call("calculate", {"expression": "123 * 456"}, id="calc-1"),+ ],+ stop_reason="tool_use",+ ),+ faux_assistant_message("The result is 56088."),+ ])+ agent = Agent(+ provider=provider,+ model=make_model(),+ system_prompt="Always use the calculator tool for math.",+ tools=[make_calculate_tool()],+ )++ pending_events = []+ agent.subscribe(lambda e, s=None: (+ pending_events.append({"type": e.type, "ids": list(agent.state.pending_tool_calls)})+ if e.type in ("tool_execution_start", "tool_execution_end") else None+ ))++ await agent.prompt("Calculate 123 * 456")++ assert agent.state.is_streaming is False+ assert len(agent.state.messages) >= 4+ tool_result = next(m for m in agent.state.messages if m.role == "tool_result")+ assert "56088" in tool_result.content[0].text+ assert agent.state.pending_tool_calls == set()++ async def test_abort_during_streaming(self):+ provider = FauxProvider(tokens_per_second=20, token_size_min=2, token_size_max=2)+ provider.set_responses([+ faux_assistant_message(+ "one two three four five six seven eight nine ten eleven twelve thirteen"+ ),+ ])+ agent = Agent(provider=provider, model=make_model())++ prompt_task = asyncio.create_task(agent.prompt("Count"))+ await asyncio.sleep(0.03)+ agent.abort()+ await prompt_task++ assert agent.state.is_streaming is False+ last_msg = agent.state.messages[-1]+ assert last_msg.role == "assistant"+ assert last_msg.stop_reason == "aborted"++ async def test_lifecycle_events_during_streaming(self):+ provider = FauxProvider(token_size_min=1, token_size_max=1)+ provider.set_responses([faux_assistant_message("1 2 3 4 5")])+ agent = Agent(provider=provider, model=make_model())++ events = []+ agent.subscribe(lambda e, s=None: events.append(e.type))++ await agent.prompt("Count from 1 to 5")++ assert "agent_start" in events+ assert "message_start" in events+ assert "message_update" in events+ assert "message_end" in events+ assert "agent_end" in events++ async def test_context_across_multiple_turns(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message("Nice to meet you, Alice."),+ lambda msgs, model: faux_assistant_message(+ "Your name is Alice."+ if any(+ hasattr(m, "content")+ and isinstance(m.content, list)+ and any(hasattr(c, "text") and "Alice" in c.text for c in m.content)+ for m in msgs+ if hasattr(m, "role") and m.role == "user"+ )+ else "I don't know your name."+ ),+ ])+ agent = Agent(provider=provider, model=make_model())++ await agent.prompt("My name is Alice.")+ assert len(agent.state.messages) == 2++ await agent.prompt("What is my name?")+ assert len(agent.state.messages) == 4+ assert "alice" in agent.state.messages[3].content[0].text.lower()++ async def test_thinking_content_preserved(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message([faux_thinking("step by step"), faux_text("4")]),+ ])+ agent = Agent(+ provider=provider,+ model=Model(id="faux-reasoning", provider="faux", reasoning=True),+ thinking="low",+ )++ await agent.prompt("What is 2+2?")++ assistant_msg = agent.state.messages[1]+ assert assistant_msg.content[0].type == "thinking"+ assert assistant_msg.content[0].thinking == "step by step"+ assert assistant_msg.content[1].type == "text"+ assert assistant_msg.content[1].text == "4"+++class TestE2EResume:+ async def test_raises_when_no_messages(self):+ provider = FauxProvider()+ agent = Agent(provider=provider, model=make_model())++ try:+ await agent.resume()+ assert False, "Should have raised"+ except RuntimeError as e:+ assert "no messages" in str(e).lower()++ async def test_continue_from_user_message(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("HELLO WORLD")])+ agent = Agent(provider=provider, model=make_model())++ agent.state.messages = [+ UserMessage(content=[TextContent(text="Say HELLO WORLD")]),+ ]++ await agent.resume()++ assert agent.state.is_streaming is False+ assert len(agent.state.messages) == 2+ assert agent.state.messages[1].role == "assistant"++ async def test_continue_from_tool_result(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("The answer is 8.")])+ agent = Agent(+ provider=provider,+ model=make_model(),+ tools=[make_calculate_tool()],+ )++ agent.state.messages = [+ UserMessage(content=[TextContent(text="What is 5 + 3?")]),+ AssistantMessage(+ content=[+ TextContent(text="Let me calculate."),+ ToolCall(id="calc-1", name="calculate", arguments={"expression": "5 + 3"}),+ ],+ stop_reason="tool_use",+ ),+ ToolResultMessage(+ tool_call_id="calc-1",+ tool_name="calculate",+ content=[TextContent(text="5 + 3 = 8")],+ ),+ ]++ await agent.resume()++ assert len(agent.state.messages) >= 4+ assert agent.state.messages[-1].role == "assistant"+ assert "8" in agent.state.messages[-1].content[0].text+```++- [ ] **Step 3: Run tests to verify they fail**++```bash+pytest tests/agent/test_agent.py tests/agent/test_e2e.py -v+```++Expected: ImportError.++- [ ] **Step 4: Implement Agent class**++Create `cubepi/agent/agent.py`:++```python+from __future__ import annotations++import asyncio+import time+from dataclasses import dataclass, field+from typing import Any, Awaitable, Callable, Generic, TypeVar++from cubepi.agent.loop import run_agent_loop, run_agent_loop_continue+from cubepi.agent.types import (+ AgentContext,+ AgentEndEvent,+ AgentEvent,+ AgentStartEvent,+ AgentTool,+ MessageEndEvent,+ MessageStartEvent,+ MessageUpdateEvent,+ ToolExecutionEndEvent,+ ToolExecutionStartEvent,+ TurnEndEvent,+)+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ Model,+ Provider,+ TextContent,+ ThinkingLevel,+ Usage,+)++TMessage = TypeVar("TMessage")+++def _default_convert_to_llm(messages: list[Any]) -> list[Message]:+ return [m for m in messages if hasattr(m, "role") and m.role in ("user", "assistant", "tool_result")]+++class _MessageQueue:+ def __init__(self, mode: str = "one-at-a-time") -> None:+ self.mode = mode+ self._messages: list[Any] = []++ def enqueue(self, message: Any) -> None:+ self._messages.append(message)++ def has_items(self) -> bool:+ return len(self._messages) > 0++ def drain(self) -> list[Any]:+ if self.mode == "all":+ drained = self._messages[:]+ self._messages = []+ return drained+ if not self._messages:+ return []+ first = self._messages[0]+ self._messages = self._messages[1:]+ return [first]++ def clear(self) -> None:+ self._messages = []+++@dataclass+class AgentState:+ system_prompt: str = ""+ model: Model = field(default_factory=lambda: Model(id="unknown", provider="unknown"))+ thinking: ThinkingLevel = "off"+ is_streaming: bool = False+ streaming_message: Any = None+ error_message: str | None = None+ _tools: list[AgentTool] = field(default_factory=list)+ _messages: list[Any] = field(default_factory=list)+ _pending_tool_calls: set[str] = field(default_factory=set)++ @property+ def tools(self) -> list[AgentTool]:+ return self._tools++ @tools.setter+ def tools(self, value: list[AgentTool]) -> None:+ self._tools = list(value)++ @property+ def messages(self) -> list[Any]:+ return self._messages++ @messages.setter+ def messages(self, value: list[Any]) -> None:+ self._messages = list(value)++ @property+ def pending_tool_calls(self) -> set[str]:+ return self._pending_tool_calls++ @pending_tool_calls.setter+ def pending_tool_calls(self, value: set[str]) -> None:+ self._pending_tool_calls = set(value)+++class Agent(Generic[TMessage]):+ def __init__(+ self,+ *,+ provider: Provider,+ model: Model,+ system_prompt: str = "",+ tools: list[AgentTool] | None = None,+ thinking: ThinkingLevel = "off",+ convert_to_llm: Callable | None = None,+ transform_context: Callable | None = None,+ before_tool_call: Callable | None = None,+ after_tool_call: Callable | None = None,+ should_stop_after_turn: Callable | 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,+ ) -> None:+ self._provider = provider+ self._state = AgentState(+ system_prompt=system_prompt,+ model=model,+ thinking=thinking,+ )+ if tools:+ self._state.tools = tools+ self.convert_to_llm = convert_to_llm or _default_convert_to_llm+ self.transform_context = transform_context+ self.before_tool_call = before_tool_call+ self.after_tool_call = after_tool_call+ self.should_stop_after_turn = should_stop_after_turn+ self.tool_execution = tool_execution+ self.checkpointer = checkpointer+ self.thread_id = thread_id++ self._steering_queue = _MessageQueue(steering_mode)+ self._follow_up_queue = _MessageQueue(follow_up_mode)+ self._listeners: list[Callable] = []+ self._active_signal: asyncio.Event | None = None+ self._active_done: asyncio.Event | None = None++ @property+ def state(self) -> AgentState:+ return self._state++ def subscribe(self, listener: Callable) -> Callable[[], None]:+ self._listeners.append(listener)+ return lambda: self._listeners.remove(listener) if listener in self._listeners else None++ def steer(self, message: Any) -> None:+ self._steering_queue.enqueue(message)++ def follow_up(self, message: Any) -> None:+ self._follow_up_queue.enqueue(message)++ def abort(self) -> None:+ if self._active_signal:+ self._active_signal.set()++ async def wait_for_idle(self) -> None:+ if self._active_done:+ await self._active_done.wait()++ def reset(self) -> None:+ self._state.messages = []+ self._state.is_streaming = False+ self._state.streaming_message = None+ self._state.pending_tool_calls = set()+ self._state.error_message = None+ self._steering_queue.clear()+ self._follow_up_queue.clear()++ async def prompt(self, message: str | Any | list[Any]) -> None:+ if self._state.is_streaming:+ raise RuntimeError(+ "Agent is already processing a prompt. Use steer() or follow_up() to queue messages."+ )++ if isinstance(message, str):+ from cubepi.providers.base import UserMessage, TextContent+ messages = [UserMessage(content=[TextContent(text=message)], timestamp=time.time())]+ elif isinstance(message, list):+ messages = message+ else:+ messages = [message]++ await self._run_prompt(messages)++ async def resume(self) -> None:+ if self._state.is_streaming:+ raise RuntimeError("Agent is already processing. Wait for completion before continuing.")++ if not self._state.messages:+ raise RuntimeError("No messages to continue from")++ last = self._state.messages[-1]+ if hasattr(last, "role") and last.role == "assistant":+ steering = self._steering_queue.drain()+ if steering:+ await self._run_prompt(steering)+ return++ follow_ups = self._follow_up_queue.drain()+ if follow_ups:+ await self._run_prompt(follow_ups)+ return++ raise RuntimeError("Cannot continue from message role: assistant")++ await self._run_continuation()++ async def _run_prompt(self, messages: list[Any]) -> None:+ await self._run_with_lifecycle(lambda signal: run_agent_loop(+ prompts=messages,+ context=self._create_context_snapshot(),+ provider=self._provider,+ model=self._state.model,+ convert_to_llm=self.convert_to_llm,+ transform_context=self.transform_context,+ before_tool_call=self.before_tool_call,+ after_tool_call=self.after_tool_call,+ should_stop_after_turn=self.should_stop_after_turn,+ get_steering_messages=lambda: self._steering_queue.drain(),+ get_follow_up_messages=lambda: self._follow_up_queue.drain(),+ thinking=self._state.thinking,+ tool_execution=self.tool_execution,+ signal=signal,+ emit=lambda e: self._process_event(e),+ ))++ async def _run_continuation(self) -> None:+ await self._run_with_lifecycle(lambda signal: run_agent_loop_continue(+ context=self._create_context_snapshot(),+ provider=self._provider,+ model=self._state.model,+ convert_to_llm=self.convert_to_llm,+ transform_context=self.transform_context,+ before_tool_call=self.before_tool_call,+ after_tool_call=self.after_tool_call,+ should_stop_after_turn=self.should_stop_after_turn,+ get_steering_messages=lambda: self._steering_queue.drain(),+ get_follow_up_messages=lambda: self._follow_up_queue.drain(),+ thinking=self._state.thinking,+ tool_execution=self.tool_execution,+ signal=signal,+ emit=lambda e: self._process_event(e),+ ))++ def _create_context_snapshot(self) -> AgentContext:+ return AgentContext(+ system_prompt=self._state.system_prompt,+ messages=list(self._state.messages),+ tools=list(self._state.tools),+ )++ async def _run_with_lifecycle(self, executor: Callable) -> None:+ signal = asyncio.Event()+ done = asyncio.Event()+ self._active_signal = signal+ self._active_done = done+ self._state.is_streaming = True+ self._state.streaming_message = None+ self._state.error_message = None++ try:+ await executor(signal)+ except Exception as error:+ await self._handle_run_failure(error, signal.is_set())+ finally:+ self._state.is_streaming = False+ self._state.streaming_message = None+ self._state.pending_tool_calls = set()+ self._active_signal = None+ done.set()+ self._active_done = None++ async def _handle_run_failure(self, error: Exception, aborted: bool) -> None:+ failure_message = AssistantMessage(+ content=[TextContent(text="")],+ stop_reason="aborted" if aborted else "error",+ error_message=str(error),+ usage=Usage(),+ timestamp=time.time(),+ )+ await self._process_event(MessageStartEvent(message=failure_message))+ await self._process_event(MessageEndEvent(message=failure_message))+ await self._process_event(TurnEndEvent(message=failure_message, tool_results=[]))+ await self._process_event(AgentEndEvent(messages=[failure_message]))++ async def _process_event(self, event: AgentEvent) -> None:+ if event.type == "message_start":+ self._state.streaming_message = event.message+ elif event.type == "message_update":+ self._state.streaming_message = event.message+ elif event.type == "message_end":+ self._state.streaming_message = None+ self._state.messages.append(event.message)+ elif event.type == "tool_execution_start":+ self._state.pending_tool_calls = self._state.pending_tool_calls | {event.tool_call_id}+ elif event.type == "tool_execution_end":+ self._state.pending_tool_calls = self._state.pending_tool_calls - {event.tool_call_id}+ elif event.type == "turn_end":+ msg = event.message+ if hasattr(msg, "role") and msg.role == "assistant" and hasattr(msg, "error_message") and msg.error_message:+ self._state.error_message = msg.error_message+ elif event.type == "agent_end":+ self._state.streaming_message = None++ for listener in self._listeners:+ result = listener(event, self._active_signal)+ if asyncio.iscoroutine(result):+ await result+```++- [ ] **Step 5: Run tests to verify they pass**++```bash+pytest tests/agent/test_agent.py tests/agent/test_e2e.py -v+```++Expected: All tests PASS.++- [ ] **Step 6: Update agent `__init__.py` with re-exports**++Update `cubepi/agent/__init__.py`:++```python+from cubepi.agent.agent import Agent, AgentState+from cubepi.agent.loop import run_agent_loop, run_agent_loop_continue+from cubepi.agent.tools import execute_tool_calls+from cubepi.agent.types import (+ AfterToolCallContext,+ AfterToolCallResult,+ AgentContext,+ AgentEndEvent,+ AgentEvent,+ AgentListener,+ AgentStartEvent,+ AgentTool,+ AgentToolResult,+ BeforeToolCallContext,+ BeforeToolCallResult,+ MessageEndEvent,+ MessageStartEvent,+ MessageUpdateEvent,+ ShouldStopAfterTurnContext,+ ToolExecutionEndEvent,+ ToolExecutionStartEvent,+ ToolExecutionUpdateEvent,+ TurnEndEvent,+ TurnStartEvent,+)++__all__ = [+ "Agent",+ "AgentState",+ "run_agent_loop",+ "run_agent_loop_continue",+ "execute_tool_calls",+ "AfterToolCallContext",+ "AfterToolCallResult",+ "AgentContext",+ "AgentEndEvent",+ "AgentEvent",+ "AgentListener",+ "AgentStartEvent",+ "AgentTool",+ "AgentToolResult",+ "BeforeToolCallContext",+ "BeforeToolCallResult",+ "MessageEndEvent",+ "MessageStartEvent",+ "MessageUpdateEvent",+ "ShouldStopAfterTurnContext",+ "ToolExecutionEndEvent",+ "ToolExecutionStartEvent",+ "ToolExecutionUpdateEvent",+ "TurnEndEvent",+ "TurnStartEvent",+]+```++- [ ] **Step 7: Commit**++```bash+git add cubepi/agent/ tests/agent/+git commit -m "feat: add Agent class with event system, queues, and lifecycle management"+```++---++### Task 8: Middleware Protocol and Composition++**Files:**+- Create: `cubepi/middleware/base.py`+- Create: `tests/middleware/test_base.py`++Implement the Middleware protocol and `compose_middleware()` function. This is new in cubepi (not in pi).++- [ ] **Step 1: Write middleware tests**++Create `tests/middleware/test_base.py`:++```python+from typing import Any++from cubepi.middleware.base import Middleware, compose_middleware+from cubepi.agent.types import (+ AfterToolCallResult,+ BeforeToolCallContext,+ BeforeToolCallResult,+ AfterToolCallContext,+ ShouldStopAfterTurnContext,+ AgentContext,+ AgentToolResult,+)+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ TextContent,+ ToolCall,+ ToolResultMessage,+ UserMessage,+)+++class TestComposeMiddlewareEmpty:+ def test_empty_list_returns_empty_dict(self):+ hooks = compose_middleware([])+ assert hooks == {}+++class TestTransformContext:+ async def test_chained_transform_context(self):+ class AddPrefix(Middleware):+ async def transform_context(self, messages, *, signal=None):+ return [UserMessage(content=[TextContent(text="PREFIX")])] + list(messages)++ class AddSuffix(Middleware):+ async def transform_context(self, messages, *, signal=None):+ return list(messages) + [UserMessage(content=[TextContent(text="SUFFIX")])]++ hooks = compose_middleware([AddPrefix(), AddSuffix()])+ result = await hooks["transform_context"]([UserMessage(content=[TextContent(text="middle")])], signal=None)++ assert len(result) == 3+ assert result[0].content[0].text == "PREFIX"+ assert result[1].content[0].text == "middle"+ assert result[2].content[0].text == "SUFFIX"+++class TestConvertToLlm:+ async def test_last_implementation_wins(self):+ class First(Middleware):+ async def convert_to_llm(self, messages):+ return [UserMessage(content=[TextContent(text="first")])]++ class Second(Middleware):+ async def convert_to_llm(self, messages):+ return [UserMessage(content=[TextContent(text="second")])]++ hooks = compose_middleware([First(), Second()])+ result = await hooks["convert_to_llm"]([])++ assert len(result) == 1+ assert result[0].content[0].text == "second"+++class TestBeforeToolCall:+ async def test_any_block_stops_execution(self):+ class Allower(Middleware):+ async def before_tool_call(self, ctx, *, signal=None):+ return None++ class Blocker(Middleware):+ async def before_tool_call(self, ctx, *, signal=None):+ return BeforeToolCallResult(block=True, reason="Blocked")++ hooks = compose_middleware([Allower(), Blocker()])++ ctx = BeforeToolCallContext(+ assistant_message=AssistantMessage(content=[]),+ tool_call=ToolCall(id="t1", name="test", arguments={}),+ args={},+ context=AgentContext(system_prompt="", messages=[]),+ )+ result = await hooks["before_tool_call"](ctx, signal=None)++ assert result is not None+ assert result.block is True+ assert result.reason == "Blocked"++ async def test_no_block_returns_none(self):+ class Allower(Middleware):+ async def before_tool_call(self, ctx, *, signal=None):+ return None++ hooks = compose_middleware([Allower()])+ ctx = BeforeToolCallContext(+ assistant_message=AssistantMessage(content=[]),+ tool_call=ToolCall(id="t1", name="test", arguments={}),+ args={},+ context=AgentContext(system_prompt="", messages=[]),+ )+ result = await hooks["before_tool_call"](ctx, signal=None)+ assert result is None+++class TestAfterToolCall:+ async def test_later_overrides_earlier(self):+ class First(Middleware):+ async def after_tool_call(self, ctx, *, signal=None):+ return AfterToolCallResult(content=[TextContent(text="first")])++ class Second(Middleware):+ async def after_tool_call(self, ctx, *, signal=None):+ return AfterToolCallResult(content=[TextContent(text="second")])++ hooks = compose_middleware([First(), Second()])++ ctx = AfterToolCallContext(+ assistant_message=AssistantMessage(content=[]),+ tool_call=ToolCall(id="t1", name="test", arguments={}),+ args={},+ result=AgentToolResult(content=[TextContent(text="original")]),+ is_error=False,+ context=AgentContext(system_prompt="", messages=[]),+ )+ result = await hooks["after_tool_call"](ctx, signal=None)++ assert result.content[0].text == "second"+++class TestShouldStopAfterTurn:+ async def test_any_true_stops(self):+ class NoStop(Middleware):+ async def should_stop_after_turn(self, ctx):+ return False++ class YesStop(Middleware):+ async def should_stop_after_turn(self, ctx):+ return True++ hooks = compose_middleware([NoStop(), YesStop()])++ ctx = ShouldStopAfterTurnContext(+ message=AssistantMessage(content=[]),+ tool_results=[],+ context=AgentContext(system_prompt="", messages=[]),+ new_messages=[],+ )+ result = await hooks["should_stop_after_turn"](ctx)+ assert result is True++ async def test_all_false_continues(self):+ class NoStop(Middleware):+ async def should_stop_after_turn(self, ctx):+ return False++ hooks = compose_middleware([NoStop()])+ ctx = ShouldStopAfterTurnContext(+ message=AssistantMessage(content=[]),+ tool_results=[],+ context=AgentContext(system_prompt="", messages=[]),+ new_messages=[],+ )+ result = await hooks["should_stop_after_turn"](ctx)+ assert result is False+++class TestPartialMiddleware:+ async def test_middleware_with_only_some_hooks(self):+ class OnlyTransform(Middleware):+ async def transform_context(self, messages, *, signal=None):+ return messages++ hooks = compose_middleware([OnlyTransform()])+ assert "transform_context" in hooks+ assert "convert_to_llm" not in hooks+ assert "before_tool_call" not in hooks+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/middleware/test_base.py -v+```++Expected: ImportError.++- [ ] **Step 3: Implement middleware**++Create `cubepi/middleware/base.py`:++```python+from __future__ import annotations++from typing import Any, Callable+++class Middleware:+ async def transform_context(self, messages: list, *, signal=None) -> list:+ raise NotImplementedError++ async def convert_to_llm(self, messages: list) -> list:+ raise NotImplementedError++ async def before_tool_call(self, ctx: Any, *, signal=None) -> Any:+ raise NotImplementedError++ async def after_tool_call(self, ctx: Any, *, signal=None) -> Any:+ raise NotImplementedError++ async def should_stop_after_turn(self, ctx: Any) -> bool:+ raise NotImplementedError+++def _has_method(middleware: Middleware, name: str) -> bool:+ method = getattr(type(middleware), name, None)+ base_method = getattr(Middleware, name, None)+ return method is not None and method is not base_method+++def compose_middleware(middlewares: list[Middleware]) -> dict[str, Callable]:+ hooks: dict[str, Callable] = {}++ transform_chain = [m for m in middlewares if _has_method(m, "transform_context")]+ if transform_chain:+ async def composed_transform(messages, *, signal=None):+ result = messages+ for mw in transform_chain:+ result = await mw.transform_context(result, signal=signal)+ return result++ hooks["transform_context"] = composed_transform++ convert_impls = [m for m in middlewares if _has_method(m, "convert_to_llm")]+ if convert_impls:+ last = convert_impls[-1]++ async def composed_convert(messages):+ return await last.convert_to_llm(messages)++ hooks["convert_to_llm"] = composed_convert++ before_chain = [m for m in middlewares if _has_method(m, "before_tool_call")]+ if before_chain:+ async def composed_before(ctx, *, signal=None):+ for mw in before_chain:+ result = await mw.before_tool_call(ctx, signal=signal)+ if result and getattr(result, "block", False):+ return result+ return None++ hooks["before_tool_call"] = composed_before++ after_chain = [m for m in middlewares if _has_method(m, "after_tool_call")]+ if after_chain:+ async def composed_after(ctx, *, signal=None):+ last_result = None+ for mw in after_chain:+ result = await mw.after_tool_call(ctx, signal=signal)+ if result is not None:+ last_result = result+ return last_result++ hooks["after_tool_call"] = composed_after++ stop_chain = [m for m in middlewares if _has_method(m, "should_stop_after_turn")]+ if stop_chain:+ async def composed_stop(ctx):+ for mw in stop_chain:+ if await mw.should_stop_after_turn(ctx):+ return True+ return False++ hooks["should_stop_after_turn"] = composed_stop++ return hooks+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/middleware/test_base.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Update middleware `__init__.py`**++Update `cubepi/middleware/__init__.py`:++```python+from cubepi.middleware.base import Middleware, compose_middleware++__all__ = ["Middleware", "compose_middleware"]+```++- [ ] **Step 6: Commit**++```bash+git add cubepi/middleware/ tests/middleware/+git commit -m "feat: add Middleware protocol and compose_middleware"+```++---++### Task 9: Checkpointer — Protocol, Memory, and SQLite++**Files:**+- Create: `cubepi/checkpointer/base.py`+- Create: `cubepi/checkpointer/memory.py`+- Create: `cubepi/checkpointer/sqlite.py`+- Create: `tests/checkpointer/test_memory.py`+- Create: `tests/checkpointer/test_sqlite.py`++- [ ] **Step 1: Write MemoryCheckpointer tests**++Create `tests/checkpointer/test_memory.py`:++```python+from cubepi.checkpointer.memory import MemoryCheckpointer+from cubepi.providers.base import TextContent, UserMessage+++class TestMemoryCheckpointer:+ async def test_load_empty_thread(self):+ cp = MemoryCheckpointer()+ data = await cp.load("thread-1")+ assert data is None++ async def test_append_and_load(self):+ cp = MemoryCheckpointer()+ msg1 = UserMessage(content=[TextContent(text="hello")])+ msg2 = UserMessage(content=[TextContent(text="world")])++ await cp.append("thread-1", [msg1])+ await cp.append("thread-1", [msg2])++ data = await cp.load("thread-1")+ assert data is not None+ assert len(data.messages) == 2+ assert data.messages[0].content[0].text == "hello"+ assert data.messages[1].content[0].text == "world"++ async def test_save_extra(self):+ cp = MemoryCheckpointer()+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="hi")])])+ await cp.save_extra("thread-1", {"compaction_index": 5})++ data = await cp.load("thread-1")+ assert data is not None+ assert data.extra["compaction_index"] == 5++ async def test_save_extra_merges(self):+ cp = MemoryCheckpointer()+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="hi")])])+ await cp.save_extra("thread-1", {"a": 1})+ await cp.save_extra("thread-1", {"b": 2})++ data = await cp.load("thread-1")+ assert data.extra == {"a": 1, "b": 2}++ async def test_multiple_threads(self):+ cp = MemoryCheckpointer()+ await cp.append("t1", [UserMessage(content=[TextContent(text="t1")])])+ await cp.append("t2", [UserMessage(content=[TextContent(text="t2")])])++ d1 = await cp.load("t1")+ d2 = await cp.load("t2")++ assert d1.messages[0].content[0].text == "t1"+ assert d2.messages[0].content[0].text == "t2"+```++- [ ] **Step 2: Write SQLiteCheckpointer tests**++Create `tests/checkpointer/test_sqlite.py`:++```python+import os+import tempfile++import pytest++from cubepi.checkpointer.sqlite import SQLiteCheckpointer+from cubepi.providers.base import TextContent, UserMessage+++def db_path():+ fd, path = tempfile.mkstemp(suffix=".db")+ os.close(fd)+ yield path+ os.unlink(path)+++class TestSQLiteCheckpointer:+ async def test_load_empty_thread(self, db_path):+ async with SQLiteCheckpointer(db_path) as cp:+ data = await cp.load("thread-1")+ assert data is None++ async def test_append_and_load(self, db_path):+ async with SQLiteCheckpointer(db_path) as cp:+ msg1 = UserMessage(content=[TextContent(text="hello")])+ msg2 = UserMessage(content=[TextContent(text="world")])+ await cp.append("thread-1", [msg1])+ await cp.append("thread-1", [msg2])++ data = await cp.load("thread-1")+ assert data is not None+ assert len(data.messages) == 2+ assert data.messages[0].content[0].text == "hello"++ async def test_save_extra(self, db_path):+ async with SQLiteCheckpointer(db_path) as cp:+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="hi")])])+ await cp.save_extra("thread-1", {"index": 42})++ data = await cp.load("thread-1")+ assert data.extra["index"] == 42++ async def test_persistence_across_instances(self, db_path):+ async with SQLiteCheckpointer(db_path) as cp:+ await cp.append("thread-1", [UserMessage(content=[TextContent(text="persist")])])++ async with SQLiteCheckpointer(db_path) as cp:+ data = await cp.load("thread-1")+ assert data is not None+ assert data.messages[0].content[0].text == "persist"++ async def test_multiple_threads(self, db_path):+ async with SQLiteCheckpointer(db_path) as cp:+ await cp.append("t1", [UserMessage(content=[TextContent(text="t1")])])+ await cp.append("t2", [UserMessage(content=[TextContent(text="t2")])])++ d1 = await cp.load("t1")+ d2 = await cp.load("t2")+ assert d1.messages[0].content[0].text == "t1"+ assert d2.messages[0].content[0].text == "t2"+```++- [ ] **Step 3: Run tests to verify they fail**++```bash+pytest tests/checkpointer/ -v+```++Expected: ImportError.++- [ ] **Step 4: Implement checkpointer base and MemoryCheckpointer**++Create `cubepi/checkpointer/base.py`:++```python+from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Protocol, runtime_checkable+++@dataclass+class CheckpointData:+ messages: list[Any] = field(default_factory=list)+ extra: dict[str, Any] = field(default_factory=dict)+++@runtime_checkable+class Checkpointer(Protocol):+ async def load(self, thread_id: str) -> CheckpointData | None: ...+ async def append(self, thread_id: str, messages: list[Any]) -> None: ...+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None: ...+```++Create `cubepi/checkpointer/memory.py`:++```python+from __future__ import annotations++from typing import Any++from cubepi.checkpointer.base import CheckpointData+++class MemoryCheckpointer:+ def __init__(self) -> None:+ self._store: dict[str, CheckpointData] = {}++ async def load(self, thread_id: str) -> CheckpointData | None:+ return self._store.get(thread_id)++ async def append(self, thread_id: str, messages: list[Any]) -> None:+ if thread_id not in self._store:+ self._store[thread_id] = CheckpointData()+ self._store[thread_id].messages.extend(messages)++ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:+ if thread_id not in self._store:+ self._store[thread_id] = CheckpointData()+ self._store[thread_id].extra.update(extra)+```++- [ ] **Step 5: Run MemoryCheckpointer tests**++```bash+pytest tests/checkpointer/test_memory.py -v+```++Expected: All PASS.++- [ ] **Step 6: Implement SQLiteCheckpointer**++Create `cubepi/checkpointer/sqlite.py`:++```python+from __future__ import annotations++import json+from typing import Any++import aiosqlite++from cubepi.checkpointer.base import CheckpointData+++class SQLiteCheckpointer:+ def __init__(self, db_path: str) -> None:+ self._db_path = db_path+ self._db: aiosqlite.Connection | None = None++ async def __aenter__(self) -> SQLiteCheckpointer:+ self._db = await aiosqlite.connect(self._db_path)+ await self._db.execute(+ "CREATE TABLE IF NOT EXISTS messages ("+ " id INTEGER PRIMARY KEY AUTOINCREMENT,"+ " thread_id TEXT NOT NULL,"+ " message_json TEXT NOT NULL,"+ " created_at REAL NOT NULL DEFAULT (julianday('now'))"+ ")"+ )+ await self._db.execute(+ "CREATE TABLE IF NOT EXISTS thread_extra ("+ " thread_id TEXT PRIMARY KEY,"+ " extra_json TEXT NOT NULL DEFAULT '{}'"+ ")"+ )+ await self._db.commit()+ return self++ async def __aexit__(self, *args: Any) -> None:+ if self._db:+ await self._db.close()+ self._db = None++ async def load(self, thread_id: str) -> CheckpointData | None:+ assert self._db is not None+ cursor = await self._db.execute(+ "SELECT message_json FROM messages WHERE thread_id = ? ORDER BY id",+ (thread_id,),+ )+ rows = await cursor.fetchall()+ if not rows:+ extra_cursor = await self._db.execute(+ "SELECT extra_json FROM thread_extra WHERE thread_id = ?",+ (thread_id,),+ )+ extra_row = await extra_cursor.fetchone()+ if not extra_row:+ return None++ messages = []+ for row in rows:+ msg_data = json.loads(row[0])+ messages.append(_deserialize_message(msg_data))++ extra_cursor = await self._db.execute(+ "SELECT extra_json FROM thread_extra WHERE thread_id = ?",+ (thread_id,),+ )+ extra_row = await extra_cursor.fetchone()+ extra = json.loads(extra_row[0]) if extra_row else {}++ return CheckpointData(messages=messages, extra=extra)++ async def append(self, thread_id: str, messages: list[Any]) -> None:+ assert self._db is not None+ for msg in messages:+ msg_json = _serialize_message(msg)+ await self._db.execute(+ "INSERT INTO messages (thread_id, message_json) VALUES (?, ?)",+ (thread_id, msg_json),+ )+ await self._db.commit()++ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:+ assert self._db is not None+ existing_cursor = await self._db.execute(+ "SELECT extra_json FROM thread_extra WHERE thread_id = ?",+ (thread_id,),+ )+ existing_row = await existing_cursor.fetchone()+ if existing_row:+ existing_extra = json.loads(existing_row[0])+ existing_extra.update(extra)+ await self._db.execute(+ "UPDATE thread_extra SET extra_json = ? WHERE thread_id = ?",+ (json.dumps(existing_extra), thread_id),+ )+ else:+ await self._db.execute(+ "INSERT INTO thread_extra (thread_id, extra_json) VALUES (?, ?)",+ (thread_id, json.dumps(extra)),+ )+ await self._db.commit()+++def _serialize_message(msg: Any) -> str:+ if hasattr(msg, "model_dump"):+ return json.dumps(msg.model_dump())+ return json.dumps(msg)+++def _deserialize_message(data: dict) -> Any:+ from cubepi.providers.base import AssistantMessage, ToolResultMessage, UserMessage++ role = data.get("role")+ if role == "user":+ return UserMessage.model_validate(data)+ elif role == "assistant":+ return AssistantMessage.model_validate(data)+ elif role == "tool_result":+ return ToolResultMessage.model_validate(data)+ return data+```++- [ ] **Step 7: Run all checkpointer tests**++```bash+pytest tests/checkpointer/ -v+```++Expected: All tests PASS.++- [ ] **Step 8: Update checkpointer `__init__.py`**++Update `cubepi/checkpointer/__init__.py`:++```python+from cubepi.checkpointer.base import Checkpointer, CheckpointData+from cubepi.checkpointer.memory import MemoryCheckpointer++__all__ = ["Checkpointer", "CheckpointData", "MemoryCheckpointer"]+```++- [ ] **Step 9: Commit**++```bash+git add cubepi/checkpointer/ tests/checkpointer/+git commit -m "feat: add Checkpointer protocol with Memory and SQLite implementations"+```++---++### Task 10: AnthropicProvider++**Files:**+- Create: `cubepi/providers/anthropic.py`+- Create: `tests/providers/test_anthropic.py`++- [ ] **Step 1: Write AnthropicProvider unit tests**++Create `tests/providers/test_anthropic.py`:++```python+import pytest++from cubepi.providers.anthropic import AnthropicProvider+from cubepi.providers.base import (+ Model,+ TextContent,+ ToolCall,+ ToolDefinition,+ UserMessage,+ AssistantMessage,+ ToolResultMessage,+)+++class TestAnthropicMessageConversion:+ def test_convert_user_message(self):+ msg = UserMessage(content=[TextContent(text="hello")])+ result = AnthropicProvider._convert_message(msg)+ assert result["role"] == "user"+ assert result["content"][0]["type"] == "text"+ assert result["content"][0]["text"] == "hello"++ def test_convert_assistant_message(self):+ msg = AssistantMessage(content=[TextContent(text="hi")])+ result = AnthropicProvider._convert_message(msg)+ assert result["role"] == "assistant"++ def test_convert_assistant_with_tool_call(self):+ msg = AssistantMessage(+ content=[ToolCall(id="tc-1", name="search", arguments={"q": "test"})],+ stop_reason="tool_use",+ )+ result = AnthropicProvider._convert_message(msg)+ assert result["content"][0]["type"] == "tool_use"+ assert result["content"][0]["id"] == "tc-1"+ assert result["content"][0]["name"] == "search"+ assert result["content"][0]["input"] == {"q": "test"}++ def test_convert_tool_result(self):+ msg = ToolResultMessage(+ tool_call_id="tc-1",+ tool_name="search",+ content=[TextContent(text="result")],+ )+ result = AnthropicProvider._convert_message(msg)+ assert result["role"] == "user"+ assert result["content"][0]["type"] == "tool_result"+ assert result["content"][0]["tool_use_id"] == "tc-1"+++class TestAnthropicToolConversion:+ def test_convert_tool_definition(self):+ td = ToolDefinition(+ name="search",+ description="Search the web",+ parameters={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ "required": ["q"],+ },+ )+ result = AnthropicProvider._convert_tool(td)+ assert result["name"] == "search"+ assert result["description"] == "Search the web"+ assert result["input_schema"]["type"] == "object"+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/providers/test_anthropic.py -v+```++Expected: ImportError.++- [ ] **Step 3: Implement AnthropicProvider**++Create `cubepi/providers/anthropic.py`:++```python+from __future__ import annotations++import asyncio+import time+from typing import Any++from cubepi.providers.base import (+ AssistantMessage,+ Content,+ ImageContent,+ Message,+ MessageStream,+ Model,+ StreamEvent,+ TextContent,+ ThinkingContent,+ ThinkingLevel,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ Usage,+ UserMessage,+)+++class AnthropicProvider:+ def __init__(self, *, api_key: str | None = None) -> None:+ import anthropic++ self._client = anthropic.AsyncAnthropic(api_key=api_key)++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ thinking: ThinkingLevel = "off",+ signal: asyncio.Event | None = None,+ ) -> MessageStream:+ ms = MessageStream()++ api_messages = [self._convert_message(m) for m in messages]+ kwargs: dict[str, Any] = {+ "model": model.id,+ "messages": api_messages,+ "max_tokens": model.max_tokens,+ }+ if system_prompt:+ kwargs["system"] = system_prompt+ if tools:+ kwargs["tools"] = [self._convert_tool(t) for t in tools]+ if thinking != "off":+ kwargs["thinking"] = {"type": "enabled", "budget_tokens": self._thinking_budget(thinking, model)}++ async def _produce() -> None:+ try:+ async with self._client.messages.stream(**kwargs) as stream:+ partial = AssistantMessage(content=[], usage=Usage(), timestamp=time.time())+ ms.push(StreamEvent(type="start", partial=partial.model_copy(deep=True)))++ async for event in stream:+ if signal and signal.is_set():+ aborted = partial.model_copy(update={+ "stop_reason": "aborted",+ "error_message": "Request was aborted",+ })+ ms.push(StreamEvent(type="error", error_message="Request was aborted"))+ ms.set_result(aborted)+ return++ self._handle_event(event, partial, ms)++ final_msg = stream.get_final_message()+ result = self._convert_response(final_msg)+ ms.push(StreamEvent(type="done"))+ ms.set_result(result)++ 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)++ asyncio.create_task(_produce())+ return ms++ @staticmethod+ def _convert_message(msg: Message) -> dict[str, Any]:+ if isinstance(msg, UserMessage):+ content = []+ for c in msg.content:+ if isinstance(c, TextContent):+ content.append({"type": "text", "text": c.text})+ elif isinstance(c, ImageContent):+ content.append({+ "type": "image",+ "source": {"type": "base64", "media_type": c.media_type, "data": c.source},+ })+ return {"role": "user", "content": content}++ elif isinstance(msg, AssistantMessage):+ content = []+ for c in msg.content:+ if isinstance(c, TextContent):+ content.append({"type": "text", "text": c.text})+ elif isinstance(c, ThinkingContent):+ content.append({"type": "thinking", "thinking": c.thinking})+ elif isinstance(c, ToolCall):+ content.append({+ "type": "tool_use",+ "id": c.id,+ "name": c.name,+ "input": c.arguments,+ })+ return {"role": "assistant", "content": content}++ elif isinstance(msg, ToolResultMessage):+ tool_content = []+ for c in msg.content:+ if isinstance(c, TextContent):+ tool_content.append({"type": "text", "text": c.text})+ return {+ "role": "user",+ "content": [{+ "type": "tool_result",+ "tool_use_id": msg.tool_call_id,+ "content": tool_content,+ "is_error": msg.is_error,+ }],+ }++ return {"role": "user", "content": []}++ @staticmethod+ def _convert_tool(td: ToolDefinition) -> dict[str, Any]:+ return {+ "name": td.name,+ "description": td.description,+ "input_schema": td.parameters,+ }++ @staticmethod+ def _thinking_budget(level: ThinkingLevel, model: Model) -> int:+ budgets = {+ "minimal": 1024,+ "low": 2048,+ "medium": 4096,+ "high": 8192,+ "xhigh": 16384,+ }+ return budgets.get(level, 4096)++ def _handle_event(self, event: Any, partial: AssistantMessage, ms: MessageStream) -> None:+ etype = getattr(event, "type", "")+ if etype == "content_block_start":+ block = event.content_block+ if block.type == "text":+ partial.content.append(TextContent(text=""))+ ms.push(StreamEvent(type="text_start", partial=partial.model_copy(deep=True)))+ elif block.type == "thinking":+ partial.content.append(ThinkingContent(thinking=""))+ ms.push(StreamEvent(type="thinking_start", partial=partial.model_copy(deep=True)))+ elif block.type == "tool_use":+ partial.content.append(ToolCall(id=block.id, name=block.name, arguments={}))+ ms.push(StreamEvent(type="toolcall_start", partial=partial.model_copy(deep=True)))+ elif etype == "content_block_delta":+ delta = event.delta+ if hasattr(delta, "text"):+ if partial.content and isinstance(partial.content[-1], TextContent):+ partial.content[-1] = TextContent(text=partial.content[-1].text + delta.text)+ ms.push(StreamEvent(type="text_delta", delta=delta.text, partial=partial.model_copy(deep=True)))+ elif hasattr(delta, "thinking"):+ if partial.content and isinstance(partial.content[-1], ThinkingContent):+ partial.content[-1] = ThinkingContent(thinking=partial.content[-1].thinking + delta.thinking)+ ms.push(StreamEvent(type="thinking_delta", delta=delta.thinking, partial=partial.model_copy(deep=True)))+ elif hasattr(delta, "partial_json"):+ ms.push(StreamEvent(type="toolcall_delta", delta=delta.partial_json, partial=partial.model_copy(deep=True)))+ elif etype == "content_block_stop":+ if partial.content:+ last = partial.content[-1]+ if isinstance(last, TextContent):+ ms.push(StreamEvent(type="text_end", partial=partial.model_copy(deep=True)))+ elif isinstance(last, ThinkingContent):+ ms.push(StreamEvent(type="thinking_end", partial=partial.model_copy(deep=True)))+ elif isinstance(last, ToolCall):+ ms.push(StreamEvent(type="toolcall_end", partial=partial.model_copy(deep=True)))++ @staticmethod+ def _convert_response(response: Any) -> AssistantMessage:+ content: list[Any] = []+ for block in response.content:+ if block.type == "text":+ content.append(TextContent(text=block.text))+ elif block.type == "thinking":+ content.append(ThinkingContent(thinking=block.thinking))+ elif block.type == "tool_use":+ content.append(ToolCall(id=block.id, name=block.name, arguments=block.input))++ stop_reason_map = {+ "end_turn": "stop",+ "tool_use": "tool_use",+ "max_tokens": "length",+ }++ return AssistantMessage(+ content=content,+ stop_reason=stop_reason_map.get(response.stop_reason, response.stop_reason),+ usage=Usage(+ input_tokens=response.usage.input_tokens,+ output_tokens=response.usage.output_tokens,+ cache_read_tokens=getattr(response.usage, "cache_read_input_tokens", 0) or 0,+ cache_write_tokens=getattr(response.usage, "cache_creation_input_tokens", 0) or 0,+ ),+ timestamp=time.time(),+ )+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/providers/test_anthropic.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Commit**++```bash+git add cubepi/providers/anthropic.py tests/providers/test_anthropic.py+git commit -m "feat: add AnthropicProvider with streaming support"+```++---++### Task 11: OpenAIProvider++**Files:**+- Create: `cubepi/providers/openai.py`+- Create: `tests/providers/test_openai.py`++- [ ] **Step 1: Write OpenAIProvider unit tests**++Create `tests/providers/test_openai.py`:++```python+from cubepi.providers.openai import OpenAIProvider+from cubepi.providers.base import (+ AssistantMessage,+ Model,+ TextContent,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ UserMessage,+)+++class TestOpenAIMessageConversion:+ def test_convert_user_message(self):+ msg = UserMessage(content=[TextContent(text="hello")])+ result = OpenAIProvider._convert_message(msg)+ assert result["role"] == "user"+ assert result["content"] == "hello"++ def test_convert_assistant_message(self):+ msg = AssistantMessage(content=[TextContent(text="hi")])+ result = OpenAIProvider._convert_message(msg)+ assert result["role"] == "assistant"+ assert result["content"] == "hi"++ def test_convert_assistant_with_tool_calls(self):+ msg = AssistantMessage(+ content=[ToolCall(id="tc-1", name="search", arguments={"q": "test"})],+ stop_reason="tool_use",+ )+ result = OpenAIProvider._convert_message(msg)+ assert result["role"] == "assistant"+ assert len(result["tool_calls"]) == 1+ assert result["tool_calls"][0]["id"] == "tc-1"+ assert result["tool_calls"][0]["function"]["name"] == "search"++ def test_convert_tool_result(self):+ msg = ToolResultMessage(+ tool_call_id="tc-1",+ tool_name="search",+ content=[TextContent(text="result")],+ )+ result = OpenAIProvider._convert_message(msg)+ assert result["role"] == "tool"+ assert result["tool_call_id"] == "tc-1"+ assert result["content"] == "result"+++class TestOpenAIToolConversion:+ def test_convert_tool_definition(self):+ td = ToolDefinition(+ name="search",+ description="Search the web",+ parameters={+ "type": "object",+ "properties": {"q": {"type": "string"}},+ "required": ["q"],+ },+ )+ result = OpenAIProvider._convert_tool(td)+ assert result["type"] == "function"+ assert result["function"]["name"] == "search"+ assert result["function"]["parameters"]["type"] == "object"+```++- [ ] **Step 2: Run tests to verify they fail**++```bash+pytest tests/providers/test_openai.py -v+```++Expected: ImportError.++- [ ] **Step 3: Implement OpenAIProvider**++Create `cubepi/providers/openai.py`:++```python+from __future__ import annotations++import asyncio+import json+import time+from typing import Any++from cubepi.providers.base import (+ AssistantMessage,+ ImageContent,+ Message,+ MessageStream,+ Model,+ StreamEvent,+ TextContent,+ ThinkingLevel,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ Usage,+ UserMessage,+)+++class OpenAIProvider:+ def __init__(self, *, api_key: str | None = None, base_url: str | None = None) -> None:+ import openai++ kwargs: dict[str, Any] = {}+ if api_key:+ kwargs["api_key"] = api_key+ if base_url:+ kwargs["base_url"] = base_url+ self._client = openai.AsyncOpenAI(**kwargs)++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ thinking: ThinkingLevel = "off",+ signal: asyncio.Event | None = None,+ ) -> MessageStream:+ ms = MessageStream()++ api_messages: list[dict[str, Any]] = []+ if system_prompt:+ api_messages.append({"role": "system", "content": system_prompt})+ api_messages.extend(self._convert_message(m) for m in messages)++ kwargs: dict[str, Any] = {+ "model": model.id,+ "messages": api_messages,+ "stream": True,+ }+ if tools:+ kwargs["tools"] = [self._convert_tool(t) for t in tools]++ async def _produce() -> None:+ try:+ response = await self._client.chat.completions.create(**kwargs)+ partial = AssistantMessage(content=[], usage=Usage(), timestamp=time.time())+ ms.push(StreamEvent(type="start", partial=partial.model_copy(deep=True)))++ current_text = ""+ tool_calls_in_progress: dict[int, dict[str, Any]] = {}+ text_started = False++ async for chunk in response:+ if signal and signal.is_set():+ aborted = partial.model_copy(update={+ "stop_reason": "aborted",+ "error_message": "Request was aborted",+ })+ ms.push(StreamEvent(type="error", error_message="Request was aborted"))+ ms.set_result(aborted)+ return++ delta = chunk.choices[0].delta if chunk.choices else None+ if not delta:+ continue++ if delta.content:+ if not text_started:+ partial.content.append(TextContent(text=""))+ ms.push(StreamEvent(type="text_start", partial=partial.model_copy(deep=True)))+ text_started = True+ current_text += delta.content+ if partial.content and isinstance(partial.content[-1], TextContent):+ partial.content[-1] = TextContent(text=current_text)+ ms.push(StreamEvent(type="text_delta", delta=delta.content, partial=partial.model_copy(deep=True)))++ if delta.tool_calls:+ for tc_delta in delta.tool_calls:+ idx = tc_delta.index+ if idx not in tool_calls_in_progress:+ if text_started:+ ms.push(StreamEvent(type="text_end", partial=partial.model_copy(deep=True)))+ text_started = False+ tool_calls_in_progress[idx] = {+ "id": tc_delta.id or "",+ "name": tc_delta.function.name if tc_delta.function else "",+ "arguments": "",+ }+ partial.content.append(ToolCall(+ id=tool_calls_in_progress[idx]["id"],+ name=tool_calls_in_progress[idx]["name"],+ arguments={},+ ))+ ms.push(StreamEvent(type="toolcall_start", partial=partial.model_copy(deep=True)))+ if tc_delta.function and tc_delta.function.arguments:+ tool_calls_in_progress[idx]["arguments"] += tc_delta.function.arguments+ ms.push(StreamEvent(+ type="toolcall_delta",+ delta=tc_delta.function.arguments,+ partial=partial.model_copy(deep=True),+ ))++ finish_reason = chunk.choices[0].finish_reason if chunk.choices else None+ if finish_reason:+ if text_started:+ ms.push(StreamEvent(type="text_end", partial=partial.model_copy(deep=True)))++ for idx, tc_data in tool_calls_in_progress.items():+ try:+ args = json.loads(tc_data["arguments"]) if tc_data["arguments"] else {}+ except json.JSONDecodeError:+ args = {}+ for i, c in enumerate(partial.content):+ if isinstance(c, ToolCall) and c.id == tc_data["id"]:+ partial.content[i] = ToolCall(+ id=tc_data["id"], name=tc_data["name"], arguments=args,+ )+ ms.push(StreamEvent(type="toolcall_end", partial=partial.model_copy(deep=True)))++ stop_map = {"stop": "stop", "tool_calls": "tool_use", "length": "length"}+ final = partial.model_copy(update={+ "stop_reason": stop_map.get(finish_reason, finish_reason),+ })+ ms.push(StreamEvent(type="done"))+ ms.set_result(final)+ return++ 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)++ asyncio.create_task(_produce())+ return ms++ @staticmethod+ def _convert_message(msg: Message) -> dict[str, Any]:+ if isinstance(msg, UserMessage):+ text_parts = [c.text for c in msg.content if isinstance(c, TextContent)]+ return {"role": "user", "content": "\n".join(text_parts)}++ elif isinstance(msg, AssistantMessage):+ text_parts = [c.text for c in msg.content if isinstance(c, TextContent)]+ tool_calls = [c for c in msg.content if isinstance(c, ToolCall)]++ result: dict[str, Any] = {"role": "assistant"}+ if text_parts:+ result["content"] = "\n".join(text_parts)+ if tool_calls:+ result["tool_calls"] = [+ {+ "id": tc.id,+ "type": "function",+ "function": {+ "name": tc.name,+ "arguments": json.dumps(tc.arguments),+ },+ }+ for tc in tool_calls+ ]+ return result++ elif isinstance(msg, ToolResultMessage):+ text_parts = [c.text for c in msg.content if isinstance(c, TextContent)]+ return {+ "role": "tool",+ "tool_call_id": msg.tool_call_id,+ "content": "\n".join(text_parts),+ }++ return {"role": "user", "content": ""}++ @staticmethod+ def _convert_tool(td: ToolDefinition) -> dict[str, Any]:+ return {+ "type": "function",+ "function": {+ "name": td.name,+ "description": td.description,+ "parameters": td.parameters,+ },+ }+```++- [ ] **Step 4: Run tests to verify they pass**++```bash+pytest tests/providers/test_openai.py -v+```++Expected: All tests PASS.++- [ ] **Step 5: Commit**++```bash+git add cubepi/providers/openai.py tests/providers/test_openai.py+git commit -m "feat: add OpenAIProvider with streaming support"+```++---++### Task 12: Package Re-exports and Final Integration++**Files:**+- Modify: `cubepi/__init__.py`+- Modify: `cubepi/providers/__init__.py`++- [ ] **Step 1: Update top-level `__init__.py`**++```python+"""cubepi — Pythonic async-native agent framework."""++from cubepi.agent import Agent, AgentState, AgentTool, AgentToolResult, run_agent_loop, run_agent_loop_continue+from cubepi.middleware import Middleware, compose_middleware+from cubepi.providers import (+ AssistantMessage,+ Message,+ MessageStream,+ Model,+ Provider,+ StreamEvent,+ TextContent,+ ThinkingLevel,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+ UserMessage,+)++__all__ = [+ "Agent",+ "AgentState",+ "AgentTool",+ "AgentToolResult",+ "AssistantMessage",+ "Message",+ "MessageStream",+ "Middleware",+ "Model",+ "Provider",+ "StreamEvent",+ "TextContent",+ "ThinkingLevel",+ "ToolCall",+ "ToolDefinition",+ "ToolResultMessage",+ "UserMessage",+ "compose_middleware",+ "run_agent_loop",+ "run_agent_loop_continue",+]+```++- [ ] **Step 2: Update providers `__init__.py` to include all providers**++Add to the existing `cubepi/providers/__init__.py`:++```python+from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_text, faux_thinking, faux_tool_call++# Lazy imports for optional providers+def get_anthropic_provider():+ from cubepi.providers.anthropic import AnthropicProvider+ return AnthropicProvider++def get_openai_provider():+ from cubepi.providers.openai import OpenAIProvider+ return OpenAIProvider+```++Add `FauxProvider`, `faux_assistant_message`, `faux_text`, `faux_thinking`, `faux_tool_call` to `__all__`.++- [ ] **Step 3: Run all tests**++```bash+pytest tests/ -v --tb=short+```++Expected: All tests PASS.++- [ ] **Step 4: Commit**++```bash+git add cubepi/__init__.py cubepi/providers/__init__.py+git commit -m "feat: add package re-exports and finalize public API"+```++---++### Task 13: Full Test Suite Run and Coverage++- [ ] **Step 1: Run full test suite with coverage**++```bash+pytest tests/ -v --cov=cubepi --cov-report=term-missing+```++Expected: All tests PASS, coverage report shows each module.++- [ ] **Step 2: Fix any failures**++If any tests fail, fix the underlying issue and re-run.++- [ ] **Step 3: Final commit if any fixes were needed**++```bash+git add -A+git commit -m "fix: resolve test suite issues"+```diff --git a/dev/plans/2026-05-10-cubepi-improvement-plan.md b/dev/plans/2026-05-10-cubepi-improvement-plan.mdnew file mode 100644index 0000000..48c843c--- /dev/null+++ b/dev/plans/2026-05-10-cubepi-improvement-plan.md@@ -0,0 +1,1491 @@+# cubepi Improvement Plan (P0 + P1 + P2)++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Bring cubepi's type safety, feature completeness, and code quality up to parity with pi-agent-core across 11 items (P0–P2).++**Architecture:** Changes are layered bottom-up: first fix the foundation types in `providers/base.py` and `agent/types.py` (P0), then wire missing features through the agent layer (P1), then clean up code smells (P2). Each task is independently committable and testable.++**Tech Stack:** Python 3.11+, Pydantic v2, asyncio, pytest-asyncio++**Baseline:** 265 tests pass. Run `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q` to verify.++---++## File Map++### Files to modify++| File | What changes |+|---|---|+| `cubepi/providers/base.py` | Add `content_index` to `StreamEvent`, add `provider_id`/`model_id`/`response_id` to `AssistantMessage`, add `details` to `ToolResultMessage`, rename `_invoke_on_payload`→`invoke_on_payload` / `_invoke_on_response`→`invoke_on_response`, store task ref in `MessageStream` |+| `cubepi/agent/types.py` | Replace `Any` with `Message` union in event types, `AgentContext`, `ShouldStopAfterTurnContext`; add `emit_event` helper |+| `cubepi/agent/agent.py` | Type callbacks/state, integrate checkpointer, remove `hasattr` checks |+| `cubepi/agent/loop.py` | Type parameters, remove local `_emit`, add initial steering poll |+| `cubepi/agent/tools.py` | Remove local `_emit`, pass `details` in `_make_tool_result_message` |+| `cubepi/providers/anthropic.py` | Add `content_index` to events, fill `provider_id`/`model_id`, rename imports |+| `cubepi/providers/openai.py` | Add `content_index` to events, fill metadata, rename imports, add image support |+| `cubepi/providers/openai_responses.py` | Add `content_index` to events, fill metadata, remove dead code |+| `cubepi/providers/faux.py` | Add `content_index` to events |++### Files to create++| File | Purpose |+|---|---|+| `tests/providers/test_content_index.py` | Tests for `content_index` on `StreamEvent` |+| `tests/agent/test_checkpointer_integration.py` | Tests for checkpointer wired into Agent |++### Existing test files to modify++| File | What changes |+|---|---|+| `tests/providers/test_base.py` | Add tests for new `AssistantMessage` fields, `ToolResultMessage.details` |+| `tests/agent/test_loop.py` | Add test for initial steering poll |+| `tests/agent/test_tools.py` | Add test for `details` propagation |+| `tests/providers/test_faux.py` | Update assertions for `content_index` |+| `tests/providers/test_openai.py` | Add image conversion test |++---++## Task 1: Add `content_index` to `StreamEvent`++**Files:**+- Modify: `cubepi/providers/base.py:148-165`+- Test: `tests/providers/test_base.py`++- [ ] **Step 1: Write the failing test**++In `tests/providers/test_base.py`, add:++```python+class TestStreamEvent:+ def test_content_index_default_none(self):+ event = StreamEvent(type="text_delta", delta="hi")+ assert event.content_index is None++ def test_content_index_set(self):+ event = StreamEvent(type="text_start", content_index=0)+ assert event.content_index == 0++ def test_content_index_on_start_event(self):+ event = StreamEvent(type="start")+ assert event.content_index is None+```++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/providers/test_base.py::TestStreamEvent -v`+Expected: FAIL with `unexpected keyword argument 'content_index'`++- [ ] **Step 3: Add `content_index` field to `StreamEvent`**++In `cubepi/providers/base.py`, change:++```python+class StreamEvent(BaseModel):+ 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 = None+ delta: str | None = None+ partial: AssistantMessage | None = None+ error_message: str | None = None+```++- [ ] **Step 4: Run test to verify it passes**++Run: `pytest tests/providers/test_base.py::TestStreamEvent -v`+Expected: PASS++- [ ] **Step 5: Run full suite to verify no regressions**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass (existing tests don't assert `content_index is absent`)++- [ ] **Step 6: Commit**++```bash+git add cubepi/providers/base.py tests/providers/test_base.py+git commit -m "feat: add content_index field to StreamEvent"+```++---++## Task 2: Fill `content_index` in AnthropicProvider++**Files:**+- Modify: `cubepi/providers/anthropic.py:259-347`+- Test: `tests/providers/test_content_index.py` (create)++- [ ] **Step 1: Write the failing test**++Create `tests/providers/test_content_index.py`:++```python+from cubepi.providers.base import StreamEvent+from cubepi.providers.faux import (+ FauxProvider,+ faux_assistant_message,+ faux_text,+ faux_thinking,+ faux_tool_call,+)+from cubepi.providers.base import Model+++def make_model() -> Model:+ return Model(id="faux-1", provider="faux")+++class TestFauxContentIndex:+ async def test_text_events_have_content_index(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("Hello")])+ stream = await provider.stream(make_model(), [])++ events: list[StreamEvent] = []+ async for event in stream:+ events.append(event)++ text_events = [e for e in events if e.type in ("text_start", "text_delta", "text_end")]+ assert len(text_events) >= 2+ for e in text_events:+ assert e.content_index == 0++ async def test_thinking_then_text_indices(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message([faux_thinking("hmm"), faux_text("answer")])+ ])+ stream = await provider.stream(make_model(), [])++ events: list[StreamEvent] = []+ async for event in stream:+ events.append(event)++ thinking_events = [e for e in events if e.type.startswith("thinking_")]+ text_events = [e for e in events if e.type.startswith("text_")]+ for e in thinking_events:+ assert e.content_index == 0+ for e in text_events:+ assert e.content_index == 1++ async def test_tool_call_content_index(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message([+ faux_text("Let me help"),+ faux_tool_call("search", {"q": "test"}),+ ])+ ])+ stream = await provider.stream(make_model(), [])++ events: list[StreamEvent] = []+ async for event in stream:+ events.append(event)++ text_events = [e for e in events if e.type.startswith("text_")]+ tool_events = [e for e in events if e.type.startswith("toolcall_")]+ for e in text_events:+ assert e.content_index == 0+ for e in tool_events:+ assert e.content_index == 1+```++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/providers/test_content_index.py -v`+Expected: FAIL — `content_index` is `None` everywhere++- [ ] **Step 3: Update FauxProvider to emit `content_index`**++In `cubepi/providers/faux.py`, in `_stream_with_deltas`, track a block counter. Before each block loop (ThinkingContent, TextContent, ToolCall), compute `block_idx = len(partial.content) - 1` after appending the empty placeholder, then pass `content_index=block_idx` to every `StreamEvent` within that block.++For **ThinkingContent** blocks (around line 320-353), after `partial.content.append(ThinkingContent(...))`:+```python+block_idx = len(partial.content) - 1+```+Then every `StreamEvent` in that block gets `content_index=block_idx`.++For **TextContent** blocks (around line 355-385), same pattern.++For **ToolCall** blocks (around line 387-424), same pattern.++The `"start"` event keeps `content_index=None` (it's a message-level event, not a content-block event).++Full replacement for the block iteration in `_stream_with_deltas` (the `for block in message.content:` loop body):++```python+if isinstance(block, ThinkingContent):+ partial.content.append(ThinkingContent(thinking=""))+ block_idx = len(partial.content) - 1+ stream.push(+ StreamEvent(+ type="thinking_start",+ content_index=block_idx,+ partial=partial.model_copy(deep=True),+ )+ )+ for chunk in _split_by_token_size(block.thinking, self._min, self._max):+ await self._schedule_chunk(chunk)+ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(+ StreamEvent(+ type="error", error_message="Request was aborted"+ )+ )+ stream.set_result(aborted)+ return+ last = partial.content[-1]+ if isinstance(last, ThinkingContent):+ partial.content[-1] = ThinkingContent(+ thinking=last.thinking + chunk+ )+ stream.push(+ StreamEvent(+ type="thinking_delta",+ content_index=block_idx,+ delta=chunk,+ partial=partial.model_copy(deep=True),+ )+ )+ stream.push(+ StreamEvent(+ type="thinking_end",+ content_index=block_idx,+ partial=partial.model_copy(deep=True),+ )+ )++elif isinstance(block, TextContent):+ partial.content.append(TextContent(text=""))+ block_idx = len(partial.content) - 1+ stream.push(+ StreamEvent(+ type="text_start",+ content_index=block_idx,+ partial=partial.model_copy(deep=True),+ )+ )+ for chunk in _split_by_token_size(block.text, self._min, self._max):+ await self._schedule_chunk(chunk)+ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(+ StreamEvent(+ type="error", error_message="Request was aborted"+ )+ )+ stream.set_result(aborted)+ return+ last = partial.content[-1]+ if isinstance(last, TextContent):+ partial.content[-1] = TextContent(text=last.text + chunk)+ stream.push(+ StreamEvent(+ type="text_delta",+ content_index=block_idx,+ delta=chunk,+ partial=partial.model_copy(deep=True),+ )+ )+ stream.push(+ StreamEvent(+ type="text_end",+ content_index=block_idx,+ partial=partial.model_copy(deep=True),+ )+ )++elif isinstance(block, ToolCall):+ partial.content.append(+ ToolCall(id=block.id, name=block.name, arguments={})+ )+ block_idx = len(partial.content) - 1+ stream.push(+ StreamEvent(+ type="toolcall_start",+ content_index=block_idx,+ partial=partial.model_copy(deep=True),+ )+ )+ json_str = json.dumps(block.arguments)+ for chunk in _split_by_token_size(json_str, self._min, self._max):+ await self._schedule_chunk(chunk)+ if signal and signal.is_set():+ aborted = self._make_aborted(partial)+ stream.push(+ StreamEvent(+ type="error", error_message="Request was aborted"+ )+ )+ stream.set_result(aborted)+ return+ stream.push(+ StreamEvent(+ type="toolcall_delta",+ content_index=block_idx,+ delta=chunk,+ partial=partial.model_copy(deep=True),+ )+ )+ last = partial.content[-1]+ if isinstance(last, ToolCall):+ partial.content[-1] = ToolCall(+ id=block.id, name=block.name, arguments=block.arguments+ )+ stream.push(+ StreamEvent(+ type="toolcall_end",+ content_index=block_idx,+ partial=partial.model_copy(deep=True),+ )+ )+```++- [ ] **Step 4: Update AnthropicProvider to emit `content_index`**++In `cubepi/providers/anthropic.py`, `_handle_event` method: Anthropic emits a block index via `event.index` on `content_block_start`, `content_block_delta`, `content_block_stop`. Use it:++In `_handle_event`, the Anthropic SDK provides `event.index` on `content_block_start`/`content_block_delta`/`content_block_stop`. Pass `content_index=event.index` to every `StreamEvent`. For example, the `content_block_start` handler:++```python+if etype == "content_block_start":+ block = event.content_block+ idx = getattr(event, "index", len(partial.content))+ if block.type == "text":+ partial.content.append(TextContent(text=""))+ ms.push(+ StreamEvent(+ type="text_start",+ content_index=idx,+ partial=partial.model_copy(deep=True),+ )+ )+ elif block.type == "thinking":+ partial.content.append(ThinkingContent(thinking=""))+ ms.push(+ StreamEvent(+ type="thinking_start",+ content_index=idx,+ partial=partial.model_copy(deep=True),+ )+ )+ elif block.type == "tool_use":+ partial.content.append(+ ToolCall(id=block.id, name=block.name, arguments={})+ )+ ms.push(+ StreamEvent(+ type="toolcall_start",+ content_index=idx,+ partial=partial.model_copy(deep=True),+ )+ )+```++Apply the same `idx = getattr(event, "index", ...)` pattern to `content_block_delta` and `content_block_stop` events.++- [ ] **Step 5: Update OpenAIProvider to emit `content_index`**++In `cubepi/providers/openai.py`, track the content index. Text always starts at index 0 (or after any prior blocks). Tool calls use the index computed from `len(partial.content) - 1` after appending.++Key changes in `_produce()`:+- After `partial.content.append(TextContent(text=""))`, compute `text_idx = len(partial.content) - 1` and pass `content_index=text_idx` to all text events.+- After `partial.content.append(ToolCall(...))`, compute `tc_idx = len(partial.content) - 1` and pass `content_index=tc_idx` to toolcall_start/delta/end events.++- [ ] **Step 6: Update OpenAIResponsesProvider to emit `content_index`**++In `cubepi/providers/openai_responses.py`, after each `partial.content.append(...)`, compute `block_idx = len(partial.content) - 1`. Pass `content_index=block_idx` to the corresponding start/delta/end events.++- [ ] **Step 7: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 8: Commit**++```bash+git add cubepi/providers/base.py cubepi/providers/faux.py cubepi/providers/anthropic.py cubepi/providers/openai.py cubepi/providers/openai_responses.py tests/providers/test_content_index.py+git commit -m "feat: populate content_index on all provider StreamEvents"+```++---++## Task 3: Add provider metadata to `AssistantMessage`++**Files:**+- Modify: `cubepi/providers/base.py:121-128`+- Modify: `cubepi/providers/anthropic.py:349-382`+- Modify: `cubepi/providers/openai.py` (in `_produce`)+- Modify: `cubepi/providers/openai_responses.py` (in `_produce`)+- Test: `tests/providers/test_base.py`++- [ ] **Step 1: Write the failing test**++In `tests/providers/test_base.py`, add:++```python+class TestAssistantMessageMetadata:+ def test_default_metadata_fields(self):+ msg = AssistantMessage(content=[])+ assert msg.provider_id == ""+ assert msg.model_id == ""+ assert msg.response_id is None++ def test_metadata_fields_set(self):+ msg = AssistantMessage(+ content=[],+ provider_id="anthropic",+ model_id="claude-sonnet-4-20250514",+ response_id="msg_abc123",+ )+ assert msg.provider_id == "anthropic"+ assert msg.model_id == "claude-sonnet-4-20250514"+ assert msg.response_id == "msg_abc123"+```++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/providers/test_base.py::TestAssistantMessageMetadata -v`+Expected: FAIL++- [ ] **Step 3: Add fields to `AssistantMessage`**++In `cubepi/providers/base.py`:++```python+class AssistantMessage(BaseModel):+ role: Literal["assistant"] = "assistant"+ content: list[Content | ThinkingContent | ToolCall]+ stop_reason: str = "stop"+ error_message: str | None = None+ usage: Usage | None = None+ provider_id: str = ""+ model_id: str = ""+ response_id: str | None = None+ timestamp: float | None = None+```++- [ ] **Step 4: Run test to verify it passes**++Run: `pytest tests/providers/test_base.py::TestAssistantMessageMetadata -v`+Expected: PASS++- [ ] **Step 5: Fill metadata in AnthropicProvider**++In `cubepi/providers/anthropic.py`, update `_convert_response` to accept `model: Model` and fill the fields:++Change `_convert_response` signature from `@staticmethod` to an instance method (or pass model):++```python+@staticmethod+def _convert_response(response: Any, model: Model) -> AssistantMessage:+ # ... existing content parsing ...+ return AssistantMessage(+ content=content,+ stop_reason=stop_reason_map.get(response.stop_reason, response.stop_reason),+ usage=Usage(+ input_tokens=response.usage.input_tokens,+ output_tokens=response.usage.output_tokens,+ cache_read_tokens=getattr(response.usage, "cache_read_input_tokens", 0) or 0,+ cache_write_tokens=getattr(response.usage, "cache_creation_input_tokens", 0) or 0,+ ),+ provider_id=model.provider,+ model_id=model.id,+ response_id=getattr(response, "id", None),+ timestamp=time.time(),+ )+```++Update the call site in `_produce()` from `self._convert_response(final_msg)` to `self._convert_response(final_msg, model)`.++Also fill metadata on the partial message created at stream start:++```python+partial = AssistantMessage(+ content=[], usage=Usage(),+ provider_id=model.provider, model_id=model.id,+ timestamp=time.time(),+)+```++- [ ] **Step 6: Fill metadata in OpenAIProvider and OpenAIResponsesProvider**++Apply the same pattern: set `provider_id=model.provider, model_id=model.id` on the initial `partial` and final messages in both providers.++- [ ] **Step 7: Run full suite**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 8: Commit**++```bash+git add cubepi/providers/base.py cubepi/providers/anthropic.py cubepi/providers/openai.py cubepi/providers/openai_responses.py tests/providers/test_base.py+git commit -m "feat: add provider_id, model_id, response_id to AssistantMessage"+```++---++## Task 4: Replace `Any` with typed `Message` union in agent layer++**Files:**+- Modify: `cubepi/agent/types.py`+- Modify: `cubepi/agent/agent.py`+- Modify: `cubepi/agent/loop.py`+- Modify: `cubepi/checkpointer/base.py`+- Test: `tests/agent/test_types.py`++- [ ] **Step 1: Write the failing test**++In `tests/agent/test_types.py`, add:++```python+from cubepi.agent.types import AgentContext, AgentEndEvent, TurnEndEvent, MessageStartEvent+from cubepi.providers.base import AssistantMessage, TextContent, ToolResultMessage, UserMessage+++class TestTypedMessages:+ def test_agent_context_accepts_message_union(self):+ ctx = AgentContext(+ system_prompt="test",+ messages=[+ UserMessage(content=[TextContent(text="hi")]),+ AssistantMessage(content=[TextContent(text="hello")]),+ ],+ )+ assert len(ctx.messages) == 2++ def test_agent_end_event_typed_messages(self):+ msg = UserMessage(content=[TextContent(text="hi")])+ event = AgentEndEvent(messages=[msg])+ assert event.messages[0].role == "user"++ def test_turn_end_event_typed_message(self):+ msg = AssistantMessage(content=[TextContent(text="done")])+ event = TurnEndEvent(message=msg, tool_results=[])+ assert event.message.role == "assistant"++ def test_message_start_event_typed(self):+ msg = UserMessage(content=[TextContent(text="hi")])+ event = MessageStartEvent(message=msg)+ assert event.message.role == "user"+```++- [ ] **Step 2: Run test — these should pass already (Any accepts anything)**++Run: `pytest tests/agent/test_types.py::TestTypedMessages -v`+Expected: PASS (since `Any` accepts `Message` types)++This test validates the new types work after we change them. The real value is that *invalid* types would now fail mypy.++- [ ] **Step 3: Update `agent/types.py` — replace `Any` with `Message`**++```python+from cubepi.providers.base import (+ AssistantMessage,+ Content,+ Message,+ StreamEvent,+ ToolCall,+ ToolDefinition,+ ToolResultMessage,+)++# ... AgentToolResult unchanged ...++@dataclass+class AgentContext:+ system_prompt: str+ messages: list[Message]+ tools: list[AgentTool] | None = None++# ... BeforeToolCallContext, AfterToolCallContext unchanged (already typed) ...++@dataclass+class ShouldStopAfterTurnContext:+ message: AssistantMessage+ tool_results: list[ToolResultMessage]+ context: AgentContext+ new_messages: list[Message]++# Event types — replace Any with Message:++class AgentEndEvent(BaseModel):+ type: Literal["agent_end"] = "agent_end"+ messages: list[Message]++class TurnEndEvent(BaseModel):+ type: Literal["turn_end"] = "turn_end"+ message: AssistantMessage+ tool_results: list[ToolResultMessage]++class MessageStartEvent(BaseModel):+ type: Literal["message_start"] = "message_start"+ message: Message++class MessageUpdateEvent(BaseModel):+ type: Literal["message_update"] = "message_update"+ message: AssistantMessage+ stream_event: StreamEvent++class MessageEndEvent(BaseModel):+ type: Literal["message_end"] = "message_end"+ message: Message+```++- [ ] **Step 4: Update `agent/agent.py` — type state and callbacks**++Replace `list[Any]` with `list[Message]` in `AgentState`:++```python+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ Model,+ OnPayloadCallback,+ OnResponseCallback,+ Provider,+ StreamOptions,+ TextContent,+ ThinkingLevel,+ ToolResultMessage,+ Usage,+ UserMessage,+)++# ...++@dataclass+class AgentState:+ system_prompt: str = ""+ model: Model = field(+ default_factory=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] = field(default_factory=list)+ _messages: list[Message] = field(default_factory=list)+ _pending_tool_calls: set[str] = field(default_factory=set)++ @property+ def messages(self) -> list[Message]:+ return list(self._messages)++ @messages.setter+ def messages(self, value: list[Message]) -> None:+ self._messages = list(value)++ # ... tools and pending_tool_calls unchanged ...+```++Update `_default_convert_to_llm`:++```python+def _default_convert_to_llm(messages: list[Message]) -> list[Message]:+ return [+ m for m in messages+ if m.role in ("user", "assistant", "tool_result")+ ]+```++Update `_MessageQueue` to use `Message`:++```python+class _MessageQueue:+ def __init__(self, mode: str = "one-at-a-time") -> None:+ self.mode = mode+ self._messages: list[Message] = []++ def enqueue(self, message: Message) -> None:+ self._messages.append(message)++ # ... rest unchanged, just change return types to list[Message] ...+```++Update `Agent` class signatures:++```python+class Agent:+ def __init__(+ 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[..., Awaitable[list[Message]]] | None = None,+ before_tool_call: Callable[..., Awaitable[BeforeToolCallResult | None]] | None = None,+ after_tool_call: Callable[..., Awaitable[AfterToolCallResult | None]] | None = None,+ should_stop_after_turn: Callable[..., Awaitable[bool]] | None = None,+ # ... rest unchanged ...+ ) -> None:+```++Update `prompt()`:++```python+async def prompt(self, message: str | Message | list[Message]) -> None:+```++Update `steer()` and `follow_up()`:++```python+def steer(self, message: Message) -> None:+def follow_up(self, message: Message) -> None:+```++Remove `hasattr` checks in `_process_event`:++```python+elif event.type == "turn_end":+ if isinstance(event.message, AssistantMessage) and event.message.error_message:+ self._state.error_message = event.message.error_message+```++Remove `hasattr` in `resume()`:++```python+last = self._state._messages[-1]+if isinstance(last, AssistantMessage):+ # ...+```++- [ ] **Step 5: Update `agent/loop.py` — type parameters**++Change `list[Any]` to `list[Message]` in `run_agent_loop`, `run_agent_loop_continue`, and `_run_loop` parameter types and return types. Add the `Message` import.++- [ ] **Step 6: Run full suite**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 7: Commit**++```bash+git add cubepi/agent/types.py cubepi/agent/agent.py cubepi/agent/loop.py tests/agent/test_types.py+git commit -m "refactor: replace Any with typed Message union across agent layer"+```++---++## Task 5: Add `details` to `ToolResultMessage`++**Files:**+- Modify: `cubepi/providers/base.py:130-137`+- Modify: `cubepi/agent/tools.py:60-67`+- Test: `tests/agent/test_tools.py`++- [ ] **Step 1: Write the failing test**++In `tests/agent/test_tools.py`, add:++```python+class TestToolResultDetails:+ async def test_details_propagated_to_tool_result_message(self):+ async def execute_with_details(tool_call_id, params, *, signal=None, on_update=None):+ return AgentToolResult(+ content=[TextContent(text="result")],+ details={"execution_time": 42},+ )++ tool = AgentTool(+ name="detailed",+ description="Tool with details",+ parameters=EchoParams,+ execute=execute_with_details,+ )+ context = AgentContext(+ system_prompt="test", messages=[], tools=[tool]+ )+ assistant_msg = AssistantMessage(+ content=[ToolCall(id="tc1", name="detailed", arguments={"value": "x"})],+ stop_reason="tool_use",+ )++ events: list = []+ batch = await execute_tool_calls(+ context,+ assistant_msg,+ emit=lambda e: events.append(e),+ )+ assert len(batch.messages) == 1+ assert batch.messages[0].details == {"execution_time": 42}+```++(Import `AgentToolResult`, `AgentTool`, `AgentContext` from `cubepi.agent.types`, `ToolCall`, `AssistantMessage`, `TextContent` from `cubepi.providers.base`, and `execute_tool_calls` from `cubepi.agent.tools`. Use `EchoParams` from the existing test file or define a local one.)++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/agent/test_tools.py::TestToolResultDetails -v`+Expected: FAIL — `ToolResultMessage` has no `details` field, or it's `None`++- [ ] **Step 3: Add `details` field to `ToolResultMessage`**++In `cubepi/providers/base.py`:++```python+class ToolResultMessage(BaseModel):+ role: Literal["tool_result"] = "tool_result"+ tool_call_id: str+ tool_name: str+ content: list[Content]+ details: Any = None+ is_error: bool = False+ timestamp: float | None = None+```++Add `Any` to the imports from `typing` if not already there.++- [ ] **Step 4: Pass `details` in `_make_tool_result_message`**++In `cubepi/agent/tools.py`:++```python+def _make_tool_result_message(finalized: _FinalizedOutcome) -> ToolResultMessage:+ return ToolResultMessage(+ tool_call_id=finalized.tool_call.id,+ tool_name=finalized.tool_call.name,+ content=finalized.result.content,+ details=finalized.result.details,+ is_error=finalized.is_error,+ timestamp=time.time(),+ )+```++- [ ] **Step 5: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 6: Commit**++```bash+git add cubepi/providers/base.py cubepi/agent/tools.py tests/agent/test_tools.py+git commit -m "feat: propagate details from AgentToolResult to ToolResultMessage"+```++---++## Task 6: Initial steering message poll in `_run_loop`++**Files:**+- Modify: `cubepi/agent/loop.py:137-238`+- Test: `tests/agent/test_loop.py`++- [ ] **Step 1: Write the failing test**++In `tests/agent/test_loop.py`, add:++```python+class TestInitialSteeringPoll:+ async def test_steering_messages_polled_before_first_turn(self):+ provider = FauxProvider()+ provider.set_responses([+ faux_assistant_message("response to steering"),+ ])++ steering_called = False++ async def get_steering():+ nonlocal steering_called+ if not steering_called:+ steering_called = True+ return [make_user_message("steering message")]+ return []++ context = AgentContext(+ system_prompt="test", messages=[], tools=[]+ )+ events: list[AgentEvent] = []++ await run_agent_loop(+ prompts=[make_user_message("initial")],+ context=context,+ provider=provider,+ model=make_model(),+ convert_to_llm=identity_converter,+ get_steering_messages=get_steering,+ emit=lambda e: events.append(e),+ )++ # Steering message should appear as a message_start/end event+ # before the assistant response+ message_events = [e for e in events if e.type in ("message_start", "message_end")]+ # Events: initial prompt start/end, steering start/end, assistant start/end, agent_end+ messages_in_order = [+ e.message for e in events if e.type == "message_end"+ ]+ assert len(messages_in_order) >= 3+ # First is the initial prompt, second is steering, third is assistant+ assert messages_in_order[0].role == "user"+ assert messages_in_order[1].role == "user"+ assert messages_in_order[2].role == "assistant"+```++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/agent/test_loop.py::TestInitialSteeringPoll -v`+Expected: FAIL — steering message not polled at start, so only 2 message_end events (prompt + assistant)++- [ ] **Step 3: Add initial steering poll to `_run_loop`**++In `cubepi/agent/loop.py`, at the beginning of `_run_loop`, after `first_turn = True`:++```python+ opts = stream_options or StreamOptions()+ first_turn = True++ # Poll for steering messages at start (user may have typed while waiting)+ pending_messages: list = []+ if get_steering_messages:+ pending_messages = await get_steering_messages() or []++ while True:+ has_more_tool_calls = True++ while has_more_tool_calls:+ if not first_turn:+ await _emit(emit, TurnStartEvent())+ else:+ first_turn = False++ # Inject pending messages before next assistant response+ if pending_messages:+ for msg in pending_messages:+ await _emit(emit, MessageStartEvent(message=msg))+ await _emit(emit, MessageEndEvent(message=msg))+ current_context.messages.append(msg)+ new_messages.append(msg)+ pending_messages = []++ message = await _stream_assistant_response(+ # ... unchanged ...+ )+```++And change the steering check after tool execution to populate `pending_messages` instead of injecting directly:++```python+ # Check for steering messages after tool execution+ if get_steering_messages and has_more_tool_calls:+ pending_messages = await get_steering_messages() or []+```++Remove the old inline injection code (the `for msg in steering:` loop that was there before).++- [ ] **Step 4: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 5: Commit**++```bash+git add cubepi/agent/loop.py tests/agent/test_loop.py+git commit -m "fix: poll steering messages at loop start before first assistant turn"+```++---++## Task 7: Integrate Checkpointer into Agent++**Files:**+- Modify: `cubepi/agent/agent.py`+- Create: `tests/agent/test_checkpointer_integration.py`++- [ ] **Step 1: Write the failing test**++Create `tests/agent/test_checkpointer_integration.py`:++```python+from cubepi.agent.agent import Agent+from cubepi.checkpointer.memory import MemoryCheckpointer+from cubepi.providers.base import Model, TextContent, UserMessage+from cubepi.providers.faux import FauxProvider, faux_assistant_message+++def make_model() -> Model:+ return Model(id="faux-1", provider="faux")+++class TestCheckpointerIntegration:+ async def test_messages_persisted_on_message_end(self):+ checkpointer = MemoryCheckpointer()+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("Hello!")])++ agent = Agent(+ provider=provider,+ model=make_model(),+ checkpointer=checkpointer,+ thread_id="thread-1",+ )+ await agent.prompt("Hi")++ data = await checkpointer.load("thread-1")+ assert data is not None+ assert len(data.messages) == 2 # user + assistant++ async def test_history_restored_on_prompt(self):+ checkpointer = MemoryCheckpointer()+ provider = FauxProvider()++ # First agent session: send a message+ provider.set_responses([faux_assistant_message("First reply")])+ agent1 = Agent(+ provider=provider,+ model=make_model(),+ checkpointer=checkpointer,+ thread_id="thread-1",+ )+ await agent1.prompt("First message")++ # Second agent session: restore history, send another+ provider.set_responses([faux_assistant_message("Second reply")])+ agent2 = Agent(+ provider=provider,+ model=make_model(),+ checkpointer=checkpointer,+ thread_id="thread-1",+ )+ await agent2.prompt("Second message")++ assert len(agent2.state.messages) == 4 # 2 from first + 2 from second++ async def test_no_checkpointer_works_as_before(self):+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("Hi")])++ agent = Agent(provider=provider, model=make_model())+ await agent.prompt("Hello")+ assert len(agent.state.messages) == 2+```++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/agent/test_checkpointer_integration.py -v`+Expected: FAIL — messages not persisted, history not restored++- [ ] **Step 3: Integrate checkpointer into Agent**++In `cubepi/agent/agent.py`:++1. In `prompt()`, before `await self._run_prompt(messages)`, restore history:++```python+async def prompt(self, message: str | Message | list[Message]) -> None:+ if self._state.is_streaming:+ raise RuntimeError(+ "Agent is already processing a prompt. "+ "Use steer() or follow_up() to queue messages."+ )++ # Restore history from checkpointer if this is first prompt+ if self.checkpointer and self.thread_id and not self._state._messages:+ data = await self.checkpointer.load(self.thread_id)+ if data and data.messages:+ self._state._messages = list(data.messages)++ if isinstance(message, str):+ messages = [+ UserMessage(content=[TextContent(text=message)], timestamp=time.time())+ ]+ elif isinstance(message, list):+ messages = message+ else:+ messages = [message]++ await self._run_prompt(messages)+```++2. In `_process_event()`, persist on `message_end`:++```python+elif event.type == "message_end":+ self._state.streaming_message = None+ self._state._messages.append(event.message)+ # Persist to checkpointer+ if self.checkpointer and self.thread_id:+ await self.checkpointer.append(self.thread_id, [event.message])+```++- [ ] **Step 4: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 5: Commit**++```bash+git add cubepi/agent/agent.py tests/agent/test_checkpointer_integration.py+git commit -m "feat: integrate checkpointer into Agent for message persistence"+```++---++## Task 8: OpenAI Provider image support++**Files:**+- Modify: `cubepi/providers/openai.py:250-254`+- Modify: `cubepi/providers/openai_responses.py:464-475`+- Test: `tests/providers/test_openai.py`++- [ ] **Step 1: Write the failing test**++In `tests/providers/test_openai.py`, add:++```python+from cubepi.providers.openai import OpenAIProvider+from cubepi.providers.openai_responses import OpenAIResponsesProvider+from cubepi.providers.base import ImageContent, TextContent, UserMessage+++class TestOpenAIImageConversion:+ def test_user_message_with_image(self):+ msg = UserMessage(content=[+ TextContent(text="What's in this image?"),+ ImageContent(source="base64data", media_type="image/png"),+ ])+ result = OpenAIProvider._convert_message(msg)+ assert result["role"] == "user"+ assert isinstance(result["content"], list)+ assert len(result["content"]) == 2+ assert result["content"][0] == {"type": "text", "text": "What's in this image?"}+ assert result["content"][1] == {+ "type": "image_url",+ "image_url": {"url": "data:image/png;base64,base64data"},+ }++ def test_user_message_text_only_stays_simple(self):+ msg = UserMessage(content=[TextContent(text="hello")])+ result = OpenAIProvider._convert_message(msg)+ assert result["role"] == "user"+ assert result["content"] == "hello"+++class TestOpenAIResponsesImageConversion:+ def test_user_message_with_image(self):+ msg = UserMessage(content=[+ TextContent(text="Describe this"),+ ImageContent(source="imgdata", media_type="image/jpeg"),+ ])+ result = OpenAIResponsesProvider._build_input([msg])+ assert len(result) == 1+ assert result[0]["role"] == "user"+ content = result[0]["content"]+ assert len(content) == 2+ assert content[0] == {"type": "input_text", "text": "Describe this"}+ assert content[1] == {+ "type": "input_image",+ "image_url": "data:image/jpeg;base64,imgdata",+ }+```++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/providers/test_openai.py::TestOpenAIImageConversion -v`+Expected: FAIL — images are dropped, content is a string not a list++- [ ] **Step 3: Update `OpenAIProvider._convert_message` for images**++In `cubepi/providers/openai.py`:++```python+@staticmethod+def _convert_message(msg: Message) -> dict[str, Any]:+ if isinstance(msg, UserMessage):+ has_images = any(isinstance(c, ImageContent) for c in msg.content)+ if not has_images:+ text_parts = [c.text for c in msg.content if isinstance(c, TextContent)]+ return {"role": "user", "content": "\n".join(text_parts)}+ content: list[dict[str, Any]] = []+ for c in msg.content:+ if isinstance(c, TextContent):+ content.append({"type": "text", "text": c.text})+ elif isinstance(c, ImageContent):+ content.append({+ "type": "image_url",+ "image_url": {"url": f"data:{c.media_type};base64,{c.source}"},+ })+ return {"role": "user", "content": content}++ # ... rest unchanged ...+```++- [ ] **Step 4: Update `OpenAIResponsesProvider._build_input` for images**++In `cubepi/providers/openai_responses.py`, in the `UserMessage` branch of `_build_input`:++```python+if isinstance(msg, UserMessage):+ content: list[dict[str, Any]] = []+ for c in msg.content:+ if isinstance(c, TextContent):+ content.append({"type": "input_text", "text": c.text})+ elif isinstance(c, ImageContent):+ content.append({+ "type": "input_image",+ "image_url": f"data:{c.media_type};base64,{c.source}",+ })+ if content:+ api_input.append({"role": "user", "content": content})+```++Add `ImageContent` to the imports from `cubepi.providers.base`.++- [ ] **Step 5: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 6: Commit**++```bash+git add cubepi/providers/openai.py cubepi/providers/openai_responses.py tests/providers/test_openai.py+git commit -m "feat: add image content support to OpenAI providers"+```++---++## Task 9: Extract shared `emit_event` helper (eliminate duplicate `_emit`)++**Files:**+- Modify: `cubepi/agent/types.py`+- Modify: `cubepi/agent/loop.py`+- Modify: `cubepi/agent/tools.py`++- [ ] **Step 1: Add `emit_event` to `agent/types.py`**++At the end of `cubepi/agent/types.py`:++```python+async def emit_event(emit_fn: Callable, event: AgentEvent) -> None:+ result = emit_fn(event)+ if asyncio.iscoroutine(result):+ await result+```++- [ ] **Step 2: Replace `_emit` in `loop.py`**++Remove the local `_emit` definition (lines 28-31). Add `emit_event` to the imports from `cubepi.agent.types`. Replace all `_emit(` calls with `emit_event(` calls throughout the file.++- [ ] **Step 3: Replace `_emit` in `tools.py`**++Remove the local `_emit` definition (lines 70-73). Add `emit_event` to the imports from `cubepi.agent.types`. Replace all `_emit(` calls with `emit_event(` calls throughout the file.++- [ ] **Step 4: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 5: Commit**++```bash+git add cubepi/agent/types.py cubepi/agent/loop.py cubepi/agent/tools.py+git commit -m "refactor: extract shared emit_event helper, remove duplicate _emit"+```++---++## Task 10: Fix fire-and-forget `asyncio.create_task` in `MessageStream`++**Files:**+- Modify: `cubepi/providers/base.py:168-194`+- Modify: `cubepi/providers/anthropic.py:155`+- Modify: `cubepi/providers/openai.py:247`+- Modify: `cubepi/providers/openai_responses.py:443`+- Modify: `cubepi/providers/faux.py:287`+- Test: `tests/providers/test_base.py`++- [ ] **Step 1: Write the failing test**++In `tests/providers/test_base.py`, add:++```python+class TestMessageStreamTaskTracking:+ async def test_attach_task_stores_reference(self):+ ms = MessageStream()++ async def dummy():+ ms.push(StreamEvent(type="done"))+ ms.set_result(AssistantMessage(content=[]))++ task = asyncio.create_task(dummy())+ ms.attach_task(task)+ assert ms._producer_task is task+ await task++ async def test_result_propagates_task_exception(self):+ ms = MessageStream()++ async def failing():+ raise RuntimeError("producer died before pushing error")++ task = asyncio.create_task(failing())+ ms.attach_task(task)++ import pytest+ with pytest.raises(RuntimeError, match="producer died"):+ await ms.result()+```++- [ ] **Step 2: Run test to verify it fails**++Run: `pytest tests/providers/test_base.py::TestMessageStreamTaskTracking -v`+Expected: FAIL — `attach_task` does not exist++- [ ] **Step 3: Add `attach_task` to `MessageStream`**++In `cubepi/providers/base.py`:++```python+class MessageStream:+ def __init__(self) -> None:+ self._queue: asyncio.Queue[StreamEvent | None] = asyncio.Queue()+ self._result_future: asyncio.Future[AssistantMessage] = (+ asyncio.get_running_loop().create_future()+ )+ self._producer_task: asyncio.Task | None = None++ def attach_task(self, task: asyncio.Task) -> None:+ self._producer_task = task+ task.add_done_callback(self._on_task_done)++ def _on_task_done(self, task: asyncio.Task) -> None:+ if task.cancelled():+ return+ exc = task.exception()+ if exc and not self._result_future.done():+ self._result_future.set_exception(exc)+ self._queue.put_nowait(None)++ # ... push, set_result, __aiter__, __anext__, result unchanged ...+```++- [ ] **Step 4: Update all providers to use `attach_task`**++In each provider's `stream()` method, change:+```python+asyncio.create_task(_produce())+```+to:+```python+ms.attach_task(asyncio.create_task(_produce()))+```++Files: `anthropic.py:155`, `openai.py:247`, `openai_responses.py:443`, `faux.py:287`.++- [ ] **Step 5: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 6: Commit**++```bash+git add cubepi/providers/base.py cubepi/providers/anthropic.py cubepi/providers/openai.py cubepi/providers/openai_responses.py cubepi/providers/faux.py tests/providers/test_base.py+git commit -m "fix: track producer task in MessageStream to prevent silent failures"+```++---++## Task 11: Clean up dead code and rename private helpers++**Files:**+- Modify: `cubepi/providers/openai_responses.py:78-86`+- Modify: `cubepi/providers/base.py:225-249`+- Modify: `cubepi/providers/anthropic.py:24-26`+- Modify: `cubepi/providers/openai.py:24-26`++- [ ] **Step 1: Remove dead code in OpenAI Responses system prompt handling**++In `cubepi/providers/openai_responses.py`, replace lines 78-86:++```python+ if system_prompt:+ role = "developer" if model.reasoning else "system"+ kwargs["instructions"] = system_prompt+ # The instructions param uses system/developer role implicitly.+ # For explicit role control, prepend to input instead.+ kwargs["input"] = [{"role": role, "content": system_prompt}] + api_input++ # Remove instructions since we use input-based system prompt+ del kwargs["instructions"]+```++With:++```python+ if system_prompt:+ role = "developer" if model.reasoning else "system"+ kwargs["input"] = [{"role": role, "content": system_prompt}] + api_input+```++- [ ] **Step 2: Rename `_invoke_on_payload` → `invoke_on_payload` and `_invoke_on_response` → `invoke_on_response`**++In `cubepi/providers/base.py`, rename both functions by removing the leading underscore.++- [ ] **Step 3: Update imports in providers**++In `cubepi/providers/anthropic.py`, change:+```python+_invoke_on_payload,+_invoke_on_response,+```+to:+```python+invoke_on_payload,+invoke_on_response,+```++And update the call sites (`_invoke_on_payload(` → `invoke_on_payload(`).++Same in `cubepi/providers/openai.py`.++- [ ] **Step 4: Run tests**++Run: `pytest tests/ --ignore=tests/checkpointer/test_sqlite.py -q`+Expected: All pass++- [ ] **Step 5: Commit**++```bash+git add cubepi/providers/base.py cubepi/providers/anthropic.py cubepi/providers/openai.py cubepi/providers/openai_responses.py+git commit -m "refactor: remove dead code, rename private helpers to public API"+```++---++## Summary++| Task | Spec Item | Priority | What |+|---|---|---|---|+| 1 | §2 | P0 | Add `content_index` to `StreamEvent` |+| 2 | §2 | P0 | Fill `content_index` in all 4 providers |+| 3 | §3 | P0 | Add `provider_id`/`model_id`/`response_id` to `AssistantMessage` |+| 4 | §1 | P0 | Replace `Any` with typed `Message` union |+| 5 | §5 | P1 | Add `details` to `ToolResultMessage` |+| 6 | §6 | P1 | Initial steering poll in `_run_loop` |+| 7 | §4 | P1 | Integrate checkpointer into Agent |+| 8 | §7 | P1 | OpenAI image support |+| 9 | §8 | P2 | Extract shared `emit_event` |+| 10 | §9 | P2 | Fix fire-and-forget task in `MessageStream` |+| 11 | §10+§11 | P2 | Dead code cleanup + rename private helpers |diff --git a/dev/plans/2026-05-13-cubepi-cubebox-readiness-plan.md b/dev/plans/2026-05-13-cubepi-cubebox-readiness-plan.mdnew file mode 100644index 0000000..7aa1409--- /dev/null+++ b/dev/plans/2026-05-13-cubepi-cubebox-readiness-plan.md@@ -0,0 +1,3376 @@+# cubepi cubebox-readiness Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Land the 9 upstream cubepi deliverables (D1-D9) required by cubebox's main agent migration (Spec B), as new public API that's backward-compatible with v0.2.0 users.++**Architecture:** Each deliverable is independently testable and committable. Order chosen to minimize cross-task coupling: types/extensions first (D5, D6), then hooks (D7, D8), then provider tweaks (D3, D4), then new modules (D1, D2), packaging last (D9). cubebox can start consuming any deliverable via `[tool.uv.sources] cubepi = { path = "/home/chris/cubepi", editable = true }` immediately after merge — no PyPI release required.++**Tech Stack:** Python 3.11+, Pydantic v2, SQLAlchemy 2.0, asyncpg, msgpack, pytest + pytest-asyncio + respx, anthropic SDK, openai SDK, mcp SDK++**Spec:** `docs/specs/2026-05-13-cubepi-cubebox-readiness-design.md`++**Baseline:** existing cubepi test suite (`pytest tests/ -q`) must pass before and after every task — no regressions to existing v0.2.0 behavior.++---++## File Map++### Files to modify++| File | What changes |+|---|---|+| `cubepi/providers/base.py` | Add `metadata: dict[str, Any]` field to `UserMessage`, `AssistantMessage`, `ToolResultMessage` (D5) |+| `cubepi/agent/types.py` | Add `extra: dict[str, Any]` field to `AgentContext` (D6) |+| `cubepi/middleware/base.py` | Add `transform_system_prompt` (D7) and `after_model_response` + `TurnAction` (D8) to `Middleware` base class and `compose_middleware()` |+| `cubepi/agent/loop.py` | Wire `transform_system_prompt` and `after_model_response` into agent loop; persist `ctx.extra` via checkpointer after each turn (D6/D7/D8) |+| `cubepi/providers/anthropic.py` | Add `cache_policy: CacheMarkerPolicy \| None` constructor parameter; refactor existing marker logic to use policy (D3) |+| `cubepi/providers/openai.py` | Add OSS reasoning field extraction (3 variants), `payload_quirks` parameter (D4) |+| `cubepi/checkpointer/memory.py` | Persist `Message.metadata` round-trip (D5) |+| `cubepi/checkpointer/sqlite.py` | Persist `Message.metadata` round-trip (D5) |+| `pyproject.toml` | Add `[postgres]` and `[mcp]` extras (D9) |++### Files to create++| File | Purpose |+|---|---|+| `cubepi/checkpointer/postgres/__init__.py` | Re-exports for `PostgresCheckpointer` (D1) |+| `cubepi/checkpointer/postgres/models.py` | SQLAlchemy declarative models + private `cubepi_metadata` + `EXPECTED_SCHEMA_VERSION` (D1) |+| `cubepi/checkpointer/postgres/checkpointer.py` | `PostgresCheckpointer` class implementing the `Checkpointer` protocol (D1) |+| `cubepi/checkpointer/postgres/alembic_helpers.py` | `create_message_partitions_op()` + `write_schema_version_op()` (D1) |+| `cubepi/checkpointer/postgres/exceptions.py` | `CubepiSchemaUninitialized`, `CubepiSchemaMismatch` (D1) |+| `cubepi/mcp/__init__.py` | Re-exports for `load_mcp_tools_http`, `load_mcp_tools_stdio` (D2) |+| `cubepi/mcp/http_loader.py` | HTTP/SSE MCP tool loader (D2) |+| `cubepi/mcp/stdio_loader.py` | stdio MCP tool loader (D2) |+| `cubepi/mcp/_adapter.py` | MCP tool → `cubepi.AgentTool` conversion (D2) |+| `tests/checkpointer/test_postgres.py` | E2E tests for `PostgresCheckpointer` (D1) |+| `tests/mcp/test_http_loader.py` | E2E tests for HTTP MCP loader using fake FastAPI server (D2) |+| `tests/mcp/test_stdio_loader.py` | E2E tests for stdio MCP loader using subprocess server (D2) |+| `tests/providers/test_anthropic_cache_policy.py` | Tests for configurable cache policy (D3) |+| `tests/providers/test_openai_reasoning.py` | Tests for OSS reasoning field extraction (D4) |+| `tests/providers/test_message_metadata.py` | Tests for `Message.metadata` round-trip (D5) |+| `tests/agent/test_context_extra.py` | Tests for `AgentContext.extra` persistence (D6) |+| `tests/middleware/test_transform_system_prompt.py` | Tests for chain composition (D7) |+| `tests/middleware/test_after_model_response.py` | Tests for `after_model_response` + `TurnAction` (D8) |++### Test infrastructure++| File | Purpose |+|---|---|+| `tests/checkpointer/conftest.py` (new) | Postgres test fixtures: `pg_dsn`, `pg_pool`, `clean_db` |+| `tests/mcp/conftest.py` (new) | MCP test fixtures: `fake_http_mcp_server`, `fake_stdio_mcp_server` |++---++## Pre-flight Setup++### Task 0: Verify baseline + worktree++**Files:** none++- [ ] **Step 1: Confirm clean working tree**++Run: `cd ~/cubepi && git status`+Expected: working tree clean on `main`.++- [ ] **Step 2: Create feature branch**++Run: `git checkout -b feat/cubebox-readiness`++- [ ] **Step 3: Confirm baseline tests pass**++Run: `pytest tests/ -q --tb=no`+Expected: all existing tests pass. Note the count — every subsequent task must keep it strictly non-decreasing.++- [ ] **Step 4: Set up Postgres for integration testing**++cubepi v0.2 has no Postgres tests. For D1 we need a test DB. Confirm a local Postgres is available:++```bash+psql -h localhost -p 5432 -U postgres -c "SELECT version();"+```++Expected: PostgreSQL 14+ version string. If not available, install or update `~/.pgpass` / connection env vars before D1 tasks.++---++## D5 — `Message.metadata` field (do first; D1 needs it for serialization)++### Task D5.1: Add `metadata` field to three Message types++**Files:**+- Modify: `cubepi/providers/base.py`+- Test: `tests/providers/test_message_metadata.py` (new)++- [ ] **Step 1: Write the failing tests**++Create `tests/providers/test_message_metadata.py`:++```python+"""Message.metadata field tests (D5)."""++import pytest+from cubepi.providers.base import (+ AssistantMessage,+ TextContent,+ ToolResultMessage,+ Usage,+ UserMessage,+)+++def test_user_message_default_metadata_is_empty_dict() -> None:+ msg = UserMessage(content=[TextContent(text="hi")])+ assert msg.metadata == {}+++def test_assistant_message_default_metadata_is_empty_dict() -> None:+ msg = AssistantMessage(content=[], usage=Usage())+ assert msg.metadata == {}+++def test_tool_result_message_default_metadata_is_empty_dict() -> None:+ msg = ToolResultMessage(content=[], tool_call_id="tc-1")+ assert msg.metadata == {}+++def test_user_message_accepts_metadata() -> None:+ msg = UserMessage(+ content=[TextContent(text="hi")],+ metadata={"memory_snapshot": {"captured_at": "t1", "ids": ["m1"]}},+ )+ assert msg.metadata["memory_snapshot"]["captured_at"] == "t1"+++def test_metadata_independent_between_instances() -> None:+ a = UserMessage(content=[TextContent(text="a")])+ b = UserMessage(content=[TextContent(text="b")])+ a.metadata["x"] = 1+ assert "x" not in b.metadata+++def test_metadata_serializes_to_dict_in_model_dump() -> None:+ msg = UserMessage(+ content=[TextContent(text="hi")],+ metadata={"k": "v"},+ )+ dumped = msg.model_dump()+ assert dumped["metadata"] == {"k": "v"}+```++- [ ] **Step 2: Run tests to verify failures**++Run: `pytest tests/providers/test_message_metadata.py -v`+Expected: 6 failures with `pydantic.ValidationError` or AttributeError on `metadata`.++- [ ] **Step 3: Add `metadata` field to all three Message classes**++In `cubepi/providers/base.py`, find the three classes `UserMessage`, `AssistantMessage`, `ToolResultMessage` and add to each:++```python+from pydantic import BaseModel, Field++# Existing class header unchanged:+class UserMessage(BaseModel):+ content: list[Content]+ metadata: dict[str, Any] = Field(default_factory=dict)+ # ... other existing fields ...++class AssistantMessage(BaseModel):+ content: list[Content]+ metadata: dict[str, Any] = Field(default_factory=dict)+ usage: Usage = Field(default_factory=Usage)+ # ... other existing fields ...++class ToolResultMessage(BaseModel):+ content: list[Content]+ metadata: dict[str, Any] = Field(default_factory=dict)+ tool_call_id: str+ # ... other existing fields ...+```++Use `Field(default_factory=dict)` (not `= {}`) to avoid shared mutable default state across instances.++- [ ] **Step 4: Run tests to verify passes**++Run: `pytest tests/providers/test_message_metadata.py -v`+Expected: all 6 pass.++- [ ] **Step 5: Run full suite to verify no regressions**++Run: `pytest tests/ -q --tb=no`+Expected: baseline count + 6 new passes.++- [ ] **Step 6: Commit**++```bash+git add cubepi/providers/base.py tests/providers/test_message_metadata.py+git commit -m "feat(messages): add metadata field to UserMessage/AssistantMessage/ToolResultMessage++Public dict[str, Any] field on all three Message types, defaulting to {}.+Use case: per-message extensibility (memory snapshots, cost attribution,+audit tags, etc.) without changing the Message API every time.++Backward-compatible: existing constructors work unchanged; existing+serialized messages deserialize with metadata={} by default."+```++### Task D5.2: Persist `metadata` through `MemoryCheckpointer` and `SQLiteCheckpointer`++**Files:**+- Modify: `cubepi/checkpointer/memory.py`+- Modify: `cubepi/checkpointer/sqlite.py`+- Test: extend `tests/providers/test_message_metadata.py`++- [ ] **Step 1: Add round-trip tests**++Append to `tests/providers/test_message_metadata.py`:++```python+import tempfile+from pathlib import Path++from cubepi.checkpointer import MemoryCheckpointer, SQLiteCheckpointer+++async def test_memory_checkpointer_preserves_metadata() -> None:+ cp = MemoryCheckpointer()+ msg = UserMessage(+ content=[TextContent(text="hi")],+ metadata={"k": "v", "nested": {"a": 1}},+ )+ await cp.append("t1", [msg])+ loaded = await cp.load("t1")+ assert loaded is not None+ assert loaded.messages[0].metadata == {"k": "v", "nested": {"a": 1}}+++async def test_sqlite_checkpointer_preserves_metadata() -> None:+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / "test.db"+ async with SQLiteCheckpointer(str(path)) as cp:+ msg = UserMessage(+ content=[TextContent(text="hi")],+ metadata={"k": "v", "nested": {"a": 1}},+ )+ await cp.append("t1", [msg])+ loaded = await cp.load("t1")+ assert loaded is not None+ assert loaded.messages[0].metadata == {"k": "v", "nested": {"a": 1}}+```++- [ ] **Step 2: Run tests to verify failures**++Run: `pytest tests/providers/test_message_metadata.py::test_memory_checkpointer_preserves_metadata tests/providers/test_message_metadata.py::test_sqlite_checkpointer_preserves_metadata -v`+Expected: both fail — metadata is lost in checkpointer ser/deser. `memory.py` likely passes (it stores references) but verify; `sqlite.py` definitely fails because its `_serialize_message` doesn't include metadata.++- [ ] **Step 3: Update SQLiteCheckpointer serialization**++In `cubepi/checkpointer/sqlite.py`, find the private `_serialize_message` and `_deserialize_message` helpers. Locate where they handle each message type and add `metadata` to both directions:++```python+def _serialize_message(msg: Any) -> str:+ # find existing branch for each Message type+ # add: data["metadata"] = msg.metadata+ ...++def _deserialize_message(data: dict[str, Any]) -> Any:+ # find construction of each Message type+ # add: metadata=data.get("metadata", {})+ ...+```++(If the existing impl uses `msg.model_dump()` and `Type(**data)`, the new field is handled automatically — but verify by running the test.)++- [ ] **Step 4: Verify MemoryCheckpointer**++`MemoryCheckpointer` typically stores message references directly. If so, no code change needed; test should pass after Step 3 if the Pydantic field is set. If `MemoryCheckpointer` does any cloning, ensure metadata is preserved.++- [ ] **Step 5: Run tests**++Run: `pytest tests/providers/test_message_metadata.py -v`+Expected: all 8 tests pass.++- [ ] **Step 6: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 8.++- [ ] **Step 7: Commit**++```bash+git add cubepi/checkpointer/+git commit -m "feat(checkpointer): preserve Message.metadata through ser/deser++Both MemoryCheckpointer and SQLiteCheckpointer now round-trip the+metadata dict on UserMessage/AssistantMessage/ToolResultMessage."+```++---++## D6 — `AgentContext.extra` mutable dict++### Task D6.1: Add `extra` field to `AgentContext`++**Files:**+- Modify: `cubepi/agent/types.py`+- Test: `tests/agent/test_context_extra.py` (new)++- [ ] **Step 1: Write the failing tests**++Create `tests/agent/test_context_extra.py`:++```python+"""AgentContext.extra field tests (D6)."""++from cubepi.agent.types import AgentContext+++def test_agent_context_default_extra_is_empty_dict() -> None:+ ctx = AgentContext(system_prompt="", messages=[])+ assert ctx.extra == {}+++def test_agent_context_accepts_extra() -> None:+ ctx = AgentContext(+ system_prompt="",+ messages=[],+ extra={"todos": ["a", "b"]},+ )+ assert ctx.extra["todos"] == ["a", "b"]+++def test_extra_is_mutable() -> None:+ ctx = AgentContext(system_prompt="", messages=[])+ ctx.extra["k"] = "v"+ assert ctx.extra == {"k": "v"}+++def test_extra_independent_between_instances() -> None:+ a = AgentContext(system_prompt="", messages=[])+ b = AgentContext(system_prompt="", messages=[])+ a.extra["x"] = 1+ assert "x" not in b.extra+```++- [ ] **Step 2: Run tests to verify failure**++Run: `pytest tests/agent/test_context_extra.py -v`+Expected: 4 failures on `extra` attribute / constructor parameter.++- [ ] **Step 3: Add `extra` field to `AgentContext`**++In `cubepi/agent/types.py`, find:++```python+@dataclass+class AgentContext:+ system_prompt: str+ messages: list[Message]+ tools: list[AgentTool] | None = None+```++Add `extra`:++```python+from dataclasses import dataclass, field++@dataclass+class AgentContext:+ system_prompt: str+ messages: list[Message]+ tools: list[AgentTool] | None = None+ extra: dict[str, Any] = field(default_factory=dict)+```++- [ ] **Step 4: Run tests**++Run: `pytest tests/agent/test_context_extra.py -v`+Expected: 4 pass.++- [ ] **Step 5: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 4.++- [ ] **Step 6: Commit**++```bash+git add cubepi/agent/types.py tests/agent/test_context_extra.py+git commit -m "feat(agent): add AgentContext.extra mutable dict for per-thread state++Middleware can read/mutate ctx.extra in any hook. Persistence to+the checkpointer happens in the agent loop (next task).+Backward-compatible: existing AgentContext constructors work unchanged."+```++### Task D6.2: Persist `ctx.extra` after each turn++**Files:**+- Modify: `cubepi/agent/loop.py` (and/or `agent.py`)+- Modify: `tests/agent/test_context_extra.py`++- [ ] **Step 1: Add integration test**++Append to `tests/agent/test_context_extra.py`:++```python+import tempfile+from pathlib import Path++import pytest+from cubepi import Agent, Model+from cubepi.checkpointer import SQLiteCheckpointer+from cubepi.middleware.base import Middleware+from cubepi.providers.faux import FauxProvider, faux_assistant_message+++class _ExtraWritingMiddleware(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ # We'll add the hook in D8; for now use a workaround:+ # mutate via transform_context which already exists+ return None++ async def transform_context(self, messages, *, signal=None):+ # this hook gets called with messages; we can't access ctx here+ # in v0.2 — that's the point: after D6, we expose ctx.extra to ALL hooks+ return messages+++async def test_extra_persisted_across_turns() -> None:+ """ctx.extra mutations after a turn must be visible on next load."""+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / "extra.db"+ async with SQLiteCheckpointer(str(path)) as cp:+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("hello")])+ agent = Agent(+ model=Model(provider=provider, model="test"),+ checkpointer=cp,+ thread_id="t-extra",+ )+ stream = await agent.prompt("hi")+ async for _ in stream:+ pass+ # ctx.extra is on the agent's context; we'll set it via a+ # middleware in later tasks. For now, set it manually via save_extra.+ await cp.save_extra("t-extra", {"counter": 1})+ data = await cp.load("t-extra")+ assert data is not None+ assert data.extra == {"counter": 1}+```++This test establishes the persistence contract via the existing+`save_extra` path. The agent-loop-driven persistence comes after we+add hooks that mutate `ctx.extra` (D7/D8). For now, this test pins+the round-trip.++- [ ] **Step 2: Run test**++Run: `pytest tests/agent/test_context_extra.py::test_extra_persisted_across_turns -v`+Expected: PASS — `SQLiteCheckpointer.save_extra` + `load` already round-trip extra.++- [ ] **Step 3: Wire `ctx.extra` initialization on agent load**++In `cubepi/agent/agent.py` (the `Agent` class), find where `AgentContext` is constructed at start of `prompt()`. If the agent loads checkpoint state, also hydrate `extra`:++```python+# Inside Agent.prompt() before constructing AgentContext:+if self._checkpointer and self._thread_id:+ data = await self._checkpointer.load(self._thread_id)+ if data is not None:+ loaded_messages = data.messages+ loaded_extra = data.extra+ else:+ loaded_messages = []+ loaded_extra = {}+else:+ loaded_messages = []+ loaded_extra = {}++ctx = AgentContext(+ system_prompt=self._system_prompt,+ messages=loaded_messages + new_messages,+ tools=self._tools,+ extra=loaded_extra,+)+```++(Find the exact existing construction point and adapt — the existing+code already loads messages via similar pattern.)++- [ ] **Step 4: Wire `save_extra` after turn ends**++In `cubepi/agent/loop.py` (or wherever the turn-completion logic+calls `checkpointer.append`), add a `save_extra` call:++```python+# After appending new messages and after_tool_call / after_model_response hooks complete:+if checkpointer and thread_id and ctx.extra:+ await checkpointer.save_extra(thread_id, ctx.extra)+```++The condition `if ctx.extra` avoids no-op writes when no middleware+populated extra. (Alternative: always call save_extra. Either works;+prefer the cheap-skip version.)++- [ ] **Step 5: Add integration test for the wiring**++Append to `tests/agent/test_context_extra.py`:++```python+async def test_ctx_extra_persisted_via_loop() -> None:+ """When something mutates ctx.extra during a turn, it persists to checkpointer."""+ with tempfile.TemporaryDirectory() as d:+ path = Path(d) / "loop.db"+ async with SQLiteCheckpointer(str(path)) as cp:+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("a")])++ # We don't have transform_system_prompt or after_model_response+ # yet — use a checkpointer hook approach: pre-seed extra and verify+ # the agent loads it correctly.+ await cp.save_extra("t-loop", {"seeded": True})++ agent = Agent(+ model=Model(provider=provider, model="test"),+ checkpointer=cp,+ thread_id="t-loop",+ )+ stream = await agent.prompt("go")+ async for _ in stream:+ pass++ data = await cp.load("t-loop")+ # Extra must still contain "seeded": True after the turn.+ assert data is not None+ assert data.extra.get("seeded") is True+```++- [ ] **Step 6: Run tests**++Run: `pytest tests/agent/test_context_extra.py -v`+Expected: 6 pass.++- [ ] **Step 7: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 6.++- [ ] **Step 8: Commit**++```bash+git add cubepi/agent/ tests/agent/test_context_extra.py+git commit -m "feat(agent): persist AgentContext.extra to checkpointer across turns++Agent loop now hydrates ctx.extra from checkpointer.load on startup+and writes back via checkpointer.save_extra after each turn. Middleware+(coming in D7/D8) can mutate ctx.extra freely with persistence handled+by the loop.++No-op when ctx.extra is empty — existing checkpointer users see no+extra writes unless they actually populate the dict."+```++---++## D7 — `transform_system_prompt` middleware hook++### Task D7.1: Add hook method + composition++**Files:**+- Modify: `cubepi/middleware/base.py`+- Test: `tests/middleware/test_transform_system_prompt.py` (new)++- [ ] **Step 1: Write failing tests**++Create `tests/middleware/test_transform_system_prompt.py`:++```python+"""transform_system_prompt hook tests (D7)."""++import pytest++from cubepi.middleware.base import Middleware, compose_middleware+++class _AppendA(Middleware):+ async def transform_system_prompt(self, sp, *, signal=None):+ return sp + "\n[A]"+++class _AppendB(Middleware):+ async def transform_system_prompt(self, sp, *, signal=None):+ return sp + "\n[B]"+++async def test_single_middleware_appends() -> None:+ hooks = compose_middleware([_AppendA()])+ fn = hooks["transform_system_prompt"]+ out = await fn("base")+ assert out == "base\n[A]"+++async def test_chain_order_preserved() -> None:+ """A then B → A first, then B sees A's output."""+ hooks = compose_middleware([_AppendA(), _AppendB()])+ fn = hooks["transform_system_prompt"]+ out = await fn("base")+ assert out == "base\n[A]\n[B]"+++async def test_no_middleware_hook_absent() -> None:+ """If no middleware implements transform_system_prompt, the hook is not in the dict."""+ class Plain(Middleware):+ pass+ hooks = compose_middleware([Plain()])+ assert "transform_system_prompt" not in hooks+++async def test_default_implementation_raises() -> None:+ """Default Middleware.transform_system_prompt raises NotImplementedError."""+ mw = Middleware()+ with pytest.raises(NotImplementedError):+ await mw.transform_system_prompt("any")+```++- [ ] **Step 2: Run tests to verify failures**++Run: `pytest tests/middleware/test_transform_system_prompt.py -v`+Expected: 4 failures (`transform_system_prompt` doesn't exist).++- [ ] **Step 3: Add the method to `Middleware` base + extend `compose_middleware`**++In `cubepi/middleware/base.py`:++```python+class Middleware:+ # ... existing methods ...++ async def transform_system_prompt(+ self,+ system_prompt: str,+ *,+ signal=None,+ ) -> str:+ raise NotImplementedError+++def compose_middleware(middlewares: list[Middleware]) -> dict[str, Callable]:+ hooks: dict[str, Callable] = {}++ # ... existing hooks ...++ sp_chain = [m for m in middlewares if _has_method(m, "transform_system_prompt")]+ if sp_chain:+ async def composed_sp(system_prompt, *, signal=None):+ result = system_prompt+ for mw in sp_chain:+ result = await mw.transform_system_prompt(result, signal=signal)+ return result+ hooks["transform_system_prompt"] = composed_sp++ return hooks+```++- [ ] **Step 4: Run tests**++Run: `pytest tests/middleware/test_transform_system_prompt.py -v`+Expected: 4 pass.++- [ ] **Step 5: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 4.++- [ ] **Step 6: Commit**++```bash+git add cubepi/middleware/base.py tests/middleware/test_transform_system_prompt.py+git commit -m "feat(middleware): add transform_system_prompt hook (chain composition)++New hook for middleware to dynamically mutate the system prompt per turn.+Composition rule: chain — each middleware receives the previous middleware's+output. Same rule as transform_context. Backward-compatible: middleware+that doesn't implement the method has no effect."+```++### Task D7.2: Wire into agent loop++**Files:**+- Modify: `cubepi/agent/loop.py` (or wherever provider.stream is invoked)+- Test: extend `tests/middleware/test_transform_system_prompt.py`++- [ ] **Step 1: Integration test**++Append to `tests/middleware/test_transform_system_prompt.py`:++```python+import asyncio++from cubepi import Agent, Model+from cubepi.providers.faux import FauxProvider, faux_assistant_message+++async def test_agent_applies_transform_system_prompt() -> None:+ """system_prompt sent to provider must reflect the middleware chain."""+ captured_payloads: list[dict] = []++ async def on_payload(payload, model):+ captured_payloads.append(payload)+ return payload++ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("ok")])+ agent = Agent(+ model=Model(provider=provider, model="test"),+ system_prompt="base",+ middleware=[_AppendA(), _AppendB()],+ )+ stream = await agent.prompt("hi", options={"on_payload": on_payload})+ async for _ in stream:+ pass++ assert len(captured_payloads) == 1+ # FauxProvider's payload structure: system_prompt is in the kwargs+ # (adapt to the actual key — check FauxProvider impl)+ assert captured_payloads[0].get("system_prompt", "").endswith("[A]\n[B]")+```++(Adjust `captured_payloads[0].get(...)` key based on FauxProvider's+actual payload shape — it might be `system` or `system_prompt`.)++- [ ] **Step 2: Run the test to find current behavior**++Run: `pytest tests/middleware/test_transform_system_prompt.py::test_agent_applies_transform_system_prompt -v`+Expected: FAIL — agent loop doesn't apply transform_system_prompt.++- [ ] **Step 3: Apply hook in agent loop**++In `cubepi/agent/loop.py`, find where the provider is called (typically `await provider.stream(model, messages, system_prompt=...)`). Before that call:++```python+# Apply transform_system_prompt chain if present+sp = system_prompt+if "transform_system_prompt" in hooks:+ sp = await hooks["transform_system_prompt"](sp)+# Apply transform_context chain (existing)+msgs = messages+if "transform_context" in hooks:+ msgs = await hooks["transform_context"](msgs)+# Call provider with transformed values+stream = await provider.stream(model, msgs, system_prompt=sp, tools=...)+```++- [ ] **Step 4: Run test**++Run: `pytest tests/middleware/test_transform_system_prompt.py -v`+Expected: 5 pass.++- [ ] **Step 5: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 5.++- [ ] **Step 6: Commit**++```bash+git add cubepi/agent/loop.py tests/middleware/test_transform_system_prompt.py+git commit -m "feat(agent): apply transform_system_prompt hook before each provider call++Agent loop now runs the composed transform_system_prompt chain on the+system prompt before sending to the provider. Per-call (not just at+Agent construction), so middleware can mutate the system prompt+turn-by-turn based on dynamic state."+```++---++## D8 — `after_model_response` hook + `TurnAction`++### Task D8.1: Add `TurnAction` dataclass + hook method++**Files:**+- Modify: `cubepi/middleware/base.py`+- Test: `tests/middleware/test_after_model_response.py` (new)++- [ ] **Step 1: Write failing tests**++Create `tests/middleware/test_after_model_response.py`:++```python+"""after_model_response hook + TurnAction tests (D8)."""++import pytest++from cubepi.agent.types import AgentContext+from cubepi.middleware.base import Middleware, TurnAction, compose_middleware+from cubepi.providers.base import (+ AssistantMessage,+ TextContent,+ Usage,+ UserMessage,+)+++def _mk_response(text: str = "hi") -> AssistantMessage:+ return AssistantMessage(content=[TextContent(text=text)], usage=Usage())+++def _mk_ctx() -> AgentContext:+ return AgentContext(system_prompt="", messages=[])+++class _MutateResponse(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ return TurnAction(response=_mk_response(text="mutated"))+++class _InjectMessages(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ return TurnAction(+ inject_messages=[UserMessage(content=[TextContent(text="injected")])]+ )+++class _Stop(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ return TurnAction(decision="stop")+++class _Loop(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ return TurnAction(decision="loop_to_model")+++class _NoOp(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ return None+++def test_turn_action_defaults() -> None:+ ta = TurnAction()+ assert ta.response is None+ assert ta.inject_messages == []+ assert ta.decision == "natural"+++async def test_single_middleware_mutates_response() -> None:+ hooks = compose_middleware([_MutateResponse()])+ result = await hooks["after_model_response"](_mk_response("orig"), _mk_ctx())+ assert isinstance(result.response, AssistantMessage)+ assert result.response.content[0].text == "mutated"+++async def test_chain_last_response_wins() -> None:+ """Two mutators; last one in chain wins for response."""+ class _MutateAgain(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ return TurnAction(response=_mk_response(text="final"))++ hooks = compose_middleware([_MutateResponse(), _MutateAgain()])+ result = await hooks["after_model_response"](_mk_response("orig"), _mk_ctx())+ assert result.response.content[0].text == "final"+++async def test_inject_messages_concatenate() -> None:+ """inject_messages from multiple middleware concatenate."""+ class _InjectMore(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ return TurnAction(+ inject_messages=[UserMessage(content=[TextContent(text="more")])]+ )++ hooks = compose_middleware([_InjectMessages(), _InjectMore()])+ result = await hooks["after_model_response"](_mk_response(), _mk_ctx())+ assert len(result.inject_messages) == 2+++async def test_decision_last_wins() -> None:+ """Last middleware's decision wins."""+ hooks = compose_middleware([_Stop(), _Loop()])+ result = await hooks["after_model_response"](_mk_response(), _mk_ctx())+ assert result.decision == "loop_to_model"+++async def test_none_return_treated_as_natural() -> None:+ """Middleware returning None doesn't affect the composed TurnAction."""+ hooks = compose_middleware([_NoOp(), _Stop()])+ result = await hooks["after_model_response"](_mk_response(), _mk_ctx())+ assert result.decision == "stop"+++async def test_default_implementation_raises() -> None:+ mw = Middleware()+ with pytest.raises(NotImplementedError):+ await mw.after_model_response(_mk_response(), _mk_ctx())+++async def test_no_middleware_hook_absent() -> None:+ class Plain(Middleware):+ pass+ hooks = compose_middleware([Plain()])+ assert "after_model_response" not in hooks+```++- [ ] **Step 2: Run tests to verify failures**++Run: `pytest tests/middleware/test_after_model_response.py -v`+Expected: 8 failures.++- [ ] **Step 3: Add `TurnAction` and the hook**++In `cubepi/middleware/base.py`:++```python+from dataclasses import dataclass, field+from typing import Literal++from cubepi.providers.base import AssistantMessage, Message+++@dataclass+class TurnAction:+ """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.+ """+ response: AssistantMessage | None = None+ inject_messages: list[Message] = field(default_factory=list)+ decision: Literal["natural", "stop", "loop_to_model"] = "natural"+++class Middleware:+ # ... existing methods ...++ async def after_model_response(+ self,+ response: AssistantMessage,+ ctx, # AgentContext; avoid circular import via forward ref or import at runtime+ *,+ signal=None,+ ) -> TurnAction | None:+ raise NotImplementedError+```++For composition, append to `compose_middleware()`:++```python+amr_chain = [m for m in middlewares if _has_method(m, "after_model_response")]+if amr_chain:+ async def composed_amr(response, ctx, *, signal=None):+ current_response = response+ all_inject: list[Message] = []+ last_decision: Literal["natural", "stop", "loop_to_model"] = "natural"+ for mw in amr_chain:+ result = await mw.after_model_response(+ current_response, ctx, signal=signal+ )+ if result is None:+ continue+ if result.response is not None:+ current_response = result.response+ if result.inject_messages:+ all_inject.extend(result.inject_messages)+ last_decision = result.decision+ return TurnAction(+ response=current_response,+ inject_messages=all_inject,+ decision=last_decision,+ )+ hooks["after_model_response"] = composed_amr+```++Also export `TurnAction` from `cubepi.middleware` (update `cubepi/middleware/__init__.py`):++```python+from cubepi.middleware.base import Middleware, TurnAction, compose_middleware++__all__ = ["Middleware", "TurnAction", "compose_middleware"]+```++- [ ] **Step 4: Run tests**++Run: `pytest tests/middleware/test_after_model_response.py -v`+Expected: 8 pass.++- [ ] **Step 5: Commit**++```bash+git add cubepi/middleware/ tests/middleware/test_after_model_response.py+git commit -m "feat(middleware): add after_model_response hook + TurnAction++New hook + return type lets middleware:+- observe and mutate the model's response (chain, last wins)+- inject messages before the next iteration (chain, concat)+- control the agent loop: natural | stop | loop_to_model (chain, last wins)++Covers cubebox's CostMiddleware (observe usage), TimestampMiddleware+(stamp turn-end), and TodoListMiddleware (guard logic + control flow)+use cases.++should_stop_after_turn is preserved unchanged for simpler stop-only+middleware."+```++### Task D8.2: Wire `after_model_response` + `TurnAction.decision` into agent loop++**Files:**+- Modify: `cubepi/agent/loop.py`+- Test: extend `tests/middleware/test_after_model_response.py`++- [ ] **Step 1: Integration tests**++Append to `tests/middleware/test_after_model_response.py`:++```python+from cubepi import Agent, Model+from cubepi.providers.faux import FauxProvider, faux_assistant_message+++async def test_agent_stops_when_middleware_returns_stop() -> None:+ """decision='stop' terminates even if response had tool calls+ (we test no-tool-calls case for simplicity; real agent will skip tool exec)."""+ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("done")])+ agent = Agent(+ model=Model(provider=provider, model="test"),+ middleware=[_Stop()],+ )+ stream = await agent.prompt("hi")+ events = []+ async for event in stream:+ events.append(event.type)+ # Agent should stop after first model response — exactly one "done" event+ assert events.count("done") == 1+++async def test_agent_loops_when_middleware_returns_loop_to_model() -> None:+ """decision='loop_to_model' re-invokes the model with inject_messages."""+ provider = FauxProvider()+ # First response: natural-stop content. Middleware will force loop.+ # Second response: terminates naturally.+ provider.set_responses([+ faux_assistant_message("first"),+ faux_assistant_message("second"),+ ])++ looped_once = False++ class _LoopOnce(Middleware):+ async def after_model_response(self, response, ctx, *, signal=None):+ nonlocal looped_once+ if not looped_once:+ looped_once = True+ return TurnAction(+ decision="loop_to_model",+ inject_messages=[+ UserMessage(content=[TextContent(text="retry")])+ ],+ )+ return None++ agent = Agent(+ model=Model(provider=provider, model="test"),+ middleware=[_LoopOnce()],+ )+ stream = await agent.prompt("hi")+ async for _ in stream:+ pass+ # Verify provider was called twice+ assert provider.call_count == 2+```++(`provider.call_count` attribute may need to be added to FauxProvider+if it doesn't exist — add it as a simple counter incremented on each+`stream()` call.)++- [ ] **Step 2: Run tests to see current behavior**++Run: `pytest tests/middleware/test_after_model_response.py::test_agent_stops_when_middleware_returns_stop tests/middleware/test_after_model_response.py::test_agent_loops_when_middleware_returns_loop_to_model -v`+Expected: FAIL — agent loop ignores `after_model_response`.++- [ ] **Step 3: Wire into agent loop**++In `cubepi/agent/loop.py`, find the main loop body — typically:++```python+# Existing structure (paraphrased):+while not should_stop:+ response = await call_model(...)+ if should_stop_after_turn(...):+ break+ tool_results = await execute_tools(response.tool_calls)+ messages.append(response)+ messages.extend(tool_results)+```++Insert the new hook between model call and tool execution:++```python+while not should_stop:+ response = await call_model(...)++ # NEW: after_model_response hook+ if "after_model_response" in hooks:+ turn_action = await hooks["after_model_response"](response, ctx)+ if turn_action.response is not None:+ response = turn_action.response+ if turn_action.inject_messages:+ messages.extend(turn_action.inject_messages)+ if turn_action.decision == "stop":+ break+ if turn_action.decision == "loop_to_model":+ messages.append(response) # still record the response+ continue # skip tool execution, go back to model call+ # decision == "natural": fall through++ # Existing should_stop_after_turn (still functional for simple use cases)+ if hooks.get("should_stop_after_turn") and await hooks["should_stop_after_turn"](...):+ break++ # Existing tool execution path+ tool_results = await execute_tools(response.tool_calls)+ messages.append(response)+ messages.extend(tool_results)+```++(Adapt to actual loop structure in cubepi v0.2.)++- [ ] **Step 4: Run tests**++Run: `pytest tests/middleware/test_after_model_response.py -v`+Expected: 10 pass.++- [ ] **Step 5: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 10.++- [ ] **Step 6: Commit**++```bash+git add cubepi/agent/loop.py tests/middleware/test_after_model_response.py+git commit -m "feat(agent): wire after_model_response hook into agent loop++Loop now runs the composed after_model_response chain after each model+call. TurnAction.decision controls flow:+- 'natural' (default): proceed to tool execution or natural stop+- 'stop': terminate this turn+- 'loop_to_model': skip tool execution, re-invoke the model with+ inject_messages appended to context++response mutation and inject_messages are applied before the decision+branch."+```++---++## D3 — Anthropic configurable cache marker policy++### Task D3.1: Define `CacheMarkerPolicy` Protocol + default impl++**Files:**+- Modify: `cubepi/providers/anthropic.py`+- Test: `tests/providers/test_anthropic_cache_policy.py` (new)++- [ ] **Step 1: Write failing tests**++Create `tests/providers/test_anthropic_cache_policy.py`:++```python+"""AnthropicProvider configurable cache_policy tests (D3)."""++import pytest++from cubepi.providers.anthropic import (+ AnthropicProvider,+ CacheMarkerPolicy,+ DefaultCacheMarkerPolicy,+)+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ TextContent,+ UserMessage,+)+++def test_default_policy_marks_system() -> None:+ p = DefaultCacheMarkerPolicy()+ assert p.mark_system() is True+++def test_default_policy_marks_last_tool() -> None:+ p = DefaultCacheMarkerPolicy()+ assert p.mark_last_tool() is True+++def test_default_policy_indices_picks_last() -> None:+ p = DefaultCacheMarkerPolicy()+ msgs: list[Message] = [+ UserMessage(content=[TextContent(text="a")]),+ UserMessage(content=[TextContent(text="b")]),+ ]+ assert p.message_breakpoint_indices(msgs) == [1]+++def test_default_policy_indices_empty() -> None:+ p = DefaultCacheMarkerPolicy()+ assert p.message_breakpoint_indices([]) == []+++def test_provider_uses_default_policy_when_none_passed() -> None:+ p = AnthropicProvider(api_key="x")+ assert isinstance(p._cache_policy, DefaultCacheMarkerPolicy)+++def test_provider_uses_custom_policy() -> None:+ class _NoSystem(CacheMarkerPolicy):+ def mark_system(self) -> bool:+ return False+ def mark_last_tool(self) -> bool:+ return False+ def message_breakpoint_indices(self, messages):+ return []++ p = AnthropicProvider(api_key="x", cache_policy=_NoSystem())+ assert p._cache_policy.mark_system() is False+```++- [ ] **Step 2: Run tests to verify failures**++Run: `pytest tests/providers/test_anthropic_cache_policy.py -v`+Expected: 6 failures — `CacheMarkerPolicy` / `DefaultCacheMarkerPolicy` don't exist.++- [ ] **Step 3: Add Protocol + default impl**++At the top of `cubepi/providers/anthropic.py`:++```python+from typing import Protocol, runtime_checkable++from cubepi.providers.base import Message+++@runtime_checkable+class CacheMarkerPolicy(Protocol):+ """Policy controlling where Anthropic cache_control markers are inserted.++ See cubebox/CLAUDE.md prompt cache discipline for a real-world consumer.+ """+ def mark_system(self) -> bool: ...+ def mark_last_tool(self) -> bool: ...+ def message_breakpoint_indices(+ self,+ messages: list[Message],+ ) -> list[int]: ...+++class DefaultCacheMarkerPolicy:+ """Preserves cubepi v0.2 behavior: system + last message + last tool."""++ def mark_system(self) -> bool:+ return True++ def mark_last_tool(self) -> bool:+ return True++ def message_breakpoint_indices(self, messages: list[Message]) -> list[int]:+ return [len(messages) - 1] if messages else []+```++- [ ] **Step 4: Add `cache_policy` parameter to `AnthropicProvider`**++```python+class AnthropicProvider:+ def __init__(+ self,+ *,+ api_key: str | None = None,+ base_url: str | None = None,+ cache_policy: CacheMarkerPolicy | None = None,+ ) -> None:+ import anthropic+ kwargs: dict[str, Any] = {}+ if api_key:+ kwargs["api_key"] = api_key+ if base_url:+ kwargs["base_url"] = base_url+ self._client = anthropic.AsyncAnthropic(**kwargs)+ self._cache_policy = cache_policy or DefaultCacheMarkerPolicy()+```++- [ ] **Step 5: Run tests**++Run: `pytest tests/providers/test_anthropic_cache_policy.py -v`+Expected: 6 pass.++- [ ] **Step 6: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 6.++- [ ] **Step 7: Commit**++```bash+git add cubepi/providers/anthropic.py tests/providers/test_anthropic_cache_policy.py+git commit -m "feat(anthropic): add configurable CacheMarkerPolicy + DefaultCacheMarkerPolicy++New constructor parameter cache_policy: CacheMarkerPolicy | None. When+not passed, behavior is identical to v0.2.0 via DefaultCacheMarkerPolicy.++Callers (like cubebox) can supply a custom policy to control which+messages get cache_control: ephemeral markers — e.g. walk back to the+last completed AIMessage rather than always the last message."+```++### Task D3.2: Refactor existing marker logic to use policy++**Files:**+- Modify: `cubepi/providers/anthropic.py` (refactor `stream()` and `_apply_message_cache_control`)+- Test: extend `tests/providers/test_anthropic_cache_policy.py`++- [ ] **Step 1: Add behavioral test (custom policy actually drives marker placement)**++Append to `tests/providers/test_anthropic_cache_policy.py`:++```python+async def test_custom_policy_drives_message_marker_placement() -> None:+ """A policy that marks index 0 (not last) must put cache_control on the first message."""+ class _FirstOnly(CacheMarkerPolicy):+ def mark_system(self) -> bool:+ return False+ def mark_last_tool(self) -> bool:+ return False+ def message_breakpoint_indices(self, messages):+ return [0] if messages else []++ p = AnthropicProvider(api_key="x", cache_policy=_FirstOnly())++ msgs: list[Message] = [+ UserMessage(content=[TextContent(text="zero")]),+ UserMessage(content=[TextContent(text="one")]),+ ]+ api_msgs = [p._convert_message(m) for m in msgs]+ # cache control is on whatever the internal _apply_message_cache_control puts it+ # We need to call the new internal method that applies policy. Refactor will+ # introduce _apply_policy_markers; assert the output structure.+ p._apply_policy_markers(api_msgs, cache_control={"type": "ephemeral"})+ # First message should have cache_control on its last content block+ first_blocks = api_msgs[0]["content"]+ if isinstance(first_blocks, list):+ assert first_blocks[-1].get("cache_control") == {"type": "ephemeral"}+ # Second message should NOT have cache_control+ second_blocks = api_msgs[1]["content"]+ if isinstance(second_blocks, list):+ assert "cache_control" not in (second_blocks[-1] if second_blocks else {})+```++- [ ] **Step 2: Run test to verify failure**++Run: `pytest tests/providers/test_anthropic_cache_policy.py::test_custom_policy_drives_message_marker_placement -v`+Expected: FAIL — `_apply_policy_markers` doesn't exist (current method is `_apply_message_cache_control` which always uses last index).++- [ ] **Step 3: Refactor `AnthropicProvider`**++Two parts: (a) replace `_apply_message_cache_control` with policy-aware `_apply_indices_markers` taking explicit indices; (b) update `stream()` to call the policy for indices + system + tool markers.++```python+def _apply_indices_markers(+ self,+ api_messages: list[dict[str, Any]],+ indices: list[int],+ cache_control: dict[str, str],+) -> None:+ """Apply cache_control to the last content block of each indexed message."""+ for idx in indices:+ if 0 <= idx < len(api_messages):+ msg = api_messages[idx]+ content = msg.get("content")+ if isinstance(content, list) and content:+ last_block = content[-1]+ if isinstance(last_block, dict):+ content[-1] = {**last_block, "cache_control": cache_control}+ elif isinstance(content, str):+ msg["content"] = [+ {"type": "text", "text": content, "cache_control": cache_control}+ ]+```++Inside `stream()` (existing method), replace the marker-application logic:++```python+async def stream(self, model, messages, *, system_prompt="", tools=None, options=None):+ ...+ cache_control = self._get_cache_control() # existing+ api_messages = [self._convert_message(m) for m in messages]++ if cache_control:+ # Policy inspects the original cubepi `messages` list to pick indices;+ # we apply markers to the parallel `api_messages` list (1:1 correspondence).+ indices = self._cache_policy.message_breakpoint_indices(messages)+ self._apply_indices_markers(api_messages, indices, cache_control)++ # ... existing kwargs build ...++ if system_prompt:+ kwargs["system"] = [+ {+ "type": "text",+ "text": system_prompt,+ **({"cache_control": cache_control}+ if cache_control and self._cache_policy.mark_system() else {}),+ }+ ]+ ...+ if cache_control and api_tools and self._cache_policy.mark_last_tool():+ api_tools[-1]["cache_control"] = cache_control+```++Delete the old `_apply_message_cache_control` method once all references are removed.++Delete the old `_apply_message_cache_control` once references are gone.++- [ ] **Step 4: Update the behavioral test to call `_apply_indices_markers` not `_apply_policy_markers`**++Adjust the test from Step 1 to use the actual method name. Verify the test passes.++- [ ] **Step 5: Run all anthropic tests + add golden-fixture pin**++Existing v0.2 behavioral tests for anthropic must still pass byte-for-byte (default policy preserves v0.2 markers). Run:++```bash+pytest tests/providers/test_anthropic.py tests/providers/test_anthropic_cache_policy.py -v+```++Expected: all pass.++- [ ] **Step 6: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 7 (6 from D3.1 + 1 from D3.2).++- [ ] **Step 7: Commit**++```bash+git add cubepi/providers/anthropic.py tests/providers/test_anthropic_cache_policy.py+git commit -m "refactor(anthropic): route cache_control placement through CacheMarkerPolicy++stream() now calls cache_policy.mark_system/mark_last_tool/+message_breakpoint_indices instead of hard-coding 'mark the last message'.+Default policy preserves v0.2 behavior; existing tests still pass.++Custom policies (e.g. cubebox's 'mark last completed AIMessage') now+work end-to-end."+```++---++## D4 — OpenAIProvider OSS reasoning extraction + payload quirks++### Task D4.1: Tests with fake openai-compatible streams++**Files:**+- Test: `tests/providers/test_openai_reasoning.py` (new)++- [ ] **Step 1: Set up tests with respx mock**++Create `tests/providers/test_openai_reasoning.py`:++```python+"""OpenAIProvider OSS reasoning extraction + payload_quirks tests (D4)."""++import json+import pytest+import respx+from httpx import Response++from cubepi import Model+from cubepi.providers.openai import OpenAIProvider+from cubepi.providers.base import UserMessage, TextContent+++def _sse_chunks(*chunks: dict) -> str:+ """Format dict chunks as OpenAI SSE stream."""+ out = []+ for c in chunks:+ out.append(f"data: {json.dumps(c)}\n\n")+ out.append("data: [DONE]\n\n")+ return "".join(out)+++async def test_extracts_reasoning_content_variant() -> None:+ """DeepSeek/Qwen/DouBao use delta.reasoning_content."""+ body = _sse_chunks(+ {"choices": [{"delta": {"reasoning_content": "Let me think"}, "finish_reason": None}]},+ {"choices": [{"delta": {"reasoning_content": " carefully"}, "finish_reason": None}]},+ {"choices": [{"delta": {"content": "Answer"}, "finish_reason": None}]},+ {"choices": [{"delta": {}, "finish_reason": "stop"}]},+ )+ respx.post("https://test.com/v1/chat/completions").mock(+ return_value=Response(200, text=body, headers={"content-type": "text/event-stream"})+ )++ p = OpenAIProvider(api_key="x", base_url="https://test.com/v1")+ stream = await p.stream(+ Model(provider="openai", model="m"),+ [UserMessage(content=[TextContent(text="hi")])],+ )+ types_seen = []+ thinking_deltas = []+ async for evt in stream:+ types_seen.append(evt.type)+ if evt.type == "thinking_delta":+ thinking_deltas.append(evt.delta)++ assert "thinking_start" in types_seen+ assert "thinking_delta" in types_seen+ assert "thinking_end" in types_seen+ assert "".join(thinking_deltas) == "Let me think carefully"+++async def test_extracts_reasoning_variant_vllm() -> None:+ """vLLM uses delta.reasoning."""+ body = _sse_chunks(+ {"choices": [{"delta": {"reasoning": "v-llm reasoning"}, "finish_reason": None}]},+ {"choices": [{"delta": {"content": "Answer"}, "finish_reason": "stop"}]},+ )+ respx.post("https://test.com/v1/chat/completions").mock(+ return_value=Response(200, text=body, headers={"content-type": "text/event-stream"})+ )++ p = OpenAIProvider(api_key="x", base_url="https://test.com/v1")+ stream = await p.stream(+ Model(provider="openai", model="m"),+ [UserMessage(content=[TextContent(text="hi")])],+ )+ deltas = []+ async for evt in stream:+ if evt.type == "thinking_delta":+ deltas.append(evt.delta)+ assert "".join(deltas) == "v-llm reasoning"+++async def test_extracts_reasoning_details_variant_minimax() -> None:+ """MiniMax uses delta.reasoning_details: [{text: ...}]."""+ body = _sse_chunks(+ {"choices": [{"delta": {"reasoning_details": [{"text": "step1"}]}, "finish_reason": None}]},+ {"choices": [{"delta": {"reasoning_details": [{"text": " step2"}]}, "finish_reason": None}]},+ {"choices": [{"delta": {"content": "Answer"}, "finish_reason": "stop"}]},+ )+ respx.post("https://test.com/v1/chat/completions").mock(+ return_value=Response(200, text=body, headers={"content-type": "text/event-stream"})+ )++ p = OpenAIProvider(api_key="x", base_url="https://test.com/v1")+ stream = await p.stream(+ Model(provider="openai", model="m"),+ [UserMessage(content=[TextContent(text="hi")])],+ )+ deltas = []+ async for evt in stream:+ if evt.type == "thinking_delta":+ deltas.append(evt.delta)+ assert "".join(deltas) == "step1 step2"+++async def test_max_completion_tokens_alias_rewrite() -> None:+ """When payload_quirks=['max_completion_tokens_alias'], rewrite to max_tokens."""+ captured: dict = {}++ def _capture(request):+ captured["body"] = json.loads(request.content)+ return Response(200, text=_sse_chunks(+ {"choices": [{"delta": {"content": "ok"}, "finish_reason": "stop"}]}+ ), headers={"content-type": "text/event-stream"})++ respx.post("https://test.com/v1/chat/completions").mock(side_effect=_capture)++ p = OpenAIProvider(+ api_key="x",+ base_url="https://test.com/v1",+ payload_quirks=["max_completion_tokens_alias"],+ )+ stream = await p.stream(+ Model(provider="openai", model="m"),+ [UserMessage(content=[TextContent(text="hi")])],+ options=None, # we'd pass max_completion_tokens here normally+ )+ async for _ in stream:+ pass+ # Note: actual max_completion_tokens injection depends on how cubepi's+ # OpenAIProvider currently builds the payload. The test asserts that+ # IF max_completion_tokens is present, it gets renamed to max_tokens.+ # If cubepi doesn't currently expose this knob, this test may need to+ # call the internal payload-build helper directly.+```++(`pytest-httpx` is an alternative to `respx`. If cubepi already uses one,+prefer that — add `respx` to `[project.optional-dependencies] dev` if not.)++- [ ] **Step 2: Run tests to verify failures**++Run: `pytest tests/providers/test_openai_reasoning.py -v`+Expected: 3 reasoning tests fail (no extraction); 1 payload quirk test may pass trivially or fail depending on current shape.++### Task D4.2: Implement OSS reasoning extraction in `OpenAIProvider`++**Files:**+- Modify: `cubepi/providers/openai.py`++- [ ] **Step 1: Add reasoning extraction in stream chunk handler**++In `cubepi/providers/openai.py`, find the streaming chunk handler (the loop that consumes `async for chunk in response`). Before the existing `delta.content` / `delta.tool_calls` branches, add:++```python+# Track thinking state across chunks+thinking_started = False+thinking_content_index: int | None = None++async for chunk in response:+ if not chunk.choices:+ continue+ delta = chunk.choices[0].delta+ finish_reason = chunk.choices[0].finish_reason++ # --- OSS reasoning extraction (D4) ---+ reasoning_delta: str | None = None+ if hasattr(delta, "reasoning_content") and delta.reasoning_content:+ reasoning_delta = delta.reasoning_content+ elif hasattr(delta, "reasoning") and delta.reasoning:+ reasoning_delta = delta.reasoning+ elif hasattr(delta, "reasoning_details") and delta.reasoning_details:+ parts = []+ for d in delta.reasoning_details:+ text = d.text if hasattr(d, "text") else (d.get("text") if isinstance(d, dict) else None)+ if text:+ parts.append(text)+ if parts:+ reasoning_delta = "".join(parts)++ if reasoning_delta:+ if not thinking_started:+ partial.content.append(ThinkingContent(thinking=""))+ thinking_content_index = len(partial.content) - 1+ ms.push(StreamEvent(+ type="thinking_start",+ content_index=thinking_content_index,+ partial=partial.model_copy(deep=True),+ ))+ thinking_started = True+ # Accumulate+ existing = partial.content[thinking_content_index].thinking+ partial.content[thinking_content_index] = ThinkingContent(+ thinking=existing + reasoning_delta+ )+ ms.push(StreamEvent(+ type="thinking_delta",+ delta=reasoning_delta,+ content_index=thinking_content_index,+ partial=partial.model_copy(deep=True),+ ))++ # ... existing delta.content branch ...++ # On finish, close any open thinking block+ if finish_reason is not None and thinking_started:+ ms.push(StreamEvent(+ type="thinking_end",+ content_index=thinking_content_index,+ partial=partial.model_copy(deep=True),+ ))+ thinking_started = False++ # ... existing finish handling ...+```++(Adapt to actual code structure in cubepi v0.2's `openai.py`.)++- [ ] **Step 2: Add `payload_quirks` parameter**++```python+class OpenAIProvider:+ def __init__(+ self,+ *,+ api_key: str | None = None,+ base_url: str | None = None,+ payload_quirks: list[Literal["max_completion_tokens_alias"]] | None = None,+ ) -> None:+ import openai+ kwargs: dict[str, Any] = {}+ if api_key:+ kwargs["api_key"] = api_key+ if base_url:+ kwargs["base_url"] = base_url+ self._client = openai.AsyncOpenAI(**kwargs)+ self._payload_quirks = set(payload_quirks or [])+```++In the request payload build, after constructing `kwargs`:++```python+if "max_completion_tokens_alias" in self._payload_quirks:+ if "max_completion_tokens" in kwargs:+ kwargs["max_tokens"] = kwargs.pop("max_completion_tokens")+```++- [ ] **Step 3: Run tests**++Run: `pytest tests/providers/test_openai_reasoning.py -v`+Expected: 4 pass.++- [ ] **Step 4: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + 4.++- [ ] **Step 5: Commit**++```bash+git add cubepi/providers/openai.py tests/providers/test_openai_reasoning.py+git commit -m "feat(openai): extract OSS reasoning fields + payload_quirks++Streaming chunk handler now extracts reasoning from three non-standard+fields in priority order:+ delta.reasoning_content (DeepSeek/Qwen/DouBao)+ delta.reasoning (vLLM)+ delta.reasoning_details[*] (MiniMax)++Emits cubepi's standard thinking_start/_delta/_end events, same shape+as Anthropic's native reasoning path and OpenAIResponsesProvider.++payload_quirks parameter supports max_completion_tokens_alias for older+openai-compatible endpoints that require max_tokens."+```++---++## D1 — PostgresCheckpointer++### Task D1.1: Define models and metadata++**Files:**+- Create: `cubepi/checkpointer/postgres/__init__.py`+- Create: `cubepi/checkpointer/postgres/models.py`+- Test: `tests/checkpointer/test_postgres.py` (placeholder for now)++- [ ] **Step 1: Create the module structure**++```bash+mkdir -p cubepi/checkpointer/postgres+touch cubepi/checkpointer/postgres/__init__.py+mkdir -p tests/checkpointer+```++- [ ] **Step 2: Write the models file**++Create `cubepi/checkpointer/postgres/models.py`:++```python+"""SQLAlchemy table definitions for cubepi PostgresCheckpointer.++cubepi uses a private MetaData instance (not SQLModel's global one)+so downstreams can compose it into alembic regardless of which ORM+they use. SQLAlchemy 2.0 declarative is the chosen style for cubepi+internal definitions.+"""+from __future__ import annotations++import datetime as _dt+from typing import Any++import sqlalchemy as sa+from sqlalchemy.dialects.postgresql import JSONB+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column++EXPECTED_SCHEMA_VERSION = 1+PARTITION_COUNT = 64++cubepi_metadata = sa.MetaData()+++class CubepiBase(DeclarativeBase):+ metadata = cubepi_metadata+++class CubepiThread(CubepiBase):+ __tablename__ = "cubepi_threads"++ thread_id: Mapped[str] = mapped_column(sa.Text, primary_key=True)+ parent_thread_id: Mapped[str | None] = mapped_column(+ sa.Text,+ sa.ForeignKey("cubepi_threads.thread_id"),+ nullable=True,+ )+ forked_at_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)+ extra: Mapped[dict[str, Any]] = mapped_column(+ JSONB, nullable=False, server_default=sa.text("'{}'::jsonb"),+ )+ created_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP(timezone=True),+ nullable=False,+ server_default=sa.text("now()"),+ )+ updated_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP(timezone=True),+ nullable=False,+ server_default=sa.text("now()"),+ )+++class CubepiMessage(CubepiBase):+ __tablename__ = "cubepi_messages"+ __table_args__ = (+ sa.Index(+ "ix_cubepi_messages_metadata_gin",+ "metadata",+ postgresql_using="gin",+ postgresql_ops={"metadata": "jsonb_path_ops"},+ ),+ {"postgresql_partition_by": "HASH (thread_id)"},+ )++ thread_id: Mapped[str] = mapped_column(+ sa.Text,+ sa.ForeignKey("cubepi_threads.thread_id", ondelete="CASCADE"),+ primary_key=True,+ )+ seq: Mapped[int] = mapped_column(sa.BigInteger, primary_key=True)+ role: Mapped[str] = mapped_column(sa.Text, nullable=False)+ metadata: Mapped[dict[str, Any]] = mapped_column(+ JSONB, nullable=False, server_default=sa.text("'{}'::jsonb"),+ )+ payload: Mapped[bytes] = mapped_column(sa.LargeBinary, nullable=False)+ created_at: Mapped[_dt.datetime] = mapped_column(+ sa.TIMESTAMP(timezone=True),+ nullable=False,+ server_default=sa.text("now()"),+ )+++class CubepiSchemaVersion(CubepiBase):+ __tablename__ = "cubepi_schema_version"++ version: Mapped[int] = mapped_column(sa.Integer, primary_key=True)+```++- [ ] **Step 3: Write a smoke test that imports without error**++Create `tests/checkpointer/test_postgres.py`:++```python+"""PostgresCheckpointer tests (D1)."""++def test_models_import() -> None:+ from cubepi.checkpointer.postgres.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ CubepiThread,+ CubepiMessage,+ CubepiSchemaVersion,+ cubepi_metadata,+ )+ assert EXPECTED_SCHEMA_VERSION == 1+ assert PARTITION_COUNT == 64+ # Metadata has all three tables registered+ assert "cubepi_threads" in cubepi_metadata.tables+ assert "cubepi_messages" in cubepi_metadata.tables+ assert "cubepi_schema_version" in cubepi_metadata.tables+```++- [ ] **Step 4: Run smoke test**++Run: `pytest tests/checkpointer/test_postgres.py::test_models_import -v`+Expected: PASS.++- [ ] **Step 5: Commit**++```bash+git add cubepi/checkpointer/postgres/ tests/checkpointer/+git commit -m "feat(postgres-checkpointer): add SQLAlchemy models + private metadata++Three tables: cubepi_threads (thread-level KV), cubepi_messages+(HASH-partitioned by thread_id, 64 partitions, append-only), and+cubepi_schema_version. cubepi_metadata is private (not SQLModel's+global) so any downstream ORM can compose it into alembic."+```++### Task D1.2: Exceptions + alembic helpers++**Files:**+- Create: `cubepi/checkpointer/postgres/exceptions.py`+- Create: `cubepi/checkpointer/postgres/alembic_helpers.py`++- [ ] **Step 1: Create exceptions**++`cubepi/checkpointer/postgres/exceptions.py`:++```python+"""Exceptions raised by PostgresCheckpointer schema verification."""+++class CubepiSchemaError(Exception):+ """Base class for cubepi Postgres schema errors."""+++class CubepiSchemaUninitialized(CubepiSchemaError):+ """The cubepi_schema_version table is empty or missing.++ Typically means the host application's alembic upgrade hasn't been+ run yet against this database.+ """+++class CubepiSchemaMismatch(CubepiSchemaError):+ """The DB schema version doesn't match cubepi's expected version.++ Typically means the cubepi library was upgraded but the host+ application's alembic is behind. Run a new alembic revision.+ """++ def __init__(self, *, expected: int, actual: int, hint: str = "") -> None:+ msg = f"cubepi schema mismatch: expected={expected} actual={actual}."+ if hint:+ msg += f" {hint}"+ super().__init__(msg)+ self.expected = expected+ self.actual = actual+```++- [ ] **Step 2: Create alembic helpers**++`cubepi/checkpointer/postgres/alembic_helpers.py`:++```python+"""SQL helpers for host application alembic migrations."""++from cubepi.checkpointer.postgres.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+)+++def create_message_partitions_op() -> str:+ """Return SQL DDL creating all 64 child partitions of cubepi_messages.++ Call inside an alembic upgrade() function via op.execute(), AFTER+ the parent cubepi_messages table has been created.+ """+ return "\n".join(+ f"CREATE TABLE cubepi_messages_p{i:02d} "+ f"PARTITION OF cubepi_messages "+ f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i});"+ for i in range(PARTITION_COUNT)+ )+++def write_schema_version_op() -> str:+ """Return SQL inserting the current schema version.++ Call inside an alembic upgrade() after CREATE TABLE+ cubepi_schema_version. Idempotent via ON CONFLICT DO NOTHING.+ """+ return (+ f"INSERT INTO cubepi_schema_version (version) "+ f"VALUES ({EXPECTED_SCHEMA_VERSION}) ON CONFLICT DO NOTHING;"+ )+```++- [ ] **Step 3: Add tests**++Append to `tests/checkpointer/test_postgres.py`:++```python+def test_create_message_partitions_op_yields_64_statements() -> None:+ from cubepi.checkpointer.postgres.alembic_helpers import create_message_partitions_op+ sql = create_message_partitions_op()+ # 64 CREATE TABLE statements+ assert sql.count("CREATE TABLE cubepi_messages_p") == 64+ # Modulus is constant; remainder ranges 0..63+ assert "modulus 64, remainder 0" in sql+ assert "modulus 64, remainder 63" in sql+++def test_write_schema_version_op_includes_expected_version() -> None:+ from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op+ sql = write_schema_version_op()+ assert "INSERT INTO cubepi_schema_version" in sql+ assert "VALUES (1)" in sql+++def test_exceptions_carry_expected_actual() -> None:+ from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch+ err = CubepiSchemaMismatch(expected=2, actual=1, hint="run alembic")+ assert err.expected == 2+ assert err.actual == 1+ assert "expected=2" in str(err)+ assert "run alembic" in str(err)+```++- [ ] **Step 4: Run tests**++Run: `pytest tests/checkpointer/test_postgres.py -v`+Expected: 4 pass.++- [ ] **Step 5: Commit**++```bash+git add cubepi/checkpointer/postgres/exceptions.py cubepi/checkpointer/postgres/alembic_helpers.py tests/checkpointer/test_postgres.py+git commit -m "feat(postgres-checkpointer): add exceptions + alembic helpers++- CubepiSchemaUninitialized / CubepiSchemaMismatch for version check failures+- create_message_partitions_op() returns DDL for 64 child partitions+- write_schema_version_op() returns INSERT for version pinning"+```++### Task D1.3: PostgresCheckpointer implementation (load/append/save_extra + schema check)++**Files:**+- Create: `cubepi/checkpointer/postgres/checkpointer.py`+- Modify: `cubepi/checkpointer/postgres/__init__.py`+- Test: extend `tests/checkpointer/test_postgres.py` + add `conftest.py`++- [ ] **Step 1: Add Postgres test fixtures**++Create `tests/checkpointer/conftest.py`:++```python+"""Postgres test fixtures."""++import os+import secrets++import asyncpg+import pytest+import pytest_asyncio++[email protected](scope="session")+def pg_dsn() -> str:+ """Postgres DSN for tests. Override via CUBEPI_TEST_PG_DSN env var."""+ return os.environ.get(+ "CUBEPI_TEST_PG_DSN",+ "postgresql://postgres@localhost:5432/postgres",+ )+++@pytest_asyncio.fixture+async def clean_db(pg_dsn: str):+ """Create a fresh database for each test; drop after."""+ db_name = f"cubepi_test_{secrets.token_hex(6)}"+ # Connect to default DB to issue CREATE DATABASE+ admin_conn = await asyncpg.connect(pg_dsn)+ try:+ await admin_conn.execute(f'CREATE DATABASE "{db_name}"')+ finally:+ await admin_conn.close()+ # Build DSN for the new DB+ test_dsn = pg_dsn.rsplit("/", 1)[0] + f"/{db_name}"+ yield test_dsn+ # Cleanup+ admin_conn = await asyncpg.connect(pg_dsn)+ try:+ # Terminate any lingering connections+ await admin_conn.execute(+ f"SELECT pg_terminate_backend(pid) FROM pg_stat_activity "+ f"WHERE datname = '{db_name}'"+ )+ await admin_conn.execute(f'DROP DATABASE IF EXISTS "{db_name}"')+ finally:+ await admin_conn.close()+```++- [ ] **Step 2: Write the PostgresCheckpointer**++Create `cubepi/checkpointer/postgres/checkpointer.py`:++```python+"""PostgresCheckpointer — Checkpointer protocol implementation against PostgreSQL.++Append-only message log + per-thread extra KV. Compatible with the+existing Checkpointer protocol so it slots into Agent(checkpointer=...)+unchanged.+"""+from __future__ import annotations++import json+from typing import Any++import asyncpg+import msgpack++from cubepi.checkpointer.base import CheckpointData+from cubepi.checkpointer.postgres.exceptions import (+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)+from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION+from cubepi.providers.base import (+ AssistantMessage,+ Message,+ ToolResultMessage,+ UserMessage,+)+++_ROLE_TO_CLS: dict[str, type[Message]] = {+ "user": UserMessage,+ "assistant": AssistantMessage,+ "tool": ToolResultMessage,+}+++class PostgresCheckpointer:+ """Checkpointer backed by PostgreSQL.++ Usage:+ cp = PostgresCheckpointer(dsn="postgresql://...")+ async with cp: # initializes pool, verifies schema+ await cp.append(thread_id, [msg1, msg2])+ data = await cp.load(thread_id)+ await cp.save_extra(thread_id, {"k": "v"})+ """++ def __init__(+ self,+ dsn: str,+ *,+ min_pool_size: int = 1,+ max_pool_size: int = 10,+ ) -> None:+ self._dsn = dsn+ self._min = min_pool_size+ self._max = max_pool_size+ self._pool: asyncpg.Pool | None = None++ async def __aenter__(self) -> "PostgresCheckpointer":+ self._pool = await asyncpg.create_pool(+ self._dsn,+ min_size=self._min,+ max_size=self._max,+ )+ await self._verify_schema()+ return self++ async def __aexit__(self, *args: Any) -> None:+ if self._pool:+ await self._pool.close()+ self._pool = None++ async def _verify_schema(self) -> None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ try:+ row = await conn.fetchrow(+ "SELECT version FROM cubepi_schema_version LIMIT 1"+ )+ except asyncpg.UndefinedTableError as e:+ raise CubepiSchemaUninitialized(+ "cubepi tables not found. Run host application's alembic upgrade."+ ) from e+ if row is None:+ raise CubepiSchemaUninitialized(+ "cubepi_schema_version table is empty. Host alembic migration "+ "must INSERT the current version (use write_schema_version_op())."+ )+ if row["version"] != EXPECTED_SCHEMA_VERSION:+ raise CubepiSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=row["version"],+ hint="cubepi was upgraded but host alembic is behind. "+ "Generate a new revision and apply.",+ )++ async def load(self, thread_id: str) -> CheckpointData | None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ msg_rows = await conn.fetch(+ "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "WHERE thread_id = $1 ORDER BY seq",+ thread_id,+ )+ extra_row = await conn.fetchrow(+ "SELECT extra FROM cubepi_threads WHERE thread_id = $1",+ thread_id,+ )++ if not msg_rows and extra_row is None:+ return None++ messages: list[Message] = []+ for r in msg_rows:+ cls = _ROLE_TO_CLS.get(r["role"])+ if cls is None:+ raise ValueError(f"unknown role in DB: {r['role']!r}")+ data = msgpack.unpackb(r["payload"], raw=False)+ # Pydantic will validate; metadata column overrides what's in payload+ # (they should be equal; metadata column is the source of truth)+ data["metadata"] = json.loads(r["metadata"]) if isinstance(r["metadata"], str) else (r["metadata"] or {})+ messages.append(cls(**data))++ if extra_row is not None:+ raw_extra = extra_row["extra"]+ extra = json.loads(raw_extra) if isinstance(raw_extra, str) else (raw_extra or {})+ else:+ extra = {}++ return CheckpointData(messages=messages, extra=extra)++ async def append(self, thread_id: str, messages: list[Message]) -> None:+ if not messages:+ return+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ async with conn.transaction():+ await conn.execute(+ "SELECT pg_advisory_xact_lock(hashtext($1))", thread_id,+ )+ # Ensure thread row exists+ await conn.execute(+ "INSERT INTO cubepi_threads (thread_id) "+ "VALUES ($1) ON CONFLICT DO NOTHING",+ thread_id,+ )+ last_seq = await conn.fetchval(+ "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "+ "WHERE thread_id = $1",+ thread_id,+ ) or 0+ rows = []+ for i, m in enumerate(messages):+ seq = last_seq + i + 1+ payload = msgpack.packb(m.model_dump(mode="json"), use_bin_type=True)+ rows.append((+ thread_id, seq, m.__class__.__name__.replace(+ "Message", ""+ ).lower(), # "user"/"assistant"/"toolresult" -> map below+ json.dumps(m.metadata),+ payload,+ ))+ # Fix the role mapping — class names → "user"/"assistant"/"tool"+ role_map = {+ "user": "user",+ "assistant": "assistant",+ "toolresult": "tool",+ }+ rows = [+ (r[0], r[1], role_map[r[2]], r[3], r[4]) for r in rows+ ]+ await conn.executemany(+ "INSERT INTO cubepi_messages "+ "(thread_id, seq, role, metadata, payload) "+ "VALUES ($1, $2, $3, $4, $5)",+ rows,+ )++ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None:+ assert self._pool is not None+ async with self._pool.acquire() as conn:+ await conn.execute(+ "INSERT INTO cubepi_threads (thread_id, extra) "+ "VALUES ($1, $2::jsonb) "+ "ON CONFLICT (thread_id) DO UPDATE "+ "SET extra = cubepi_threads.extra || EXCLUDED.extra, "+ " updated_at = now()",+ thread_id, json.dumps(extra),+ )+```++NOTE: the role mapping is awkward — better to derive from the+Message subclass type directly:++```python+def _role_of(m: Message) -> str:+ if isinstance(m, UserMessage):+ return "user"+ if isinstance(m, AssistantMessage):+ return "assistant"+ if isinstance(m, ToolResultMessage):+ return "tool"+ raise TypeError(f"unknown Message type: {type(m).__name__}")+```++Use that helper in `append()`.++- [ ] **Step 3: Update `__init__.py`**++`cubepi/checkpointer/postgres/__init__.py`:++```python+from cubepi.checkpointer.postgres.checkpointer import PostgresCheckpointer+from cubepi.checkpointer.postgres.exceptions import (+ CubepiSchemaError,+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+)+from cubepi.checkpointer.postgres.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ cubepi_metadata,+)++__all__ = [+ "PostgresCheckpointer",+ "CubepiSchemaError",+ "CubepiSchemaMismatch",+ "CubepiSchemaUninitialized",+ "EXPECTED_SCHEMA_VERSION",+ "PARTITION_COUNT",+ "cubepi_metadata",+]+```++Also update top-level `cubepi/checkpointer/__init__.py` to re-export+(lazy-load to avoid hard dependency on `asyncpg`):++```python+# cubepi/checkpointer/__init__.py — keep existing exports, ADD:++def get_postgres_checkpointer():+ from cubepi.checkpointer.postgres import PostgresCheckpointer+ return PostgresCheckpointer+```++(Don't unconditionally import — `asyncpg` is in the optional+`[postgres]` extra.)++- [ ] **Step 4: Add E2E tests**++Append to `tests/checkpointer/test_postgres.py`:++```python+import pytest+import pytest_asyncio+import asyncpg++from cubepi.checkpointer.postgres import (+ CubepiSchemaMismatch,+ CubepiSchemaUninitialized,+ PostgresCheckpointer,+ cubepi_metadata,+)+from cubepi.checkpointer.postgres.alembic_helpers import (+ create_message_partitions_op,+ write_schema_version_op,+)+from cubepi.providers.base import TextContent, UserMessage, AssistantMessage, Usage+++async def _setup_schema(dsn: str) -> None:+ """Create cubepi tables + partitions + version row."""+ conn = await asyncpg.connect(dsn)+ try:+ # Use SQLAlchemy DDL to create the metadata tables+ from sqlalchemy import create_engine+ from sqlalchemy.dialects import postgresql+ engine = create_engine(dsn.replace("postgresql://", "postgresql+psycopg2://"))+ # ALTERNATIVE: emit DDL directly without an engine, using compile+ for table in cubepi_metadata.sorted_tables:+ ddl = str(+ table.compile(dialect=postgresql.dialect())+ )+ # NOTE: compile may not emit PARTITION BY — handle manually for cubepi_messages+ ...+ # Easier: manually CREATE TABLE statements that match the models+ await conn.execute("""+ 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()+ );+ """)+ await conn.execute("""+ 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);+ """)+ await conn.execute(create_message_partitions_op())+ await conn.execute("""+ CREATE INDEX ix_cubepi_messages_metadata_gin+ ON cubepi_messages USING GIN (metadata jsonb_path_ops);+ """)+ await conn.execute("""+ CREATE TABLE cubepi_schema_version (+ version INTEGER PRIMARY KEY+ );+ """)+ await conn.execute(write_schema_version_op())+ finally:+ await conn.close()+++async def test_postgres_checkpointer_round_trip(clean_db) -> None:+ await _setup_schema(clean_db)+ async with PostgresCheckpointer(clean_db) as cp:+ msg1 = UserMessage(+ content=[TextContent(text="hello")],+ metadata={"memory_snapshot": {"id": "m1"}},+ )+ msg2 = AssistantMessage(+ content=[TextContent(text="hi back")],+ usage=Usage(),+ metadata={"cost_cents": 5},+ )+ await cp.append("t-1", [msg1, msg2])+ data = await cp.load("t-1")+ assert data is not None+ assert len(data.messages) == 2+ assert data.messages[0].metadata == {"memory_snapshot": {"id": "m1"}}+ assert data.messages[1].metadata == {"cost_cents": 5}+++async def test_postgres_checkpointer_save_extra_merges(clean_db) -> None:+ await _setup_schema(clean_db)+ async with PostgresCheckpointer(clean_db) as cp:+ await cp.append("t-2", [UserMessage(content=[TextContent(text="x")])])+ await cp.save_extra("t-2", {"a": 1})+ await cp.save_extra("t-2", {"b": 2})+ data = await cp.load("t-2")+ assert data.extra == {"a": 1, "b": 2}+++async def test_postgres_checkpointer_seq_monotonic(clean_db) -> None:+ await _setup_schema(clean_db)+ async with PostgresCheckpointer(clean_db) as cp:+ msgs = [UserMessage(content=[TextContent(text=str(i))]) for i in range(5)]+ await cp.append("t-3", msgs)+ # Append another batch+ more = [UserMessage(content=[TextContent(text=str(i))]) for i in range(5, 10)]+ await cp.append("t-3", more)+ data = await cp.load("t-3")+ assert len(data.messages) == 10+ # Verify order is preserved+ assert [c.text for m in data.messages for c in m.content] == [str(i) for i in range(10)]+++async def test_uninitialized_schema_raises(clean_db) -> None:+ """Empty DB (no cubepi tables) → CubepiSchemaUninitialized."""+ with pytest.raises(CubepiSchemaUninitialized):+ async with PostgresCheckpointer(clean_db):+ pass+++async def test_version_mismatch_raises(clean_db) -> None:+ await _setup_schema(clean_db)+ # Manually set version to a wrong value+ conn = await asyncpg.connect(clean_db)+ try:+ await conn.execute("UPDATE cubepi_schema_version SET version = 999")+ finally:+ await conn.close()+ with pytest.raises(CubepiSchemaMismatch) as exc_info:+ async with PostgresCheckpointer(clean_db):+ pass+ assert exc_info.value.expected == 1+ assert exc_info.value.actual == 999+```++- [ ] **Step 5: Run tests**++Run: `pytest tests/checkpointer/test_postgres.py -v`+Expected: 9 pass (1 import + 2 helpers + 1 exception + 5 E2E).++If Postgres isn't running locally, all E2E tests will fail — skip+or set `CUBEPI_TEST_PG_DSN` first.++- [ ] **Step 6: Commit**++```bash+git add cubepi/checkpointer/postgres/checkpointer.py cubepi/checkpointer/__init__.py cubepi/checkpointer/postgres/__init__.py tests/checkpointer/+git commit -m "feat(postgres-checkpointer): implement load/append/save_extra + schema verify++PostgresCheckpointer is an async-context-managed checkpointer:+- __aenter__: open asyncpg pool, verify cubepi_schema_version matches+- load(): single PK range scan + thread extra fetch+- append(): per-thread advisory lock, monotonic seq, msgpack payload,+ metadata JSONB column kept in sync with serialized message+- save_extra(): UPSERT with JSONB || merge++Raises CubepiSchemaUninitialized / CubepiSchemaMismatch at __aenter__+when DB schema state doesn't match library version."+```++---++## D2 — MCP adapter (HTTP + stdio)++### Task D2.1: Adapter — MCP tool → cubepi.AgentTool++**Files:**+- Create: `cubepi/mcp/__init__.py`+- Create: `cubepi/mcp/_adapter.py`+- Test: `tests/mcp/test_adapter.py` (unit-test the conversion)++- [ ] **Step 1: Set up module structure**++```bash+mkdir -p cubepi/mcp+touch cubepi/mcp/__init__.py+mkdir -p tests/mcp+touch tests/mcp/__init__.py+```++- [ ] **Step 2: Write the adapter**++Create `cubepi/mcp/_adapter.py`:++```python+"""MCP tool descriptor → cubepi.AgentTool adapter."""+from __future__ import annotations++from typing import Any, Awaitable, Callable++from pydantic import BaseModel, create_model++from cubepi.agent.types import AgentTool, AgentToolResult+from cubepi.providers.base import Content, TextContent+++def mcp_schema_to_pydantic_model(+ *,+ tool_name: str,+ input_schema: dict[str, Any],+) -> type[BaseModel]:+ """Convert an MCP JSON schema to a pydantic model class.++ MCP tools advertise `inputSchema` as JSON schema. cubepi.AgentTool+ requires `parameters: type[BaseModel]`. We synthesize a model from+ the schema's top-level properties.++ Limitations: this is a minimal converter — covers string/int/bool/+ array primitives and nested dicts as dict[str, Any]. Complex schemas+ may need manual mapping.+ """+ properties = input_schema.get("properties", {})+ required = set(input_schema.get("required", []))++ fields: dict[str, Any] = {}+ for prop_name, prop_schema in properties.items():+ py_type = _json_schema_type_to_python(prop_schema)+ default = ... if prop_name in required else None+ fields[prop_name] = (py_type, default)++ model_name = f"MCP_{tool_name}_Input"+ return create_model(model_name, **fields)+++def _json_schema_type_to_python(schema: dict[str, Any]) -> Any:+ t = schema.get("type")+ if t == "string":+ return str+ if t == "integer":+ return int+ if t == "number":+ return float+ if t == "boolean":+ return bool+ if t == "array":+ item_t = _json_schema_type_to_python(schema.get("items", {}))+ return list[item_t] # type: ignore[valid-type]+ if t == "object":+ return dict[str, Any]+ return Any+++def make_mcp_agent_tool(+ *,+ name: str,+ description: str,+ input_schema: dict[str, Any],+ call_remote: Callable[[str, dict[str, Any]], Awaitable[dict[str, Any]]],+) -> AgentTool:+ """Build a cubepi.AgentTool wrapping an MCP tool call.++ call_remote is the transport-specific RPC: given (tool_name, args_dict),+ returns the MCP tools/call response dict.+ """+ parameters_model = mcp_schema_to_pydantic_model(+ tool_name=name, input_schema=input_schema,+ )++ async def _execute(args) -> AgentToolResult:+ # args is an instance of parameters_model+ args_dict = args.model_dump() if hasattr(args, "model_dump") else dict(args)+ result = await call_remote(name, args_dict)+ # MCP tools/call response shape: {"content": [{"type": "text", "text": "..."}], "isError": bool}+ content_blocks: list[Content] = []+ for c in result.get("content", []):+ if c.get("type") == "text":+ content_blocks.append(TextContent(text=c.get("text", "")))+ # extend for image/audio/resource as needed+ return AgentToolResult(+ content=content_blocks,+ details={"raw_mcp_response": result},+ )++ return AgentTool(+ name=name,+ description=description,+ parameters=parameters_model,+ execute=_execute,+ )+```++- [ ] **Step 3: Unit tests for the adapter**++Create `tests/mcp/test_adapter.py`:++```python+"""MCP adapter tests."""++import pytest++from cubepi.mcp._adapter import (+ make_mcp_agent_tool,+ mcp_schema_to_pydantic_model,+)+++def test_schema_to_model_required_fields() -> None:+ schema = {+ "type": "object",+ "properties": {+ "city": {"type": "string"},+ "limit": {"type": "integer"},+ },+ "required": ["city"],+ }+ M = mcp_schema_to_pydantic_model(tool_name="search", input_schema=schema)+ # Required field+ instance = M(city="Tokyo")+ assert instance.city == "Tokyo"+ assert instance.limit is None+++def test_schema_to_model_array_field() -> None:+ schema = {+ "type": "object",+ "properties": {+ "tags": {"type": "array", "items": {"type": "string"}},+ },+ "required": ["tags"],+ }+ M = mcp_schema_to_pydantic_model(tool_name="tag", input_schema=schema)+ instance = M(tags=["a", "b"])+ assert instance.tags == ["a", "b"]+++async def test_make_mcp_agent_tool_routes_to_call_remote() -> None:+ called_with: dict = {}++ async def _fake_call(name, args):+ called_with["name"] = name+ called_with["args"] = args+ return {+ "content": [{"type": "text", "text": "result"}],+ "isError": False,+ }++ tool = make_mcp_agent_tool(+ name="search",+ description="Search the web",+ input_schema={+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ call_remote=_fake_call,+ )+ assert tool.name == "search"+ args_instance = tool.parameters(query="cats")+ result = await tool.execute(args_instance)+ assert called_with == {"name": "search", "args": {"query": "cats"}}+ assert result.content[0].text == "result"+```++- [ ] **Step 4: Run tests**++Run: `pytest tests/mcp/test_adapter.py -v`+Expected: 3 pass.++- [ ] **Step 5: Commit**++```bash+git add cubepi/mcp/ tests/mcp/+git commit -m "feat(mcp): add MCP tool → cubepi.AgentTool adapter++mcp_schema_to_pydantic_model converts MCP inputSchema (JSON Schema) to a+pydantic model class for cubepi.AgentTool.parameters.++make_mcp_agent_tool builds an AgentTool wrapping a transport-agnostic+call_remote callable. HTTP and stdio loaders (next tasks) use this."+```++### Task D2.2: HTTP MCP loader++**Files:**+- Create: `cubepi/mcp/http_loader.py`+- Test: `tests/mcp/test_http_loader.py`++- [ ] **Step 1: Add fake HTTP MCP server fixture**++Create `tests/mcp/conftest.py`:++```python+"""MCP test fixtures: fake HTTP server, fake stdio server."""++import asyncio+import json+from typing import Any++import pytest+import pytest_asyncio+++class FakeMCPHTTPServer:+ """Minimal MCP HTTP/SSE server for testing.++ Advertises a fixed tool list and responds to tools/call.+ """++ def __init__(self, tools: list[dict[str, Any]]) -> None:+ self.tools = tools+ self.calls: list[tuple[str, dict]] = []++ async def handle(self, request_body: dict) -> dict:+ method = request_body.get("method")+ if method == "tools/list":+ return {"result": {"tools": self.tools}}+ if method == "tools/call":+ params = request_body.get("params", {})+ self.calls.append((params.get("name"), params.get("arguments", {})))+ return {+ "result": {+ "content": [{"type": "text", "text": f"called {params.get('name')}"}],+ "isError": False,+ }+ }+ return {"error": {"code": -32601, "message": "Method not found"}}+++# Actual HTTP server spinning requires aiohttp/starlette; use respx-style mock+# OR a real fastapi TestClient. The simplest approach: skip a real network+# server for unit-level coverage and test http_loader via injecting a+# call_remote stub. Real-network E2E lives in tests/mcp/test_http_loader.py+# using `mcp` SDK's own test fixtures if available.++def fake_mcp_server_tools() -> list[dict[str, Any]]:+ return [+ {+ "name": "echo",+ "description": "Echo the input back",+ "inputSchema": {+ "type": "object",+ "properties": {"text": {"type": "string"}},+ "required": ["text"],+ },+ },+ ]+```++- [ ] **Step 2: Write the HTTP loader**++Create `cubepi/mcp/http_loader.py`:++```python+"""HTTP/SSE transport MCP tool loader."""+from __future__ import annotations++from typing import Any++from cubepi.agent.types import AgentTool+from cubepi.mcp._adapter import make_mcp_agent_tool+++async def load_mcp_tools_http(+ server_url: str,+ *,+ headers: dict[str, str] | None = None,+ timeout: float = 30.0,+) -> list[AgentTool]:+ """Connect to an HTTP/SSE MCP server, discover tools, return AgentTools.++ Uses the `mcp` SDK's HTTP client. Each returned AgentTool's execute+ method invokes tools/call via the live session.+ """+ from mcp import ClientSession+ from mcp.client.sse import sse_client++ # Open a persistent session for the lifetime of these tools.+ # NOTE: callers must keep the returned tools' associated session alive.+ # In v1 we use a simple per-tool session — connection cost per call.+ # Optimization (later): pool / per-loader session.++ async def _call_remote(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:+ async with sse_client(server_url, headers=headers, timeout=timeout) 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)++ # Initial connection just to discover tools.+ async with sse_client(server_url, headers=headers, timeout=timeout) as streams:+ async with ClientSession(*streams) as session:+ await session.initialize()+ tools_resp = await session.list_tools()+ tool_descs = tools_resp.tools++ agent_tools: list[AgentTool] = []+ for desc in tool_descs:+ agent_tools.append(make_mcp_agent_tool(+ name=desc.name,+ description=desc.description or "",+ input_schema=desc.inputSchema or {"type": "object", "properties": {}},+ call_remote=_call_remote,+ ))+ return agent_tools+++def _serialize_call_tool_response(resp: Any) -> dict[str, Any]:+ """Normalize mcp SDK response object → dict for adapter."""+ return {+ "content": [+ {"type": "text", "text": c.text}+ for c in (resp.content or [])+ if getattr(c, "type", None) == "text"+ ],+ "isError": bool(getattr(resp, "isError", False)),+ }+```++- [ ] **Step 3: Integration test (skipped if mcp SDK testing complex)**++Create `tests/mcp/test_http_loader.py`:++```python+"""HTTP MCP loader integration test.++Requires a running MCP test server or careful mocking. v1 strategy:+skip if no test server URL is configured; provide explicit env var+to point at a real fake server for CI.+"""++import os+import pytest+++async def test_load_mcp_tools_http_against_test_server() -> None:+ """End-to-end: connect to a real MCP test server, list + call a tool."""+ server_url = os.environ.get("CUBEPI_TEST_MCP_HTTP_URL")+ if not server_url:+ pytest.skip("Set CUBEPI_TEST_MCP_HTTP_URL to run this test")++ from cubepi.mcp import load_mcp_tools_http+ tools = await load_mcp_tools_http(server_url)+ assert len(tools) > 0+ # Smoke: at least one tool is callable+ first = tools[0]+ assert first.name+ assert first.description+```++(Real MCP integration testing needs either a running test server or+mocking the mcp SDK internals. Mocking the SDK is brittle. Recommend+spinning up a tiny stdio-MCP test server for both transports — see+D2.3.)++- [ ] **Step 4: Smoke-import test**++Append to `tests/mcp/test_http_loader.py`:++```python+def test_import_http_loader() -> None:+ from cubepi.mcp import load_mcp_tools_http+ assert callable(load_mcp_tools_http)+```++- [ ] **Step 5: Run tests**++Run: `pytest tests/mcp/test_http_loader.py -v`+Expected: 1 pass (smoke), 1 skip (no test server URL).++- [ ] **Step 6: Commit**++```bash+git add cubepi/mcp/http_loader.py tests/mcp/test_http_loader.py tests/mcp/conftest.py+git commit -m "feat(mcp): add HTTP/SSE MCP tool loader++load_mcp_tools_http(server_url, headers=, timeout=) discovers tools+from an MCP server via SSE and returns them as cubepi.AgentTool list.+Each tool's execute opens a fresh session per call (v1 simplicity);+later optimization: persistent session pool."+```++### Task D2.3: stdio MCP loader++**Files:**+- Create: `cubepi/mcp/stdio_loader.py`+- Modify: `cubepi/mcp/__init__.py` to export both loaders+- Test: `tests/mcp/test_stdio_loader.py`++- [ ] **Step 1: Implement stdio loader**++Create `cubepi/mcp/stdio_loader.py`:++```python+"""stdio transport MCP tool loader."""+from __future__ import annotations++from typing import Any++from cubepi.agent.types import AgentTool+from cubepi.mcp._adapter import make_mcp_agent_tool+++async def load_mcp_tools_stdio(+ command: str,+ args: list[str],+ *,+ env: dict[str, str] | None = None,+ cwd: str | None = None,+ timeout: float = 30.0,+) -> list[AgentTool]:+ """Spawn a stdio MCP server subprocess, discover tools, return AgentTools.++ Uses the `mcp` SDK's stdio client. Each returned tool's execute+ opens a fresh subprocess per call (v1 simplicity).+ """+ from mcp import ClientSession, StdioServerParameters+ from mcp.client.stdio import stdio_client++ server_params = StdioServerParameters(+ command=command, args=args, env=env, cwd=cwd,+ )++ async def _call_remote(tool_name: str, args_dict: dict[str, Any]) -> dict[str, Any]:+ async with stdio_client(server_params) as streams:+ async with ClientSession(*streams) as session:+ await session.initialize()+ resp = await session.call_tool(tool_name, args_dict)+ return _serialize_call_tool_response(resp)++ async with stdio_client(server_params) as streams:+ async with ClientSession(*streams) as session:+ await session.initialize()+ tools_resp = await session.list_tools()+ tool_descs = tools_resp.tools++ agent_tools: list[AgentTool] = []+ for desc in tool_descs:+ agent_tools.append(make_mcp_agent_tool(+ name=desc.name,+ description=desc.description or "",+ input_schema=desc.inputSchema or {"type": "object", "properties": {}},+ call_remote=_call_remote,+ ))+ return agent_tools+++def _serialize_call_tool_response(resp: Any) -> dict[str, Any]:+ return {+ "content": [+ {"type": "text", "text": c.text}+ for c in (resp.content or [])+ if getattr(c, "type", None) == "text"+ ],+ "isError": bool(getattr(resp, "isError", False)),+ }+```++- [ ] **Step 2: Update `__init__.py`**++`cubepi/mcp/__init__.py`:++```python+from cubepi.mcp.http_loader import load_mcp_tools_http+from cubepi.mcp.stdio_loader import load_mcp_tools_stdio++__all__ = ["load_mcp_tools_http", "load_mcp_tools_stdio"]+```++- [ ] **Step 3: Integration test using a fake stdio server**++Create `tests/mcp/_fake_stdio_server.py` — a minimal MCP-protocol-+speaking Python script. It will be run as a subprocess by the test:++```python+"""Minimal stdio MCP server for tests.++Implements just enough of the MCP protocol to: respond to initialize,+list one 'echo' tool, and respond to tools/call for that tool.++Invoke: python -m tests.mcp._fake_stdio_server+"""+import json+import sys+++def _read_message() -> dict:+ line = sys.stdin.readline()+ if not line:+ return None+ return json.loads(line)+++def _send_message(msg: dict) -> None:+ sys.stdout.write(json.dumps(msg) + "\n")+ sys.stdout.flush()+++def main() -> None:+ while True:+ msg = _read_message()+ if msg is None:+ return+ method = msg.get("method")+ msg_id = msg.get("id")+ if method == "initialize":+ _send_message({+ "jsonrpc": "2.0",+ "id": msg_id,+ "result": {+ "protocolVersion": "2024-11-05",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "fake", "version": "0.1"},+ },+ })+ elif method == "tools/list":+ _send_message({+ "jsonrpc": "2.0",+ "id": msg_id,+ "result": {+ "tools": [{+ "name": "echo",+ "description": "echo input",+ "inputSchema": {+ "type": "object",+ "properties": {"text": {"type": "string"}},+ "required": ["text"],+ },+ }]+ }+ })+ elif method == "tools/call":+ params = msg.get("params", {})+ args = params.get("arguments", {})+ _send_message({+ "jsonrpc": "2.0",+ "id": msg_id,+ "result": {+ "content": [{"type": "text", "text": args.get("text", "")}],+ "isError": False,+ },+ })+ elif method == "notifications/initialized":+ # No response expected+ continue+ else:+ _send_message({"jsonrpc": "2.0", "id": msg_id, "error": {+ "code": -32601, "message": "Method not found"+ }})+++if __name__ == "__main__":+ main()+```++NOTE: real MCP protocol is more nuanced — the above may need+adjustments to actually work with the mcp SDK client. If the SDK+expects framed messages or a different newline convention, adapt.+Alternative: use the mcp SDK's own server primitives to build a+test server.++- [ ] **Step 4: Test against the fake stdio server**++Create `tests/mcp/test_stdio_loader.py`:++```python+"""stdio MCP loader integration test."""++import sys++import pytest++from cubepi.mcp import load_mcp_tools_stdio+++async def test_stdio_loader_against_fake_server() -> None:+ """Load the fake stdio server, discover the 'echo' tool, invoke it."""+ tools = await load_mcp_tools_stdio(+ command=sys.executable,+ args=["-m", "tests.mcp._fake_stdio_server"],+ )+ assert len(tools) == 1+ echo = tools[0]+ assert echo.name == "echo"+ result = await echo.execute(echo.parameters(text="hello"))+ assert result.content[0].text == "hello"+++def test_import_stdio_loader() -> None:+ from cubepi.mcp import load_mcp_tools_stdio+ assert callable(load_mcp_tools_stdio)+```++- [ ] **Step 5: Run tests**++Run: `pytest tests/mcp/ -v`+Expected: 1 import test passes; integration test may need adjustment+to fake server protocol — iterate until it passes.++- [ ] **Step 6: Run full suite**++Run: `pytest tests/ -q --tb=no`+Expected: baseline + all new MCP tests.++- [ ] **Step 7: Commit**++```bash+git add cubepi/mcp/stdio_loader.py cubepi/mcp/__init__.py tests/mcp/+git commit -m "feat(mcp): add stdio MCP tool loader++load_mcp_tools_stdio(command, args, env=, cwd=) spawns an MCP server+subprocess via stdio, lists tools, and returns cubepi.AgentTool list.+Each tool's execute opens a fresh subprocess per call (v1 simplicity).++Tested via tests/mcp/_fake_stdio_server.py — a minimal Python-script+MCP server."+```++---++## D9 — Packaging extras++### Task D9.1: Add `[postgres]` and `[mcp]` extras++**Files:**+- Modify: `pyproject.toml`++- [ ] **Step 1: Add extras**++Edit `pyproject.toml`, find `[project.optional-dependencies]`:++```toml+[project.optional-dependencies]+sqlite = ["aiosqlite>=0.19"]+postgres = ["sqlalchemy>=2.0", "asyncpg>=0.29", "msgpack>=1.0"]+mcp = ["mcp>=1.0"]+```++For dev tooling, ensure `respx` and `pytest-httpx` are available in+`[project.optional-dependencies] dev` (or wherever cubepi currently+lists dev deps):++```toml+dev = [+ # ... existing dev deps ...+ "respx>=0.20",+]+```++- [ ] **Step 2: Lock dependencies**++Run: `uv lock`+Expected: lockfile updates with new extras.++- [ ] **Step 3: Verify installable**++```bash+uv sync --extra postgres --extra mcp --extra dev+```++Expected: clean install, no conflicts.++- [ ] **Step 4: Run full suite under fresh env**++Run: `pytest tests/ -q --tb=no`+Expected: all tests pass.++- [ ] **Step 5: Commit**++```bash+git add pyproject.toml uv.lock+git commit -m "feat(packaging): add [postgres] and [mcp] optional extras++[postgres] = sqlalchemy>=2.0, asyncpg>=0.29, msgpack>=1.0+[mcp] = mcp>=1.0++cubepi base install remains lean. Downstreams opt in:+ cubepi[postgres] for PostgresCheckpointer+ cubepi[mcp] for HTTP+stdio MCP tool loaders+ cubepi[postgres,mcp] both"+```++---++## Final integration++### Task Final.1: Run acceptance criteria from spec++**Files:** none new++- [ ] **Step 1: Verify spec acceptance A1-A14**++Walk through each criterion in `docs/specs/2026-05-13-cubepi-cubebox-readiness-design.md` § "Acceptance criteria":++| # | Check | Run |+|---|---|---|+| A1 | PostgresCheckpointer round-trip | `pytest tests/checkpointer/test_postgres.py::test_postgres_checkpointer_round_trip` |+| A2 | Schema version check on uninit / mismatch | `pytest tests/checkpointer/test_postgres.py::test_uninitialized_schema_raises tests/checkpointer/test_postgres.py::test_version_mismatch_raises` |+| A3 | 64 partitions, route + read correctly | `pytest tests/checkpointer/test_postgres.py::test_postgres_checkpointer_seq_monotonic` (large append should hit multiple partitions if test_setup uses multiple thread_ids) |+| A4 | MCP HTTP loader | `pytest tests/mcp/test_http_loader.py` (set CUBEPI_TEST_MCP_HTTP_URL for full E2E) |+| A5 | MCP stdio loader | `pytest tests/mcp/test_stdio_loader.py::test_stdio_loader_against_fake_server` |+| A6 | AnthropicProvider with custom cache_policy | `pytest tests/providers/test_anthropic_cache_policy.py::test_custom_policy_drives_message_marker_placement` |+| A7 | AnthropicProvider without cache_policy preserves v0.2 | `pytest tests/providers/test_anthropic.py` |+| A8 | OpenAIProvider 3 reasoning variants | `pytest tests/providers/test_openai_reasoning.py` |+| A9 | OpenAIProvider payload_quirks | `pytest tests/providers/test_openai_reasoning.py::test_max_completion_tokens_alias_rewrite` |+| A10 | Message.metadata round-trip | `pytest tests/providers/test_message_metadata.py` |+| A11 | AgentContext.extra persists | `pytest tests/agent/test_context_extra.py` |+| A12 | transform_system_prompt chain | `pytest tests/middleware/test_transform_system_prompt.py` |+| A13 | after_model_response chain composition | `pytest tests/middleware/test_after_model_response.py` |+| A14 | Full suite, no regressions | `pytest tests/ -q --tb=no` |++- [ ] **Step 2: Run them all**++Run: `pytest tests/ -q --tb=short`+Expected: every acceptance criterion check passes.++- [ ] **Step 3: Manual smoke test**++Open Python REPL with `cubepi[postgres,mcp]` installed:++```python+import asyncio++async def smoke():+ from cubepi import Agent, Model+ from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubepi.middleware.base import Middleware, TurnAction++ # Custom middleware exercising new hooks+ class _SmokeMW(Middleware):+ async def transform_system_prompt(self, sp, *, signal=None):+ return sp + "\n[smoke]"++ async def after_model_response(self, response, ctx, *, signal=None):+ ctx.extra["smoke_seen"] = True+ return TurnAction()++ provider = FauxProvider()+ provider.set_responses([faux_assistant_message("ok")])+ agent = Agent(+ model=Model(provider=provider, model="test"),+ system_prompt="base",+ middleware=[_SmokeMW()],+ )+ stream = await agent.prompt("hi")+ async for _ in stream:+ pass+ print("smoke passed")++asyncio.run(smoke())+```++Expected: prints "smoke passed".++- [ ] **Step 4: Open PR**++```bash+git push -u origin feat/cubebox-readiness+gh pr create --title "feat: cubebox-readiness — Postgres checkpointer, MCP, middleware extensions" --body "$(cat <<'EOF'+## Summary++Implements 9 deliverables (D1-D9) per `docs/specs/2026-05-13-cubepi-cubebox-readiness-design.md`:++- D1 PostgresCheckpointer (3 tables, HASH partition x64, schema version check)+- D2 MCP HTTP + stdio loaders → cubepi.AgentTool+- D3 AnthropicProvider configurable CacheMarkerPolicy+- D4 OpenAIProvider OSS reasoning extraction (3 variants) + payload_quirks+- D5 Message.metadata field on all three Message types+- D6 AgentContext.extra mutable dict + agent-loop persistence+- D7 transform_system_prompt middleware hook (chain composition)+- D8 after_model_response hook + TurnAction (chain, with control flow)+- D9 [postgres] and [mcp] optional extras++All additions backward-compatible with v0.2.0 — existing users see no+behavior change.++## Test plan++- [x] All existing tests pass (no regressions)+- [x] PostgresCheckpointer E2E against local PG+- [x] MCP stdio loader E2E against bundled fake server+- [x] All new middleware hooks unit-tested+- [x] OpenAI reasoning extraction tested against all 3 variants++## Consumer++cubebox depends on this via path dep (`uv add --editable ~/cubepi`)+during its main agent migration. See cubebox `docs/superpowers/specs/+2026-05-13-cubepi-main-agent-migration-design.md`.+EOF+)"+```++---++## Self-review checklist++After completing all tasks:++- [ ] Every D-item from spec has a corresponding task: D1 (D1.1-D1.3), D2 (D2.1-D2.3), D3 (D3.1-D3.2), D4 (D4.1-D4.2), D5 (D5.1-D5.2), D6 (D6.1-D6.2), D7 (D7.1-D7.2), D8 (D8.1-D8.2), D9 (D9.1) ✅+- [ ] No placeholders ("TBD", "TODO", "Add tests", "implement later") in the plan ✅+- [ ] All file paths concrete and absolute under `cubepi/` and `tests/` ✅+- [ ] Code shown in every step that modifies code ✅+- [ ] Commit messages drafted ✅+- [ ] Acceptance criteria from spec map to specific test commands ✅diff --git a/dev/plans/2026-05-15-cubepi-docs-site.md b/dev/plans/2026-05-15-cubepi-docs-site.mdnew file mode 100644index 0000000..fbca28c--- /dev/null+++ b/dev/plans/2026-05-15-cubepi-docs-site.md@@ -0,0 +1,2351 @@+# CubePi Documentation Site Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Build the first public CubePi documentation site under `website/`, with versioning, EN + zh-Hans i18n, page-level PostHog feedback, a custom Operator-styled homepage, and an auto-generated API reference via `griffe`. Deploy to Cloudflare Pages on every push to `main`.++**Architecture:** Docusaurus 3.x lives in a `website/` subdirectory peer to the Python package. Python tooling (`uv` + `griffe`) feeds an auto-generated MDX API reference into the Docusaurus content tree at build time. The custom homepage is React + a hand-tuned CSS-token system in the Operator design language. PostHog is wired through a Docusaurus client module; a swizzled `theme/DocItem/Footer` mounts a 👍/👎 component that captures events directly. CI runs build-and-check on every PR (with broken-link / anchor / spelling guards) and deploys via `cloudflare/pages-action@v1` on `main`.++**Tech Stack:** Docusaurus 3.x, TypeScript, React, pnpm 9, Node 22, Python 3.11 + `uv`, `griffe>=0.45`, PostHog JS SDK, Cloudflare Pages, GitHub Actions.++**Spec:** `docs/specs/2026-05-15-cubepi-docs-site-design.md`++---++## Phase 0 — Repo prep++### Task 1: Migrate brand assets to `website/static/img/brand/`++**Files:**+- Move (4): `assets/brand/cubepi-logo.svg`, `assets/brand/cubepi-logo.png`, `assets/brand/cubepi-social-preview.svg`, `assets/brand/cubepi-social-preview.png` → `website/static/img/brand/`+- Delete: `assets/brand/` (after move)+- Delete: `assets/` (if empty after delete)+- Modify: `README.md` — image references++- [ ] **Step 1: Create the destination directory**++```bash+mkdir -p website/static/img/brand+```++- [ ] **Step 2: Move every brand asset**++```bash+git mv assets/brand/cubepi-logo.svg website/static/img/brand/cubepi-logo.svg+git mv assets/brand/cubepi-logo.png website/static/img/brand/cubepi-logo.png+git mv assets/brand/cubepi-social-preview.svg website/static/img/brand/cubepi-social-preview.svg+git mv assets/brand/cubepi-social-preview.png website/static/img/brand/cubepi-social-preview.png+```++- [ ] **Step 3: Remove empty old directories**++```bash+rmdir assets/brand 2>/dev/null+rmdir assets 2>/dev/null+```++- [ ] **Step 4: Update README image references**++Replace every occurrence of `assets/brand/` with `website/static/img/brand/` in `README.md`. Verify with:++```bash+grep -n 'assets/brand' README.md+```++Expected: no output. Then verify the new paths resolve:++```bash+grep -n 'website/static/img/brand' README.md+```++Expected: at least 1 hit (the top-of-file logo).++- [ ] **Step 5: Commit**++```bash+git add -A+git commit -m "chore: relocate brand assets under website/static/img/brand/"+```++---++### Task 2: Ignore Docusaurus build artefacts++**Files:**+- Modify: `.gitignore`++- [ ] **Step 1: Append website rules**++Add at the end of `.gitignore`:++```+# Docusaurus+website/.docusaurus/+website/build/+website/node_modules/+website/docs/api/*.mdx+!website/docs/api/_index.mdx+```++- [ ] **Step 2: Verify**++```bash+tail -8 .gitignore+```++Expected: shows the new block.++- [ ] **Step 3: Commit**++```bash+git add .gitignore+git commit -m "chore: ignore website/ build artefacts and generated api MDX"+```++---++## Phase 1 — Docusaurus scaffold++### Task 3: Scaffold Docusaurus TypeScript project++**Files:**+- Create: `website/package.json`, `website/tsconfig.json`, `website/docusaurus.config.ts`, `website/sidebars.ts`, `website/src/css/custom.css`, `website/src/pages/index.tsx`, `website/docs/intro.md`, etc. (created by template)+- Modify: subsequent tasks overwrite many of these.++- [ ] **Step 1: Run the classic-TS template**++From repo root:++```bash+pnpm dlx create-docusaurus@latest website classic --typescript+```++When prompted, accept defaults.++- [ ] **Step 2: Verify the dev server boots**++```bash+cd website && pnpm install && pnpm start --no-open+```++Expected: console prints `[SUCCESS] Docusaurus website is running at: http://localhost:3000/`. Hit `Ctrl+C` once verified.++- [ ] **Step 3: Replace generated `docusaurus.config.ts`**++Overwrite `website/docusaurus.config.ts` with:++```ts+import type { Config } from '@docusaurus/types';+import { themes as prismThemes } from 'prism-react-renderer';++const POSTHOG_KEY = process.env.POSTHOG_KEY ?? '';+const POSTHOG_HOST = process.env.POSTHOG_HOST ?? 'https://us.i.posthog.com';+const GIT_SHA = process.env.GITHUB_SHA?.slice(0, 7) ?? 'dev';++const config: Config = {+ title: 'CubePi',+ tagline: 'A Pythonic, async-native agent framework',+ favicon: 'img/brand/cubepi-logo.svg',++ url: 'https://cubepi.pages.dev',+ baseUrl: '/',+ organizationName: 'cubeplexai',+ projectName: 'cubepi',++ onBrokenLinks: 'throw',+ onBrokenAnchors: 'throw',+ onBrokenMarkdownLinks: 'throw',++ i18n: {+ defaultLocale: 'en',+ locales: ['en', 'zh-Hans'],+ localeConfigs: {+ en: { label: 'English' },+ 'zh-Hans':{ label: '简体中文' },+ },+ },++ customFields: { POSTHOG_KEY, POSTHOG_HOST, GIT_SHA },++ clientModules: [require.resolve('./src/clientModules/posthog.ts')],++ presets: [+ ['classic', {+ docs: {+ sidebarPath: './sidebars.ts',+ editUrl: 'https://github.com/cubeplexai/cubepi/edit/main/website/',+ lastVersion: 'current',+ versions: {+ current: { label: 'Next 🚧', path: 'next', banner: 'unreleased' },+ },+ },+ blog: false,+ theme: {+ customCss: './src/css/custom.css',+ },+ } satisfies import('@docusaurus/preset-classic').Options],+ ],++ themeConfig: {+ image: 'img/brand/cubepi-social-preview.png',+ navbar: {+ title: 'CubePi',+ logo: { alt: 'CubePi logo', src: 'img/brand/cubepi-logo.svg' },+ items: [+ { to: '/getting-started/installation', label: 'Docs', position: 'left' },+ { to: '/api/', label: 'API', position: 'left' },+ { to: '/recipes/', label: 'Recipes', position: 'left' },+ { type: 'docsVersionDropdown', position: 'right' },+ { type: 'localeDropdown', position: 'right' },+ { href: 'https://github.com/cubeplexai/cubepi', label: 'GitHub', position: 'right' },+ ],+ },+ prism: {+ theme: prismThemes.github,+ darkTheme: prismThemes.dracula,+ additionalLanguages: ['python', 'bash', 'toml'],+ },+ colorMode: { defaultMode: 'light', respectPrefersColorScheme: true },+ },+};++export default config;+```++(Task 5 wires versioning to `0.3` once the first snapshot is taken. For now we run with `current` only.)++- [ ] **Step 4: Confirm config compiles**++```bash+cd website && pnpm build+```++Expected: `[SUCCESS] Generated static files in "build".` Two warnings about `clientModules` / `versionDropdown` referencing files-that-don't-exist-yet are normal — we'll add them in later tasks. **If the build errors**, fix the path before continuing.++- [ ] **Step 5: Stage and commit the scaffold**++```bash+git add website/+git commit -m "feat(website): scaffold Docusaurus 3 with TS preset and base config"+```++---++### Task 4: Add the `docs` Python extra with `griffe`++**Files:**+- Modify: `pyproject.toml:24-35`++- [ ] **Step 1: Add the extra**++After the `mcp = [...]` block in `[project.optional-dependencies]`, append:++```toml+docs = [+ "griffe>=0.45",+]+```++- [ ] **Step 2: Sync and verify import**++```bash+uv sync --extra docs+uv run python -c "import griffe; print(griffe.__version__)"+```++Expected: a version string ≥ 0.45.++- [ ] **Step 3: Commit**++```bash+git add pyproject.toml uv.lock+git commit -m "build(deps): add docs extra with griffe>=0.45 for API reference generation"+```++---++## Phase 2 — Operator design tokens & fonts++### Task 5: Self-host fonts++**Files:**+- Create (6): `website/static/fonts/Inter-Regular.woff2`, `website/static/fonts/Inter-Medium.woff2`, `website/static/fonts/Inter-SemiBold.woff2`, `website/static/fonts/InterTight-SemiBold.woff2`, `website/static/fonts/JetBrainsMono-Regular.woff2`, `website/static/fonts/JetBrainsMono-Medium.woff2`++- [ ] **Step 1: Fetch font files**++Use Fontsource CDN sources (Apache 2.0 / OFL). Run from repo root:++```bash+mkdir -p website/static/fonts+cd website/static/fonts++curl -L -o Inter-Regular.woff2 'https://cdn.jsdelivr.net/fontsource/fonts/inter@latest/latin-400-normal.woff2'+curl -L -o Inter-Medium.woff2 'https://cdn.jsdelivr.net/fontsource/fonts/inter@latest/latin-500-normal.woff2'+curl -L -o Inter-SemiBold.woff2 'https://cdn.jsdelivr.net/fontsource/fonts/inter@latest/latin-600-normal.woff2'+curl -L -o InterTight-SemiBold.woff2 'https://cdn.jsdelivr.net/fontsource/fonts/inter-tight@latest/latin-600-normal.woff2'+curl -L -o JetBrainsMono-Regular.woff2 'https://cdn.jsdelivr.net/fontsource/fonts/jetbrains-mono@latest/latin-400-normal.woff2'+curl -L -o JetBrainsMono-Medium.woff2 'https://cdn.jsdelivr.net/fontsource/fonts/jetbrains-mono@latest/latin-500-normal.woff2'+```++- [ ] **Step 2: Verify all six files exist and are non-zero**++```bash+ls -lh website/static/fonts/+```++Expected: 6 entries, each between 20–80 KB.++- [ ] **Step 3: Commit**++```bash+git add website/static/fonts/+git commit -m "feat(website): self-host Inter, Inter Tight, JetBrains Mono"+```++---++### Task 6: Apply Operator design tokens++**Files:**+- Overwrite: `website/src/css/custom.css`++- [ ] **Step 1: Replace `custom.css` with Operator tokens**++```css+/* ============== Fonts ============== */+@font-face { font-family: 'Inter'; src: url('/fonts/Inter-Regular.woff2') format('woff2'); font-weight: 400; font-display: swap; }+@font-face { font-family: 'Inter'; src: url('/fonts/Inter-Medium.woff2') format('woff2'); font-weight: 500; font-display: swap; }+@font-face { font-family: 'Inter'; src: url('/fonts/Inter-SemiBold.woff2') format('woff2'); font-weight: 600; font-display: swap; }+@font-face { font-family: 'Inter Tight'; src: url('/fonts/InterTight-SemiBold.woff2') format('woff2'); font-weight: 600; font-display: swap; }+@font-face { font-family: 'JetBrains Mono'; src: url('/fonts/JetBrainsMono-Regular.woff2') format('woff2'); font-weight: 400; font-display: swap; }+@font-face { font-family: 'JetBrains Mono'; src: url('/fonts/JetBrainsMono-Medium.woff2') format('woff2'); font-weight: 500; font-display: swap; }++/* ============== Operator tokens ============== */+:root {+ --ink-12: #0a0a0b;+ --ink-11: #1f1f22;+ --ink-9: #52525b;+ --ink-7: #a1a1aa;+ --ink-5: #e4e4e7;+ --ink-3: #f4f4f5;+ --ink-1: #fafafa;+ --surface: #ffffff;+ --accent: #3b5bd9;+ --accent-soft: #eef1fe;+ --accent-ink: #1e3aa8;+ --ok: #16a34a;+ --warn: #d97706;+ --err: #dc2626;++ /* Docusaurus overrides */+ --ifm-color-primary: var(--accent);+ --ifm-color-primary-dark: #2f4fc4;+ --ifm-color-primary-darker: #2c4abc;+ --ifm-color-primary-darkest: #243d9b;+ --ifm-color-primary-light: #5470de;+ --ifm-color-primary-lighter: #6a83e3;+ --ifm-color-primary-lightest: #93a6ec;+ --ifm-background-color: var(--ink-1);+ --ifm-background-surface-color: var(--surface);+ --ifm-color-content: var(--ink-11);+ --ifm-heading-color: var(--ink-12);+ --ifm-font-family-base: 'Inter', system-ui, -apple-system, sans-serif;+ --ifm-heading-font-family: 'Inter Tight', 'Inter', system-ui;+ --ifm-font-family-monospace: 'JetBrains Mono', ui-monospace, monospace;+ --ifm-font-size-base: 14px;+ --ifm-line-height-base: 1.55;+ --ifm-navbar-height: 56px;+ --ifm-navbar-background-color: var(--surface);+ --ifm-navbar-shadow: none;+ --ifm-toc-border-color: var(--ink-5);+ --ifm-hr-border-color: var(--ink-5);+ --ifm-code-font-size: 92%;+ --docusaurus-highlighted-code-line-bg: var(--ink-3);+}++[data-theme='dark'] {+ --ink-12: #f4f4f5;+ --ink-11: #e4e4e7;+ --ink-9: #a1a1aa;+ --ink-7: #71717a;+ --ink-5: #3f3f46;+ --ink-3: #27272a;+ --ink-1: #18181b;+ --surface: #0a0a0b;+ --accent: #6a83e3;+ --accent-soft: #1e3aa820;+ --accent-ink: #93a6ec;+ --ifm-color-primary: var(--accent);+ --ifm-background-color: var(--ink-1);+ --ifm-background-surface-color: var(--surface);+}++html, body { font-feature-settings: 'cv11', 'ss01'; -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }++/* No shadows except modals (which Docusaurus does not use in docs). */+.navbar { border-bottom: 1px solid var(--ink-5); }+.menu__link, .navbar__link { font-weight: 500; }+.menu__link--active, .navbar__link--active { color: var(--accent); }++/* Tabular numerals globally in code and tables */+code, pre, table td.num, .num { font-variant-numeric: tabular-nums; }+```++- [ ] **Step 2: Rebuild and visually inspect**++```bash+cd website && pnpm start --no-open+```++Open `http://localhost:3000` in a browser. Expected: the default Docusaurus homepage now uses Inter Tight headings, ink-1 background, and the `#3b5bd9` accent on links. Hit `Ctrl+C` when satisfied.++- [ ] **Step 3: Commit**++```bash+git add website/src/css/custom.css+git commit -m "feat(website): apply Operator design tokens and Docusaurus overrides"+```++---++## Phase 3 — Content scaffold (English)++### Task 7: Replace default content with the IA skeleton++**Files:**+- Delete: every file under `website/docs/` produced by the template (`intro.md`, `tutorial-basics/`, `tutorial-extras/`).+- Delete: `website/blog/` (whole directory — blog is disabled).+- Create (placeholder pages, one paragraph each):+ - `website/docs/intro.md`+ - `website/docs/getting-started/installation.md`+ - `website/docs/getting-started/quick-start.md`+ - `website/docs/getting-started/core-concepts.md`+ - `website/docs/guides/agents/first-agent.md`+ - `website/docs/guides/agents/tool-use.md`+ - `website/docs/guides/agents/multi-turn.md`+ - `website/docs/guides/agents/streaming.md`+ - `website/docs/guides/providers/anthropic.md`+ - `website/docs/guides/providers/openai.md`+ - `website/docs/guides/providers/custom.md`+ - `website/docs/guides/checkpointing/sqlite.md`+ - `website/docs/guides/checkpointing/postgres.md`+ - `website/docs/guides/checkpointing/custom.md`+ - `website/docs/guides/middleware/hooks.md`+ - `website/docs/guides/middleware/composition.md`+ - `website/docs/guides/middleware/examples.md`+ - `website/docs/guides/mcp/loading.md`+ - `website/docs/guides/mcp/auth.md`+ - `website/docs/api/_index.mdx`+ - `website/docs/recipes/weather-agent.md`+ - `website/docs/recipes/multi-provider-failover.md`+ - `website/docs/recipes/persistent-chat.md`+ - `website/docs/recipes/resumable-tasks.md`+ - `website/docs/recipes/postgres-fastapi.md`+ - `website/docs/migration/from-langgraph.md`++- [ ] **Step 1: Clear template content**++```bash+rm -rf website/docs website/blog+mkdir -p website/docs/getting-started \+ website/docs/guides/{agents,providers,checkpointing,middleware,mcp} \+ website/docs/api \+ website/docs/recipes \+ website/docs/migration+```++- [ ] **Step 2: Create the entry page**++`website/docs/intro.md`:++```markdown+---+id: intro+title: CubePi+slug: /+sidebar_position: 0+---++# CubePi++A Pythonic, async-native agent framework.++Start with the [Quick Start](/getting-started/quick-start) or browse the [API Reference](/api/).+```++- [ ] **Step 3: Stub every other page**++For each path in the *Create* list above (except `intro.md` and `api/_index.mdx`), create a file with the following template, substituting `<TITLE>` with a human-readable title derived from the path (e.g. `getting-started/installation.md` → `Installation`):++```markdown+---+title: <TITLE>+---++# <TITLE>++_Placeholder. Content arrives in a follow-up content PR._+```++You can do this with a script:++```bash+cd website/docs+for f in \+ getting-started/installation.md \+ getting-started/quick-start.md \+ getting-started/core-concepts.md \+ guides/agents/first-agent.md \+ guides/agents/tool-use.md \+ guides/agents/multi-turn.md \+ guides/agents/streaming.md \+ guides/providers/anthropic.md \+ guides/providers/openai.md \+ guides/providers/custom.md \+ guides/checkpointing/sqlite.md \+ guides/checkpointing/postgres.md \+ guides/checkpointing/custom.md \+ guides/middleware/hooks.md \+ guides/middleware/composition.md \+ guides/middleware/examples.md \+ guides/mcp/loading.md \+ guides/mcp/auth.md \+ recipes/weather-agent.md \+ recipes/multi-provider-failover.md \+ recipes/persistent-chat.md \+ recipes/resumable-tasks.md \+ recipes/postgres-fastapi.md \+ migration/from-langgraph.md ; do+ title=$(basename "${f%.md}" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++)$i=toupper(substr($i,1,1))substr($i,2)} 1')+ cat > "$f" <<EOF+---+title: $title+---++# $title++_Placeholder. Content arrives in a follow-up content PR._+EOF+done+```++- [ ] **Step 4: Create the API index**++`website/docs/api/_index.mdx`:++```mdx+---+title: API Reference+slug: /api/+---++# API Reference++Auto-generated from CubePi's public modules.++- [cubepi.agent](./cubepi-agent.mdx)+- [cubepi.providers](./cubepi-providers.mdx)+- [cubepi.checkpointer](./cubepi-checkpointer.mdx)+- [cubepi.middleware](./cubepi-middleware.mdx)+- [cubepi.mcp](./cubepi-mcp.mdx)+- [cubepi.utils](./cubepi-utils.mdx)++The module pages above are generated at build time from docstrings and are not editable by hand.+```++- [ ] **Step 5: Write the sidebar**++Overwrite `website/sidebars.ts`:++```ts+import type { SidebarsConfig } from '@docusaurus/plugin-content-docs';++const sidebars: SidebarsConfig = {+ 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/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: 'API Reference',+ link: { type: 'doc', id: 'api/_index' },+ items: [+ { type: 'autogenerated', dirName: 'api' },+ ],+ },+ {+ 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'],+ },+ ],+};++export default sidebars;+```++- [ ] **Step 6: Verify the site builds**++```bash+cd website && pnpm build+```++Expected: build succeeds. `Broken link` errors mean a path is wrong — fix and rerun.++- [ ] **Step 7: Commit**++```bash+git add website/docs/ website/sidebars.ts website/docusaurus.config.ts+git rm -r --cached website/blog 2>/dev/null || true+git commit -m "feat(website): replace template content with cubepi IA skeleton"+```++---++## Phase 4 — API reference pipeline++### Task 8: Build the `griffe → MDX` generator with tests++**Files:**+- Create: `website/scripts/build-api-reference.py`+- Create: `website/scripts/tests/test_build_api_reference.py`+- Create: `website/scripts/tests/__init__.py` (empty)+- Modify: `pyproject.toml` — `[tool.pytest.ini_options].testpaths`++- [ ] **Step 1: Add the script's test path to pytest**++In `pyproject.toml`, change:++```toml+testpaths = ["tests"]+```++to:++```toml+testpaths = ["tests", "website/scripts/tests"]+```++- [ ] **Step 2: Write the first failing test**++Create `website/scripts/tests/__init__.py` empty. Then `website/scripts/tests/test_build_api_reference.py`:++```python+"""Tests for the griffe → MDX API reference generator."""+import importlib.util+import sys+from pathlib import Path++import pytest++SCRIPT_PATH = Path(__file__).resolve().parents[1] / "build_api_reference.py"+++def _load_module():+ spec = importlib.util.spec_from_file_location("build_api_reference", SCRIPT_PATH)+ assert spec and spec.loader, f"cannot load {SCRIPT_PATH}"+ mod = importlib.util.module_from_spec(spec)+ sys.modules["build_api_reference"] = mod+ spec.loader.exec_module(mod)+ return mod+++def test_render_signature_includes_return_annotation():+ mod = _load_module()+ rendered = mod.render_signature(+ name="run",+ parameters=[("self", None, None), ("x", "int", None)],+ returns="str",+ )+ assert "run(self, x: int) -> str" in rendered+++def test_render_docstring_parses_google_sections():+ mod = _load_module()+ doc = (+ "Summary line.\n\n"+ "Args:\n"+ " name (str): The name.\n\n"+ "Returns:\n"+ " bool: Whether it worked.\n"+ )+ out = mod.render_docstring(doc)+ assert "Summary line." in out+ assert "**Args**" in out+ assert "`name`" in out+ assert "**Returns**" in out+++def test_emit_module_writes_generated_marker(tmp_path):+ mod = _load_module()+ module_path = tmp_path / "cubepi-utils.mdx"+ mod.emit_module(+ out_path=module_path,+ module_name="cubepi.utils",+ sidebar_position=6,+ symbols=[],+ commit_sha="abc1234",+ )+ body = module_path.read_text(encoding="utf-8")+ assert body.startswith("---\n")+ assert "title: cubepi.utils" in body+ assert "<!-- GENERATED by build-api-reference.py — DO NOT EDIT -->" in body+```++- [ ] **Step 3: Run tests, verify they fail because the script doesn't exist**++```bash+uv run pytest website/scripts/tests/ -v+```++Expected: `AssertionError: cannot load …/build_api_reference.py` or `FileNotFoundError`.++- [ ] **Step 4: Implement the script**++Create `website/scripts/build-api-reference.py` (note: hyphenated for the CLI command, but the test loads it through `importlib` so the filename hyphen is fine). Use **`build_api_reference.py`** (underscored) so Python `importlib.util` can load it as a module:++Rename: `website/scripts/build_api_reference.py` is the canonical filename. The npm `prebuild` script (Task 9) will invoke it via `python website/scripts/build_api_reference.py`.++Content:++```python+"""Generate Docusaurus-compatible MDX from cubepi public API via griffe."""+from __future__ import annotations++import argparse+import os+import re+import subprocess+import sys+from pathlib import Path+from typing import Iterable++import griffe++MODULES = [+ ("cubepi.agent", "Agents", 1),+ ("cubepi.providers", "Providers", 2),+ ("cubepi.checkpointer", "Checkpointing", 3),+ ("cubepi.middleware", "Middleware", 4),+ ("cubepi.mcp", "MCP", 5),+ ("cubepi.utils", "Utils", 6),+]+++def _is_public(name: str, parent_all: list[str] | None) -> bool:+ if parent_all is not None:+ return name in parent_all+ return not name.startswith("_")+++def collect_public_symbols(module: griffe.Module) -> list[griffe.Object]:+ parent_all = module.exports if hasattr(module, "exports") else None+ out: list[griffe.Object] = []+ for member_name, member in module.members.items():+ if not _is_public(member_name, parent_all):+ continue+ if member.is_alias:+ try:+ member = member.final_target+ except griffe.AliasResolutionError:+ continue+ out.append(member)+ return out+++def render_signature(name: str, parameters: list[tuple[str, str | None, str | None]], returns: str | None) -> str:+ parts = []+ for pname, ptype, pdefault in parameters:+ s = pname+ if ptype:+ s += f": {ptype}"+ if pdefault:+ s += f" = {pdefault}"+ parts.append(s)+ sig = f"{name}({', '.join(parts)})"+ if returns:+ sig += f" -> {returns}"+ return f"```python\n{sig}\n```"+++_GOOGLE_SECTIONS = ("Args", "Arguments", "Returns", "Raises", "Yields", "Example", "Examples", "Note", "Notes")+++def render_docstring(text: str | None) -> str:+ if not text:+ return ""+ lines = text.strip("\n").splitlines()+ out: list[str] = []+ in_section: str | None = None+ for line in lines:+ m = re.match(r"^([A-Z][a-zA-Z]+):\s*$", line.strip())+ if m and m.group(1) in _GOOGLE_SECTIONS:+ in_section = m.group(1)+ out.append("")+ out.append(f"**{in_section}**")+ out.append("")+ continue+ if in_section in {"Args", "Arguments"} and line.startswith((" ", "\t")):+ stripped = line.strip()+ arg_m = re.match(r"^(\w+)\s*(\([^)]+\))?:\s*(.*)$", stripped)+ if arg_m:+ arg, _ty, desc = arg_m.groups()+ out.append(f"- `{arg}` — {desc}")+ continue+ if in_section in {"Returns", "Yields"} and line.startswith((" ", "\t")):+ out.append(f"- {line.strip()}")+ continue+ if in_section == "Raises" and line.startswith((" ", "\t")):+ stripped = line.strip()+ raise_m = re.match(r"^(\w+):\s*(.*)$", stripped)+ if raise_m:+ exc, desc = raise_m.groups()+ out.append(f"- `{exc}` — {desc}")+ continue+ out.append(line)+ return "\n".join(out).strip() + "\n"+++def render_symbol(symbol: griffe.Object, github_blob_root: str) -> str:+ name = symbol.name+ kind = symbol.kind.value+ block: list[str] = [f"### {name}", "", f"_{kind}_", ""]++ if hasattr(symbol, "parameters"):+ params: list[tuple[str, str | None, str | None]] = []+ for p in symbol.parameters:+ ptype = str(p.annotation) if p.annotation else None+ pdefault = str(p.default) if p.default is not None else None+ params.append((p.name, ptype, pdefault))+ returns = str(symbol.returns) if getattr(symbol, "returns", None) else None+ block.append(render_signature(name, params, returns))+ block.append("")++ block.append(render_docstring(symbol.docstring.value if symbol.docstring else None))++ if symbol.filepath and symbol.lineno:+ rel = Path(symbol.filepath).as_posix()+ rel = rel.split("cubepi/")[-1]+ link = f"{github_blob_root}/cubepi/{rel}#L{symbol.lineno}"+ block.append(f"[source]({link})")+ block.append("")++ return "\n".join(block)+++def emit_module(out_path: Path, module_name: str, sidebar_position: int,+ symbols: Iterable, commit_sha: str) -> None:+ out_path.parent.mkdir(parents=True, exist_ok=True)+ frontmatter = (+ "---\n"+ f"id: {module_name.replace('.', '-')}\n"+ f"title: {module_name}\n"+ f"sidebar_position: {sidebar_position}\n"+ "hide_table_of_contents: false\n"+ "---\n\n"+ )+ body = [f"# `{module_name}`", ""]+ for sym in symbols:+ body.append(render_symbol(sym, github_blob_root=f"https://github.com/cubeplexai/cubepi/blob/{commit_sha}"))+ body.append("")+ body.append("")+ body.append("<!-- GENERATED by build-api-reference.py — DO NOT EDIT -->")+ out_path.write_text(frontmatter + "\n".join(body), encoding="utf-8")+++def current_commit_sha() -> str:+ env = os.environ.get("GITHUB_SHA")+ if env:+ return env+ try:+ return subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()+ except Exception:+ return "main"+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--out", required=True, type=Path,+ help="Output directory, typically website/docs/api/")+ args = parser.parse_args()+ args.out.mkdir(parents=True, exist_ok=True)++ sha = current_commit_sha()+ loader = griffe.GriffeLoader()+ loader.load("cubepi")++ for mod_name, _label, position in MODULES:+ try:+ mod = loader.modules_collection[mod_name]+ except KeyError:+ print(f"[warn] {mod_name} not importable; skipping", file=sys.stderr)+ continue+ symbols = collect_public_symbols(mod)+ out_path = args.out / f"{mod_name.replace('.', '-')}.mdx"+ emit_module(out_path, mod_name, position, symbols, sha)+ print(f"[ok] wrote {out_path} ({len(symbols)} symbols)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())+```++Note: tests load by path so they pass with this filename. The hyphenated CLI alias (`build-api-reference.py`) is unnecessary — refer to it everywhere as `build_api_reference.py`. Update the spec mentally if there is a contradiction.++- [ ] **Step 5: Run the tests, verify they pass**++```bash+uv run pytest website/scripts/tests/ -v+```++Expected: 3 passing.++- [ ] **Step 6: Smoke-run the script end-to-end**++```bash+uv run python website/scripts/build_api_reference.py --out website/docs/api/+ls website/docs/api/*.mdx+```++Expected: 6 mdx files (`cubepi-agent.mdx`, …, `cubepi-utils.mdx`), each with `<!-- GENERATED` trailer.++- [ ] **Step 7: Verify Docusaurus builds with the generated content**++```bash+cd website && pnpm build+```++Expected: build succeeds. **Likely surprises:**+- Some symbols may emit raw `<` / `>` from generics — if MDX parser complains, escape with `<` and `>` in `render_signature` before pasting into a code fence (already inside ```python fence, so MDX shouldn't try to parse — but if a docstring contains a raw `<`, the test will still work; only fix in `render_docstring` if a real build error appears).++- [ ] **Step 8: Commit**++```bash+git add pyproject.toml website/scripts/+git commit -m "feat(website): griffe-based API reference generator with tests"+```++---++### Task 9: Wire the prebuild hook++**Files:**+- Modify: `website/package.json`++- [ ] **Step 1: Add scripts**++In `website/package.json` `"scripts"`, add `prebuild` and `apiref`:++```json+"scripts": {+ "docusaurus": "docusaurus",+ "start": "docusaurus start",+ "build": "docusaurus build",+ "swizzle": "docusaurus swizzle",+ "deploy": "docusaurus deploy",+ "clear": "docusaurus clear",+ "serve": "docusaurus serve",+ "write-translations": "docusaurus write-translations",+ "write-heading-ids": "docusaurus write-heading-ids",+ "typecheck": "tsc",+ "apiref": "cd .. && uv run python website/scripts/build_api_reference.py --out website/docs/api/",+ "prebuild": "pnpm apiref",+ "prestart": "pnpm apiref",+ "check": "pnpm build && pnpm typecheck"+}+```++- [ ] **Step 2: Verify the generated MDX is excluded from git**++```bash+git status website/docs/api/+```++Expected: only `_index.mdx` (if any state). The generated `cubepi-*.mdx` files should not appear — they're matched by the `.gitignore` rule from Task 2.++- [ ] **Step 3: Smoke `pnpm build`**++```bash+cd website && pnpm build+```++Expected: prebuild step runs griffe; main build succeeds.++- [ ] **Step 4: Commit**++```bash+git add website/package.json+git commit -m "build(website): run griffe before every Docusaurus build/start"+```++---++## Phase 5 — Custom homepage++### Task 10: Hero component++**Files:**+- Create: `website/src/components/Home/Hero.tsx`+- Create: `website/src/components/Home/Hero.module.css`++- [ ] **Step 1: `Hero.tsx`**++```tsx+import React from 'react';+import Link from '@docusaurus/Link';+import useBaseUrl from '@docusaurus/useBaseUrl';+import styles from './Hero.module.css';++export default function Hero() {+ const social = useBaseUrl('/img/brand/cubepi-social-preview.png');+ const installCmd = 'pip install cubepi';++ return (+ <section className={styles.hero}>+ <img+ className={styles.banner}+ src={social}+ alt="CubePi · A Pythonic, async-native agent framework"+ width={1280}+ height={640}+ />+ <div className={styles.eyebrow}>cubepi · v0.3.0 · alpha</div>+ <h1 className={styles.h1}>A Pythonic, async-native agent framework.</h1>+ <p className={styles.lead}>+ Plain async functions instead of graph nodes. 3 deps. Append-only checkpointing.+ </p>+ <div className={styles.actions}>+ <button+ type="button"+ className={`${styles.cta} ${styles.ctaPrimary}`}+ onClick={() => navigator.clipboard?.writeText(installCmd)}+ aria-label={`Copy install command: ${installCmd}`}+ >+ <code>{installCmd}</code>+ <kbd className={styles.kbd}>⌘C</kbd>+ </button>+ <Link className={`${styles.cta} ${styles.ctaGhost}`} to="/getting-started/quick-start">+ Quick Start →+ <kbd className={styles.kbd}>G Q</kbd>+ </Link>+ </div>+ </section>+ );+}+```++- [ ] **Step 2: `Hero.module.css`**++```css+.hero {+ max-width: 880px;+ margin: 48px auto 64px;+ padding: 0 24px;+ text-align: left;+}+.banner {+ display: block;+ width: 100%;+ height: auto;+ border: 1px solid var(--ink-5);+ border-radius: 6px;+ margin-bottom: 40px;+}+.eyebrow {+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 12px;+ color: var(--ink-7);+ letter-spacing: 0.06em;+ margin-bottom: 12px;+}+.h1 {+ font-family: 'Inter Tight', 'Inter', system-ui;+ font-size: 44px;+ line-height: 1.08;+ letter-spacing: -0.02em;+ font-weight: 600;+ color: var(--ink-12);+ margin: 0 0 16px;+}+.lead {+ font-size: 16px;+ line-height: 1.55;+ color: var(--ink-9);+ margin: 0 0 28px;+ max-width: 640px;+}+.actions { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; }+.cta {+ display: inline-flex;+ align-items: center;+ gap: 10px;+ height: 36px;+ padding: 0 14px;+ border: 1px solid var(--ink-5);+ border-radius: 5px;+ background: var(--surface);+ font-size: 14px;+ color: var(--ink-11);+ font-weight: 500;+ cursor: pointer;+ text-decoration: none;+}+.cta:hover { background: var(--ink-3); }+.ctaPrimary { background: var(--ink-12); border-color: var(--ink-12); color: var(--surface); }+.ctaPrimary:hover { background: var(--ink-11); }+.ctaPrimary code { background: transparent; color: inherit; font-size: 13px; }+.ctaGhost { background: transparent; }+.kbd {+ font-family: 'JetBrains Mono', ui-monospace, monospace;+ font-size: 10.5px;+ height: 18px;+ min-width: 18px;+ padding: 0 5px;+ display: inline-flex;+ align-items: center;+ border: 1px solid var(--ink-5);+ border-bottom-width: 2px;+ border-radius: 4px;+ background: var(--surface);+ color: var(--ink-9);+ opacity: 0.85;+}+.ctaPrimary .kbd { background: rgba(255,255,255,0.12); color: rgba(255,255,255,0.85); border-color: transparent; }+@media (max-width: 640px) {+ .h1 { font-size: 32px; }+ .hero { margin-top: 24px; }+}+```++- [ ] **Step 3: Commit**++```bash+git add website/src/components/Home/Hero.tsx website/src/components/Home/Hero.module.css+git commit -m "feat(website): Hero component with social preview banner"+```++---++### Task 11: WhyTable component++**Files:**+- Create: `website/src/components/Home/WhyTable.tsx`+- Create: `website/src/components/Home/WhyTable.module.css`++- [ ] **Step 1: `WhyTable.tsx`**++```tsx+import React from 'react';+import styles from './WhyTable.module.css';++const ROWS: { label: string; langgraph: string; cubepi: string }[] = [+ { label: 'Abstraction', langgraph: 'Graph nodes + edges + channels', cubepi: 'Plain async functions — run_agent_loop is a while loop' },+ { label: 'Streaming', langgraph: 'Callback-based, multiple handler types', cubepi: 'async for event in stream — one pattern everywhere' },+ { label: 'Checkpointing', langgraph: 'Full snapshot per step; serializes entire message list', cubepi: 'Append-only — O(1) DB I/O regardless of conversation length' },+ { label: 'Dependencies', langgraph: 'langchain-core, langgraph-sdk, and transitive deps', cubepi: '3 core deps: pydantic, anthropic, openai' },+ { label: 'Tool execution', langgraph: 'Tools are graph nodes with manual wiring', cubepi: 'Declare tools as functions; framework routes and parallelizes' },+ { label: 'Multi-provider', langgraph: 'Via langchain chat model adapters', cubepi: 'Native Provider protocol — Anthropic, OpenAI built in' },+ { label: 'Middleware', langgraph: 'Graph-level middleware on node entry/exit', cubepi: '5 typed hooks with declarative composition rules' },+ { label: 'Observability', langgraph: 'LangSmith / Langfuse integration', cubepi: 'Events + middleware hooks — bring your own tracing' },+];++export default function WhyTable() {+ return (+ <section className={styles.section}>+ <h2 className={styles.h2}>Why CubePi</h2>+ <div className={styles.tableWrap}>+ <table className={styles.table}>+ <thead>+ <tr>+ <th></th>+ <th>langgraph</th>+ <th>CubePi</th>+ </tr>+ </thead>+ <tbody>+ {ROWS.map((r) => (+ <tr key={r.label}>+ <td className={styles.label}>{r.label}</td>+ <td>{r.langgraph}</td>+ <td className={styles.us}>{r.cubepi}</td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </section>+ );+}+```++- [ ] **Step 2: `WhyTable.module.css`**++```css+.section { max-width: 1080px; margin: 0 auto 64px; padding: 0 24px; }+.h2 {+ font-family: 'Inter Tight';+ font-size: 11px;+ letter-spacing: 0.12em;+ text-transform: uppercase;+ font-weight: 600;+ color: var(--ink-7);+ margin-bottom: 16px;+}+.tableWrap { overflow-x: auto; border: 1px solid var(--ink-5); border-radius: 8px; background: var(--surface); }+.table { width: 100%; border-collapse: collapse; font-size: 13px; }+.table th, .table td {+ padding: 12px 16px;+ border-bottom: 1px solid var(--ink-5);+ text-align: left;+ vertical-align: top;+ line-height: 1.55;+}+.table tr:last-child td { border-bottom: 0; }+.table th { font-weight: 500; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-7); background: var(--ink-3); }+.label { font-weight: 500; color: var(--ink-12); width: 22%; }+.us { color: var(--ink-12); font-family: 'JetBrains Mono'; font-size: 12.5px; }+```++- [ ] **Step 3: Commit**++```bash+git add website/src/components/Home/WhyTable.tsx website/src/components/Home/WhyTable.module.css+git commit -m "feat(website): WhyTable comparison component"+```++---++### Task 12: HelloAgent component++**Files:**+- Create: `website/src/components/Home/HelloAgent.tsx`+- Create: `website/src/components/Home/HelloAgent.module.css`++- [ ] **Step 1: `HelloAgent.tsx`**++```tsx+import React from 'react';+import Link from '@docusaurus/Link';+import CodeBlock from '@theme/CodeBlock';+import styles from './HelloAgent.module.css';++const SAMPLE = `import asyncio+from cubepi import Agent, AgentTool, Model+from cubepi.providers.anthropic import AnthropicProvider++provider = AnthropicProvider(api_key="sk-...")++def get_weather(city: str) -> str:+ """Get current weather for a city."""+ return f"72°F and sunny in {city}"++agent = Agent(+ model=Model(provider=provider, model="claude-sonnet-4-5-20250929"),+ tools=[AgentTool(+ name="get_weather",+ description="Get current weather for a city",+ parameters={+ "type": "object",+ "properties": {"city": {"type": "string"}},+ "required": ["city"],+ },+ execute=get_weather,+ )],+ system_prompt="You are a helpful weather assistant.",+)++async def main():+ stream = await agent.prompt("What's the weather in Tokyo?")+ async for event in stream:+ if event.type == "text_delta":+ print(event.delta, end="", flush=True)++asyncio.run(main())+`;++export default function HelloAgent() {+ return (+ <section className={styles.section}>+ <div className={styles.left}>+ <h2 className={styles.h2}>Hello, agent.</h2>+ <p className={styles.lede}>+ A single async function loop. One <code>Provider</code>, one <code>AgentTool</code>, and you're streaming.+ </p>+ <Link to="/getting-started/quick-start" className={styles.link}>+ Full quick-start →+ </Link>+ </div>+ <div className={styles.right}>+ <CodeBlock language="python">{SAMPLE}</CodeBlock>+ </div>+ </section>+ );+}+```++- [ ] **Step 2: `HelloAgent.module.css`**++```css+.section {+ max-width: 1080px;+ margin: 0 auto 64px;+ padding: 0 24px;+ display: grid;+ grid-template-columns: 1fr 1.4fr;+ gap: 40px;+ align-items: start;+}+.h2 { font-family: 'Inter Tight'; font-size: 24px; letter-spacing: -0.015em; color: var(--ink-12); margin: 0 0 12px; }+.lede { font-size: 14px; color: var(--ink-9); line-height: 1.55; margin: 0 0 16px; }+.link { font-size: 13px; color: var(--accent); }+.right :global(.theme-code-block) { margin: 0; }+@media (max-width: 768px) {+ .section { grid-template-columns: 1fr; gap: 16px; }+}+```++- [ ] **Step 3: Commit**++```bash+git add website/src/components/Home/HelloAgent.tsx website/src/components/Home/HelloAgent.module.css+git commit -m "feat(website): HelloAgent code-block section"+```++---++### Task 13: FeatureGrid component++**Files:**+- Create: `website/src/components/Home/FeatureGrid.tsx`+- Create: `website/src/components/Home/FeatureGrid.module.css`++- [ ] **Step 1: `FeatureGrid.tsx`**++Inline 16px Lucide-style monoline icons as plain SVG (no library — Operator dictates "no decorative icon set"). Six cards:++```tsx+import React from 'react';+import Link from '@docusaurus/Link';+import styles from './FeatureGrid.module.css';++type Icon = React.FC<React.SVGProps<SVGSVGElement>>;++const IconBox: Icon = (p) => (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" {...p}>+ <rect x="2" y="2" width="12" height="12" rx="2" />+ </svg>+);+const IconStream: Icon = (p) => (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" {...p}>+ <path d="M1 4h14M1 8h14M1 12h10" />+ </svg>+);+const IconTool: Icon = (p) => (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" {...p}>+ <path d="M11 2l3 3-2 2-3-3zM10 5l-7 7v3h3l7-7" />+ </svg>+);+const IconPlug: Icon = (p) => (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" {...p}>+ <path d="M5 1v4M11 1v4M3 5h10v4a4 4 0 01-4 4H7a4 4 0 01-4-4V5zM8 13v2" />+ </svg>+);+const IconDisk: Icon = (p) => (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" {...p}>+ <ellipse cx="8" cy="4" rx="6" ry="2" />+ <path d="M2 4v8c0 1.1 2.7 2 6 2s6-.9 6-2V4M2 8c0 1.1 2.7 2 6 2s6-.9 6-2" />+ </svg>+);+const IconMcp: Icon = (p) => (+ <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round" {...p}>+ <circle cx="8" cy="8" r="6" />+ <path d="M2 8h12M8 2v12" />+ </svg>+);++const CARDS = [+ { Icon: IconBox, title: 'Agents', body: 'One async loop, fully typed events.', href: '/guides/agents/first-agent' },+ { Icon: IconStream, title: 'Streaming', body: 'async for event in stream.', href: '/guides/agents/streaming' },+ { Icon: IconTool, title: 'Tools', body: 'Plain functions, parallel execution.', href: '/guides/agents/tool-use' },+ { Icon: IconPlug, title: 'Providers', body: 'Anthropic, OpenAI, or write your own.', href: '/guides/providers/anthropic' },+ { Icon: IconDisk, title: 'Checkpointing', body: 'Append-only, O(1) per turn.', href: '/guides/checkpointing/sqlite' },+ { Icon: IconMcp, title: 'MCP', body: 'Load remote tools at startup.', href: '/guides/mcp/loading' },+];++export default function FeatureGrid() {+ return (+ <section className={styles.section}>+ <div className={styles.grid}>+ {CARDS.map((c) => (+ <Link key={c.title} to={c.href} className={styles.card}>+ <c.Icon className={styles.icon} width={16} height={16} />+ <h3 className={styles.title}>{c.title}</h3>+ <p className={styles.body}>{c.body}</p>+ <span className={styles.more}>→ Guides / {c.title}</span>+ </Link>+ ))}+ </div>+ </section>+ );+}+```++- [ ] **Step 2: `FeatureGrid.module.css`**++```css+.section { max-width: 1080px; margin: 0 auto 64px; padding: 0 24px; }+.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px; }+.card {+ display: flex;+ flex-direction: column;+ gap: 6px;+ padding: 18px 16px 14px;+ border: 1px solid var(--ink-5);+ border-radius: 6px;+ background: var(--surface);+ color: inherit;+ text-decoration: none;+ position: relative;+ min-height: 132px;+}+.card:hover { border-color: var(--ink-7); background: var(--ink-3); }+.icon { color: var(--ink-9); }+.title {+ font-family: 'Inter Tight';+ font-size: 15px;+ font-weight: 600;+ letter-spacing: -0.005em;+ color: var(--ink-12);+ margin: 4px 0 0;+}+.body { font-size: 13px; color: var(--ink-9); line-height: 1.5; margin: 0; }+.more {+ margin-top: auto;+ font-family: 'JetBrains Mono';+ font-size: 11px;+ color: var(--accent);+}+@media (max-width: 900px) { .grid { grid-template-columns: repeat(2, 1fr); } }+@media (max-width: 560px) { .grid { grid-template-columns: 1fr; } }+```++- [ ] **Step 3: Commit**++```bash+git add website/src/components/Home/FeatureGrid.tsx website/src/components/Home/FeatureGrid.module.css+git commit -m "feat(website): FeatureGrid with six monoline cards"+```++---++### Task 14: InstallMatrix component++**Files:**+- Create: `website/src/components/Home/InstallMatrix.tsx`+- Create: `website/src/components/Home/InstallMatrix.module.css`++- [ ] **Step 1: `InstallMatrix.tsx`**++```tsx+import React from 'react';+import styles from './InstallMatrix.module.css';++const ROWS: { tool: string; cmd: string }[] = [+ { tool: 'pip', cmd: 'pip install cubepi' },+ { tool: 'uv', cmd: 'uv add cubepi' },+ { tool: 'poetry', cmd: 'poetry add cubepi' },+ { tool: 'extras', cmd: 'pip install cubepi[sqlite,postgres,mcp]' },+];++export default function InstallMatrix() {+ return (+ <section className={styles.section}>+ <h2 className={styles.h2}>Install</h2>+ <div className={styles.table}>+ {ROWS.map((r) => (+ <div key={r.tool} className={styles.row}>+ <span className={styles.tool}>{r.tool}</span>+ <code className={styles.cmd}>{r.cmd}</code>+ <button+ type="button"+ className={styles.copy}+ onClick={() => navigator.clipboard?.writeText(r.cmd)}+ aria-label={`Copy ${r.tool} command`}+ >Copy</button>+ </div>+ ))}+ </div>+ </section>+ );+}+```++- [ ] **Step 2: `InstallMatrix.module.css`**++```css+.section { max-width: 1080px; margin: 0 auto 64px; padding: 0 24px; }+.h2 { font-family: 'Inter Tight'; font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase; font-weight: 600; color: var(--ink-7); margin-bottom: 12px; }+.table { border: 1px solid var(--ink-5); border-radius: 8px; background: var(--surface); overflow: hidden; }+.row {+ display: grid;+ grid-template-columns: 96px 1fr auto;+ align-items: center;+ gap: 12px;+ padding: 10px 14px;+ border-bottom: 1px solid var(--ink-5);+}+.row:last-child { border-bottom: 0; }+.tool { font-family: 'JetBrains Mono'; font-size: 12px; color: var(--ink-7); text-transform: uppercase; letter-spacing: 0.06em; }+.cmd { font-family: 'JetBrains Mono'; font-size: 13px; color: var(--ink-12); background: var(--ink-3); padding: 6px 10px; border: 1px solid var(--ink-5); border-radius: 5px; }+.copy { font-size: 11px; padding: 4px 10px; border: 1px solid var(--ink-5); background: var(--surface); color: var(--ink-9); border-radius: 4px; cursor: pointer; }+.copy:hover { background: var(--ink-3); color: var(--ink-11); }+```++- [ ] **Step 3: Commit**++```bash+git add website/src/components/Home/InstallMatrix.tsx website/src/components/Home/InstallMatrix.module.css+git commit -m "feat(website): InstallMatrix table"+```++---++### Task 15: MetaBar component++**Files:**+- Create: `website/src/components/Home/MetaBar.tsx`+- Create: `website/src/components/Home/MetaBar.module.css`++- [ ] **Step 1: `MetaBar.tsx`**++```tsx+import React from 'react';+import useDocusaurusContext from '@docusaurus/useDocusaurusContext';+import styles from './MetaBar.module.css';++export default function MetaBar() {+ const { siteConfig } = useDocusaurusContext();+ const sha = (siteConfig.customFields?.GIT_SHA as string | undefined) ?? 'dev';+ return (+ <section className={styles.bar}>+ <span>v0.3.0</span>+ <span className={styles.sep}>·</span>+ <span>py 3.11+</span>+ <span className={styles.sep}>·</span>+ <span>MIT</span>+ <span className={styles.sep}>·</span>+ <span>build {sha}</span>+ <span className={styles.sep}>·</span>+ <span className={styles.ok}>● ci passing</span>+ <span className={styles.sep}>·</span>+ <span>pypi · weekly downloads via shields badge</span>+ </section>+ );+}+```++- [ ] **Step 2: `MetaBar.module.css`**++```css+.bar {+ max-width: 1080px;+ margin: 0 auto;+ padding: 14px 24px;+ border-top: 1px solid var(--ink-5);+ font-family: 'JetBrains Mono';+ font-size: 11px;+ color: var(--ink-7);+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+}+.sep { color: var(--ink-5); }+.ok { color: var(--ok); }+```++- [ ] **Step 3: Commit**++```bash+git add website/src/components/Home/MetaBar.tsx website/src/components/Home/MetaBar.module.css+git commit -m "feat(website): MetaBar status footer"+```++---++### Task 16: Wire the homepage++**Files:**+- Overwrite: `website/src/pages/index.tsx`++- [ ] **Step 1: Implementation**++```tsx+import React from 'react';+import Layout from '@theme/Layout';+import Hero from '@site/src/components/Home/Hero';+import WhyTable from '@site/src/components/Home/WhyTable';+import HelloAgent from '@site/src/components/Home/HelloAgent';+import FeatureGrid from '@site/src/components/Home/FeatureGrid';+import InstallMatrix from '@site/src/components/Home/InstallMatrix';+import MetaBar from '@site/src/components/Home/MetaBar';++export default function Home(): JSX.Element {+ return (+ <Layout title="CubePi — Pythonic async-native agent framework"+ description="CubePi is a Pythonic, async-native agent framework. Plain async functions, append-only checkpointing, 3 core dependencies.">+ <Hero />+ <WhyTable />+ <HelloAgent />+ <FeatureGrid />+ <InstallMatrix />+ <MetaBar />+ </Layout>+ );+}+```++- [ ] **Step 2: Build and visually inspect**++```bash+cd website && pnpm start --no-open+```++Open `http://localhost:3000`. Expected: full custom homepage in correct order. Resize to 600px wide → hero/feature grid collapse to single column.++- [ ] **Step 3: Commit**++```bash+git add website/src/pages/index.tsx+git commit -m "feat(website): assemble Operator-styled homepage"+```++---++## Phase 6 — PostHog + feedback widget++### Task 17: PostHog client module++**Files:**+- Create: `website/src/clientModules/posthog.ts`++- [ ] **Step 1: Add the SDK**++```bash+cd website && pnpm add posthog-js@1+```++- [ ] **Step 2: Write the module**++```ts+import posthog from 'posthog-js';+import siteConfig from '@generated/docusaurus.config';++const key = (siteConfig.customFields?.POSTHOG_KEY as string | undefined) ?? '';+const host = (siteConfig.customFields?.POSTHOG_HOST as string | undefined) ?? 'https://us.i.posthog.com';++if (typeof window !== 'undefined' && key) {+ posthog.init(key, {+ api_host: host,+ capture_pageview: true,+ persistence: 'memory',+ autocapture: false,+ disable_session_recording: true,+ });+ (window as any).__cubepi_posthog = posthog;+}++export {};+```++- [ ] **Step 3: Verify the build still works without `POSTHOG_KEY` set**++```bash+unset POSTHOG_KEY+cd website && pnpm build+```++Expected: build succeeds, no console errors. (When `POSTHOG_KEY` is empty the init block is skipped.)++- [ ] **Step 4: Commit**++```bash+git add website/package.json website/pnpm-lock.yaml website/src/clientModules/posthog.ts+git commit -m "feat(website): PostHog client module gated on env"+```++---++### Task 18: DocFeedback component (TDD)++**Files:**+- Create: `website/src/components/DocFeedback/index.tsx`+- Create: `website/src/components/DocFeedback/styles.module.css`+- Create: `website/src/components/DocFeedback/index.test.tsx`+- Modify: `website/package.json` — devDependencies + scripts++- [ ] **Step 1: Add test tooling**++```bash+cd website && pnpm add -D vitest@1 @testing-library/react@16 @testing-library/jest-dom@6 jsdom@24+```++In `website/package.json` `"scripts"`, add:++```json+"test": "vitest run",+"test:watch": "vitest"+```++Create `website/vitest.config.ts`:++```ts+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'jsdom',+ setupFiles: ['./vitest.setup.ts'],+ globals: true,+ },+});+```++`website/vitest.setup.ts`:++```ts+import '@testing-library/jest-dom/vitest';+```++- [ ] **Step 2: Write the failing test**++`website/src/components/DocFeedback/index.test.tsx`:++```tsx+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi, beforeEach } from 'vitest';+import DocFeedback from './index';++declare global { interface Window { __cubepi_posthog?: { capture: (e: string, p: object) => void } } }++beforeEach(() => {+ window.__cubepi_posthog = { capture: vi.fn() };+});++describe('DocFeedback', () => {+ it('renders the prompt and two buttons', () => {+ render(<DocFeedback slug="/foo" version="0.3" locale="en" />);+ expect(screen.getByText(/was this page helpful/i)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /yes/i })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /no/i })).toBeInTheDocument();+ });++ it('captures a doc_feedback event with helpful=true on 👍', () => {+ const capture = vi.fn();+ window.__cubepi_posthog = { capture };+ render(<DocFeedback slug="/foo" version="0.3" locale="en" />);+ fireEvent.click(screen.getByRole('button', { name: /yes/i }));+ expect(capture).toHaveBeenCalledWith('doc_feedback', {+ slug: '/foo', helpful: true, version: '0.3', locale: 'en',+ });+ expect(screen.getByText(/thanks/i)).toBeInTheDocument();+ });++ it('shows a comment textarea on 👎 and captures doc_feedback_comment on submit', () => {+ const capture = vi.fn();+ window.__cubepi_posthog = { capture };+ render(<DocFeedback slug="/foo" version="0.3" locale="en" />);+ fireEvent.click(screen.getByRole('button', { name: /no/i }));+ expect(capture).toHaveBeenCalledWith('doc_feedback', {+ slug: '/foo', helpful: false, version: '0.3', locale: 'en',+ });+ const ta = screen.getByRole('textbox');+ fireEvent.change(ta, { target: { value: 'unclear example' } });+ fireEvent.click(screen.getByRole('button', { name: /submit/i }));+ expect(capture).toHaveBeenCalledWith('doc_feedback_comment', {+ slug: '/foo', version: '0.3', locale: 'en', comment: 'unclear example',+ });+ });+});+```++Run:++```bash+cd website && pnpm test+```++Expected: all 3 tests fail with "Cannot find module './index'".++- [ ] **Step 3: Implement the component**++`website/src/components/DocFeedback/index.tsx`:++```tsx+import React, { useState } from 'react';+import styles from './styles.module.css';++interface Props {+ slug: string;+ version: string;+ locale: string;+}++type Phase = 'ask' | 'thanks' | 'comment' | 'submitted';++function capture(event: string, payload: object) {+ const ph = (window as any).__cubepi_posthog;+ if (ph && typeof ph.capture === 'function') ph.capture(event, payload);+}++export default function DocFeedback({ slug, version, locale }: Props): JSX.Element {+ const [phase, setPhase] = useState<Phase>('ask');+ const [comment, setComment] = useState('');++ const onYes = () => {+ capture('doc_feedback', { slug, helpful: true, version, locale });+ setPhase('thanks');+ };+ const onNo = () => {+ capture('doc_feedback', { slug, helpful: false, version, locale });+ setPhase('comment');+ };+ const onSubmit = () => {+ capture('doc_feedback_comment', { slug, version, locale, comment });+ setPhase('submitted');+ };++ return (+ <aside className={styles.box}>+ {phase === 'ask' && (+ <>+ <span className={styles.q}>Was this page helpful?</span>+ <button type="button" className={styles.btn} onClick={onYes} aria-label="Yes">👍</button>+ <button type="button" className={styles.btn} onClick={onNo} aria-label="No">👎</button>+ </>+ )}+ {phase === 'thanks' && <span className={styles.q}>Thanks!</span>}+ {phase === 'comment' && (+ <div className={styles.commentWrap}>+ <span className={styles.q}>What was missing?</span>+ <textarea+ className={styles.textarea}+ value={comment}+ onChange={(e) => setComment(e.target.value)}+ rows={3}+ />+ <button type="button" className={styles.btn} onClick={onSubmit}>Submit</button>+ </div>+ )}+ {phase === 'submitted' && <span className={styles.q}>Thanks — we'll review it.</span>}+ </aside>+ );+}+```++`website/src/components/DocFeedback/styles.module.css`:++```css+.box {+ margin: 32px 0 0;+ padding: 14px 16px;+ border: 1px solid var(--ink-5);+ border-radius: 6px;+ background: var(--surface);+ display: flex;+ align-items: center;+ gap: 12px;+ font-size: 13px;+ color: var(--ink-9);+}+.q { color: var(--ink-11); font-weight: 500; }+.btn {+ font: inherit;+ background: var(--surface);+ border: 1px solid var(--ink-5);+ border-radius: 5px;+ padding: 4px 10px;+ cursor: pointer;+ color: var(--ink-11);+}+.btn:hover { background: var(--ink-3); border-color: var(--ink-7); }+.commentWrap { display: flex; flex-direction: column; gap: 8px; width: 100%; }+.textarea {+ font: inherit;+ font-family: 'Inter';+ padding: 8px 10px;+ border: 1px solid var(--ink-5);+ border-radius: 5px;+ background: var(--surface);+ color: var(--ink-12);+ resize: vertical;+}+.textarea:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(59,91,217,0.12); }+```++- [ ] **Step 4: Run tests, verify pass**++```bash+cd website && pnpm test+```++Expected: 3 passed.++- [ ] **Step 5: Commit**++```bash+git add website/package.json website/pnpm-lock.yaml website/vitest.config.ts website/vitest.setup.ts website/src/components/DocFeedback/+git commit -m "feat(website): DocFeedback widget with PostHog capture and tests"+```++---++### Task 19: Swizzle `DocItem/Footer` to mount DocFeedback++**Files:**+- Create: `website/src/theme/DocItem/Footer/index.tsx`++- [ ] **Step 1: Eject the default footer to inspect it**++```bash+cd website && pnpm swizzle @docusaurus/theme-classic DocItem/Footer --wrap --typescript --danger+```++Pick "Yes" at any prompts. This creates `src/theme/DocItem/Footer/index.tsx` wrapping the upstream component.++- [ ] **Step 2: Replace the wrapper**++`website/src/theme/DocItem/Footer/index.tsx`:++```tsx+import React from 'react';+import Footer from '@theme-original/DocItem/Footer';+import { useDoc } from '@docusaurus/plugin-content-docs/client';+import { useLocation } from '@docusaurus/router';+import useDocusaurusContext from '@docusaurus/useDocusaurusContext';+import DocFeedback from '@site/src/components/DocFeedback';++export default function FooterWrapper(props: any): JSX.Element {+ const { metadata } = useDoc();+ const { i18n } = useDocusaurusContext();+ const { pathname } = useLocation();+ const version = (metadata as any).version ?? 'current';+ return (+ <>+ <DocFeedback slug={pathname} version={version} locale={i18n.currentLocale} />+ <Footer {...props} />+ </>+ );+}+```++- [ ] **Step 3: Build and verify**++```bash+cd website && pnpm build+```++Open the built site (`pnpm serve`) and navigate to `/getting-started/installation`. Expected: a 👍/👎 box appears above the prev/next footer.++- [ ] **Step 4: Commit**++```bash+git add website/src/theme/DocItem/Footer/+git commit -m "feat(website): swizzle DocItem/Footer to mount DocFeedback"+```++---++## Phase 7 — i18n++### Task 20: Enable Simplified Chinese locale with core translations++**Files:**+- Create (≥ 6): translation files under `website/i18n/zh-Hans/`++- [ ] **Step 1: Scaffold translation directories**++```bash+mkdir -p \+ website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started \+ website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents \+ website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers \+ website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing \+ website/i18n/zh-Hans/docusaurus-theme-classic+```++- [ ] **Step 2: Generate UI string templates**++```bash+cd website && pnpm write-translations --locale zh-Hans+```++This creates `i18n/zh-Hans/code.json` and theme JSON files. Hand-edit:++- `code.json` — translate string values, leave keys.+- `docusaurus-theme-classic/navbar.json` — translate `Docs`, `API`, `Recipes`, `GitHub`.+- `docusaurus-theme-classic/footer.json` — translate any footer labels.++- [ ] **Step 3: Copy and translate the 6 core docs**++For each of these pages, copy the English markdown to the parallel zh-Hans path and translate the prose. Leave code blocks unchanged. Six core pages:++| English source | zh-Hans destination |+|---|---|+| `docs/intro.md` | `i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.md` |+| `docs/getting-started/installation.md` | `i18n/zh-Hans/.../current/getting-started/installation.md` |+| `docs/getting-started/quick-start.md` | `i18n/zh-Hans/.../current/getting-started/quick-start.md` |+| `docs/getting-started/core-concepts.md` | `i18n/zh-Hans/.../current/getting-started/core-concepts.md` |+| `docs/guides/agents/first-agent.md` | `i18n/zh-Hans/.../current/guides/agents/first-agent.md` |+| `docs/guides/agents/streaming.md` | `i18n/zh-Hans/.../current/guides/agents/streaming.md` |+| `docs/guides/agents/tool-use.md` | `i18n/zh-Hans/.../current/guides/agents/tool-use.md` |+| `docs/guides/providers/anthropic.md` | `i18n/zh-Hans/.../current/guides/providers/anthropic.md` |+| `docs/guides/checkpointing/sqlite.md` | `i18n/zh-Hans/.../current/guides/checkpointing/sqlite.md` |++Because the English content is still placeholder, translate each placeholder paragraph to a Chinese placeholder (`_占位。内容将在后续内容 PR 中补充。_`). The real translation will follow the real English content in subsequent PRs.++- [ ] **Step 4: Verify the locale build**++```bash+cd website && pnpm build -- --locale zh-Hans+```++Expected: build succeeds; navbar Locale dropdown is visible on the built site at `/zh-Hans/`.++- [ ] **Step 5: Commit**++```bash+git add website/i18n/zh-Hans/+git commit -m "feat(website): enable zh-Hans locale with stubbed core translations"+```++---++## Phase 8 — Versioning++### Task 21: Snapshot version 0.3 and set as default++**Files:**+- Create (auto): `website/versioned_docs/version-0.3/`, `website/versioned_sidebars/version-0.3-sidebars.json`, `website/versions.json`+- Modify: `website/docusaurus.config.ts:lastVersion` and `versions`++- [ ] **Step 1: Run the snapshot**++```bash+cd website && pnpm docusaurus docs:version 0.3+```++Expected: creates `versioned_docs/version-0.3/`, `versioned_sidebars/version-0.3-sidebars.json`, and updates `versions.json` to `["0.3"]`.++- [ ] **Step 2: Re-route URLs**++Edit `website/docusaurus.config.ts` so the `presets.classic.docs` block reads:++```ts+docs: {+ sidebarPath: './sidebars.ts',+ editUrl: 'https://github.com/cubeplexai/cubepi/edit/main/website/',+ lastVersion: '0.3',+ versions: {+ current: { label: 'Next 🚧', path: 'next', banner: 'unreleased' },+ '0.3': { label: '0.3 (latest)', path: '' },+ },+},+```++- [ ] **Step 3: Mirror the zh-Hans translation tree**++```bash+mkdir -p website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3+cp -r website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/* \+ website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/+```++- [ ] **Step 4: Build and verify URLs**++```bash+cd website && pnpm build+```++Expected: `build/` contains both `/index.html` (for 0.3 docs) and `/next/...` (for next). Version dropdown in navbar shows `0.3 (latest)` and `Next 🚧`.++- [ ] **Step 5: Commit**++```bash+git add website/versioned_docs/ website/versioned_sidebars/ website/versions.json website/docusaurus.config.ts website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-0.3/+git commit -m "feat(website): snapshot 0.3 as default; next routed to /next/"+```++---++## Phase 9 — CI++### Task 22: GitHub Actions workflow++**Files:**+- Create: `.github/workflows/docs.yml`++- [ ] **Step 1: Workflow content**++```yaml+name: docs++on:+ push:+ branches: [main]+ paths:+ - 'website/**'+ - 'cubepi/**'+ - 'pyproject.toml'+ - '.github/workflows/docs.yml'+ pull_request:+ paths:+ - 'website/**'+ - 'cubepi/**'+ - 'pyproject.toml'+ - '.github/workflows/docs.yml'++permissions:+ contents: read+ deployments: write++concurrency:+ group: docs-${{ github.ref }}+ cancel-in-progress: true++jobs:+ build-and-check:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: pnpm/action-setup@v4+ with: { version: 9 }+ - uses: actions/setup-node@v4+ with:+ node-version: 22+ cache: 'pnpm'+ cache-dependency-path: website/pnpm-lock.yaml+ - uses: astral-sh/setup-uv@v3+ with: { python-version: '3.11' }+ - name: Install Python deps+ run: uv sync --frozen --extra docs+ - name: Install website deps+ working-directory: website+ run: pnpm install --frozen-lockfile+ - name: Guard against hand-edited API mdx+ run: |+ if find website/docs/api -type f -name 'cubepi-*.mdx' 2>/dev/null | grep .; then+ echo "::error::Generated API MDX files were committed. Delete them." && exit 1+ fi+ - name: Build (runs griffe via prebuild)+ working-directory: website+ env:+ POSTHOG_KEY: ${{ secrets.POSTHOG_KEY }}+ POSTHOG_HOST: ${{ secrets.POSTHOG_HOST }}+ run: pnpm build+ - name: Run vitest suite+ working-directory: website+ run: pnpm test+ - name: Upload artefact+ if: github.ref == 'refs/heads/main'+ uses: actions/upload-artifact@v4+ with:+ name: website-build+ path: website/build/+ if-no-files-found: error++ deploy-cloudflare:+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'+ needs: build-and-check+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/download-artifact@v4+ with:+ name: website-build+ path: website/build/+ - name: Deploy to Cloudflare Pages+ uses: cloudflare/pages-action@v1+ with:+ apiToken: ${{ secrets.CF_API_TOKEN }}+ accountId: ${{ secrets.CF_ACCOUNT_ID }}+ projectName: cubepi+ directory: website/build+ gitHubToken: ${{ secrets.GITHUB_TOKEN }}+ branch: main+```++- [ ] **Step 2: Local dry-run**++```bash+cd website && pnpm build && pnpm test+```++Expected: both pass.++- [ ] **Step 3: Commit**++```bash+git add .github/workflows/docs.yml+git commit -m "ci: build, test, and deploy docs to Cloudflare Pages"+```++- [ ] **Step 4: Configure repository secrets**++Manually (cannot be automated):++1. In Cloudflare dashboard → Pages → create a project named `cubepi`, "Direct upload" mode.+2. Cloudflare → My Profile → API Tokens → create token with `Cloudflare Pages:Edit`.+3. GitHub repo → Settings → Secrets and variables → Actions, add:+ - `CF_API_TOKEN`+ - `CF_ACCOUNT_ID`+ - `POSTHOG_KEY`+ - `POSTHOG_HOST` (optional; defaults to US endpoint)++Record completion of this manual step in the PR description.++---++## Phase 10 — README & links++### Task 23: README & link out++**Files:**+- Modify: `README.md`++- [ ] **Step 1: Add a docs banner near the top**++After the badges block in `README.md`, insert:++```markdown+**Docs:** https://cubepi.pages.dev — Getting Started · API Reference · Recipes+```++- [ ] **Step 2: Verify image paths**++```bash+grep -n 'assets/brand' README.md+```++Expected: no output. Already fixed by Task 1, this is a sanity check.++- [ ] **Step 3: Commit**++```bash+git add README.md+git commit -m "docs: link README to https://cubepi.pages.dev"+```++---++## Phase 11 — Open PR++### Task 24: Push the branch and open a PR++- [ ] **Step 1: Push**++```bash+git push -u origin <current-branch>+```++- [ ] **Step 2: Open the PR**++```bash+gh pr create --title "Add CubePi documentation site (Docusaurus 3, EN+zh-Hans, PostHog feedback, CF Pages)" --body "$(cat <<'EOF'+## Summary+- New `website/` Docusaurus 3 site with Operator-styled custom homepage+- EN default + zh-Hans (core 6–8 pages stubbed) with locale + version dropdowns+- API reference auto-generated from docstrings via griffe (prebuild)+- 👍/👎 footer widget capturing `doc_feedback` / `doc_feedback_comment` to PostHog+- CI: build + test + deploy to Cloudflare Pages at `cubepi.pages.dev`+- First snapshot `0.3` is the default; `Next 🚧` at `/next/`++Spec: `docs/specs/2026-05-15-cubepi-docs-site-design.md`+Plan: `docs/plans/2026-05-15-cubepi-docs-site.md`++## Test plan+- [ ] `pnpm install` + `uv sync --extra docs` succeeds on a fresh clone+- [ ] `pnpm dev` (== `pnpm start`) serves the site at http://localhost:3000+- [ ] `pnpm build` succeeds locally+- [ ] `pnpm test` passes (3 DocFeedback + 3 build_api_reference)+- [ ] Click 👍 / 👎 on any page; verify `doc_feedback` event lands in PostHog+- [ ] Switch locale to 简体中文; verify zh-Hans pages render and API pages show fallback+- [ ] Switch version to Next 🚧; verify URL is `/next/...`+- [ ] CI green; preview URL deployable from CF Pages dashboard+EOF+)"+```++---++## Out of scope (explicit non-tasks)++- Translating full English content into zh-Hans (stubs only; content PRs follow).+- Replacing placeholder page content with real prose (separate content PR).+- Algolia DocSearch application — relies on the site being live first.+- Custom domain binding — deferred until post-1.0.+- Lighthouse perf tuning — add as follow-up issue.++---++## Pre-flight assumptions++The first executor of this plan should verify these are true before starting Task 1:++1. `pnpm dlx create-docusaurus` works locally (Node 22 installed).+2. `uv` is installed and `uv run python -V` prints 3.11+.+3. The `cubepi` package imports cleanly from a fresh `uv sync` — required for griffe.+4. `gh` CLI is authenticated for Task 24.++If any of these are not true, stop and surface the gap before starting.diff --git a/dev/plans/2026-05-18-cubepi-tracing-phase-0.md b/dev/plans/2026-05-18-cubepi-tracing-phase-0.mdnew file mode 100644index 0000000..added1f--- /dev/null+++ b/dev/plans/2026-05-18-cubepi-tracing-phase-0.md@@ -0,0 +1,846 @@+# CubePi Tracing — Phase 0 Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Land the two cubepi-internal extensions that the tracing module depends on, with no `cubepi/tracing/` code introduced yet. After Phase 0, the existing agent loop and providers behave identically for users who haven't subscribed any listener, and a third party can attach observers to capture wire payloads, per-chunk timing, assembled response body, and richer tool-execution context.++**Architecture:** Two independent, additive extensions to cubepi:++1. **Provider listener registry** (`cubepi/providers/`) — keeps the existing `Provider` `runtime_checkable` Protocol **unchanged** (preserves the documented duck-typing contract for user providers; see Task 2 rationale). Introduces a new concrete base class `BaseProvider` carrying a multi-subscriber listener registry. Adds three new persistent subscription methods (`subscribe_request`, `subscribe_chunk`, `subscribe_response`) and three new callback types. Existing per-call `StreamOptions.on_payload` / `on_response` slots retain their current semantics. Built-in providers (`anthropic.py`, `openai.py`, `openai_responses.py`, `faux.py`) inherit from `BaseProvider` and call a single `_fire_listeners` helper at three points in `stream()`: after the request payload is finalized, for each `StreamEvent` pushed onto the message stream, and exactly once in a `finally` block after the stream terminates (normal completion, exception, or `asyncio.CancelledError`). Duck-typed user providers continue to work; the tracer detects listener support via `isinstance(provider, BaseProvider)` and skips request/chunk/response capture for providers that don't opt in.++2. **`ToolExecutionEndEvent` extension** (`cubepi/agent/`) — adds three additive fields (`terminate`, `blocked_by_hook`, `block_reason`) to the event. The tool-execution layer (`cubepi/agent/tools.py`) already has all the information internally; it just needs to thread three more values through the existing `_ImmediateOutcome` / `_FinalizedOutcome` dataclasses and the three `ToolExecutionEndEvent` emission sites (sequential path, parallel path's immediate-outcome branch, and parallel path's async-execution branch). Backward compatible — defaults are conservative.++Both extensions are additive: no existing tests should change, no public API names change, no behavior changes for callers that don't opt in. The PRs can land in either order.++**Tech Stack:** Python 3.10+, `pydantic>=2`, `pytest`, `pytest-asyncio`. No new runtime dependencies.++**Spec:** `docs/specs/2026-05-18-cubepi-tracing-design.md` §3.4++---++## Phase 0a — Provider listener registry++### Task 1: Add new callback types and helper to `providers/base.py`++**Files:**+- Modify: `cubepi/providers/base.py`++**Goal:** Expose the three new callback type aliases and a single `_fire_listeners` helper that all providers will use. No behavior change yet.++- [ ] **Step 1: Add callback type aliases**++In `cubepi/providers/base.py`, after the existing `OnPayloadCallback` / `OnResponseCallback` declarations, add:++```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."""++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."""++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."""+```++- [ ] **Step 2: Add `_fire_listeners` helper**++Below the new callback types, add a single async helper that invokes every listener in registration order and swallows their exceptions:++```python+async def _fire_listeners(+ listeners: "list[Callable]",+ *args: Any,+) -> None:+ """Invoke each listener with *args. Listener return values and exceptions+ are ignored — a buggy listener must never crash the stream. Exceptions+ are logged via the loguru logger if available, otherwise via stdlib+ logging.warning.++ Iterates a snapshot (``tuple(listeners)``) so a listener that detaches+ itself mid-iteration does not silently skip subsequent listeners.+ Caller is responsible for the hot-path guard — see Step 4 below."""+ if not listeners:+ return+ for cb in tuple(listeners):+ try:+ result = cb(*args)+ if inspect.isawaitable(result):+ await result+ except Exception as exc: # noqa: BLE001 — intentional broad catch+ _log_listener_exception(cb, exc)+++def _log_listener_exception(cb: Callable, exc: BaseException) -> None:+ try:+ from loguru import logger+ logger.opt(exception=exc).warning(+ "cubepi provider listener {} raised; swallowed", cb+ )+ except ImportError:+ import logging+ logging.getLogger("cubepi.providers").warning(+ "cubepi provider listener %r raised; swallowed", cb, exc_info=exc+ )+```++- [ ] **Step 3: Run `uv run pytest tests/` to confirm no regression**++No tests should fail or change. This task is purely additive.++- [ ] **Step 4: (Documentation) Note the per-site hot-path guard pattern**++Every provider call site that invokes `_fire_listeners` for chunks (which can fire hundreds of times per stream) MUST guard with a synchronous `if` to avoid `await` overhead when no listeners are registered:++```python+# at every chunk emission site:+if self._chunk_listeners:+ await _fire_listeners(self._chunk_listeners, event, model)+```++For the request and response sites (one call each per stream), the guard is optional but recommended for symmetry. Tasks 3–5 use this guard at every call site.++---++### Task 2: Introduce `BaseProvider` alongside the existing `Provider` Protocol++**Files:**+- Modify: `cubepi/providers/base.py`+- Modify: `cubepi/providers/__init__.py`+- Modify: `cubepi/__init__.py`++**Goal:** Preserve backward compatibility for duck-typed user providers (`tests/agent/test_loop.py:512` `_NoFinalEventProvider` and `:567` `_NoFinalEventNoPartialProvider` are existing duck-typed providers; `website/docs/guides/providers/custom.md` documents the duck-typing contract publicly). Adding `subscribe_*` methods to the existing `Protocol` would silently break any caller relying on the documented "any class with a `stream()` method works" promise — `isinstance(x, Provider)` would return False for them after the change.++Strategy: leave `Provider` as the unchanged `runtime_checkable` Protocol; introduce a **new** concrete base class `BaseProvider` that built-in providers (`AnthropicProvider`, `OpenAIProvider`, `OpenAIResponsesProvider`, `FauxProvider`) inherit from. The Protocol covers everyone; the base class adds the listener registry for built-ins.++The tracer (Phase 1) discovers listener support via `isinstance(provider, BaseProvider)` or `hasattr(provider, "subscribe_request")`; for duck-typed providers without the registry, the tracer emits high-level spans (from `agent.subscribe`) but no `chat` span attributes for request/chunk/response — and logs an INFO line about this.++- [ ] **Step 1: Leave the existing `Provider` Protocol untouched**++Do **not** modify `class Provider(Protocol)`. It stays as today:++```python+@runtime_checkable+class Provider(Protocol):+ async def stream(...) -> MessageStream: ...+```++- [ ] **Step 2: Add a new `BaseProvider` concrete class to `cubepi/providers/base.py`**++Place it immediately after the `Provider` Protocol declaration:++```python+class BaseProvider:+ """Concrete base class for built-in cubepi providers.++ Built-in providers (Anthropic, OpenAI, FauxProvider) 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.+ """++ def __init__(self) -> None:+ self._request_listeners: list[OnRequestCallback] = []+ self._chunk_listeners: list[OnChunkCallback] = []+ self._response_listeners: list[OnResponseBodyCallback] = []++ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ options: StreamOptions | None = None,+ ) -> MessageStream:+ raise NotImplementedError++ def subscribe_request(self, cb: OnRequestCallback) -> Callable[[], None]:+ """Register a persistent observer for request payloads.+ Returns a detach callable that removes this specific subscription."""+ self._request_listeners.append(cb)+ return lambda: _detach(self._request_listeners, cb)++ def subscribe_chunk(self, cb: OnChunkCallback) -> Callable[[], None]:+ """Register a persistent observer for stream chunks.+ Returns a detach callable."""+ self._chunk_listeners.append(cb)+ return lambda: _detach(self._chunk_listeners, cb)++ def subscribe_response(self, cb: OnResponseBodyCallback) -> Callable[[], None]:+ """Register a persistent observer for assembled responses.+ Returns a detach callable."""+ self._response_listeners.append(cb)+ return lambda: _detach(self._response_listeners, cb)+++def _detach(listeners: list, cb: Callable) -> None:+ try:+ listeners.remove(cb)+ except ValueError:+ pass+```++- [ ] **Step 3: Export `BaseProvider` from the package**++In `cubepi/providers/__init__.py`, add `BaseProvider` (alongside the existing `Provider`) to imports and `__all__`. In `cubepi/__init__.py`, do the same so users can `from cubepi import BaseProvider`.++- [ ] **Step 4: Run `uv run pytest tests/`**++All existing tests pass — duck-typed test providers still work because the `Provider` Protocol is unchanged.++---++### Task 3: Update `AnthropicProvider` to inherit and fire listeners++**Files:**+- Modify: `cubepi/providers/anthropic.py`++**Goal:** Make `AnthropicProvider` inherit from `BaseProvider`, call `_fire_listeners` at three points in `stream()`, and guarantee `on_response` fires exactly once in a `finally` block.++**Codebase anchors** (verified against current `anthropic.py`):+- Class at `anthropic.py:60` is plain `class AnthropicProvider:` — no base class today.+- `invoke_on_payload` is called at `anthropic.py:143`.+- The internal `MessageStream` variable inside the producer is named **`ms`**, not `stream`.+- Direct `ms.push(...)` sites at lines 165, 177, 190, 201.+- A synchronous helper `_handle_event(event, partial, ms)` defined at `anthropic.py:334` makes **9 internal `ms.push(...)` calls** (lines 343, 352, 363, 378, 391, 400, 413, 421, 429). Caller at line 186: `self._handle_event(event, partial, ms)`.+- The producer body lives inside `stream()` and is what `MessageStream.attach_task` runs.++- [ ] **Step 1: Inherit from `BaseProvider`**++Find:++```python+class AnthropicProvider:+```++Change to:++```python+class AnthropicProvider(BaseProvider):+```++If an `__init__` exists, add `super().__init__()` as its first statement. If not, add one:++```python+def __init__(self) -> None:+ super().__init__()+```++- [ ] **Step 2: Fire `_request_listeners` after `invoke_on_payload`**++After the existing line at `anthropic.py:143` (`kwargs = await invoke_on_payload(opts.on_payload, kwargs, model)`), append:++```python+if self._request_listeners:+ await _fire_listeners(self._request_listeners, kwargs, model)+```++- [ ] **Step 3: Refactor `_handle_event` to async + add an `_emit` helper**++`_handle_event` (sync, line 334) cannot `await` listener firings. Two coupled changes:++ a) Add a private async helper to the class:++ ```python+ async def _emit(self, ms: MessageStream, event: StreamEvent, model: Model) -> None:+ ms.push(event)+ if self._chunk_listeners:+ await _fire_listeners(self._chunk_listeners, event, model)+ ```++ b) Refactor `_handle_event` from `def _handle_event(self, event, partial, ms)` to `async def _handle_event(self, event, partial, ms, model)`. Update its call site at `anthropic.py:186` to `await self._handle_event(event, partial, ms, model)`.++ c) Inside the refactored `_handle_event`, replace every `ms.push(...)` (the 9 sites at lines 343, 352, 363, 378, 391, 400, 413, 421, 429) with `await self._emit(ms, ..., model)`.++ d) Replace the 4 direct `ms.push(...)` sites in `stream()` itself (lines 165, 177, 190, 201) with `await self._emit(ms, ..., model)`.++- [ ] **Step 4: Wrap the producer body in `try / except BaseException / finally`**++Locate the producer coroutine body inside `stream()` — the section that does HTTP streaming, pushes events, and concludes with `ms.push(StreamEvent(type="done"))`. The wrap is around **that** body, not the `stream()` setup that synchronously returns a `MessageStream`. Structure:++```python+body: dict | None = None+exc: BaseException | None = None+try:+ # existing producer body — HTTP stream open, event loop, accumulating+ # `partial` AssistantMessage and any provider-side state needed to+ # assemble `body` below.+ # On normal completion, just before pushing the final "done" event:+ body = self._assemble_response(partial, response_id, response_model, ...)+except BaseException as e:+ exc = e+ raise+finally:+ if self._response_listeners:+ await _fire_listeners(self._response_listeners, body, model, exc)+```++`asyncio.CancelledError` is a `BaseException`, not an `Exception`. Catching `BaseException` is intentional; the exception is re-raised after listeners fire.++- [ ] **Step 5: Add `_assemble_response()`**++Returns a dict shaped like Anthropic's non-streaming `messages.create()` response. Source every field from state the streaming loop already accumulates — **do not** issue a second HTTP call.++Required fields, with sources:++| Key | Source |+|---|---|+| `id` | the `message_start` event's `message.id` (already captured) |+| `type` | constant `"message"` |+| `role` | constant `"assistant"` |+| `model` | the `message_start` event's `message.model` |+| `content` | accumulated `partial.content` translated back to Anthropic's content-block shape: `TextContent → {"type": "text", "text": ...}`, `ThinkingContent → {"type": "thinking", "thinking": ...}`, `ToolCall → {"type": "tool_use", "id": ..., "name": ..., "input": ...}` |+| `stop_reason` | raw Anthropic stop reason from `message_delta` (e.g. `"end_turn"`, `"tool_use"`, `"max_tokens"`, `"stop_sequence"`) — **NOT** the normalized cubepi value |+| `stop_sequence` | from `message_delta`, or `None` |+| `usage.input_tokens` | from `message_delta.usage.input_tokens` |+| `usage.output_tokens` | from `message_delta.usage.output_tokens` |+| `usage.cache_creation_input_tokens` | from `message_delta.usage.cache_creation_input_tokens`, or `0` |+| `usage.cache_read_input_tokens` | from `message_delta.usage.cache_read_input_tokens`, or `0` |++If the stream aborts before any of these are available, that field is omitted (not set to `None`). The recorder treats absent fields as "provider didn't return this" and skips the corresponding span attribute.++- [ ] **Step 6: Run `uv run pytest tests/providers/test_anthropic*.py`**++Existing tests pass — listener-related code is no-op when registries are empty.++---++### Task 4: Update OpenAI providers++**Files:**+- Modify: `cubepi/providers/openai.py`+- Modify: `cubepi/providers/openai_responses.py`++**Goal:** Same listener wiring as Task 3, applied to both OpenAI providers. The two providers have different stream shapes and different assembly paths — handled separately below.++**Note on the absence of `_handle_event`:** unlike `anthropic.py`, both OpenAI providers call `ms.push(...)` inline within their stream loop — no synchronous helper exists. Each call site can be inlined with `await self._emit(ms, ..., model)` directly (define `_emit` as a method on each provider class).++#### 4A. `openai.py` (`OpenAIProvider`, chat completions API)++**Codebase anchors:**+- Class at `openai.py:31` is plain `class OpenAIProvider:`.+- 16+ inline `ms.push(...)` sites between lines 132 and 383 (none in a helper function).+- `invoke_on_response` is called around line 119 with HTTP metadata; `invoke_on_payload` follows the same pattern as Anthropic — find it in the same file.+- The streaming loop accumulates `response_id` (line 169), `usage` (`u` variable at line 148), and tool-call deltas; finish reason is captured at line 326.++- [ ] **Step 1: Inherit from `BaseProvider`** — same pattern as Task 3 Step 1.++- [ ] **Step 2: Add `_emit` helper method on the class.** Identical signature/body to the Anthropic helper (Task 3 Step 3a).++- [ ] **Step 3: Fire `_request_listeners` after `invoke_on_payload`** — find the call site, append the guarded fire as in Task 3 Step 2.++- [ ] **Step 4: Replace every `ms.push(...)` with `await self._emit(ms, ..., model)`** at all 16+ sites. (Search/replace, then visually verify each.)++- [ ] **Step 5: Wrap producer body in `try / except BaseException / finally`** — same pattern as Task 3 Step 4.++- [ ] **Step 6: Implement `_assemble_response()`** — returns OpenAI's `chat.completion` non-streaming response shape:++| Key | Source |+|---|---|+| `id` | `response_id` captured at line 169 |+| `object` | constant `"chat.completion"` |+| `created` | first chunk's `created` (capture during stream) |+| `model` | first chunk's `model` (capture during stream) |+| `system_fingerprint` | first chunk's `system_fingerprint`, or absent |+| `service_tier` | first chunk's `service_tier`, or absent |+| `choices` | one-element array: `[{"index": 0, "message": {"role": "assistant", "content": <accumulated text>, "tool_calls": <accumulated tool_calls in OpenAI's format>}, "finish_reason": <captured at line 326>, "logprobs": null}]` |+| `usage` | accumulated `Usage` dict: `{"prompt_tokens", "completion_tokens", "total_tokens", "prompt_tokens_details": {"cached_tokens": ...}}` — sourced from the `u` variable around line 148 |++Tool-call shape inside `choices[0].message.tool_calls` follows OpenAI's spec: `[{"id": ..., "type": "function", "function": {"name": ..., "arguments": <json string>}}]`. Accumulate from the `toolcall_*` `StreamEvent`s during streaming.++#### 4B. `openai_responses.py` (`OpenAIResponsesProvider`, Responses API)++**Codebase anchors:**+- Class at `openai_responses.py:42` is plain `class OpenAIResponsesProvider:`.+- Many inline `ms.push(...)` sites between lines 131 and 479.+- **Key shortcut:** at line 410, the streaming code already binds `resp = event.response` — this is the OpenAI SDK's `Response` object containing the fully-assembled response. No manual accumulation needed; `resp.model_dump()` (or `dict(resp)`) gives the canonical shape.++- [ ] **Step 1: Inherit from `BaseProvider`.**++- [ ] **Step 2: Add `_emit` helper method.**++- [ ] **Step 3: Fire `_request_listeners` after `invoke_on_payload`.**++- [ ] **Step 4: Replace every `ms.push(...)` with `await self._emit(ms, ..., model)`.**++- [ ] **Step 5: Wrap producer body in `try / except BaseException / finally`.**++- [ ] **Step 6: Implement `_assemble_response()`** — leverage the SDK's already-assembled response object. Capture `resp` at line 410 (and the analogous line 450 for the failure path) into an instance/local variable accessible from the `finally` block, then:++ ```python+ body = resp.model_dump(mode="json") if resp is not None else None+ ```++ This yields the canonical Responses-API shape. No field-by-field assembly required.++- [ ] **Step 7: Run `uv run pytest tests/providers/test_openai*.py`**++---++### Task 5: Update `FauxProvider`++**Files:**+- Modify: `cubepi/providers/faux.py`++**Goal:** Same listener wiring as Task 3, applied to the test/dev faux provider. **This is the most important provider** for testing the listener registry itself (Task 6 pins contract via faux). Tests must be deterministic — `faux.py` currently uses `random.randbytes`, `random.randint`, and `time.time()` (see `_random_id` at line 36, the token-size sampling at line 81, `timestamp` at lines 76, 241, 285, 476). The faux response assembly must NOT inherit that nondeterminism.++**Codebase anchors:**+- Class at `faux.py:151` is `class FauxProvider:`.+- `_random_id(prefix)` at line 36 builds non-deterministic IDs from `time.time()` + `random.randbytes`.++- [ ] **Step 1: Inherit from `BaseProvider`** — same pattern as Task 3.++- [ ] **Step 2: Add `_emit` helper method and replace every `ms.push(...)`** — same pattern.++- [ ] **Step 3: Fire `_request_listeners` after `invoke_on_payload`** — same pattern.++- [ ] **Step 4: Wrap producer body in `try / except BaseException / finally`** — same pattern.++- [ ] **Step 5: Implement `_assemble_response()` with a pinned schema**++Define a per-instance monotonic counter (`self._response_seq`, initialized in `__init__`, incremented at the start of each `stream()` call) so IDs are deterministic per FauxProvider instance:++```python+def __init__(self, ...) -> None:+ super().__init__()+ self._response_seq = 0+ # ... existing init++# inside stream() producer:+self._response_seq += 1+seq = self._response_seq+```++Pin the dict schema exactly:++```python+def _assemble_response(+ self,+ *,+ seq: int,+ model: Model,+ content_blocks: list[dict],+ stop_reason: str,+ input_tokens: int,+ output_tokens: int,+) -> dict:+ return {+ "id": f"faux-{seq}",+ "model": model.id,+ "role": "assistant",+ "content": content_blocks, # list of {"type", "text"|...}+ "stop_reason": stop_reason, # "stop" / "tool_use" / "length" / "error"+ "usage": {+ "input_tokens": input_tokens,+ "output_tokens": output_tokens,+ },+ }+```++Tests in Task 6 will assert against this exact shape — no extra keys, no missing keys, no random IDs.++- [ ] **Step 6: Run `uv run pytest tests/providers/test_faux*.py`**++---++### Task 6: Listener registry tests++**Files:**+- Create: `tests/providers/test_listener_registry.py`++**Goal:** Pin the listener registry contract with tests that don't rely on any real provider.++- [ ] **Step 1: Test that listeners can be subscribed and called**++Use `FauxProvider` (subclassing `BaseProvider` after Task 5). Subscribe one listener of each type. Run a streamed call. Assert each listener was invoked at least once, with the documented argument shapes.++- [ ] **Step 2: Test detach()**++Subscribe a listener; detach; run another call. Listener must not be invoked again.++- [ ] **Step 3: Test multiple subscribers, in registration order**++Subscribe two listeners on `subscribe_request`. Assert both fire, in registration order.++- [ ] **Step 4: Test that a raising listener does not crash the stream**++Subscribe a listener that raises `RuntimeError`. Subscribe a second listener after it. Run a call. Assert: (a) the call completes successfully, (b) the second listener still fires.++- [ ] **Step 5: Test response listener fires exactly once on normal completion**++- [ ] **Step 6: Test response listener fires exactly once on exception**++Make `FauxProvider.stream()` raise mid-stream (via a test-only knob or by injecting an error). Assert `response_listener` was called once with `(None, model, exc)` (or with a partial body and `exc`, depending on how faux assembles).++- [ ] **Step 7: Test response listener fires exactly once on `asyncio.CancelledError`**++Start a stream, cancel the task before it completes. Assert `response_listener` was called once with `(body_or_None, model, isinstance=CancelledError)`. The `CancelledError` should propagate out.++- [ ] **Step 8: Test that `StreamOptions.on_payload` mutation runs before `subscribe_request` listeners see the payload**++Provide a per-call `on_payload` that mutates the payload. Subscribe a `subscribe_request` listener. Assert the listener sees the mutated payload, not the pre-mutation one.++- [ ] **Step 9: Test concurrent streams on the same Provider**++Subscribe one chunk listener. Launch two `faux.stream(...)` calls concurrently via `asyncio.gather`. Assert the listener receives events from both streams (use the `Model` argument to distinguish, since each call passes its own model) and that response_listener fires exactly twice — once per call.++- [ ] **Step 10: Test that a listener can detach itself mid-iteration**++Subscribe two listeners on `subscribe_chunk`. The first one calls its own detach callable on its first invocation. The second listener must still fire on the same and subsequent chunks. (This is the `tuple(listeners)` snapshot semantics — verify it.)++- [ ] **Step 11: Test that a listener subscribed mid-stream begins firing on the next call (not retroactively)**++Subscribe a `subscribe_response` listener. Inside its body, subscribe a second `subscribe_response` listener. Assert: on the same stream, only the first listener fired; on a follow-up stream, both fire.++- [ ] **Step 12: Test that a slow async listener serializes the stream**++Subscribe a chunk listener that `await asyncio.sleep(0.05)`. Time a faux stream end-to-end. Assert the wall time is at least `0.05 * chunk_count`. This documents the contract: listeners run **inline** in the producer coroutine and block subsequent chunks. The Phase 1 tracer's listeners are designed to be cheap; a slow listener is the listener-author's problem, but the contract must be visible in tests.++- [ ] **Step 13: Run `uv run pytest tests/providers/test_listener_registry.py -v`**++All tests pass.++---++## Phase 0b — `ToolExecutionEndEvent` extension++These tasks are independent of Phase 0a and can land in a separate PR.++### Task 7: Extend `ToolExecutionEndEvent`++**Files:**+- Modify: `cubepi/agent/types.py`++**Goal:** Add three additive fields with conservative defaults.++- [ ] **Step 1: Update the `ToolExecutionEndEvent` class**++Find:++```python+class ToolExecutionEndEvent(BaseModel):+ type: Literal["tool_execution_end"] = "tool_execution_end"+ tool_call_id: str+ tool_name: str+ result: Any = None+ is_error: bool = False+```++Replace with:++```python+class ToolExecutionEndEvent(BaseModel):+ type: Literal["tool_execution_end"] = "tool_execution_end"+ tool_call_id: str+ tool_name: str+ result: Any = None+ is_error: bool = False+ terminate: bool = False+ """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."""+ blocked_by_hook: bool = False+ """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)."""+ block_reason: str | None = None+ """When blocked_by_hook is True, the reason string from+ BeforeToolCallResult.reason (or None if the hook supplied no reason)."""+```++- [ ] **Step 2: Run `uv run pytest tests/`**++Tests pass. No existing test should be checking these fields yet; defaults mean nothing changes.++---++### Task 8: Track block reason in `_ImmediateOutcome`++**Files:**+- Modify: `cubepi/agent/tools.py`++**Goal:** Internally distinguish "blocked by hook" from other immediate errors, and carry the reason string.++- [ ] **Step 1: Add fields to `_ImmediateOutcome`**++Find:++```python+@dataclass+class _ImmediateOutcome:+ result: AgentToolResult+ is_error: bool+```++Replace with:++```python+@dataclass+class _ImmediateOutcome:+ result: AgentToolResult+ is_error: bool+ blocked_by_hook: bool = False+ block_reason: str | None = None+```++- [ ] **Step 2: Set the fields in `_prepare_tool_call` when `before_tool_call` blocks**++In `_prepare_tool_call`, find the block-handling branch:++```python+if before_result and before_result.block:+ return _ImmediateOutcome(+ result=_error_result(+ before_result.reason or "Tool execution was blocked"+ ),+ is_error=True,+ )+```++Change to:++```python+if before_result and before_result.block:+ return _ImmediateOutcome(+ result=_error_result(+ before_result.reason or "Tool execution was blocked"+ ),+ is_error=True,+ blocked_by_hook=True,+ block_reason=before_result.reason,+ )+```++Leave all other `_ImmediateOutcome` constructions unchanged — they keep `blocked_by_hook=False`, `block_reason=None` by default.++---++### Task 9: Thread `terminate` / `blocked_by_hook` / `block_reason` through `_FinalizedOutcome`++**Files:**+- Modify: `cubepi/agent/tools.py`++**Goal:** Carry the three values from `_ImmediateOutcome` (when applicable) and `AgentToolResult.terminate` through to the event emission sites.++- [ ] **Step 1: Add fields to `_FinalizedOutcome`**++Find:++```python+@dataclass+class _FinalizedOutcome:+ tool_call: ToolCall+ result: AgentToolResult+ is_error: bool+```++Replace with:++```python+@dataclass+class _FinalizedOutcome:+ tool_call: ToolCall+ result: AgentToolResult+ is_error: bool+ blocked_by_hook: bool = False+ block_reason: str | None = None+```++- [ ] **Step 2: Propagate blocked-by-hook info when building `_FinalizedOutcome` from an immediate-blocked outcome**++In both `_execute_sequential` and `_execute_parallel`, locate the point that creates a `_FinalizedOutcome` from an `_ImmediateOutcome`. Update it to copy the new fields:++```python+finalized = _FinalizedOutcome(+ tool_call=tc,+ result=preparation.result,+ is_error=preparation.is_error,+ blocked_by_hook=preparation.blocked_by_hook,+ block_reason=preparation.block_reason,+)+```++All other `_FinalizedOutcome` construction sites stay at default (`False`, `None`).++---++### Task 10: Emit new fields at all three `ToolExecutionEndEvent` sites++**Files:**+- Modify: `cubepi/agent/tools.py`++**Goal:** Populate the three new event fields in both the sequential and parallel emission paths.++- [ ] **Step 1: Sequential path**++Find the `ToolExecutionEndEvent` emission in `_execute_sequential` (around line 283):++```python+ToolExecutionEndEvent(+ tool_call_id=tc.id,+ tool_name=tc.name,+ result=finalized.result,+ is_error=finalized.is_error,+),+```++Replace with:++```python+ToolExecutionEndEvent(+ tool_call_id=tc.id,+ tool_name=tc.name,+ result=finalized.result,+ is_error=finalized.is_error,+ terminate=bool(finalized.result.terminate),+ blocked_by_hook=finalized.blocked_by_hook,+ block_reason=finalized.block_reason,+),+```++- [ ] **Step 2: Parallel path — immediate-outcome branch**++Same pattern at the equivalent emission site in `_execute_parallel`:++```python+ToolExecutionEndEvent(+ tool_call_id=tc.id,+ tool_name=tc.name,+ result=finalized.result,+ is_error=finalized.is_error,+ terminate=bool(finalized.result.terminate),+ blocked_by_hook=finalized.blocked_by_hook,+ block_reason=finalized.block_reason,+),+```++- [ ] **Step 3: Parallel path — async-execution branch**++There's a third emission inside the `_run` inner function (around line 355). Update the same way; `fin` is the `_FinalizedOutcome`:++```python+ToolExecutionEndEvent(+ tool_call_id=prep.tool_call.id,+ tool_name=prep.tool_call.name,+ result=fin.result,+ is_error=fin.is_error,+ terminate=bool(fin.result.terminate),+ blocked_by_hook=fin.blocked_by_hook,+ block_reason=fin.block_reason,+),+```++- [ ] **Step 4: Run `uv run pytest tests/agent/`**++All existing tests pass.++---++### Task 11: Event extension tests++**Files:**+- Create: `tests/agent/test_tool_event_extension.py`++**Goal:** Pin the three new field behaviors.++- [ ] **Step 1: Test `terminate=True` propagates**++Build an `AgentTool` whose execute returns `AgentToolResult(content=[...], terminate=True)`. Run the agent. Capture `ToolExecutionEndEvent` via `agent.subscribe(...)`. Assert `event.terminate is True`.++- [ ] **Step 2: Test `terminate=False` for normal tools**++Same setup with a tool that returns `terminate=None` or unset. Assert `event.terminate is False`.++- [ ] **Step 3: Test `blocked_by_hook=True` and `block_reason`**++Define a `before_tool_call` hook that returns `BeforeToolCallResult(block=True, reason="not allowed")`. Run the agent so the tool gets blocked. Assert the emitted event has `blocked_by_hook=True`, `block_reason="not allowed"`, `is_error=True`.++- [ ] **Step 4: Test other immediate errors don't set `blocked_by_hook`**++Force a tool-not-found case (call a tool the agent doesn't know). Assert the emitted event has `is_error=True` but `blocked_by_hook=False` and `block_reason is None`.++- [ ] **Step 5: Test arg-validation error doesn't set `blocked_by_hook`**++Pass invalid arguments. Same assertion as Step 4.++- [ ] **Step 6: Test parallel-execution path also populates the fields**++Run with `tool_execution="parallel"` and two tool calls, one of which the hook blocks. Both events should fire with correct fields.++- [ ] **Step 7: Run `uv run pytest tests/agent/test_tool_event_extension.py -v`**++---++## Cross-cutting++### Task 12: Version bump++**Files:**+- Modify: `pyproject.toml`++- [ ] **Step 1: (skipped — no CHANGELOG.md in repo)**++- [ ] **Step 2: Bump version**++Version lives in `pyproject.toml:3` (`version = "0.3.0"`). cubepi does **not** expose a `cubepi.__version__` attribute on the package; do not add one as part of this plan unless other work depends on it.++Bump `pyproject.toml` to `0.4.0` — additive but introduces new public API surface (`BaseProvider.subscribe_*`, three new `ToolExecutionEndEvent` fields).++There is no `CHANGELOG.md` in the repo today. Skip Step 1 (changelog) entirely; capture the release note in the PR description instead.++---++### Task 13: PR breakdown++These two phases land in **two separate PRs** on **two separate branches**:++- [ ] **PR 1:** `feat/provider-listener-registry` — Tasks 1–6 + Task 12 (version bump to 0.4.0)+- [ ] **PR 2:** `feat/tool-event-extension` — Tasks 7–11 (no separate version bump — PR 1's 0.4.0 covers both)++Order does not matter; they are independent. Phase 1 (the `cubepi/tracing/` module) waits on both.++---++## Acceptance Criteria++After Phase 0:++- [ ] `uv run pytest tests/` is green+- [ ] `uv run ruff check cubepi/ tests/` is clean+- [ ] `uv run ruff format --check cubepi/ tests/` is clean+- [ ] `Provider` remains an unchanged `runtime_checkable` Protocol; duck-typed user providers still satisfy `isinstance(x, Provider)`+- [ ] `BaseProvider` is a concrete class; all four built-in providers inherit from it+- [ ] `BaseProvider.subscribe_request` / `subscribe_chunk` / `subscribe_response` exist, return detach callables, support multiple subscribers+- [ ] Each provider's `stream()` invokes `_fire_listeners` at the three documented points+- [ ] `_response_listeners` fires exactly once per `stream()` call, including under `asyncio.CancelledError`+- [ ] A listener that raises does not crash the stream and does not prevent other listeners from firing+- [ ] `ToolExecutionEndEvent` has `terminate`, `blocked_by_hook`, `block_reason` fields with conservative defaults+- [ ] `cubepi/agent/tools.py` populates these fields correctly in both sequential and parallel paths+- [ ] No existing test is modified to pass (i.e., backwards compatible)+- [ ] No new runtime dependency added+- [ ] Version bumped to reflect new public API surfacediff --git a/dev/specs/2026-05-09-cubepi-framework-design.md b/dev/specs/2026-05-09-cubepi-framework-design.mdnew file mode 100644index 0000000..c938b84--- /dev/null+++ b/dev/specs/2026-05-09-cubepi-framework-design.md@@ -0,0 +1,536 @@+# cubepi Framework Design Spec++A Pythonic agent framework inspired by pi-agent-core, designed to replace langgraph in cubebox.++## Goals++- General-purpose Python agent framework, not cubebox-specific+- Built-in multi-provider LLM abstraction (Anthropic, OpenAI)+- Hook callbacks (like pi) + Middleware protocol (new) for extensibility+- Optional Checkpointer with built-in Memory and SQLite implementations+- Streaming-first, async-native++## Module Structure++```+cubepi/+├── __init__.py+├── providers/ # LLM provider abstraction+│ ├── __init__.py+│ ├── base.py # Provider Protocol, Message types, StreamEvent, MessageStream+│ ├── anthropic.py # Anthropic implementation+│ ├── openai.py # OpenAI implementation+│ └── faux.py # FauxProvider (testing utility, public API)+├── agent/ # Agent runtime core+│ ├── __init__.py+│ ├── agent.py # Agent class (stateful wrapper)+│ ├── loop.py # run_agent_loop (stateless core loop)+│ ├── types.py # AgentEvent, AgentContext, AgentTool, hooks+│ └── tools.py # Tool execution engine (sequential/parallel)+├── middleware/ # Middleware protocol and composition+│ ├── __init__.py+│ └── base.py # Middleware Protocol + compose_middleware()+├── checkpointer/ # Optional state persistence+│ ├── __init__.py+│ ├── base.py # Checkpointer Protocol+│ ├── memory.py # MemoryCheckpointer (dev/test)+│ └── sqlite.py # SQLiteCheckpointer (lightweight persistence)+└── py.typed # PEP 561 marker+```++## Provider Layer++Corresponds to pi-ai. Each provider is a class implementing the `Provider` Protocol.++### Divergences from pi-ai++| pi-ai | cubepi | Reason |+|-------|--------|--------|+| `streamSimple` global function + `Model.api` dispatch | `Provider` instance per backend | More Pythonic, easier to test/mock |+| API key in `SimpleStreamOptions` per call | API key in Provider constructor | Config belongs at init, not per-request |+| TypeBox schema for tool params | Pydantic model → JSON Schema | Pydantic is the Python standard |+| `EventStream<T, R>` class | `MessageStream` (async iterator + `.result()`) | Python async generator pattern |++### Types++All types use Pydantic `BaseModel`.++```python+ThinkingLevel = Literal["off", "minimal", "low", "medium", "high", "xhigh"]++class ModelCost(BaseModel):+ input: float = 0 # per million tokens+ output: float = 0+ cache_read: float = 0+ cache_write: float = 0++class Usage(BaseModel):+ input_tokens: int = 0+ output_tokens: int = 0+ cache_read_tokens: int = 0+ cache_write_tokens: int = 0++class Model(BaseModel):+ id: str+ provider: str+ api: str = ""+ reasoning: bool = False+ context_window: int = 200_000+ max_tokens: int = 8192+ cost: ModelCost | None = None++class TextContent(BaseModel):+ type: Literal["text"] = "text"+ text: str = ""++class ImageContent(BaseModel):+ type: Literal["image"] = "image"+ source: str = ""+ media_type: str = ""++Content = TextContent | ImageContent++class ToolCall(BaseModel):+ type: Literal["tool_call"] = "tool_call"+ id: str+ name: str+ arguments: dict[str, Any]++class UserMessage(BaseModel):+ role: Literal["user"] = "user"+ content: list[Content]+ timestamp: float | None = None++class AssistantMessage(BaseModel):+ role: Literal["assistant"] = "assistant"+ content: list[Content | ToolCall]+ stop_reason: str = "stop" # "stop" | "tool_use" | "length" | "error" | "aborted"+ error_message: str | None = None+ usage: Usage | None = None+ timestamp: float | None = None++class ToolResultMessage(BaseModel):+ role: Literal["tool_result"] = "tool_result"+ tool_call_id: str+ tool_name: str+ content: list[Content]+ is_error: bool = False+ timestamp: float | None = None++Message = UserMessage | AssistantMessage | ToolResultMessage+```++### Provider Protocol++```python+class Provider(Protocol):+ async def stream(+ self,+ model: Model,+ messages: list[Message],+ *,+ system_prompt: str = "",+ tools: list[ToolDefinition] | None = None,+ thinking: ThinkingLevel = "off",+ signal: asyncio.Event | None = None,+ ) -> MessageStream: ...+```++### MessageStream++```python+class MessageStream:+ def __aiter__(self) -> AsyncIterator[StreamEvent]: ...+ async def result(self) -> AssistantMessage: ...+```++### StreamEvent Types++Identical to pi-ai's AssistantMessageEvent:++- `start` — initial partial message+- `text_start` / `text_delta` / `text_end`+- `thinking_start` / `thinking_delta` / `thinking_end`+- `toolcall_start` / `toolcall_delta` / `toolcall_end`+- `done` — normal completion+- `error` — error completion++### ToolDefinition++Schema-only description sent to the LLM (no execution logic):++```python+class ToolDefinition(BaseModel):+ name: str+ description: str+ parameters: dict[str, Any] # JSON Schema+```++`AgentTool` auto-generates `ToolDefinition` from its Pydantic parameters model.++## Agent Runtime++Corresponds to pi-agent-core's agent.ts + agent-loop.ts.++### AgentMessage Extension++**pi's approach**: TypeScript declaration merging extends `CustomAgentMessages`.++**cubepi's approach**: Generic type parameter.++```python+# Default: AgentMessage = Message+agent = Agent(...)++# Extended with custom messages:+CubeboxMessage = Message | NotificationMessage | ArtifactMessage+agent = Agent[CubeboxMessage](convert_to_llm=my_converter, ...)+```++More explicit than pi's global declaration merging, but safer (no cross-library pollution).++### AgentEvent++Identical to pi's 11 event types, snake_case naming:++```python+AgentEvent = (+ AgentStartEvent | AgentEndEvent |+ TurnStartEvent | TurnEndEvent |+ MessageStartEvent | MessageUpdateEvent | MessageEndEvent |+ ToolExecutionStartEvent | ToolExecutionUpdateEvent | ToolExecutionEndEvent+)+```++Each event is a Pydantic model with `type: Literal[...]` discriminator.++`MessageUpdateEvent.stream_event` corresponds to pi's `assistantMessageEvent` (renamed for clarity).++### AgentTool++```python+class AgentTool(Generic[TParams]):+ name: str+ description: str+ parameters: type[TParams] # Pydantic model class+ label: str = ""+ execution_mode: Literal["sequential", "parallel"] | None = None++ async def execute(+ self,+ tool_call_id: str,+ params: TParams,+ *,+ signal: asyncio.Event | None = None,+ on_update: Callable[[ToolResult], None] | None = None,+ ) -> ToolResult: ...+```++**Divergences from pi**:+- pi uses TypeBox schema → cubepi uses Pydantic model class (auto JSON Schema generation)+- pi's `prepareArguments` compatibility shim omitted (YAGNI)+- Execution failure via `raise` (same as pi), framework catches and converts to error tool result++### Agent Class++```python+class Agent(Generic[TMessage]):+ def __init__(+ self,+ *,+ provider: Provider,+ model: Model,+ system_prompt: str = "",+ tools: list[AgentTool] | None = None,+ thinking: ThinkingLevel = "off",+ checkpointer: Checkpointer | None = None,+ thread_id: str | None = None,+ convert_to_llm: Callable | None = None,+ transform_context: Callable | None = None,+ before_tool_call: Callable | None = None,+ after_tool_call: Callable | None = None,+ should_stop_after_turn: Callable | None = None,+ steering_mode: Literal["all", "one-at-a-time"] = "one-at-a-time",+ follow_up_mode: Literal["all", "one-at-a-time"] = "one-at-a-time",+ tool_execution: Literal["sequential", "parallel"] = "parallel",+ ): ...++ @property+ def state(self) -> AgentState: ...++ def subscribe(self, listener: AgentListener) -> Callable[[], None]: ...++ async def prompt(self, message: str | TMessage | list[TMessage]) -> None: ...+ async def resume(self) -> None: ... # pi: continue() — renamed, Python keyword+ def abort(self) -> None: ...+ async def wait_for_idle(self) -> None: ...+ def reset(self) -> None: ...++ def steer(self, message: TMessage) -> None: ...+ def follow_up(self, message: TMessage) -> None: ...+```++**Divergences from pi**:+- `continue()` → `resume()` (Python reserved word)+- pi: `new Agent({ initialState: { model, tools, systemPrompt }, streamFn })` → cubepi: explicit keyword args `Agent(provider=..., model=..., tools=...)`+- Cancel signal: `asyncio.Event` instead of `AbortSignal`+- `subscribe()` returns unsubscribe callable (same as pi)+- Two message queues (steering/follow-up) with configurable drain mode (same as pi)+- Checkpointer and thread_id accepted directly by Agent (pi has no persistence)++### Agent Loop++Stateless core function, identical nested-loop structure to pi's `runLoop`:++```+Outer loop: follow-up message processing+├─ Inner loop: tool execution + steering messages+│ ├─ Stream assistant response (Provider.stream)+│ ├─ Extract tool calls from response+│ ├─ Execute tools (sequential or parallel)+│ ├─ Poll steering messages+│ └─ Repeat if tool calls remain+├─ Check should_stop_after_turn+├─ Poll follow-up messages+└─ Continue or exit+```++Two-level API (same as pi):+- `Agent` class for most use cases+- `run_agent_loop()` / `run_agent_loop_continue()` for custom control++### Hooks++All hooks from pi's `AgentLoopConfig`, mapped 1:1:++| pi hook | cubepi hook | Notes |+|---------|-------------|-------|+| `convertToLlm` | `convert_to_llm` | Required when using custom message types |+| `transformContext` | `transform_context` | Optional, runs before convert_to_llm |+| `beforeToolCall` | `before_tool_call` | Return `BeforeToolCallResult(block=True)` to prevent execution |+| `afterToolCall` | `after_tool_call` | Override content/details/is_error/terminate |+| `shouldStopAfterTurn` | `should_stop_after_turn` | Graceful stop after current turn |+| `getSteeringMessages` | `get_steering_messages` | Inject messages mid-run |+| `getFollowUpMessages` | `get_follow_up_messages` | Inject messages when agent would stop |++Contract: hooks must not raise. Return safe fallback values on failure (same as pi).++## Middleware++New layer not present in pi. Added because cubebox has 11+ middleware classes that need clean composition.++### Middleware Protocol++```python+class Middleware(Protocol[TMessage]):+ async def transform_context(self, messages, signal=None) -> list: ...+ async def convert_to_llm(self, messages) -> list[Message]: ...+ async def before_tool_call(self, ctx, signal=None) -> BeforeToolCallResult | None: ...+ async def after_tool_call(self, ctx, signal=None) -> AfterToolCallResult | None: ...+ async def should_stop_after_turn(self, ctx) -> bool: ...+```++All methods optional. Implementations only define the hooks they need.++### Composition++```python+def compose_middleware(middlewares: list[Middleware]) -> dict[str, Callable]:+ """Compose multiple Middleware into hook callbacks for AgentLoopConfig.++ Composition semantics:+ - transform_context: chained (output of one is input to next)+ - convert_to_llm: last one providing an implementation wins+ - before_tool_call: sequential, any returning block=True stops execution+ - after_tool_call: sequential, later ones can override earlier results+ - should_stop_after_turn: any returning True stops the agent+ """+```++Simple cases use hooks directly. Complex cases (cubebox) use Middleware + compose.++## Checkpointer++New layer not present in pi. pi has no persistence; applications handle it themselves.++### Protocol++```python+class Checkpointer(Protocol):+ async def load(self, thread_id: str) -> CheckpointData | None: ...+ async def append(self, thread_id: str, messages: list[Any]) -> None: ...+ async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None: ...++class CheckpointData:+ messages: list[Any]+ extra: dict[str, Any]+```++### Save Timing++The framework saves incrementally per step:++- `message_end` → `append([message])` for each new message+- `turn_end` → `save_extra(extra)` for mutable state (compaction, etc.)++This avoids the full-snapshot-per-step overhead of langgraph's Postgres checkpointer, which serializes the entire messages list on every channel version change.++### Why Not Full Snapshot++langgraph saves a full messages blob each time the messages channel changes. For a 1000-message conversation, that means serializing and writing ~1000 messages on every step. cubepi's append-based approach writes only the new message(s), keeping DB I/O constant regardless of conversation length.++### Built-in Implementations++| Implementation | Use case | Dependency |+|----------------|----------|------------|+| `MemoryCheckpointer` | Dev/test, in-memory dict | None |+| `SQLiteCheckpointer` | Lightweight local persistence | `aiosqlite` |++Postgres, Redis, etc. are implemented by applications (cubebox will provide `PostgresCheckpointer`).++### HITL Considerations++pi does not implement human-in-the-loop pause/resume. Its `beforeToolCall` with `block=True` immediately rejects the tool call with an error result — the LLM sees the rejection and can ask the user for confirmation in the next turn.++cubepi follows the same pattern. The tool call information is not lost:+1. `AssistantMessage` (containing the tool call) is already in messages+2. `ToolResultMessage` (with error: "blocked") is added to messages+3. Both are checkpointed via `append`+4. LLM naturally asks the user for confirmation+5. Next user message → LLM retries the tool call → `before_tool_call` allows it++No special pause/resume mechanism or `pending_tool_calls` field needed.++## Cancel Mechanism++**pi**: `AbortController` / `AbortSignal`, passed to all async operations.++**cubepi**: `asyncio.Event` as signal, matching `AbortSignal` semantics — a checkable, awaitable flag.++Tools check `signal.is_set()` during execution. The Agent's `abort()` method sets the event.++## Testing++### Framework++- `pytest` + `pytest-asyncio` for all tests+- Tests live in `tests/` mirroring the `cubepi/` module structure++### Faux Provider++`cubepi.providers.faux` — a public module, shipped with the package. Downstream projects (e.g., cubebox) can import and use it for their own tests.++A fake `Provider` implementation that:+- Accepts pre-configured responses (queued, consumed in order)+- Supports async response factories+- Streams realistic event sequences (text, thinking, tool call deltas)+- Simulates usage estimation from serialized context+- Supports abort mid-stream (text, thinking, tool call phases)+- Emits error/aborted terminal events++All agent loop tests and e2e tests depend on it.++### Test Coverage from pi-agent-core++All tests from pi's `packages/agent/test/` must be ported:++**Agent Loop tests** (from `agent-loop.test.ts`):+- Event emission with AgentMessage types+- Custom message types via `convert_to_llm`+- `transform_context` applied before `convert_to_llm`+- Tool call execution and results+- `before_tool_call` argument mutation (executed without revalidation)+- `prepare_arguments` for tool argument validation+- Parallel tool execution: `tool_execution_end` in completion order, tool results in source order+- Steering message injection after tool calls complete+- Per-tool `execution_mode` override (sequential forces sequential even under parallel config)+- Mixed execution modes (one sequential tool forces entire batch sequential)+- All-parallel execution when every tool opts in+- `should_stop_after_turn` hook+- Early termination when all tool results set `terminate=True`+- Partial termination (not all tools terminate → continue)+- `after_tool_call` marking batch as terminating++**Agent Loop Continue tests** (from `agent-loop.test.ts`):+- Raise when context has no messages+- Continue from existing context without emitting user message events+- Custom message types as last message++**Agent class tests** (from `agent.test.ts`):+- Default state creation+- Custom initial state+- Event subscription and unsubscription+- Full lifecycle events for thrown run failures+- Async subscriber awaiting before `prompt()` resolves+- `wait_for_idle` awaits async subscribers+- Abort signal passed to subscribers+- State mutation+- Steering message queue+- Follow-up message queue+- Abort handling+- Raise when `prompt()` called while streaming+- Raise when `resume()` called while streaming+- `resume()` processes queued follow-up messages after assistant turn+- `resume()` keeps one-at-a-time steering semantics from assistant tail++**E2E tests** (from `e2e.test.ts`, using FauxProvider):+- Basic text prompt+- Tool execution with pending tool call tracking+- Abort during streaming+- Lifecycle event emission during streaming+- Context maintained across multiple turns+- Thinking content block preservation+- `resume()` validation (no messages, last message is assistant)+- Continue from user message+- Continue from tool result++### Tests for cubepi-specific Features++**Middleware tests**:+- `compose_middleware` composition semantics:+ - `transform_context`: chained (output → input)+ - `convert_to_llm`: last implementation wins+ - `before_tool_call`: sequential, any `block=True` stops execution+ - `after_tool_call`: sequential, later overrides earlier+ - `should_stop_after_turn`: any `True` stops+- Empty middleware list+- Middleware with partial method implementations (only some hooks defined)+- Middleware ordering matters for chained hooks++**Checkpointer tests**:+- `MemoryCheckpointer`: load/append/save_extra round-trip, multiple threads, empty thread+- `SQLiteCheckpointer`: same as MemoryCheckpointer, plus persistence across instances, concurrent access+- Incremental append correctness (append N messages → load returns all N)+- `save_extra` merges with existing extra data+- Agent integration: checkpoint saved at `message_end` and `turn_end`++**Provider tests** (unit, no real API calls):+- `AnthropicProvider`: message format conversion, tool definition mapping, streaming event parsing+- `OpenAIProvider`: same as Anthropic+- Abort mid-stream for both providers+- Error handling (API errors → `AssistantMessage` with `stop_reason="error"`)++**Provider E2E tests** (require API keys, skipped in CI by default):+- Basic text streaming+- Tool call streaming+- Thinking/reasoning streaming+- Abort mid-stream+- Error recovery++## Dependencies++Core (required):+- `pydantic` — types, validation, JSON Schema generation++Provider implementations:+- `anthropic` — for AnthropicProvider+- `openai` — for OpenAIProvider++Checkpointer implementations:+- `aiosqlite` — for SQLiteCheckpointer (optional)++Dev/test:+- `pytest` + `pytest-asyncio` — test framework+- `pytest-cov` — coverage reporting++No dependency on langchain, langgraph, or any other agent framework.diff --git a/dev/specs/2026-05-10-cubepi-improvement-roadmap.md b/dev/specs/2026-05-10-cubepi-improvement-roadmap.mdnew file mode 100644index 0000000..7d50301--- /dev/null+++ b/dev/specs/2026-05-10-cubepi-improvement-roadmap.md@@ -0,0 +1,175 @@+# cubepi 改进路线图++> 基于与 pi-agent-core / pi-ai 的对比审查,按优先级排列。++## P0 — 类型安全与正确性++这些问题直接影响代码正确性、可维护性和开发者体验。++### 1. 消除 `list[Any]` — 引入 `AgentMessage` 联合类型++**现状**: `AgentContext.messages`、`AgentState._messages`、事件类型中的 `message` 字段大量使用 `Any`,导致:+- 无法静态类型检查,IDE 无法补全+- 运行时靠 `hasattr(msg, "role")` 判断类型,脆弱且不安全+- 回调签名全部是 `Callable | None`,无参数类型信息++**Pi 做法**: 定义 `AgentMessage = Message | CustomAgentMessages[keyof CustomAgentMessages]`,所有回调签名完整标注。++**改动范围**:+- 定义 `AgentMessage = UserMessage | AssistantMessage | ToolResultMessage`+- `AgentContext.messages: list[AgentMessage]`+- `AgentState._messages: list[AgentMessage]`+- 所有事件类型的 `message` 字段标注为 `AgentMessage` 或具体类型+- `Agent.__init__` 的回调参数加上完整签名(参考 pi 的 `AgentOptions`)+- 消除 `_default_convert_to_llm` 中的 `hasattr` 检查+- 消除 `_process_event` 中的 `hasattr` 检查++### 2. `StreamEvent` 增加 `content_index`++**现状**: `StreamEvent` 没有 `content_index`,provider 实现依赖"partial.content 的最后一个元素"来判断当前正在流式传输的 content block。当内容块交错时(如 text → tool_call → text),定位会出错。++**Pi 做法**: 所有 content 事件都携带 `contentIndex: number`。++**改动范围**:+- `StreamEvent` 新增 `content_index: int | None = None`+- 三个 provider 实现(Anthropic、OpenAI、OpenAI Responses)在生成事件时填充 `content_index`+- FauxProvider 同步更新+- `MessageUpdateEvent` 传递 `content_index` 信息++### 3. `AssistantMessage` 补充 provider 元数据++**现状**: `AssistantMessage` 不记录是哪个 provider/model 生成的,无法追踪来源。++**Pi 做法**: `AssistantMessage` 包含 `api`、`provider`、`model`、`responseModel`、`responseId`、`diagnostics`。++**改动范围**:+- `AssistantMessage` 新增 `provider_id: str = ""`、`model_id: str = ""`、`response_id: str | None = None`+- 各 provider 在 `_convert_response` / 构造 final message 时填充这些字段+- 对现有代码无破坏性影响(新增字段有默认值)++---++## P1 — 功能补全++这些是 pi-agent 有而 cubepi 缺失的功能,影响实际可用性。++### 4. Checkpointer 集成到 Agent++**现状**: `Agent.__init__` 接受 `checkpointer` 和 `thread_id` 参数,`MemoryCheckpointer` 和 `SQLiteCheckpointer` 实现完整,但 Agent 从未调用它们。这是死代码。++**改动范围**:+- `Agent.prompt()` 启动时,若有 checkpointer + thread_id,调用 `load()` 恢复历史消息+- `_process_event` 中 `message_end` 时调用 `append()`+- `Agent.reset()` 决定是否清除持久化数据(可通过参数控制)+- 补充集成测试++### 5. `ToolResultMessage` 传递 `details`++**现状**: `AgentToolResult` 有 `details` 字段,但 `_make_tool_result_message()` 构造 `ToolResultMessage` 时丢弃了它。++**Pi 做法**: `ToolResultMessage<TDetails>` 有 `details?: TDetails`,全程传递。++**改动范围**:+- `ToolResultMessage` 新增 `details: Any = None`+- `_make_tool_result_message()` 填充 `finalized.result.details`+- `__init__.py` 导出不变(`ToolResultMessage` 已导出)++### 6. 循环开始时轮询 steering 消息++**现状**: `_run_loop` 只在工具执行后检查 steering 消息。如果用户在 agent 初始化期间发送了消息,会被丢失。++**Pi 做法**: `runLoop` 在循环开始前执行 `let pendingMessages = (await config.getSteeringMessages?.()) || []`。++**改动范围**:+- `_run_loop` 入口处增加一次 `get_steering_messages()` 调用+- 将取得的消息注入到第一轮 assistant 响应之前++### 7. OpenAI Provider 支持图片输入++**现状**: `OpenAIProvider._convert_message()` 对 `UserMessage` 只提取 `TextContent`,`ImageContent` 被丢弃。++**改动范围**:+- `_convert_message` 检测 `ImageContent`,转换为 OpenAI 的 `image_url` 格式+- `OpenAIResponsesProvider._build_input` 同理处理图片++---++## P2 — 代码质量与健壮性++### 8. 消除重复的 `_emit` 辅助函数++**现状**: `loop.py` 和 `tools.py` 各定义了一个相同的 `_emit` 函数。++**改动范围**:+- 将 `_emit` 移到共享位置(如 `agent/types.py` 或新的 `agent/_utils.py`)+- 两处导入替换++### 9. 修复 fire-and-forget `asyncio.create_task`++**现状**: 所有 provider 的 `stream()` 方法用 `asyncio.create_task(_produce())` 启动生产者协程,但不保存 task 引用。若 task 在推送 error 事件之前就失败,异常会被静默吞掉。++**改动范围**:+- `MessageStream` 持有 task 引用+- `MessageStream.result()` 等待时同时检查 task 异常+- 或改为在 `stream()` 方法中保存 task 引用并设置 done callback++### 10. 清理 OpenAI Responses 的 system prompt 死代码++**现状**: `openai_responses.py:78-86` 先设置 `kwargs["instructions"]`,又删除它,中间的赋值是死代码。++**改动范围**:+- 删除 `kwargs["instructions"] = system_prompt` 和 `del kwargs["instructions"]`+- 只保留 input 前置逻辑++### 11. 私有函数跨模块导入规范化++**现状**: `anthropic.py` 和 `openai.py` 导入 `_invoke_on_payload` 和 `_invoke_on_response`(下划线前缀表示私有)。++**改动范围**:+- 去掉下划线前缀,改为 `invoke_on_payload` / `invoke_on_response`+- 或将它们移到 `StreamOptions` 的方法中++---++## P3 — API 增强++这些是 pi-agent 有但 cubepi 当前不急需的能力,可在需要时再实现。++### 12. Agent 级别的 EventStream++**现状**: 只有 callback-based 的 `run_agent_loop`。Pi 还提供 `agentLoop()` 返回 `EventStream<AgentEvent, AgentMessage[]>`,可用 `async for` 消费。++**参考**: Pi 的 `EventStream` 类和 `createAgentStream()` 工厂。++### 13. 动态 API Key 解析 (`get_api_key`)++**现状**: Provider 在构造时绑定 API key。对于短期 OAuth token(如 GitHub Copilot),长时间运行的 tool 执行期间 token 可能过期。++**Pi 做法**: `AgentLoopConfig.getApiKey` 在每次 LLM 调用前动态解析 key。++### 14. 工具参数预处理 (`prepare_arguments`)++**现状**: 工具参数直接用 Pydantic 校验,无法做兼容性转换。++**Pi 做法**: `AgentTool.prepareArguments` 可在校验前转换原始参数。++### 15. Queue 管理 API++**现状**: Agent 没有暴露 `clear_steering_queue()`、`clear_follow_up_queue()`、`has_queued_messages()` 等方法。只有 `reset()` 会清除所有状态。++**Pi 做法**: 提供细粒度的队列管理方法。++### 16. 重试与 `max_retry_delay_ms`++**现状**: Provider 没有重试逻辑。++**Pi 做法**: `StreamOptions.maxRetryDelayMs` 控制重试上限,超时则立即失败并向上层报告。++---++## 实施建议++- P0 的 3 项应当在下一个迭代周期内完成,它们是基础设施级改进+- P1 的 4 项可以独立分支并行推进+- P2 的 4 项可以合并为一个代码清理 PR+- P3 的 5 项按实际需求触发,不必提前实现diff --git a/dev/specs/2026-05-13-cubepi-cubebox-readiness-design.md b/dev/specs/2026-05-13-cubepi-cubebox-readiness-design.mdnew file mode 100644index 0000000..485e4ee--- /dev/null+++ b/dev/specs/2026-05-13-cubepi-cubebox-readiness-design.md@@ -0,0 +1,824 @@+# cubepi cubebox-readiness — Design++Date: 2026-05-13+Status: Design+Companion spec: `cubebox/docs/superpowers/specs/2026-05-13-cubepi-main-agent-migration-design.md` (Spec B)++## Why this spec exists++cubebox plans to drop LangGraph entirely and run on cubepi (Spec B).+cubepi v0.2.0 lacks several pieces that cubebox needs. This spec+collects those gaps as upstream cubepi work so cubebox's migration+(Spec B) has a clean dependency surface. None of the work here is+cubebox-specific in shape — every addition is designed as general+public API for any cubepi user.++cubebox depends on cubepi via local path dependency (`uv add --editable+/home/chris/cubepi`) throughout development. No cubepi releases are+required for Spec B to start consuming these changes.++## Non-goals++- LangGraph compatibility shims. cubepi stays pure.+- Behavioral changes to existing cubepi APIs. All additions are new+ surface; existing users see no behavior change.+- Auto-migration tooling from langgraph checkpoint format. cubebox has+ no released data; greenfield write.+- cubepi.Responses API integration into cubebox — already shipped, this+ spec doesn't touch `OpenAIResponsesProvider`.++## Deliverables overview++| # | Item | Module / surface |+|---|---|---|+| D1 | Postgres checkpointer | `cubepi.checkpointer.postgres` (new) |+| D2 | MCP adapter (HTTP + stdio) | `cubepi.mcp` (new) |+| D3 | AnthropicProvider configurable cache marker policy | `cubepi.providers.anthropic` |+| D4 | OpenAIProvider OSS reasoning extraction + payload quirks | `cubepi.providers.openai` |+| D5 | `Message.metadata` field on all three Message types | `cubepi.providers.base` |+| D6 | `AgentContext.extra` mutable dict | `cubepi.agent.types` |+| D7 | `transform_system_prompt` middleware hook | `cubepi.middleware.base` |+| D8 | `after_model_response` middleware hook + `TurnAction` | `cubepi.middleware.base` |+| D9 | Packaging: `[postgres]`, `[mcp]` extras | `pyproject.toml` |++All deliverables are backward-compatible. Existing cubepi users get+no behavior change unless they opt in.++---++## D1 — Postgres checkpointer++### Scope++`cubepi.checkpointer.postgres.PostgresCheckpointer` implementing the+existing `Checkpointer` protocol (`load` / `append` / `save_extra`)+against PostgreSQL.++### Schema++cubepi defines table classes on a private `MetaData` instance (NOT on+`SQLModel.metadata`) so downstreams using any ORM (SQLModel, plain+SQLAlchemy, none) can compose it into their alembic.++```python+# cubepi/checkpointer/postgres/models.py+import sqlalchemy as sa+from sqlalchemy.dialects.postgresql import JSONB+from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column+from datetime import datetime++EXPECTED_SCHEMA_VERSION = 1+PARTITION_COUNT = 64+cubepi_metadata = sa.MetaData()++class CubepiBase(DeclarativeBase):+ metadata = cubepi_metadata++class CubepiThread(CubepiBase):+ __tablename__ = "cubepi_threads"+ thread_id: Mapped[str] = mapped_column(sa.Text, primary_key=True)+ parent_thread_id: Mapped[str | None] = mapped_column(+ sa.Text, sa.ForeignKey("cubepi_threads.thread_id"), nullable=True)+ forked_at_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)+ extra: Mapped[dict] = mapped_column(+ JSONB, nullable=False, server_default=sa.text("'{}'::jsonb"))+ created_at: Mapped[datetime] = mapped_column(+ sa.TIMESTAMP(timezone=True), nullable=False, server_default=sa.text("now()"))+ updated_at: Mapped[datetime] = mapped_column(+ sa.TIMESTAMP(timezone=True), nullable=False, server_default=sa.text("now()"))++class CubepiMessage(CubepiBase):+ __tablename__ = "cubepi_messages"+ __table_args__ = (+ sa.Index(+ "ix_cubepi_messages_metadata_gin", "metadata",+ postgresql_using="gin",+ postgresql_ops={"metadata": "jsonb_path_ops"},+ ),+ {"postgresql_partition_by": "HASH (thread_id)"},+ )++ thread_id: Mapped[str] = mapped_column(+ sa.Text,+ sa.ForeignKey("cubepi_threads.thread_id", ondelete="CASCADE"),+ primary_key=True,+ )+ seq: Mapped[int] = mapped_column(sa.BigInteger, primary_key=True)+ role: Mapped[str] = mapped_column(sa.Text, nullable=False)+ metadata: Mapped[dict] = mapped_column(+ JSONB, nullable=False, server_default=sa.text("'{}'::jsonb"))+ payload: Mapped[bytes] = mapped_column(sa.LargeBinary, nullable=False)+ created_at: Mapped[datetime] = mapped_column(+ sa.TIMESTAMP(timezone=True), nullable=False, server_default=sa.text("now()"))++class CubepiSchemaVersion(CubepiBase):+ __tablename__ = "cubepi_schema_version"+ version: Mapped[int] = mapped_column(sa.Integer, primary_key=True)+```++### Why these shape choices++| Decision | Rationale |+|---|---|+| Private `cubepi_metadata` (not `SQLModel.metadata`) | Downstream ORM-agnostic. SQLAlchemy `target_metadata` accepts a list; SQLModel users add it alongside their own metadata. |+| Composite PK `(thread_id, seq)` | Append-only writes hit one B-tree path; `WHERE thread_id ORDER BY seq` is a PK range scan = sequential I/O. |+| `seq BIGINT` monotonic per-thread | Simpler than langgraph's `version: "123.random"` string format. cubepi has no snapshot semantics → no version dedup needed. |+| `payload BYTEA + msgpack` | ~30% smaller than JSONB serialization for messages; faster ser/deser; messages are opaque blobs. |+| `metadata JSONB` (separate column) | Queryable via `@>` for role-independent filters (cost, tool_call_id, source). Carrying snapshot data for memory middleware (Spec B). |+| GIN(metadata) `jsonb_path_ops` | Efficient `@>` queries; `jsonb_path_ops` is ~30% smaller than default GIN. |+| No separate blob dedup table | cubepi has no snapshot model → no value to dedup. langgraph's `checkpoint_blobs` is a fix for snapshot bloat we don't have. |+| No `checkpoint_ns` | cubepi doesn't model namespaces. Subagents use distinct `thread_id`s. |+| HASH(thread_id) PARTITION BY, 64 partitions | All hot queries filter by `thread_id` → partition pruning O(1). 64 partitions cover ~6B rows comfortably; PG hash partition count is fixed (changing requires full rewrite) so over-provision now. |+| `cubepi_threads` not partitioned | Metadata-table sized (one row per conversation); orders of magnitude smaller than messages. |+| FK `cubepi_messages.thread_id → cubepi_threads` with `ON DELETE CASCADE` | Integrity + simple cleanup. Lazy `INSERT ... ON CONFLICT DO NOTHING` on first append per thread. |+| `parent_thread_id` + `forked_at_seq` nullable | Schema-ready for future fork API; columns sit empty until cubepi protocol exposes fork. |++### Why partition from v1++PostgreSQL hash partition count is **static** — changing modulus+requires full data rewrite (`INSERT ... SELECT`) or logical+replication. Both require maintenance windows or significant ops+work. The cost of starting with 64 partitions is negligible+(~200-400MB metadata, no measurable query impact under PG 14++pruning). The expected reward (never rehashing) is large. Over-+provision now.++### Schema version enforcement++cubepi runtime checks DB schema matches `EXPECTED_SCHEMA_VERSION` on+first connect:++```python+async def _verify_schema(self, conn) -> None:+ row = await conn.fetchrow("SELECT version FROM cubepi_schema_version LIMIT 1")+ if row is None:+ raise CubepiSchemaUninitialized(+ "cubepi tables not found. Run host application's alembic upgrade."+ )+ if row["version"] != EXPECTED_SCHEMA_VERSION:+ raise CubepiSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=row["version"],+ hint="cubepi was upgraded but host alembic is behind. "+ "Generate a new revision and apply.",+ )+```++When cubepi changes schema → bump `EXPECTED_SCHEMA_VERSION` → host+application gets a startup-time hard failure if their alembic is+behind. Downstream is forced to acknowledge the schema change.++### Alembic helpers++cubepi exports two SQL helpers for host alembic migrations:++```python+# cubepi/checkpointer/postgres/alembic_helpers.py+from .models import EXPECTED_SCHEMA_VERSION, PARTITION_COUNT++def create_message_partitions_op() -> str:+ """SQL DDL creating all 64 child partitions of cubepi_messages.+ Call inside an alembic upgrade() after the parent table is created."""+ return "\n".join(+ f"CREATE TABLE cubepi_messages_p{i:02d} "+ f"PARTITION OF cubepi_messages "+ f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i});"+ for i in range(PARTITION_COUNT)+ )++def write_schema_version_op() -> str:+ """SQL to record the current schema version. Call inside upgrade()."""+ return (+ f"INSERT INTO cubepi_schema_version (version) "+ f"VALUES ({EXPECTED_SCHEMA_VERSION}) ON CONFLICT DO NOTHING;"+ )+```++Host application alembic env.py imports the metadata to enable+autogenerate:++```python+from cubepi.checkpointer.postgres.models import cubepi_metadata+target_metadata = [SQLModel.metadata, cubepi_metadata]+```++### Append path (seq allocation)++Concurrent `append()` calls to the same `thread_id` must produce+strictly monotonic `seq`. Strategy: per-thread advisory lock for the+duration of the append transaction.++```python+async def append(self, thread_id: str, messages: list[Message]) -> None:+ async with self._pool.acquire() as conn:+ async with conn.transaction():+ await conn.execute(+ "SELECT pg_advisory_xact_lock(hashtext($1))",+ thread_id,+ )+ await conn.execute(+ "INSERT INTO cubepi_threads (thread_id) "+ "VALUES ($1) ON CONFLICT DO NOTHING",+ thread_id,+ )+ last_seq = await conn.fetchval(+ "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "+ "WHERE thread_id = $1",+ thread_id,+ )+ rows = [+ (thread_id, last_seq + i + 1, m.role, m.metadata,+ msgpack.packb(m.model_dump(mode="json")))+ for i, m in enumerate(messages)+ ]+ await conn.executemany(+ "INSERT INTO cubepi_messages "+ "(thread_id, seq, role, metadata, payload) "+ "VALUES ($1, $2, $3, $4, $5)",+ rows,+ )+```++Advisory lock scope is the transaction; released automatically on+commit/rollback. No background cleanup needed.++### Load path++```sql+SELECT seq, role, metadata, payload+FROM cubepi_messages+WHERE thread_id = $1+ORDER BY seq;+```++Single query, PK range scan + partition pruning to a single+`cubepi_messages_pNN` child. `payload` deserialized via msgpack into+the appropriate `Message` subclass (dispatched on `role`).++### `save_extra` path++```sql+INSERT INTO cubepi_threads (thread_id, extra, updated_at)+VALUES ($1, $2, now())+ON CONFLICT (thread_id) DO UPDATE+SET extra = cubepi_threads.extra || EXCLUDED.extra,+ updated_at = now();+```++PostgreSQL `||` on JSONB does shallow merge — matches existing+`SQLiteCheckpointer.save_extra` semantics (caller-side merge in+SQLite, server-side merge here).++### Packaging++```toml+# pyproject.toml additions+[project.optional-dependencies]+postgres = ["sqlalchemy>=2.0", "asyncpg>=0.29", "msgpack>=1.0"]+```++### Out of scope (deferred)++- Application-layer thread archival / pruning+- Time-based partitioning (use case: log/audit data — doesn't fit+ conversation access patterns)+- Read replicas / multi-region+- Online schema migration tooling beyond schema version check+- Compression (TOAST + msgpack already covers common cases)++---++## D2 — MCP adapter++### Scope++`cubepi.mcp` module with `load_mcp_tools_http` and+`load_mcp_tools_stdio` returning `list[cubepi.AgentTool]`. Both+transports supported; cubebox today uses HTTP only, future+cubepi-coding-agent use cases (stdio servers like+`@modelcontextprotocol/server-filesystem`) need stdio.++### API++```python+# cubepi/mcp/__init__.py+from cubepi import AgentTool++async def load_mcp_tools_http(+ server_url: str,+ *,+ headers: dict[str, str] | None = None,+ timeout: float = 30.0,+) -> list[AgentTool]:+ """Connect to an HTTP/SSE MCP server, discover tools,+ convert each to cubepi.AgentTool."""+ ...++async def load_mcp_tools_stdio(+ command: str,+ args: list[str],+ *,+ env: dict[str, str] | None = None,+ cwd: str | None = None,+ timeout: float = 30.0,+) -> list[AgentTool]:+ """Spawn a stdio MCP server subprocess, discover tools,+ convert each to cubepi.AgentTool."""+ ...+```++Each returned `AgentTool.execute` invokes the corresponding MCP+`tools/call` RPC and translates the response into `AgentToolResult`.++### Packaging++```toml+[project.optional-dependencies]+mcp = ["mcp>=1.0"]+```++Single extra covers both transports; `mcp>=1.0` Python package+includes stdio + HTTP/SSE client.++### Testing++cubepi E2E:+- HTTP transport: spin up a fake MCP server (FastAPI) that advertises+ two tools; load via `load_mcp_tools_http`; invoke each; verify+ result translation.+- stdio transport: spawn a Python subprocess implementing minimal MCP+ stdio protocol; load via `load_mcp_tools_stdio`; same assertions.++### Out of scope++- MCP server-side helpers (cubepi consumes MCP, doesn't expose itself+ as an MCP server)+- OAuth flows for MCP servers (host application handles credentials,+ passes headers)+- Resource / prompt primitives (only tools supported; aligns with+ cubebox's use)++---++## D3 — Anthropic configurable cache marker policy++### Why++cubepi `AnthropicProvider` currently marks: system + last message ++last tool. cubebox needs: system + last completed AIMessage + tools.+The "last completed AIMessage" requires walking back the message+list. Hard-coded policy doesn't fit; needs to be caller-configurable.++### API++```python+# cubepi/providers/anthropic.py additions+from typing import Protocol++class CacheMarkerPolicy(Protocol):+ def mark_system(self) -> bool: ...+ def mark_last_tool(self) -> bool: ...+ def message_breakpoint_indices(+ self,+ messages: list[Message],+ ) -> list[int]: ...++class DefaultCacheMarkerPolicy:+ """Preserves current cubepi behavior: system + last message + last tool."""+ def mark_system(self) -> bool:+ return True+ def mark_last_tool(self) -> bool:+ return True+ def message_breakpoint_indices(self, messages):+ return [len(messages) - 1] if messages else []++class AnthropicProvider:+ def __init__(+ self,+ *,+ api_key: str | None = None,+ base_url: str | None = None,+ cache_policy: CacheMarkerPolicy | None = None,+ ):+ ...+ self._cache_policy = cache_policy or DefaultCacheMarkerPolicy()+```++Provider applies marker policy at message conversion time. Existing+users who don't pass `cache_policy` see no behavior change.++### Out of scope++- Provider-side knowledge of "completed AIMessage" semantics. Policy+ callback is given the message list as-is; caller decides what+ "completed" means in their domain.+- OpenAI cache markers — OpenAI auto-caches on byte-identical prefix,+ no markers needed.++---++## D4 — OpenAI Chat Completions OSS reasoning + payload quirks++### Why++cubepi `OpenAIResponsesProvider` already handles OpenAI's official+Responses API reasoning. But cubebox uses Chat Completions endpoints+against openai-compatible servers (DeepSeek, DouBao, Qwen, vLLM,+MiniMax) which return reasoning via three different non-standard+fields:++- `reasoning_content` — DeepSeek, DouBao, Qwen+- `reasoning` — vLLM+- `reasoning_details: [{text: ...}, ...]` — MiniMax++`OpenAIProvider` currently ignores all of these.++### API++```python+# cubepi/providers/openai.py additions+from typing import Literal++class OpenAIProvider:+ def __init__(+ self,+ *,+ api_key: str | None = None,+ base_url: str | None = None,+ payload_quirks: list[Literal["max_completion_tokens_alias"]] | None = None,+ ):+ ...+ self._payload_quirks = set(payload_quirks or [])+```++Two changes inside `OpenAIProvider`:++1. **Streaming chunk handler** (and non-streaming `_create_chat_result`+ equivalent): after standard content/tool_call extraction, check+ `delta.reasoning_content` → `delta.reasoning` →+ `delta.reasoning_details[*].text` in that priority order. Emit+ existing `thinking_start` / `thinking_delta` / `thinking_end`+ events (no new event types needed).++2. **Payload preparation**: if `"max_completion_tokens_alias"` is in+ `payload_quirks`, rewrite `max_completion_tokens → max_tokens` in+ the outgoing request body (some older openai-compatible endpoints+ reject the newer param name).++### Testing++cubepi E2E:+- Fake OpenAI-compatible server emitting each of the three reasoning+ field variants in streaming + non-streaming responses; verify+ cubepi emits correct `thinking_*` events.+- Fake server requires `max_tokens`; verify `payload_quirks=+ ["max_completion_tokens_alias"]` produces correct rewrite.++### Out of scope++- Tool call timing metadata (cubebox-specific telemetry — host+ application's responsibility, not provider's)+- New event types — existing `thinking_*` already covers reasoning+ semantics across both OpenAI Responses and Chat Completions paths++---++## D5 — `Message.metadata` field++### Why++cubebox's memory system stores per-user-message immutable snapshots+of the relevance memory shown to the model at that turn. The cubebox+side persists them per message, not as a separate state channel.+cubepi needs to carry arbitrary metadata alongside each message+through ser/deser.++This is also useful for any cubepi user who needs to attach metadata+to messages (cost, source, tool_call_id linking, audit tags, etc.).++### API++```python+# cubepi/providers/base.py changes+from pydantic import BaseModel, Field++class UserMessage(BaseModel):+ content: list[Content]+ metadata: dict[str, Any] = Field(default_factory=dict)+ ...++class AssistantMessage(BaseModel):+ content: list[Content]+ metadata: dict[str, Any] = Field(default_factory=dict)+ ...++class ToolResultMessage(BaseModel):+ content: list[Content]+ metadata: dict[str, Any] = Field(default_factory=dict)+ ...+```++### Checkpointer integration++- `PostgresCheckpointer.append`: writes `message.metadata` to+ `cubepi_messages.metadata JSONB`.+- `PostgresCheckpointer.load`: hydrates `message.metadata` from the+ row.+- `SQLiteCheckpointer`: same; existing serialization to/from JSON+ already round-trips dicts.++### Backwards compatibility++Existing `UserMessage(content=[...])` calls work unchanged —+`metadata` defaults to `{}`. Existing serialized messages (without+the field) deserialize cleanly because pydantic defaults the field.++---++## D6 — `AgentContext.extra` mutable dict++### Why++Middleware needs access to per-thread non-message state (cubebox's+compaction summary, TodoListMiddleware's 6 planning channels, etc.).+The `Checkpointer` protocol already exposes `save_extra(thread_id,+extra)` / `load` returns `CheckpointData.extra`. But the+middleware hooks don't currently expose extra to the middleware+implementation.++Adding `extra` to `AgentContext` and threading it through hook+contexts lets middleware read/mutate per-thread state in any hook,+with the agent loop persisting at the right times.++### API++```python+# cubepi/agent/types.py changes+from dataclasses import dataclass, field++@dataclass+class AgentContext:+ system_prompt: str+ messages: list[Message]+ tools: list[AgentTool] | None = None+ extra: dict[str, Any] = field(default_factory=dict) # NEW+```++`extra` is mutable. Middleware in any hook with access to+`AgentContext` (or a context type embedding it like+`BeforeToolCallContext.context`, `AfterToolCallContext.context`,+`ShouldStopAfterTurnContext.context`, and the new hook contexts+introduced in D7/D8) can read and mutate `ctx.context.extra` in+place.++### Agent loop persistence++After each tool execution turn (post `after_tool_call`) and after+each model response (post `after_model_response`), the agent loop+calls `checkpointer.save_extra(thread_id, agent_context.extra)`.+This is unconditional — cheap UPSERT on JSONB.++On load: `agent.prompt(...)` calls `checkpointer.load(thread_id)` and+initializes `AgentContext.extra` from `CheckpointData.extra`.++### Backwards compatibility++Existing middleware that doesn't access `ctx.extra` works unchanged.+Existing `AgentContext` constructors work — `extra` defaults to `{}`.++---++## D7 — `transform_system_prompt` middleware hook++### Why++cubebox's `SandboxMiddleware` and `SkillsMiddleware` dynamically+mutate the system prompt per turn (sandbox capability text injected+when sandbox is initialized; skill content appended after a `load_skill`+tool call). cubepi's `system_prompt` is currently set once at+`Agent` construction; middleware has no hook to modify it per call.++### API++```python+# cubepi/middleware/base.py additions+class Middleware:+ async def transform_system_prompt(+ self,+ system_prompt: str,+ *,+ signal: asyncio.Event | None = None,+ ) -> str:+ raise NotImplementedError+```++### Composition++Chain — each middleware receives the previous middleware's return+value. Identical to `transform_context`'s composition rule.++```python+def compose_middleware(middlewares: list[Middleware]) -> dict[str, Callable]:+ ...+ sp_chain = [m for m in middlewares if _has_method(m, "transform_system_prompt")]+ if sp_chain:+ async def composed_sp(system_prompt, *, signal=None):+ result = system_prompt+ for mw in sp_chain:+ result = await mw.transform_system_prompt(result, signal=signal)+ return result+ hooks["transform_system_prompt"] = composed_sp+```++### Agent loop integration++Before each provider call, agent loop applies `transform_context` to+messages AND `transform_system_prompt` to the system prompt, then+sends both to the provider's `stream(...)`.++### Backwards compatibility++Middleware that doesn't override `transform_system_prompt` has no+effect. Existing `Agent(system_prompt="...")` constructors work+unchanged.++---++## D8 — `after_model_response` middleware hook + `TurnAction`++### Why++cubebox uses LangChain's `after_model` hook for three purposes:++- **CostMiddleware**: read `AssistantMessage.usage`, record billing+- **TimestampMiddleware**: stamp turn-end time on response+- **TodoListMiddleware**: inspect response for write_todos usage,+ inject corrective SystemMessages, optionally force loop to model or+ force stop++cubepi today has `should_stop_after_turn` (bool, simple termination)+but no hook for response observation, response mutation, message+injection, or forced loop-back.++### API++```python+# cubepi/middleware/base.py additions+from dataclasses import dataclass, field+from typing import Literal++@dataclass+class TurnAction:+ """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.+ """+ response: AssistantMessage | None = None+ inject_messages: list[Message] = field(default_factory=list)+ decision: Literal["natural", "stop", "loop_to_model"] = "natural"++class Middleware:+ async def after_model_response(+ self,+ response: AssistantMessage,+ ctx: AgentContext,+ *,+ signal: asyncio.Event | None = None,+ ) -> TurnAction | None:+ raise NotImplementedError+```++### Semantics++| `decision` | Effect on agent loop |+|---|---|+| `natural` | Default flow — if response has tool calls, execute them; otherwise terminate the turn |+| `stop` | Force termination, override natural continuation |+| `loop_to_model` | Re-invoke the model (with `inject_messages` added to context); override natural termination |++Returning `None` is shorthand for `TurnAction(decision="natural")`.++### Composition++Chain. Each middleware receives the previous middleware's+`TurnAction` as input (via wrapping logic in `compose_middleware`).++```python+after_resp_chain = [+ m for m in middlewares if _has_method(m, "after_model_response")+]+if after_resp_chain:+ async def composed(response, ctx, *, signal=None):+ current_response = response+ all_inject: list[Message] = []+ last_decision: Literal["natural", "stop", "loop_to_model"] = "natural"+ for mw in after_resp_chain:+ result = await mw.after_model_response(+ current_response, ctx, signal=signal+ )+ if result is None:+ continue+ if result.response is not None:+ current_response = result.response+ if result.inject_messages:+ all_inject.extend(result.inject_messages)+ last_decision = result.decision+ return TurnAction(+ response=current_response,+ inject_messages=all_inject,+ decision=last_decision,+ )+ hooks["after_model_response"] = composed+```++### Relationship to `should_stop_after_turn`++`should_stop_after_turn` stays in cubepi (no change, no deprecation).+It remains the simple bool-returning termination hook. Cubebox+middleware uses `after_model_response` for the richer use case;+existing cubepi users keep using `should_stop_after_turn` for simple+stop conditions.++### Agent loop integration++After receiving the model's `AssistantMessage`:++1. Call composed `after_model_response(response, ctx)` → `TurnAction`+2. If `decision == "stop"`: terminate turn, return `TurnAction.response`+3. If `decision == "loop_to_model"`: append `inject_messages` to+ `ctx.messages`, jump back to model call+4. If `decision == "natural"`: proceed (execute tool calls or+ terminate)++### Backwards compatibility++Middleware that doesn't override `after_model_response` has no+effect. The agent loop's natural behavior (execute tools then loop,+or stop if no tools) is preserved when no middleware overrides.++---++## D9 — Packaging extras (consolidated)++```toml+# pyproject.toml+[project.optional-dependencies]+sqlite = ["aiosqlite>=0.19"] # existing+postgres = ["sqlalchemy>=2.0", "asyncpg>=0.29", "msgpack>=1.0"] # D1+mcp = ["mcp>=1.0"] # D2+```++Anthropic, OpenAI client deps stay as base requirements (already+there).++---++## Acceptance criteria++Spec A is complete when all of the following hold:++| # | Check | Verified by |+|---|---|---|+| A1 | `cubepi.checkpointer.postgres.PostgresCheckpointer` round-trips `append` / `load` / `save_extra` against real Postgres | cubepi E2E |+| A2 | Schema version check raises on uninitialized DB / on mismatch | cubepi E2E |+| A3 | 64 hash partitions created via alembic helpers; insert routes correctly; load reads correctly | cubepi E2E |+| A4 | `cubepi.mcp.load_mcp_tools_http` loads + executes tools against fake MCP server | cubepi E2E |+| A5 | `cubepi.mcp.load_mcp_tools_stdio` loads + executes tools against subprocess MCP server | cubepi E2E |+| A6 | `AnthropicProvider(cache_policy=CustomPolicy())` applies custom marker placement | cubepi unit + E2E |+| A7 | `AnthropicProvider()` without `cache_policy` preserves v0.2 behavior byte-for-byte | cubepi unit (golden fixture) |+| A8 | `OpenAIProvider` emits `thinking_*` events for all three OSS reasoning field variants | cubepi unit + E2E |+| A9 | `OpenAIProvider(payload_quirks=["max_completion_tokens_alias"])` rewrites payload correctly | cubepi unit |+| A10 | `Message.metadata` round-trips through `PostgresCheckpointer` + `SQLiteCheckpointer` byte-identical | cubepi unit |+| A11 | `AgentContext.extra` mutated in any hook persists via `save_extra` after the turn | cubepi unit |+| A12 | `transform_system_prompt` chain composition: 2 middlewares applied in order produce expected output | cubepi unit |+| A13 | `after_model_response` chain composition: response mutation + message injection + decision precedence per spec | cubepi unit |+| A14 | All 9 deliverables backward-compatible: existing v0.2 tests pass unchanged | cubepi full test suite |++cubepi may release as v0.3.0 once A1-A14 pass; cubebox path+dependency consumes earlier (during dev iteration).++---++## Timeline relationship to Spec B++cubebox Spec B's milestone M0 depends on D1 (Postgres checkpointer).+M1 / M3 depend on D3 / D5 / D6 / D7 / D8. M2 depends on D2.++Spec A deliverables can land in any order in cubepi as long as the+dependency relationships above hold. cubebox can start M0 as soon as+D1 + D5 are merged in cubepi.++## Out of scope (deferred to future cubepi work)++- Provider-level retry / rate-limit policies (host application's+ responsibility today)+- New hook types beyond D7 / D8 — add singly if cubebox's middleware+ port turns up a real gap+- Online schema migration tooling+- Multi-region / read replica support in `PostgresCheckpointer`+- Subagent persistence primitive (cubepi loop currently subagent-+ agnostic; subagents-as-tools pattern remains in host application)+- Time-based partitioning support+- cubepi-side observability (tracing, metrics) integrationdiff --git a/dev/specs/2026-05-15-cubepi-docs-site-design.md b/dev/specs/2026-05-15-cubepi-docs-site-design.mdnew file mode 100644index 0000000..c283261--- /dev/null+++ b/dev/specs/2026-05-15-cubepi-docs-site-design.md@@ -0,0 +1,504 @@+# CubePi Documentation Site — Design Spec++**Date:** 2026-05-15+**Author:** xf gong ([email protected])+**Status:** Draft — awaiting review++## 1. Goal & Scope++Stand up the first public documentation site for **CubePi**, a Pythonic+async-native agent framework currently at `v0.3.0` alpha on PyPI.++The site is a **pure developer documentation site** (no marketing landing+page). Its single job is to make CubePi discoverable, learnable, and+referenceable — for users evaluating it against `langgraph`, for users+writing their first agent, and for users debugging a specific API.++Three hard requirements drive the framework choice:++- **Versioning**: snapshot every minor release (`0.3`, `0.4`, …)+- **i18n**: English (default) + Simplified Chinese (`zh-Hans`)+- **Feedback**: page-level 👍/👎 with optional comment, signal goes to PostHog++Out of scope: paid SaaS tooling (Mintlify / GitBook), API playground /+sandbox, blog, changelog page (handled by GitHub Releases).++## 2. Framework Selection++**Choice: Docusaurus 3.x** (latest), with TypeScript config.++Rationale — versioning is the deciding factor. Of all open-source doc+frameworks evaluated (VitePress, Nextra, Starlight, MkDocs Material,+Docusaurus), **Docusaurus is the only one with versioning as a core,+first-class command** (`docusaurus docs:version`). Starlight has community+plugin `starlight-versions` but it lags core releases and is single-maintainer+risk. VitePress and Nextra require manual directory copying for each+snapshot. MkDocs needs `mike` plus Insiders for i18n.++Docusaurus also has i18n built into core, mature React-based theming+(needed for the custom homepage), and battle-tested by Babel / Redux /+Jest / Supabase / Prisma.++The known downside — slower builds than Vite-based alternatives — is+acceptable for a docs site that builds on CI, not on every keystroke.++## 3. Tech Stack++| Layer | Choice |+|---|---|+| Framework | Docusaurus 3.x |+| Config | TypeScript (`docusaurus.config.ts`) |+| Node | 22 LTS |+| Package manager | pnpm 9 |+| API reference generator | [griffe](https://github.com/mkdocstrings/griffe) (Python) |+| Hosting | Cloudflare Pages |+| Analytics & feedback | PostHog (self-hosted-cloud) |+| Search | Algolia DocSearch (free tier for OSS) |+| CI | GitHub Actions |+| Default domain | `cubepi.pages.dev` (custom domain TBD) |++## 4. Repository Layout++The docs site lives under a new top-level `website/` directory, peer to+the Python package `cubepi/`. Brand assets move from `assets/brand/` to+`website/static/img/brand/` so there is a single source of truth.++```+cubepi/+├── cubepi/ # Python package — unchanged+├── docs/ # specs / plans — unchanged+├── website/ # ← entire docs site+│ ├── docusaurus.config.ts+│ ├── sidebars.ts+│ ├── package.json+│ ├── pnpm-lock.yaml+│ ├── tsconfig.json+│ ├── .gitignore # ignores build/ and docs/api/*.mdx+│ │+│ ├── docs/ # next-version English content+│ │ ├── intro.md+│ │ ├── getting-started/+│ │ ├── guides/+│ │ ├── api/ # griffe-generated, gitignored+│ │ │ └── _index.mdx # hand-written overview, tracked+│ │ ├── recipes/+│ │ └── migration/+│ │+│ ├── versioned_docs/+│ │ └── version-0.3/ # first snapshot+│ ├── versioned_sidebars/+│ │ └── version-0.3-sidebars.json+│ ├── versions.json # ["0.3"]+│ │+│ ├── i18n/+│ │ └── zh-Hans/+│ │ ├── code.json+│ │ └── docusaurus-plugin-content-docs/+│ │ ├── current/ # next-version zh-Hans+│ │ └── version-0.3/ # 0.3 zh-Hans+│ │+│ ├── src/+│ │ ├── clientModules/+│ │ │ └── posthog.ts+│ │ ├── components/+│ │ │ ├── DocFeedback/+│ │ │ └── Home/+│ │ │ ├── Hero.tsx+│ │ │ ├── WhyTable.tsx+│ │ │ ├── HelloAgent.tsx+│ │ │ ├── FeatureGrid.tsx+│ │ │ ├── InstallMatrix.tsx+│ │ │ └── MetaBar.tsx+│ │ ├── theme/+│ │ │ └── DocItem/Footer/index.tsx # swizzled — mounts DocFeedback+│ │ ├── css/+│ │ │ └── custom.css # Operator design tokens+│ │ └── pages/+│ │ └── index.tsx # custom homepage+│ │+│ ├── static/+│ │ ├── img/+│ │ │ └── brand/ # ← migrated from /assets/brand/+│ │ │ ├── cubepi-logo.svg+│ │ │ ├── cubepi-logo.png+│ │ │ ├── cubepi-social-preview.svg+│ │ │ └── cubepi-social-preview.png+│ │ ├── fonts/ # self-hosted Inter / Inter Tight / JetBrains Mono+│ │ └── llms.txt+│ │+│ └── scripts/+│ └── build-api-reference.py # griffe → MDX+│+├── .github/+│ └── workflows/+│ └── docs.yml # new+│+├── pyproject.toml # adds [project.optional-dependencies].docs+└── README.md # updated image paths+```++Conventions:++- No root-level `package.json` — keeps CubePi unambiguously a Python project.+- Generated API MDX files are gitignored; the build runs `griffe` every+ time. CI failures point at the source code, not at stale MDX.+- The `docs` Python extra in `pyproject.toml` carries `griffe` and any+ other build-time helpers.++## 5. Information Architecture++Top-level navigation has five sections. The sidebar tree:++```+Getting Started+ ├─ Installation+ ├─ Quick Start (5-min agent)+ └─ Core Concepts (Agent / Tool / Provider / Stream)++Guides+ ├─ Agents+ │ ├─ Building Your First Agent+ │ ├─ Tool Use & Parallel Execution+ │ ├─ Multi-turn Conversations+ │ └─ Streaming Events+ ├─ Providers+ │ ├─ Anthropic+ │ ├─ OpenAI+ │ └─ Writing a Custom Provider+ ├─ Checkpointing+ │ ├─ SQLite+ │ ├─ Postgres+ │ └─ Custom Backends+ ├─ Middleware+ │ ├─ The 5 Hooks+ │ ├─ Composition Rules+ │ └─ Examples (rate limit / logging / retries)+ └─ MCP+ ├─ Loading MCP Tools+ └─ Server Authentication++API Reference (griffe-generated)+ ├─ cubepi.agent+ ├─ cubepi.providers+ ├─ cubepi.checkpointer+ ├─ cubepi.middleware+ ├─ cubepi.mcp+ └─ cubepi.utils++Recipes+ ├─ Weather Agent (tool use)+ ├─ Multi-Provider Failover+ ├─ Persistent Chat (SQLite)+ ├─ Resumable Long Tasks+ └─ Postgres + FastAPI Service++Migration+ └─ From langgraph+```++zh-Hans sidebar is structurally identical (UI strings translated); see+§7 for content translation scope.++## 6. Versioning Strategy++**Snapshot every minor.** First snapshot is `0.3` at site launch.++- `next` (under development): driven by `website/docs/`, served at `/next/...`.+- Default published version: `0.3`, served at `/` (no version prefix).+- Each new minor release runs `pnpm docusaurus docs:version <X.Y>` in the+ release PR, copying the current `docs/` to `versioned_docs/version-X.Y/`+ and freezing it.+- `versions.json` keeps the array of snapshots. When it grows past 3+ active versions, the oldest is labelled `unmaintained` (still+ reachable, but flagged in UI).++Config:++```ts+presets: [['classic', {+ docs: {+ lastVersion: '0.3',+ versions: {+ current: { label: 'Next 🚧', path: 'next', banner: 'unreleased' },+ '0.3': { label: '0.3 (latest)', path: '' },+ },+ },+}]]+```++A **version switcher** sits in the top-right navbar.++## 7. Internationalisation Strategy++- `defaultLocale: 'en'`, `locales: ['en', 'zh-Hans']`.+- Translation lives at+ `website/i18n/zh-Hans/docusaurus-plugin-content-docs/{current,version-0.3}/`.+- **Initial Chinese coverage**: Getting Started (3 pages) + Guides core+ (Building Your First Agent, Tool Use, Streaming, Anthropic provider,+ SQLite checkpointing) = **6–8 pages**, not the full site.+- **API Reference is English-only**. When a Chinese reader navigates to+ an API page, Docusaurus's built-in `<TranslationNotice>` reads+ "This page is only available in English." with a link to the+ authoritative English version.+- Translation workflow: manual edits to the mirrored Markdown files. No+ Crowdin / Lokalise integration — solo maintainer, SaaS overhead not+ justified.++A **language switcher** sits in the top-right navbar, adjacent to the+version switcher.++## 8. Feedback Mechanism++**👍 / 👎 footer widget**, signal goes to PostHog.++### PostHog setup++- Initialised in `website/src/clientModules/posthog.ts`:+ ```ts+ posthog.init(process.env.POSTHOG_KEY!, {+ api_host: 'https://us.i.posthog.com',+ capture_pageview: true,+ persistence: 'memory', // no cookie → no GDPR banner+ });+ ```+- `POSTHOG_KEY` is set in Cloudflare Pages environment variables and+ exposed at build time via `customFields` in `docusaurus.config.ts`.++### `<DocFeedback />` component++- Mounted by swizzling `theme/DocItem/Footer`.+- Visual: 1px ink-5 border, 6px radius, no shadow.+ ```+ Was this page helpful? [ 👍 ] [ 👎 ]+ ```+- On click:+ - 👍 → `posthog.capture('doc_feedback', { slug, helpful: true, version, locale })`,+ button label changes to "Thanks!".+ - 👎 → same event with `helpful: false`, then reveals a textarea ++ Submit button; submitting fires `doc_feedback_comment` with+ `comment` and the same context fields.+- **No anti-spam / dedup** — every click captures an event. Operator+ decision: low-stakes signal, dedup would reduce signal more than it+ prevents abuse.++### Dashboards (PostHog side, configured manually after launch)++- Insight 1: `helpful%` per page slug, sorted ascending → worst pages+ first → editorial backlog.+- Insight 2: `helpful%` broken down by `version` → regression detection.+- Insight 3: comment stream, weekly review.++## 9. Custom Homepage++### Design language: Operator++The homepage adopts the **Direction A · Operator** design language+(reference: `/home/chris/cubebox/_design-explorations/direction-a-operator/DESIGN.md`).+Operator is a Linear / Vercel / Raycast-style "information architecture"+discipline: 1px hairlines, no shadows, no purple gradients, no emoji,+tabular numerals on every numeric span, single accent colour, kbd hints+as first-class citizens.++**Type system**: Inter Tight (display, -1.5% letter-spacing), Inter+(body, 14/20), JetBrains Mono (numerals & code, `font-variant-numeric:+tabular-nums`). Self-hosted from `static/fonts/`, never Google Fonts.++**Colour system**: 9 ink shades (`--ink-1` … `--ink-12`) + single accent+`#3B5BD9` + `ok / warn / err` (used sparingly).++### Homepage section layout (top-to-bottom, single column)++```+┌─────────────────────────────────────────────────────────────┐+│ navbar (Docusaurus default, themed with Operator tokens) │+├─────────────────────────────────────────────────────────────┤+│ HERO │+│ • Banner image: cubepi-social-preview.png │+│ - max-width 880px, centred │+│ - 1px ink-5 border, 6px radius, no shadow │+│ • Eyebrow: cubepi · v0.3.0 · alpha (JetBrains Mono) │+│ • H1: A Pythonic, async-native agent framework. │+│ • Lead: Plain async functions instead of graph nodes. │+│ 3 deps. Append-only checkpointing. │+│ • Actions: [ pip install cubepi ⌘C ] │+│ [ Quick Start → G Q ] │+│ (no "CubePi" wordmark below image — already baked in) │+├─────────────────────────────────────────────────────────────┤+│ WHY CUBEPI │+│ • 9-row × 3-col comparison table (cubepi vs langgraph) │+│ • Hairline rules, no shadow, JetBrains Mono in cells │+│ • Direct port of the table from README.md │+├─────────────────────────────────────────────────────────────┤+│ HELLO, AGENT. │+│ • Left: H2 + one-sentence tagline │+│ • Right: 10-line code block, JetBrains Mono, ink-3 bg │+│ • Bottom link: "Full quick-start → /getting-started" │+├─────────────────────────────────────────────────────────────┤+│ FEATURE GRID (3 × 2, six cards) │+│ • Agents · Streaming · Tools · Providers · │+│ Checkpointing · MCP │+│ • Per card: 16px Lucide stroke-1.5 monoline icon, │+│ Inter Tight title, ≤ 22-char ink-9 description, │+│ "→ Guides / <topic>" link bottom-right │+├─────────────────────────────────────────────────────────────┤+│ INSTALL MATRIX │+│ • 4-column table: pip / uv / poetry / extras │+│ • Each row: equal-width code, copy button to the right │+├─────────────────────────────────────────────────────────────┤+│ META STATUS BAR │+│ • JetBrains Mono 11px, ink-7, 1px ink-5 top border │+│ • Shows: v0.3.0 · py 3.11+ · MIT · build a1b2c3d · │+│ pypi:weekly 1.2k · ci:passing · coverage:91% │+├─────────────────────────────────────────────────────────────┤+│ Docusaurus default footer (links, copyright) │+└─────────────────────────────────────────────────────────────┘+```++### Responsive++Below 768px:++- Hero stays single-column; the social-preview banner stays at the top.+- Feature grid collapses to 1 column.+- WHY CUBEPI table becomes horizontally scrollable inside its own+ container (don't reflow rows — readers compare cells).++### Justified divergences from Operator++| Aspect | Operator says | Homepage does | Justification |+|---|---|---|---|+| Hero exists | "marketing distance not needed" | Keeps a restrained hero | Without one, a docs landing page is just a link list; the hero is severe and informational, no animations |+| No sidebar / inspector / statusbar chrome | Identity feature of Operator | Homepage uses a single-column layout, only carries the meta status bar at the bottom | A homepage is not an app shell; copying chrome would be cargo cult |+| kbd hints sparing | First-class citizen | Only two `<kbd>` chips, on the two hero CTAs | docs site is not an IDE; heavy kbd hints would feel performative |++### ⚠️ Outstanding review reference++`memory/feedback_design_review.md` requires comparing cubepi designs+against `pi-agent-core`. `pi-agent-core` was not present on this+machine when the spec was written. Once the repo is available, the+homepage will be re-reviewed against it and divergences documented in+the implementation plan.++## 10. API Reference Generation Pipeline++**Tool: [griffe](https://github.com/mkdocstrings/griffe)** — the engine+behind `mkdocstrings`. Pure Python, parses signatures, type annotations,+decorators, and Google-style docstrings.++### Script: `website/scripts/build-api-reference.py`++Roughly 150 lines. Flow:++1. `griffe.load("cubepi")` → full module tree.+2. Filter to public symbols (in `__all__` or without leading underscore).+3. For each top-level module (`agent`, `providers`, `checkpointer`,+ `middleware`, `mcp`, `utils`), emit one `<module>.mdx`.+4. Per symbol, render:+ - Signature block with type annotations (JetBrains Mono).+ - Docstring description (Google-style sections parsed: `Args`,+ `Returns`, `Raises`, `Example` → mdx-native tables / code blocks).+ - Source link → GitHub blob URL at the current commit, anchored to+ the line.+5. Inject frontmatter (`id`, `title`, `sidebar_position`).+6. Trailing `<!-- GENERATED by build-api-reference.py — DO NOT EDIT -->`+ marker. CI grep step rejects PRs that hand-edit these files.++### Integration++- `pnpm build` runs `"prebuild": "uv run python scripts/build-api-reference.py"`.+- CubePi is `uv sync --extra docs`-installed in CI before docs build.++### Versioning++- When `docs:version 0.4` runs, the latest generated API MDX is copied+ into `versioned_docs/version-0.4/api/` and frozen forever (so the API+ reference for `0.3` continues to reflect `0.3`'s code, not main).++### Docstring contract++- Google-style (existing convention in the codebase).+- All public API has docstrings; `ruff` rule `D` (pydocstyle) enforced+ in CI on the `cubepi/` package.++## 11. CI / Deployment / PR Preview++### `.github/workflows/docs.yml`++Two jobs:++**`build-and-check`** (PR + push):++- `actions/checkout@v4`+- `pnpm/action-setup@v4` (pnpm 9)+- `actions/setup-node@v4` (Node 22)+- `astral-sh/setup-uv@v3`+- `uv python install 3.11 && uv sync --frozen --extra docs`+- `cd website && pnpm install --frozen-lockfile`+- `pnpm build` (runs griffe prebuild → docusaurus build)+- `pnpm run check`:+ - Docusaurus `onBrokenLinks: 'throw'` + `onBrokenAnchors: 'throw'`+ - `cspell` over `docs/` and `i18n/` with a project dictionary+ (entries: `cubepi`, `langgraph`, `anthropic`, `mcp`, etc.)+ - Grep guard: reject hand-edits to `docs/api/*.mdx`++**`deploy-cloudflare`** (push to `main` only):++- Reuses the artefact from `build-and-check`.+- Uses `cloudflare/pages-action@v1` with a Wrangler API token+ (`CF_API_TOKEN`, stored in GitHub Secrets) and account ID.++### PR preview++Cloudflare Pages provides preview URLs natively (`<sha>.cubepi.pages.dev`).+`cloudflare/pages-action@v1` posts a sticky comment with the preview+link on every PR.++### Domain++Launch domain: `cubepi.pages.dev`. Custom domain (e.g. `cubepi.dev`,+`docs.cubepi.dev`) is deferred — site config supports late binding via+`url` / `baseUrl` swap.++## 12. Performance & Compliance Notes++- All fonts self-hosted (no Google Fonts request) → faster LCP, GDPR-clean.+- PostHog initialised with `persistence: 'memory'` → no cookies →+ no consent banner needed in EU.+- Docusaurus produces fully static output → first byte from CF edge.+- Target Lighthouse scores at launch: ≥ 95 on Performance, Accessibility,+ Best Practices, SEO for the homepage on mid-tier mobile profile.++## 13. Open Items (to resolve during implementation)++1. **`pi-agent-core` design parity review** (see §9) — needs repo+ access.+2. **Algolia DocSearch application** — apply for the OSS free tier;+ takes 1–2 weeks. Until approved, use Docusaurus's built-in local+ search plugin.+3. **PostHog project provisioning** — choose project (US vs EU+ endpoint).+4. **README.md updates** — image references must point at the new+ `website/static/img/brand/` path; add a single line linking to+ `cubepi.pages.dev` at the top.++## 14. Out of Scope (explicitly deferred)++- Blog / changelog (use GitHub Releases).+- API playground / interactive sandbox.+- Authenticated content / paid tiers.+- Multi-repo doc aggregation.+- Crowdin / SaaS translation workflow.+- Custom domain binding (deferred until product is post-1.0).++## 15. Success Criteria++- `pnpm dev` runs locally on a fresh clone with one command after+ `pnpm install` + `uv sync --extra docs`.+- `pnpm build` produces a deployable artefact on CI in under 4 minutes.+- A new minor release can be snapshotted with a single command+ (`pnpm docusaurus docs:version <X.Y>`).+- 👍 / 👎 events are visible in PostHog within 30 seconds of clicking.+- Every page is reachable via the navbar in ≤ 2 clicks from the+ homepage.+- Lighthouse ≥ 95 on the four core categories for `/` and a representative+ Guides page on mobile.diff --git a/dev/specs/2026-05-18-cubepi-tracing-design.md b/dev/specs/2026-05-18-cubepi-tracing-design.mdnew file mode 100644index 0000000..2e9638e--- /dev/null+++ b/dev/specs/2026-05-18-cubepi-tracing-design.md@@ -0,0 +1,1024 @@+# CubePi Tracing — Design Spec++**Date:** 2026-05-18+**Author:** xf gong ([email protected])+**Status:** Draft — awaiting review+**Spec target:** OpenTelemetry Semantic Conventions, GenAI working set as of 2026-05 (SemConv v1.41.0)++## 1. Goal & Scope++Give CubePi a first-class debugging/observability story that is **fully compatible with the OpenTelemetry data model and the GenAI semantic conventions**. A developer should be able to:++- Inspect any `agent.run()` after the fact: full prompt sent, full response received, per-call timing, token usage, tool args/results, errors with stacktraces.+- Pipe traces into any OTel-aware backend (Jaeger, Tempo, Phoenix, Honeycomb, Datadog, …) with zero translation.+- Run cubepi locally with zero infrastructure (jsonl on disk).++Two exporters in this scope:++| Exporter | Purpose |+|---|---|+| **`JsonlSpanExporter`** | Append-only file, one OTLP/JSON span per line. For local dev, CI repro. |+| **`OTLPSpanExporter`** (re-export) | OTLP/HTTP over protobuf. For production, OTel Collector, Jaeger, SaaS. |++Deferred to a later phase: SQLite exporter, OpenSearch exporter, sampling.++Out of scope:+- Query backend / UI (separate repo, separate spec).+- Auto-instrumentation of third-party libraries.++## 2. Non-Goals & Explicit Rejections++| Option | Rejected because |+|---|---|+| Read `CheckpointData` to drive debugging UI | Checkpoint stores final messages + extra dict only — no timing, tokens, durations, payloads. |+| Adopt Traceloop / OpenLLMetry SDK | LangChain-flavored autoinstrumentation; cubepi is not LangChain. |+| Implement as cubepi `Middleware` | Middleware is a mutation API. Tracing must not have that power. |+| Roll our own span / resource / scope dataclasses | Duplicating `opentelemetry-sdk`. See §3.3. |+| Persist every `MessageUpdateEvent` / `ToolExecutionUpdateEvent` | Streaming deltas are useful for *live* UI, not for *trace* storage. Record final state only. |+| Use ad-hoc field names (`cubepi.tool.args`, `gen_ai.system`) | Not OTel-compatible. Use standardized `gen_ai.tool.call.arguments`, `gen_ai.provider.name`. |++## 3. Design Decisions++### 3.1 Instrumentation surface: `agent.subscribe()` + provider listener registry++cubepi exposes one observation-only hook today and requires one new one:++- `Agent.subscribe(listener)` in `cubepi/agent/agent.py` — emits the 10-event `AgentEvent` union (agent/turn/message/tool-execution × start/[update]/end). **Already exists.**+- A persistent multi-subscriber listener registry on `Provider` — exposes request payload, per-chunk timing, and assembled response body to the tracer. **Requires a small extension to `cubepi/providers/base.py`**; specified in §3.4 below.++The existing per-call `StreamOptions.on_payload` / `on_response` callbacks are insufficient for tracing — `on_response` carries only HTTP status + headers, not the response body — and they are single-slot, so a user-supplied callback would clobber the tracer. The new registry coexists with these per-call slots.++No monkey-patching, no SDK auto-instrumentation, no `Middleware`.++### 3.2 Span hierarchy using semconv operation names++All spans use names from the semconv `gen_ai.operation.name` enum:++| Span | `gen_ai.operation.name` | `SpanKind` | Source event |+|---|---|---|---|+| Root | `invoke_agent` | `INTERNAL` | `AgentStartEvent` / `AgentEndEvent` |+| Per turn | (cubepi-namespaced; no `gen_ai.operation.name`) | `INTERNAL` | `TurnStartEvent` / `TurnEndEvent` |+| Per LLM call | `chat` | `CLIENT` | assistant `MessageStartEvent` / `MessageEndEvent` |+| Per tool call (cubepi-side) | `execute_tool` | `INTERNAL` | `ToolExecutionStartEvent` / `ToolExecutionEndEvent` |+| Per MCP call (when tool is MCP-backed) | `execute_tool` (with `mcp.method.name="tools/call"`) | `CLIENT` | inside `cubepi/mcp/` client |++Rationale for **not** using `gen_ai.operation.name = "invoke_workflow"` on the turn span: the semconv agent-spans page states `invoke_workflow` "should not be reported when instrumentation cannot distinguish workflow from agent invocation," and the meaning of "workflow" in cubepi (one model→tool roundtrip) is narrower than the semconv intent (orchestration of multiple agents and/or tools). To stay conservatively correct, the turn span uses the cubepi-namespaced name `cubepi.turn` and carries only `cubepi.turn.*` attributes — no `gen_ai.operation.name`, no `gen_ai.workflow.name`. Standard OTel UIs will still render the parent-child structure correctly via the `invoke_agent → cubepi.turn → chat / execute_tool` tree; only the operation-name-keyed dashboards skip the intermediate layer, which is the right default.++### 3.3 Build on `opentelemetry-sdk`, do not reimplement++cubepi's tracing module **depends on `opentelemetry-sdk`** for:++- `Span` / `Resource` / `InstrumentationScope` / `Status` / `SpanKind` data types — full OTLP proto fidelity, `AnyValue` encoding, `dropped_*_count` bookkeeping all handled.+- `TracerProvider` / `Tracer` — span lifecycle, schema URL plumbing, `IdGenerator`, `SpanLimits`.+- `BatchSpanProcessor` / `SimpleSpanProcessor` — async batching, retries, shutdown.+- `SpanExporter` base class — pluggable export pipeline.+- `record_exception()`, `set_status()`, `add_event()` — all standardized formats.+- `MeterProvider` / `Histogram` — for the metrics in §13.+- `TraceContextTextMapPropagator` — W3C `traceparent` injection (used by MCP integration).+- `OTLPSpanExporter` (from `opentelemetry-exporter-otlp-proto-http`) — re-exported as-is.++**Library/application boundary.** cubepi as a library declares OTel as **optional**. Users opt in via `pip install cubepi[tracing]`. Without that extra, `cubepi.tracing` raises `ImportError` cleanly; the rest of cubepi works untouched.++We use SDK in **explicit-span mode**, not in `with start_as_current_span` mode. Reason: cubepi's event stream gives us discrete start/end callbacks, not bracketed scopes — so we manually call `tracer.start_span()`, hold the `Span` reference on a per-run stack, then call `span.end()` at the matching end event. The SDK supports this first-class via `start_span(context=...)` with an explicit parent. This also avoids any `contextvars` ambiguity when parallel tools run concurrently.++What we still write ourselves (~400-600 lines, including Phase 0):++- **Phase 0 — prerequisite cubepi changes** (§3.4): (a) Provider listener registry — converts `Provider` from `Protocol` to a base class, adds three persistent subscription methods, threads listener invocations through every provider implementation; (b) extends `ToolExecutionEndEvent` with `terminate` / `blocked_by_hook` / `block_reason` fields.+- `Recorder`: AgentEvent + provider listeners → SDK API calls.+- `schema.py`: `gen_ai.*` / `cubepi.*` field-name constants.+- `Tracer` (config class): wraps `TracerProvider` setup, exporter registration, `attach(agent)`.+- `JsonlSpanExporter`: ~30-line `SpanExporter` subclass.+- `mcp.py`: helper for the MCP client to wrap calls in a CLIENT span.+- Provider-specific attribute extraction (Anthropic token reconciliation, OpenAI service tier).++### 3.4 Required cubepi extensions (Phase 0)++Two small changes to cubepi are prerequisites for Phase 1.++#### 3.4.1 Provider listener registry++The tracer cannot capture the wire payload, time-to-first-chunk, or assembled response body using the current `Provider` interface.++**Current state** (`cubepi/providers/base.py`):++- `Provider` is a `Protocol` with no instance state.+- Per-call `StreamOptions.on_payload` / `on_response` are single-slot callbacks.+- `OnResponseCallback` receives `ProviderResponse(status, headers), Model` — HTTP metadata only, no body.++**Required additions:**++1. **Make `Provider` a base class** (or introduce a mixin) carrying a listener registry so multiple subscribers (tracer + user code + future extensions) coexist without clobbering each other.++2. **New persistent subscription API**, three methods, each returning a detach callable:++ ```python+ class Provider:+ def subscribe_request(self, cb: OnRequestCallback) -> Callable[[], None]: ...+ def subscribe_chunk(self, cb: OnChunkCallback) -> Callable[[], None]: ...+ def subscribe_response(self, cb: OnResponseBodyCallback) -> Callable[[], None]: ...+ ```++ These fire on **every** `provider.stream()` call. They are observers, never mutators. The existing per-call `StreamOptions.on_payload` (mutate the request) and `on_response` (inspect HTTP metadata) retain their current semantics; the new listeners fire **after** any `StreamOptions.on_payload` mutation, so they see the final wire payload.++3. **New callback signatures:**++ ```python+ OnRequestCallback = Callable[[dict, Model], None | Awaitable[None]]+ # fires just before HTTP send; payload is the final dict after any+ # StreamOptions.on_payload mutation.++ OnChunkCallback = Callable[[StreamEvent, Model], None | Awaitable[None]]+ # fires for each StreamEvent (start / text_delta / done / error / ...).+ # The tracer uses this ONLY to time TTFT and count chunks; content is not+ # stored. Heavy listeners should early-return on irrelevant event types.++ OnResponseBodyCallback = Callable[+ [dict | None, Model, Exception | None],+ None | Awaitable[None],+ ]+ # fires after the stream terminates (normal completion or error).+ # - dict: the assembled provider response (the same structure a buffered+ # non-streaming call would have returned), or None on early failure.+ # - Exception: present iff the stream raised; None on normal completion.+ ```++4. **Provider implementations** invoke listeners at these points (anthropic.py / openai.py / openai_responses.py):++ ```python+ # inside provider.stream()+ request_dict = build_request(...)+ request_dict = await invoke_on_payload(opts.on_payload, request_dict, model)+ await _fire_listeners(self._request_listeners, request_dict, model)++ try:+ async for raw_chunk in http_stream:+ event = parse_chunk(raw_chunk)+ stream.push(event)+ await _fire_listeners(self._chunk_listeners, event, model)+ final_response_dict = assemble_response(...)+ await _fire_listeners(self._response_listeners, final_response_dict, model, None)+ except Exception as exc:+ await _fire_listeners(self._response_listeners, None, model, exc)+ raise+ ```++**What this enables for the tracer:**++| Need | Hook |+|---|---|+| `cubepi.llm.raw_request` | `subscribe_request` |+| `chat` span **open** | `subscribe_request` |+| `gen_ai.response.time_to_first_chunk` | `subscribe_chunk` (timestamp of first non-`start` chunk) |+| `gen_ai.client.operation.time_per_output_chunk` metric | `subscribe_chunk` (consecutive non-`start` chunks) |+| `cubepi.llm.raw_response`, all `gen_ai.response.*`, all `gen_ai.usage.*`, provider-specific attrs | `subscribe_response` |+| `chat` span **close** (success or error) | `subscribe_response` |++**Listener invocation contract:**++- Listeners run on the asyncio event loop in registration order.+- Exceptions in listeners are logged and **swallowed** by the provider — a buggy tracer must never crash the stream. The contract is enforced inside `_fire_listeners`, not at each call site.+- **`subscribe_response` listeners MUST be invoked exactly once per `stream()` call, before that call returns or raises.** This is the contract that lets the tracer guarantee `chat` span closure. Provider implementations enforce it with a `finally` block:++ ```python+ request_dict = build_request(...)+ request_dict = await invoke_on_payload(opts.on_payload, request_dict, model)+ await _fire_listeners(self._request_listeners, request_dict, model)++ body: dict | None = None+ exc: BaseException | None = None+ try:+ async for raw_chunk in http_stream:+ event = parse_chunk(raw_chunk)+ stream.push(event)+ await _fire_listeners(self._chunk_listeners, event, model)+ body = assemble_response(...)+ except BaseException as e: # includes asyncio.CancelledError+ exc = e+ raise+ finally:+ # Fires exactly once, even on abort / cancellation / network drop.+ # Body may be partial-and-not-None if the provider managed to assemble+ # a final message with stop_reason="aborted" before the stream broke.+ await _fire_listeners(self._response_listeners, body, model, exc)+ ```++ Note `except BaseException`: `asyncio.CancelledError` is a `BaseException` in Python 3.8+, not an `Exception`. The provider must still fire the listener on cancel; it then re-raises to honor cancellation semantics.++#### 3.4.2 `ToolExecutionEndEvent` extension++Current `ToolExecutionEndEvent` carries only `tool_call_id`, `tool_name`, `result`, `is_error` — insufficient to populate `cubepi.tool.terminate`, `cubepi.tool.blocked_by_hook`, `cubepi.tool.block_reason` cleanly. `result.terminate` is reachable by unwrapping the `AgentToolResult`, but block reasons today are only visible as a string buried inside the result's content.++Add three fields:++```python+class ToolExecutionEndEvent(BaseModel):+ type: Literal["tool_execution_end"] = "tool_execution_end"+ tool_call_id: str+ tool_name: str+ result: Any = None+ is_error: bool = False+ # New:+ terminate: bool = False+ blocked_by_hook: bool = False+ block_reason: str | None = None+```++The tool-execution layer (`cubepi/agent/tools.py`) populates these:+- `terminate` is copied from the finalized `AgentToolResult.terminate` (already plumbed through `after_tool_call`).+- `blocked_by_hook` is `True` only when the `_ImmediateOutcome` was produced by `before_tool_call` returning `block=True`. Distinguish this from other immediate errors (tool not found, arg validation failure) so the recorder can tag the span correctly.+- `block_reason` is the `BeforeToolCallResult.reason` string when blocked, else `None`.++This change is additive — existing consumers continue to work; defaults are conservative.++#### 3.4.3 No checkpointer changes++The `extra` field on `AgentContext` and `CheckpointData` remains tracing-free. Nested-run parent-span propagation uses OTel's standard context propagation (see §8), not `extra`.++### 3.5 Repository split++Recorder/tracer/exporters live in cubepi repo. Query backend + UI live in a separate repo (`cubepi-trace`), reading exported documents through a storage boundary. No shared schema package.++## 4. Architecture++```+┌───────────────────────────────────────────────────────────────┐+│ cubepi (this repo) │+│ │+│ Agent ──┬─ subscribe(listener) ──▶ Recorder │+│ │ │ │+│ Provider ─ on_payload / on_response ───┤ │+│ MCP client ─ wraps call site ──────────┤ │+│ ▼ │+│ opentelemetry-sdk Tracer │+│ │ │+│ ▼ │+│ TracerProvider │+│ │ │+│ ┌───────┴───────┐ │+│ ▼ ▼ │+│ JsonlSpanExporter OTLPSpanExporter│+│ │+│ MeterProvider (optional) │+│ ──▶ OTLPMetricExporter │+└───────────────────────────────────────────────────────────────┘+ │ │+ ▼ ▼+ ┌────────────────────┐ ┌──────────────────────────┐+ │ cubepi-traces/ │ │ OTel Collector / Jaeger /│+ │ YYYY-MM-DD/ │ │ Tempo / Phoenix / │+ │ <run_id>.jsonl │ │ Honeycomb / Datadog / … │+ └────────────────────┘ └──────────────────────────┘+```++## 5. Module Layout++```+cubepi/tracing/+├── __init__.py # public: Tracer, attach helpers, schema constants+├── tracer.py # Tracer config class: builds TracerProvider, wires exporters+├── recorder.py # consumes AgentEvent + provider callbacks → SDK API calls+├── schema.py # field-name constants (gen_ai.*, cubepi.*, mcp.*, openai.*)+├── errors.py # error.type derivation from exceptions / stop reasons+├── meter.py # MeterProvider setup + histogram registry (phase 4)+├── mcp.py # helper for cubepi.mcp client: open tools/call CLIENT spans+└── exporters/+ ├── __init__.py # re-exports OTLPSpanExporter for convenience+ └── jsonl.py # JsonlSpanExporter: SpanExporter subclass, span.to_json() per line+```++`pyproject.toml`:++```toml+[project.optional-dependencies]+tracing = ["opentelemetry-sdk>=1.30"]+tracing-otlp = ["opentelemetry-exporter-otlp-proto-http>=1.30"]+```++A user who does not install `cubepi[tracing]` cannot import `cubepi.tracing` (the package's `__init__` does an SDK import at module level and will fail with a clear message). All other cubepi functionality is unaffected.++## 6. Public API++```python+from cubepi.tracing import Tracer+from cubepi.tracing.exporters.jsonl import JsonlSpanExporter+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter++tracer = Tracer(+ service_name="my-bot",+ service_version="0.1.0",+ deployment_environment="dev",+ agent_name="coding-agent",+ agent_id="agent-abc",+ exporters=[+ JsonlSpanExporter(directory="./cubepi-traces"),+ OTLPSpanExporter(endpoint="http://collector:4318/v1/traces"),+ ],+ record_content=False, # default: do not record prompt/completion bodies+)+tracer.attach(agent)++# Per-run override:+async with tracer.run_scope(extra_attrs={"cubepi.user.id": user_id}):+ await agent.run([UserMessage(...)])+```++What `Tracer.__init__` does:+1. Builds a `Resource` with `service.name`, `service.version`, `deployment.environment.name`, `gen_ai.agent.*`, `telemetry.sdk.*` (auto by SDK).+2. Builds a `TracerProvider(resource=resource)`.+3. For each exporter, wraps it in `BatchSpanProcessor(exporter)` and registers via `provider.add_span_processor(...)`.+4. Calls `provider.get_tracer(name="cubepi.tracing", version=cubepi.__version__, schema_url=SCHEMA_URL)`; holds the `Tracer` instance.++What `tracer.attach(agent)` does:+1. `agent.subscribe(self._recorder.on_agent_event)` — high-level lifecycle (agent / turn / tool spans).+2. `agent.provider.subscribe_request(self._recorder.on_provider_request)` — opens `chat` span and records `cubepi.llm.raw_request`.+3. `agent.provider.subscribe_chunk(self._recorder.on_provider_chunk)` — times TTFT and chunk metric.+4. `agent.provider.subscribe_response(self._recorder.on_provider_response)` — records `gen_ai.response.*` / `gen_ai.usage.*` / `cubepi.llm.raw_response` and closes `chat` span.+5. Returns a `detach()` callable that reverses all four subscriptions and forces a final flush.++### 6.1 Lifecycle and flush++`BatchSpanProcessor` exports spans asynchronously — `AgentEnd` does **not** guarantee that the corresponding spans have hit disk or the wire. cubepi exposes three controls:++```python+class Tracer:+ async def force_flush(self, timeout_seconds: float = 30) -> bool:+ """Block until all currently-buffered spans are exported.+ Returns False on timeout."""++ async def shutdown(self, timeout_seconds: float = 30) -> None:+ """Flush, then close all exporters. Tracer is unusable afterwards."""++ async def __aenter__(self) -> Tracer: ...+ async def __aexit__(self, *exc) -> None:+ """Calls shutdown() on context exit."""+```++Common patterns:++```python+# CI / short-lived script — guarantee data is on disk before process exits+async with Tracer(...) as tracer:+ tracer.attach(agent)+ await agent.run(...)+ # __aexit__ flushes and closes exporters here++# Long-running service — flush at known checkpoints+tracer = Tracer(...)+detach = tracer.attach(agent)+await agent.run(...)+await tracer.force_flush() # spans guaranteed exported now+# ... later, on shutdown signal:+await tracer.shutdown()+```++`detach()` returned from `attach()` calls `force_flush()` internally before unsubscribing, so any in-flight spans for that agent settle before the listener chain disconnects.++Under the hood, `Tracer.force_flush()` / `shutdown()` delegate to `provider.force_flush()` / `provider.shutdown()`, which propagate to every registered `SpanProcessor`. `JsonlSpanExporter` honors flush by `fsync`'ing the active file; `OTLPSpanExporter` drains its retry queue.++Note we **do not** call `trace.set_tracer_provider(provider)` — that mutates global state. cubepi's `Tracer` owns its provider so multiple agents can coexist in one process with different exporter configs.++## 7. Schema URL & SDK Setup++```python+SCHEMA_URL = "https://opentelemetry.io/schemas/1.41.0"+```++Pinned to the semconv version we promise to follow. Set in two places:++```python+resource = Resource.create(+ attributes={"service.name": ..., ...},+ schema_url=SCHEMA_URL,+)+tracer_internal = provider.get_tracer(+ instrumenting_module_name="cubepi.tracing",+ instrumenting_library_version=cubepi.__version__,+ schema_url=SCHEMA_URL,+)+```++`cubepi.*` extensions are versioned by cubepi releases. `gen_ai.*` keys follow OTel deprecation policy.++## 8. Trace & Span ID Inheritance++The SDK's `RandomIdGenerator` generates `trace_id` (16 bytes) and `span_id` (8 bytes) by default. cubepi does not override it.++**Inbound trace context.** When a host service wants to make cubepi a child of its own trace:++```python+async with tracer.run_scope(+ parent_trace_id=incoming_trace_id_int, # int128+ parent_span_id=incoming_span_id_int, # int64+ trace_flags=0x01,+):+ await agent.run(...)+```++Implementation:++```python+from opentelemetry.trace import SpanContext, TraceFlags, NonRecordingSpan, set_span_in_context++parent_ctx = SpanContext(+ trace_id=parent_trace_id,+ span_id=parent_span_id,+ is_remote=True,+ trace_flags=TraceFlags(trace_flags),+)+context = set_span_in_context(NonRecordingSpan(parent_ctx))+root = self._sdk_tracer.start_span(+ name=f"invoke_agent {agent_name}",+ context=context,+ kind=SpanKind.INTERNAL,+)+```++**Nested cubepi runs** (an inner `agent.run()` inside a tool): propagation uses OTel's standard context, **not** `AgentContext.extra`. `extra` is JSON-serialized by the checkpointer (see `cubepi/checkpointer/sqlite.py`), and an SDK `Span` is not serializable; storing one there would crash on first checkpoint flush.++Mechanism: when the recorder opens `execute_tool`, it attaches the new span to the OTel context for the duration of that tool's body:++```python+import opentelemetry.context as context_api+from opentelemetry import trace++# inside Recorder.on_tool_exec_start+tool_span = self._sdk_tracer.start_span(...)+ctx_with_tool = trace.set_span_in_context(tool_span)+token = context_api.attach(ctx_with_tool)+self._tool_contexts[tool_call_id] = (tool_span, token)++# inside Recorder.on_tool_exec_end+tool_span, token = self._tool_contexts.pop(tool_call_id)+context_api.detach(token)+tool_span.end()+```++When the tool body calls `agent.run()` on an inner agent (with its own `Tracer`), that inner Tracer's root `start_span()` (called with no explicit `context=`) picks up the outer tool span as parent via SDK's default context lookup. `trace_id` is inherited automatically; `parent_span_id` becomes the outer tool span's id.++Two cubepi processes / agents that share the same Python process share the OTel `contextvars`, so this works across `Tracer` instances. For inner agents that run in a separate `asyncio` task (`asyncio.create_task(...)` inside a tool) the context inheritance is the standard Python contextvars behavior — the new task inherits the current context at creation time.++For cross-process nesting (inner agent runs in a subprocess or worker), the outer Tracer must serialize the W3C `traceparent` string and the inner host must call `tracer.run_scope(parent_trace_id=..., parent_span_id=...)` explicitly. See "Inbound trace context" above.++## 9. Event → Span Mapping++The `chat` span is **driven by provider listeners**, not by `MessageStartEvent` / `MessageEndEvent`. Reason: `MessageEndEvent` fires after `after_model_response` middleware hooks have run, so closing the span there would include hook time in the duration and would let stream errors leak (an exception during streaming can synthesize a failure message via the loop, but the partial `chat` span would never be closed). Driving from provider listeners ties the span lifetime to the actual HTTP roundtrip.++```+AgentStart → start_span("invoke_agent ...", kind=INTERNAL, context=root_ctx)+TurnStart → start_span("cubepi.turn", kind=INTERNAL, context=in(agent_span))+provider.on_request → start_span("chat <model>", kind=CLIENT, context=in(turn_span))+ + set request attrs, raw_request+provider.on_chunk (1st) → record TTFT on chat span+provider.on_chunk (subseq.) → optional: emit time_per_output_chunk metric observation+provider.on_response (ok) → set response/usage/raw_response attrs; chat_span.end()+provider.on_response (err) → if isinstance(exc, asyncio.CancelledError):+ set chat_span.attribute("cubepi.aborted", true)+ set error.type = "cubepi.aborted"+ Status stays UNSET (abort is not a failure)+ else:+ add_event("gen_ai.client.operation.exception",...)+ set Status.ERROR; set error.type+ chat_span.end() ← always closes+MessageStart [a] → no-op for spans (already opened by on_request)+MessageEnd [a] → no-op for chat span (already closed by on_response).+ Used by turn span to collect post-hook output.+ToolExecStart → start_span("execute_tool <name>", kind=INTERNAL, context=in(turn_span))+ToolExecEnd → set tool attrs; tool_span.end()+TurnEnd → set workflow output attrs; turn_span.end()+AgentEnd → set agent output attrs; agent_span.end()++MessageStart [u/t] → recorded into turn span's `gen_ai.input.messages` buffer+MessageUpdate → IGNORED (TTFT and chunk timing are sourced from provider.on_chunk, not from agent-level update events)+ToolExecUpdate → IGNORED+```++`in(span)` is shorthand for `trace.set_span_in_context(span)`.++**`chat` span recorded output is pre-hook.** `gen_ai.output.messages` and `cubepi.llm.raw_response` on the `chat` span reflect what the provider actually returned. Any mutation performed by an `after_model_response` middleware is captured on the parent `cubepi.turn` span's `gen_ai.output.messages` instead. This preserves the rule "chat span describes the provider call; turn span describes cubepi's processed turn."++**No-provider-call case.** A middleware can inject a synthetic assistant message via `TurnAction.inject_messages` without ever calling the provider. In that case no `chat` span is opened — the `MessageStart` / `MessageEnd` pair has no associated provider events. The synthetic message still appears on the `turn span's `gen_ai.output.messages``.++**Recorder span stack.** The Recorder keeps a per-run map of open spans:+- `agent_span` (1 per run)+- `turn_span` (1 at a time per run)+- `chat_span` (1 at a time per run; opened by `on_request`, closed by `on_response`)+- `tool_spans: dict[tool_call_id, Span]` — parallel tools are keyed by `tool_call_id` so each execution has an unambiguous lifetime regardless of `contextvars` state.++**Provider listener implementations** (sketch):++```python+def on_provider_request(self, payload: dict, model: Model) -> None:+ turn_span = self._current_turn_span()+ if turn_span is None:+ return # not in an attached run+ chat_span = self._sdk_tracer.start_span(+ name=f"chat {model.id}",+ kind=SpanKind.CLIENT,+ context=trace.set_span_in_context(turn_span),+ )+ self._chat_span = chat_span+ self._chat_open_ns = time.time_ns()+ chat_span.set_attribute("gen_ai.operation.name", "chat")+ chat_span.set_attribute("gen_ai.provider.name", map_provider(model.provider))+ chat_span.set_attribute("gen_ai.request.model", model.id)+ # ... other gen_ai.request.* from payload+ if self._record_content:+ chat_span.set_attribute("cubepi.llm.raw_request", json.dumps(payload))++def on_provider_chunk(self, event: StreamEvent, model: Model) -> None:+ if self._chat_span is None or self._first_chunk_recorded:+ return+ if event.type in ("text_delta", "thinking_delta", "toolcall_delta"):+ ttft_s = (time.time_ns() - self._chat_open_ns) / 1e9+ self._chat_span.set_attribute("gen_ai.response.time_to_first_chunk", ttft_s)+ self._first_chunk_recorded = True++def on_provider_response(+ self,+ body: dict | None,+ model: Model,+ exc: BaseException | None, # BaseException to catch CancelledError+) -> None:+ if self._chat_span is None:+ return+ span = self._chat_span+ try:+ if body is not None:+ # Even on abort, the provider may have assembled a partial body+ # with stop_reason="aborted". Record what we have.+ self._record_response_attrs(span, body, model)+ if isinstance(exc, asyncio.CancelledError):+ span.set_attribute("cubepi.aborted", True)+ span.set_attribute("error.type", "cubepi.aborted")+ # status stays UNSET — abort is a control signal, not a failure+ elif exc is not None:+ span.set_status(Status(StatusCode.ERROR, str(exc)[:256]))+ span.set_attribute("error.type", cubepi_error_type_for(exc))+ span.add_event(+ name="gen_ai.client.operation.exception",+ attributes={+ "exception.type": type(exc).__name__,+ "exception.message": str(exc),+ "exception.stacktrace": "".join(traceback.format_exception(exc)),+ },+ )+ finally:+ span.end()+ self._chat_span = None+ self._first_chunk_recorded = False+```++## 10. Span Attribute Schemas++Notation: **R** = Required, **CR** = Conditionally Required, **Rec** = Recommended, **Opt** = Opt-In.++### 10.1 `invoke_agent` (root)++| Attribute | Type | Status | Source |+|---|---|---|---|+| `gen_ai.operation.name` | string | **R** | `"invoke_agent"` |+| `gen_ai.provider.name` | string | **R** | provider id of first chat call, or `"cubepi"` if undetermined at root open |+| `gen_ai.agent.name` | string | CR | from `Tracer.agent_name` or `run_scope(extra_attrs=...)` |+| `gen_ai.agent.id` | string | CR | caller-supplied |+| `gen_ai.agent.description` | string | CR | caller-supplied |+| `gen_ai.agent.version` | string | CR | caller-supplied |+| `gen_ai.conversation.id` | string | CR | `thread_id` |+| `gen_ai.request.model` | string | CR | model id of first chat call (if pre-known) |+| `error.type` | string | CR (on error) | see §12.3 |+| `cubepi.run_id` | string | **R** | uuid generated at root open |+| `cubepi.thread_id` | string | Rec | same as `gen_ai.conversation.id`, duplicated for `cubepi.*` namespace ergonomics |+| `cubepi.agent.tools` | string[] | Opt | tool names registered |+| `cubepi.agent.system_prompt.sha256` | string | Opt | first 16 hex of `sha256(system_prompt)` |+| `cubepi.input.messages.count` | int | Rec | input message count |+| `cubepi.output.messages.count` | int | Rec | new messages produced |+| `cubepi.aborted` | bool | Opt | `true` if the run terminated via `asyncio.CancelledError` or assistant `stop_reason == "aborted"`. Status stays `UNSET`. |+| `gen_ai.system_instructions` | array | Opt | gated by `record_content` |+| `gen_ai.input.messages` | array | Opt | gated by `record_content` |+| `gen_ai.output.messages` | array | Opt | gated by `record_content` |++**Span name:** `invoke_agent {gen_ai.agent.name}` or `invoke_agent`. **Kind:** `INTERNAL`.++### 10.2 `cubepi.turn` (one turn)++cubepi-specific INTERNAL span; carries no `gen_ai.operation.name`. See §3.2 rationale.++| Attribute | Type | Status | Source |+|---|---|---|---|+| `error.type` | string | CR (on error) | see §12.3 |+| `gen_ai.input.messages` | array | Opt | messages going into this turn (cubepi extends opt-in content attrs to non-semconv spans) |+| `gen_ai.output.messages` | array | Opt | assistant message + any tool results (post-hook view, includes middleware mutations) |+| `cubepi.turn.index` | int | **R** | 0-based |+| `cubepi.turn.stop_reason` | string | Rec | cubepi-normalized: `stop` / `tool_use` / `length` / `error` / `aborted` (see `cubepi/providers/anthropic.py` `stop_reason_map`) |+| `cubepi.turn.tool_calls.count` | int | Rec | count |+| `cubepi.turn.terminated_by_tool` | bool | Opt | a tool returned `terminate=True` |++**Span name:** `cubepi.turn`. **Kind:** `INTERNAL`.++### 10.3 `chat` (LLM call)++| Attribute | Type | Status | Source |+|---|---|---|---|+| `gen_ai.operation.name` | string | **R** | `"chat"` |+| `gen_ai.provider.name` | string | **R** | mapped `Model.provider` (see §10.6) |+| `gen_ai.request.model` | string | CR | `Model.id` |+| `gen_ai.response.model` | string | Rec | from provider response |+| `gen_ai.response.id` | string | Rec | from provider response |+| `gen_ai.response.finish_reasons` | string[] | Rec | semconv-standard values: `["stop"]`, `["tool_use"]`, `["length"]`, `["content_filter"]`, `["error"]`. cubepi providers already normalize to these (see `stop_reason_map` in `anthropic.py`). The cubepi-synthetic value `"aborted"` is NOT emitted here — abort is tracked separately via the `cubepi.aborted` attribute on `chat` and `invoke_agent` spans. |+| `gen_ai.request.max_tokens` | int | Rec | `StreamOptions` |+| `gen_ai.request.temperature` | double | Rec | `StreamOptions` |+| `gen_ai.request.top_p` | double | Rec | `StreamOptions` |+| `gen_ai.request.top_k` | double | Rec | `StreamOptions` |+| `gen_ai.request.stop_sequences` | string[] | Rec | `StreamOptions` |+| `gen_ai.request.frequency_penalty` | double | Rec | `StreamOptions` |+| `gen_ai.request.presence_penalty` | double | Rec | `StreamOptions` |+| `gen_ai.request.seed` | int | CR | `StreamOptions` |+| `gen_ai.request.stream` | bool | CR | `true` |+| `gen_ai.request.choice.count` | int | CR | if `≠ 1` |+| `gen_ai.output.type` | string | CR | `"text"` / `"json"` / `"image"` |+| `gen_ai.response.time_to_first_chunk` | double | Rec | seconds between request send and first delta |+| `gen_ai.usage.input_tokens` | int | Rec | from `Usage` (Anthropic: reconciled, see §11.1) |+| `gen_ai.usage.output_tokens` | int | Rec | from `Usage` |+| `gen_ai.usage.reasoning.output_tokens` | int | Opt | extended-thinking tokens |+| `gen_ai.usage.cache_read.input_tokens` | int | Opt | Anthropic / OpenAI cache hit |+| `gen_ai.usage.cache_creation.input_tokens` | int | Opt | Anthropic cache write |+| `server.address` | string | Rec | host of LLM API endpoint |+| `server.port` | int | CR | if non-default port |+| `error.type` | string | CR (on error) | see §12.3 |+| `gen_ai.input.messages` | array | Opt | gated by `record_content` (§10.5) |+| `gen_ai.output.messages` | array | Opt | gated by `record_content` (§10.5) |+| `gen_ai.system_instructions` | array | Opt | gated by `record_content` |+| `gen_ai.tool.definitions` | array | Opt | gated by `record_content` |+| `cubepi.llm.thinking_level` | string | Opt | `off` / `low` / `medium` / `high` |+| `cubepi.llm.raw_request` | string | Opt | full provider request, JSON-serialized — gated by `record_content` |+| `cubepi.llm.raw_response` | string | Opt | full provider response, JSON-serialized — gated by `record_content` |++Plus provider-specific opt-in attributes from §11.++**Span name:** `chat {gen_ai.request.model}`. **Kind:** `CLIENT`.+**Lifetime:** opened by `provider.on_request`, closed by `provider.on_response` (success or failure). Duration reflects the actual HTTP roundtrip, **not** post-stream middleware processing time. See §9.++### 10.4 `execute_tool` (cubepi-side)++| Attribute | Type | Status | Source |+|---|---|---|---|+| `gen_ai.operation.name` | string | **R** | `"execute_tool"` |+| `gen_ai.tool.name` | string | **R** | tool name |+| `gen_ai.tool.call.id` | string | Rec | `tool_call_id` from assistant message |+| `gen_ai.tool.type` | string | Rec | `"function"` |+| `gen_ai.tool.description` | string | Rec | from `AgentTool.description` |+| `gen_ai.tool.call.arguments` | any | Opt | gated by `record_content` |+| `gen_ai.tool.call.result` | any | Opt | gated by `record_content` |+| `error.type` | string | CR (on error) | see §12.3 |+| `cubepi.tool.execution_mode` | string | Rec | `"parallel"` / `"sequential"`. Recorder reads `AgentTool.execution_mode` from the agent's tool registry at `ToolExecutionStartEvent`, falling back to the agent-level `tool_execution` parameter. Not carried on the event itself. |+| `cubepi.tool.is_error` | bool | Rec | mirrors `AgentToolResult.is_error` |+| `cubepi.tool.terminate` | bool | Opt | tool returned `terminate=True` |+| `cubepi.tool.blocked_by_hook` | bool | Opt | `before_tool_call` blocked the call |+| `cubepi.tool.block_reason` | string | Opt | reason string |++**Span name:** `execute_tool {gen_ai.tool.name}`. **Kind:** `INTERNAL`.++### 10.5 `gen_ai.input.messages` / `output.messages` content schema++Opt-in. When `Tracer(record_content=True)`, the recorder serializes messages into the OTel GenAI messages JSON schema:++```jsonc+[+ {+ "role": "user" | "assistant" | "tool" | "system",+ "parts": [+ { "type": "text", "content": "..." },+ { "type": "tool_call", "id": "...", "name": "...", "arguments": { ... } },+ { "type": "tool_call_response", "id": "...", "result": "..." },+ { "type": "reasoning", "content": "..." }+ ]+ }+]+```++Mapping from cubepi `Content` union (`cubepi/providers/base.py`):++| cubepi type | semconv `part` |+|---|---|+| `TextContent` | `{"type": "text", "content": <text>}` |+| `ThinkingContent` | `{"type": "reasoning", "content": <text>}` — `reasoning` is **not yet a standardized part type** in semconv; documented as a cubepi extension (the spec does standardize `gen_ai.usage.reasoning.output_tokens`). |+| `ToolCall` | `{"type": "tool_call", "id": <id>, "name": <name>, "arguments": <args>}` |+| `ToolResultMessage` content | `{"type": "tool_call_response", "id": <tool_call_id>, "result": <content>}` |++### 10.6 `gen_ai.provider.name` value mapping++| cubepi `Model.provider` | `gen_ai.provider.name` |+|---|---|+| `anthropic` | `"anthropic"` |+| `openai` | `"openai"` |+| `azure_openai` | `"azure.ai.openai"` |+| `gemini` | `"gcp.gemini"` |+| `vertex_ai` | `"gcp.vertex_ai"` |+| `bedrock` | `"aws.bedrock"` |+| `cohere` | `"cohere"` |+| `mistral` | `"mistral_ai"` |+| `groq` | `"groq"` |+| `xai` | `"x_ai"` |+| `deepseek` | `"deepseek"` |+| `perplexity` | `"perplexity"` |+| `watsonx` | `"ibm.watsonx.ai"` |+| (unknown) | the raw `Model.provider` string, prefixed with `"unknown:"` |++## 11. Provider-Specific Attributes++### 11.1 Anthropic++`gen_ai.provider.name = "anthropic"`.++**Token reconciliation** — per the Anthropic semconv page, `input_tokens` from the API **excludes** cached tokens. The recorder must compute:++```python+gen_ai_input_tokens = (+ response.usage.input_tokens+ + response.usage.cache_read_input_tokens+ + response.usage.cache_creation_input_tokens+)+```++This is the value emitted on `gen_ai.usage.input_tokens`. Cache fields go on their own attributes unchanged.++### 11.2 OpenAI++`gen_ai.provider.name = "openai"` (or `"azure.ai.openai"`).++| Attribute | Type | Source |+|---|---|---|+| `openai.api.type` | string | `"chat_completions"` / `"responses"` |+| `openai.request.service_tier` | string | `"auto"` / `"default"` |+| `openai.response.service_tier` | string | `"scale"` / `"default"` |+| `openai.response.system_fingerprint` | string | from response |++OpenAI uses `gen_ai.usage.cache_read.input_tokens` for prompt caching. The OpenAI semconv page also lists `gen_ai.usage.cache_creation.input_tokens`; emit it only when the provider response actually exposes the field (current OpenAI responses do not — Anthropic does).++### 11.3 Other providers++Common `gen_ai.*` attributes only. Provider-specific raw fields are preserved in `cubepi.llm.raw_response`.++## 12. Exceptions & Errors++### 12.1 LLM API errors++When the provider returns an error, raises a typed exception, or times out, the `chat` span:++```python+chat_span.set_status(Status(StatusCode.ERROR, description=str(exc)[:256]))+chat_span.set_attribute("error.type", cubepi_error_type_for(exc))+chat_span.add_event(+ name="gen_ai.client.operation.exception",+ attributes={+ "exception.type": type(exc).__name__,+ "exception.message": str(exc),+ "exception.stacktrace": traceback.format_exc(),+ },+)+```++Note: we add a **named event** (`gen_ai.client.operation.exception`), distinct from the standard `exception` event. Per the GenAI semconv exceptions page, this is the dedicated event for LLM client failures.++### 12.2 cubepi-internal Python exceptions++For exceptions inside tool execution or cubepi-internal code (not LLM-provider failures), use SDK's built-in:++```python+tool_span.record_exception(exc, escaped=True)+tool_span.set_status(Status(StatusCode.ERROR, description=str(exc)[:256]))+tool_span.set_attribute("error.type", type(exc).__name__)+```++`record_exception` produces the standard `exception` event with `exception.type` / `exception.message` / `exception.stacktrace` / `exception.escaped`.++### 12.3 `error.type` value conventions++The semconv does not prescribe a closed enum. cubepi conventions:++| Situation | `error.type` value |+|---|---|+| Provider HTTP 4xx/5xx | `"<provider>.<status_code>"` e.g. `"anthropic.429"` |+| Provider client class raised | fully-qualified Python class name, e.g. `"anthropic.RateLimitError"` |+| Network timeout | `"timeout"` |+| Connection refused | `"connection_error"` |+| Tool raised business error | tool's exception class name |+| Agent aborted | `"cubepi.aborted"` |+| Agent error stop_reason | `"cubepi.<stop_reason>"` |++### 12.4 Status mapping++| Situation | Span `status.code` |+|---|---|+| Healthy completion | `UNSET` (do not affirmatively set `OK`) |+| Tool `is_error == true` | `ERROR` on `execute_tool`; parent stays `UNSET` |+| Assistant `stop_reason == "error"` | `ERROR` on `chat`, bubble to parent `cubepi.turn` |+| Assistant `stop_reason == "aborted"` | `UNSET` + `cubepi.aborted = true` attribute on both `chat` and `invoke_agent` |+| `asyncio.CancelledError` during stream | `UNSET` + `cubepi.aborted = true` + `error.type = "cubepi.aborted"` on `chat`; span closes via provider's `finally` block (§3.4); the `CancelledError` is re-raised after listeners fire |+| Exception during provider call | `ERROR` on `chat` |+| Exception during tool execution | `ERROR` on `execute_tool` |++## 13. Metrics++Histograms emitted independently of spans, via `opentelemetry-sdk-metrics`. Phase 4 in the roadmap; pinned here so consumers know the field names ahead of time.++```python+from cubepi.tracing import Meter+from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter++meter = Meter(+ resource=tracer.resource,+ exporter=OTLPMetricExporter(endpoint="http://collector:4318/v1/metrics"),+ export_interval_millis=60_000,+)+meter.attach(tracer)+```++Internally `Meter` wires the exporter through a `PeriodicExportingMetricReader` (this is the SDK's required wrapper; passing a raw exporter to `MeterProvider` doesn't work):++```python+from opentelemetry.sdk.metrics import MeterProvider+from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader++reader = PeriodicExportingMetricReader(+ exporter=exporter,+ export_interval_millis=export_interval_millis,+)+provider = MeterProvider(resource=resource, metric_readers=[reader])+self._otel_meter = provider.get_meter(+ name="cubepi.tracing",+ version=cubepi.__version__,+ schema_url=SCHEMA_URL,+)+```++`Meter` has its own `force_flush()` / `shutdown()` mirroring `Tracer.6.1` and is closed automatically when `Tracer.shutdown()` is called if `meter.attach(tracer)` was invoked.++### 13.1 Histograms emitted++| Metric | Unit | When | Required attrs |+|---|---|---|---|+| `gen_ai.client.operation.duration` | `s` | every `chat` / `execute_tool` / `invoke_agent` close (NOT `cubepi.turn` — turn span has no `gen_ai.operation.name`) | `gen_ai.operation.name`, `gen_ai.provider.name` |+| `gen_ai.client.token.usage` | `{token}` | one observation per token type on `chat` close | `gen_ai.operation.name`, `gen_ai.provider.name`, `gen_ai.token.type` (`input` / `output`) |+| `gen_ai.client.operation.time_to_first_chunk` | `s` | `chat` close (streaming) | `gen_ai.operation.name`, `gen_ai.provider.name` |+| `gen_ai.client.operation.time_per_output_chunk` | `s` | `chat` close (streaming, > 1 chunk) | `gen_ai.operation.name`, `gen_ai.provider.name` |++Recommended attrs on all: `gen_ai.response.model`, `server.address`.++### 13.2 MCP histograms++When MCP is active:++| Metric | Unit | When | Required attrs |+|---|---|---|---|+| `mcp.client.operation.duration` | `s` | every `tools/call` close | `mcp.method.name` |+| `mcp.client.session.duration` | `s` | MCP session close | `mcp.session.id`, `mcp.protocol.version` |++Suggested bucket boundaries (from semconv): `[0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300]` s.++## 14. MCP Integration++cubepi has an MCP client at `cubepi/mcp/`. When the agent calls a tool backed by MCP, a child `tools/call` CLIENT span wraps the network call.++```+execute_tool {tool_name} INTERNAL ← cubepi side+└── tools/call {tool_name} CLIENT ← MCP wire+```++The MCP client uses a helper from `cubepi.tracing.mcp`:++```python+from cubepi.tracing.mcp import mcp_client_span++async with mcp_client_span(+ method="tools/call",+ target=tool_name,+ session_id=session.id,+ protocol_version=session.protocol_version,+ server_address=session.server_url,+) as span:+ # The helper has already injected traceparent into params._meta via+ # TraceContextTextMapPropagator before sending.+ span.set_attribute("jsonrpc.request.id", request_id)+ response = await mcp_client.send(...)+```++Span attributes:++| Attribute | Status |+|---|---|+| `mcp.method.name` | **R** |+| `gen_ai.tool.name` | CR (when method is `tools/call`) |+| `mcp.protocol.version` | Rec |+| `mcp.session.id` | Rec |+| `jsonrpc.request.id` | CR |+| `gen_ai.operation.name` | Rec (`"execute_tool"`) |+| `server.address` | Rec |+| `server.port` | CR |+| `error.type` | CR (on error) |++The helper is a no-op when no `Tracer` is attached. Discovery is via a contextvar that `Tracer.attach` sets to the current SDK `TracerProvider`.++**W3C propagation.** The helper injects `traceparent` (and `tracestate` if set) into the MCP message's `params._meta` field, per the MCP semconv recommendation, so an instrumented MCP server can continue the trace.++## 15. Exporters++### 15.1 `JsonlSpanExporter`++```python+from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult+from opentelemetry.sdk.trace import ReadableSpan++class JsonlSpanExporter(SpanExporter):+ def __init__(self, directory: str = "./cubepi-traces"):+ self._dir = Path(directory)++ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:+ # Group by run_id (read from cubepi.run_id attribute on each span).+ # Append each span's OTLP/JSON encoding to {dir}/{date}/{run_id}.jsonl.+ for span in spans:+ run_id = span.attributes.get("cubepi.run_id", "no-run")+ path = self._dir / date.today().isoformat() / f"{run_id}.jsonl"+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.open("a") as f:+ f.write(span.to_json(indent=None))+ f.write("\n")+ return SpanExportResult.SUCCESS++ def shutdown(self) -> None: ...+```++`Span.to_json()` is provided by the SDK and produces OTLP/JSON-shaped output. Each line is **one span** (not a `ResourceSpans` envelope) — simpler and the dominant convention for jsonl trace storage. Consumers (cubepi-trace) reconstruct the trace by joining lines with the same `traceId`.++For full OTLP/JSON ResourceSpans-per-line format, consumers can run the file through the OTel Collector's `fileexporter` reader.++### 15.2 `OTLPSpanExporter`++Direct re-export from `opentelemetry-exporter-otlp-proto-http`. cubepi adds no wrapping:++```python+# in cubepi/tracing/exporters/__init__.py+from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter++__all__ = ["JsonlSpanExporter", "OTLPSpanExporter"]+```++This exporter handles protobuf encoding, retries (with exponential backoff), gzip compression, auth headers, and gRPC alternative endpoint configuration — none of which we reimplement.++## 16. Resource Attributes++| Attribute | Status | Note |+|---|---|---|+| `service.name` | Rec | from `Tracer.service_name` |+| `service.namespace` | Opt | from `Tracer.service_namespace` |+| `service.version` | Opt | from `Tracer.service_version` |+| `service.instance.id` | Opt | uuid generated at Tracer init if not supplied |+| `deployment.environment.name` | Opt | from `Tracer.deployment_environment` |+| `gen_ai.agent.name` | Opt | process-level |+| `gen_ai.agent.id` | Opt | process-level |+| `gen_ai.agent.description` | Opt | process-level |+| `gen_ai.agent.version` | Opt | process-level |+| `telemetry.sdk.name` | auto | `"opentelemetry"` (set by SDK) |+| `telemetry.sdk.language` | auto | `"python"` (set by SDK) |+| `telemetry.sdk.version` | auto | set by SDK |++cubepi could add `telemetry.distro.name = "cubepi.tracing"` and `telemetry.distro.version = cubepi.__version__` to be discoverable as a custom distro — TBD.++## 17. Storage / Query Boundary++cubepi writes; cubepi-trace (separate repo) reads. Wire format:++- jsonl files (one OTLP-JSON span per line) for local.+- OTLP protobuf over HTTP for production.++Schema reference: this document + the pinned `SCHEMA_URL`.++cubepi-trace **must not** import from `cubepi.tracing`. It parses OTLP/JSON with its own pydantic models. When a breaking change is needed: bump cubepi major version, update cubepi-trace in lockstep.++## 18. Repository Plan++| Item | Where |+|---|---|+| `cubepi.tracing.*` | this repo, `cubepi/tracing/` |+| Schema constants | this repo, `cubepi/tracing/schema.py` + this doc |+| Query backend (FastAPI, reads jsonl/OTLP) | new repo `cubepi-trace` |+| Query frontend (React) | same `cubepi-trace` repo |++## 19. Implementation Phases++0. **Phase 0 (prerequisite cubepi changes):** Both extensions in §3.4 ship before any of `cubepi/tracing/` is written.+ - **3.4.1 Provider listener registry** in `cubepi/providers/`: convert `Provider` from Protocol to base class with listener registry; add `subscribe_request` / `subscribe_chunk` / `subscribe_response`; thread listener invocations through `anthropic.py`, `openai.py`, `openai_responses.py`, `faux.py`. Tests verifying listeners fire in the right order and exceptions don't leak.+ - **3.4.2 `ToolExecutionEndEvent` extension** in `cubepi/agent/`: add `terminate`, `blocked_by_hook`, `block_reason` fields; populate from `cubepi/agent/tools.py`. Backward compatible (additive, conservative defaults).+1. **Phase 1 (MVP):** `Tracer`, `Recorder`, `JsonlSpanExporter`. Span lifecycle for `invoke_agent` / `cubepi.turn` / `chat` / `execute_tool`. `gen_ai.*` attribute set complete; `record_content=False` only. Provider listener subscriptions wired.+2. **Phase 2:** `record_content=True` path. `gen_ai.input.messages` / `output.messages` / `system_instructions` / `tool.definitions`. Redaction hook.+3. **Phase 3:** `OTLPSpanExporter` wiring + docs. Provider-specific Anthropic / OpenAI attributes.+4. **Phase 4:** `Meter` + metrics histograms. `cubepi.tracing.mcp` helper. MCP CLIENT spans + W3C propagation.+5. **Phase 5 (deferred):** `SqliteSpanExporter`, OpenSearch exporter, sampling, span links for cross-run causality.++## 20. Open Questions++- **Redaction hook signature.** `redact: Callable[[Span], None]` invoked just before export, mutating in place? Or per-attribute callback at write time? Phase 2 will decide.+- **Span linking for fire-and-forget inner agents.** Currently we use parent-child. If a tool spawns a background inner agent without `await`, parent-child is wrong — that's `SpanLink` territory. Add when use case appears.+- **Async tool spans in parallel mode.** The recorder keys its span stack by `tool_call_id` rather than relying on `contextvars`. Needs explicit test coverage.+- **`MetricsExporter` lifecycle.** Phase 4 will decide whether `Meter` owns its own background flush loop separate from `Tracer`'s per-run flush. Likely yes.+- **Schema URL bump cadence.** Pin and audit on bump once GenAI semconv graduates from Experimental.+- **Should `record_exception` be used for `gen_ai.client.operation.exception` too?** SDK's `record_exception` always emits the event name `"exception"`. To emit `"gen_ai.client.operation.exception"`, we call `span.add_event(...)` manually. We do not extend `record_exception` — both paths are explicit and the recorder picks based on whether the error originated from the provider client.