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
feat: rename CubePi to CubeLoop (0.14)
xf gong105af5df9458
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 766cc42..56943b5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -45,8 +45,8 @@ jobs:--health-retries 20env:- CUBEPI_TEST_PG_DSN: postgresql://postgres:postgres@localhost:5432/postgres- CUBEPI_TEST_MYSQL_DSN: mysql://root:root@localhost:3306/mysql+ CUBELOOP_TEST_PG_DSN: postgresql://postgres:postgres@localhost:5432/postgres+ CUBELOOP_TEST_MYSQL_DSN: mysql://root:root@localhost:3306/mysqlsteps:- uses: actions/checkout@v7@@ -62,7 +62,7 @@ jobs:run: uv sync --all-extras --dev- name: Run tests- run: uv run pytest tests/ -v --cov=cubepi --cov-report=term-missing --cov-report=xml+ run: uv run pytest tests/ -v --cov=cubeloop --cov-report=term-missing --cov-report=xml- name: Upload coverage to Codecovif: matrix.python-version == '3.13'@@ -73,7 +73,7 @@ jobs:fail_ci_if_error: false- name: Check import- run: uv run python -c "import cubepi; print(cubepi.__all__)"+ run: uv run python -c "import cubeloop; print(cubeloop.__all__)"lint:runs-on: ubuntu-latest@@ -88,10 +88,10 @@ jobs:run: uv sync --all-extras --dev- name: Ruff check- run: uv run ruff check cubepi/ tests/+ run: uv run ruff check cubeloop/ tests/- name: Ruff format check- run: uv run ruff format --check cubepi/ tests/+ run: uv run ruff format --check cubeloop/ tests/- name: Mypy- run: uv run mypy cubepi+ run: uv run mypy cubeloopdiff --git a/.github/workflows/docs.yml b/.github/workflows/docs.ymlindex 1c0a73d..46e1256 100644--- a/.github/workflows/docs.yml+++ b/.github/workflows/docs.yml@@ -5,14 +5,14 @@ on:branches: [main]paths:- 'website/**'- - 'cubepi/**'+ - 'cubeloop/**'- 'pyproject.toml'- 'README.md'- '.github/workflows/docs.yml'pull_request:paths:- 'website/**'- - 'cubepi/**'+ - 'cubeloop/**'- 'pyproject.toml'- 'README.md'- '.github/workflows/docs.yml'@@ -46,7 +46,7 @@ jobs:run: pnpm install --frozen-lockfile- name: Guard against hand-edited API mdxrun: |- if find website/docs/api -type f -name 'cubepi-*.mdx' 2>/dev/null | grep .; then+ if find website/docs/api -type f -name 'cubeloop-*.mdx' 2>/dev/null | grep .; thenecho "::error::Generated API MDX files were committed. Delete them." && exit 1fi- name: Build (runs griffe via prebuild)diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.ymlindex c2b7cb1..5276210 100644--- a/.github/workflows/publish.yml+++ b/.github/workflows/publish.yml@@ -17,8 +17,10 @@ jobs:with:version: "latest"- - name: Build package- run: uv build+ - name: Build packages+ run: |+ uv build+ uv build --package cubepi- uses: actions/upload-artifact@v7with:@@ -41,6 +43,7 @@ jobs:uses: pypa/gh-action-pypi-publish@release/v1with:repository-url: https://test.pypi.org/legacy/+ skip-existing: truepublish-pypi:needs: publish-testpypi@@ -56,3 +59,5 @@ jobs:- name: Publish to PyPIuses: pypa/gh-action-pypi-publish@release/v1+ with:+ skip-existing: truediff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 6d4410b..a133d48 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -3,17 +3,17 @@ repos:hooks:- id: ruff-checkname: ruff check- entry: uv run ruff check cubepi/ tests/+ entry: uv run ruff check cubeloop/ tests/language: systempass_filenames: false- id: ruff-format-checkname: ruff format --check- entry: uv run ruff format --check cubepi/ tests/+ entry: uv run ruff format --check cubeloop/ tests/language: systempass_filenames: false- id: mypy- name: mypy cubepi- entry: uv run mypy cubepi+ name: mypy cubeloop+ entry: uv run mypy cubelooplanguage: systempass_filenames: false- id: pytestdiff --git a/AGENTS.md b/AGENTS.mdindex 12ea882..8d85355 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,4 +1,4 @@-# cubepi+# cubeloopPythonic async-native agent framework (an alternative to langgraph). Async-first,strongly typed, deliberately few dependencies.@@ -9,9 +9,9 @@ strongly typed, deliberately few dependencies.uv sync --all-extras --dev # install everythinguv 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-uv run mypy cubepi+uv run ruff check cubeloop/ tests/+uv run ruff format --check cubeloop/ tests/ # CI checks formatting, doesn't fix+uv run mypy cubeloop```CI runs pytest + ruff + mypy. Tests run on Python 3.11–3.14 (3.14 is@@ -19,11 +19,11 @@ CI runs pytest + ruff + mypy. Tests run on Python 3.11–3.14 (3.14 is## Architecture-`cubepi/` modules: `providers/` (LLM abstraction — `Provider` protocol returning+`cubeloop/` 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+`mcp/`, `tracing/` (OTel, optional), `cli/` (`cubeloop trace`). See the README"Architecture" section for the full annotated tree.## Conventions & gotchas@@ -31,14 +31,14 @@ execution engine), `middleware/`, `checkpointer/` (memory / sqlite / postgres),- **Lean deps**: core deps are anthropic, openai, pydantic only.Everything else (sqlite, postgres, mcp, tracing, trace-cli) is an optionalextra in `pyproject.toml`. Don't add a hard dependency without strong reason.-- **`cubepi.tracing` is lazily importable** (PEP 562 `__getattr__`): schema+- **`cubeloop.tracing` is lazily importable** (PEP 562 `__getattr__`): schemaconstants 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+ `cubeloop[trace-cli]`-only install. Don't add eager OTel imports to its`__init__.py`.- **Tests use `FauxProvider`** for deterministic, no-API-call runs with realisticstreaming. 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.+- **`cubeloop/cli/**` is excluded from codecov** (`codecov.yml` ignore).+- Packaged data: `cubeloop/providers/catalog/data/*.yaml` ships in the wheel.## Development workflow@@ -55,7 +55,7 @@ directly on `main`. Subagents that write code must also use `isolation: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+the result. Call out notable divergences ("library does X, cubeloop does Y becauseZ") so they can be reviewed. Specs go in `dev/specs/` (dated`YYYY-MM-DD-<topic>.md`), plans in `dev/plans/`.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ace6b39..f5ef1d8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,12 +1,22 @@# Changelog-All notable changes to CubePi are documented here.+All notable changes to CubeLoop are documented here.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Breaking++- **Renamed CubePi / `cubepi` to CubeLoop / `cubeloop`.** The import path,+ PyPI project, CLI, docs site (`https://cubeloop.dev`), OTel vendor+ namespace (`cubeloop.*`), and Postgres/MySQL table names (`cubeloop_*`)+ all move. `pip install cubepi` 0.14+ is a transitional wrapper that+ depends on `cubeloop` and warns. Postgres/MySQL hosts must run+ `upgrade_v5_to_v6_op()` before opening 0.14. SQLite table names are+ unchanged. See the [migration guide](https://cubeloop.dev/docs/migration/from-cubepi).+## [0.13.6] - 2026-09-04### Fixed@@ -103,7 +113,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0normalized output messages where derivable", but only`cubepi.llm.raw_response` was ever set on this span;`gen_ai.output.messages` was written only on `invoke_agent` and- `cubepi.turn`. The recorder now reconstructs the semconv+ `cubeloop.turn`. The recorder now reconstructs the semconvoutput-message parts (text / reasoning / tool_call) directly from theassembled response body via a new `_derive_output_message_from_body()`helper, mirroring the existing three-way provider-shape dispatch@@ -266,7 +276,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`metadata["synthetic"] = True` so downstream UIs can tell internalscaffolding apart from real human input. Real `Agent.prompt()` /`Agent.steer()` messages remain unmarked. Closes #171. Exported from- `cubepi` and `cubepi.providers`. Use this factory (not bare+ `cubepi` and `cubeloop.providers`. Use this factory (not bare`UserMessage`) when returning messages from `TurnAction.inject_messages`or `on_run_end`.@@ -403,7 +413,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`ProviderUnavailable`, or `ContextLengthExceeded` (configurable via`trigger_errors`), or on a first-event stream error, the next model in thechain is tried transparently. Optional `on_failover` callback for- billing/metrics hooks. Exported from `cubepi` and `cubepi.providers`.+ billing/metrics hooks. Exported from `cubepi` and `cubeloop.providers`.- **`DEFAULT_TRIGGER_ERRORS`** — `frozenset({RateLimited, ProviderUnavailable,ContextLengthExceeded})`. The default set of error types that trigger failover@@ -430,7 +440,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **`Middleware.extra_llm_calls()` returns `Iterable[BoundModel]`** insteadof `Iterable[tuple[Provider, Model]]`. Third-party middleware overridingthis hook must update the return shape (see Migration). The recorder- consumer in `cubepi.tracing` was adapted in lock-step; built-in+ consumer in `cubeloop.tracing` was adapted in lock-step; built-in`CompactionMiddleware` already updated.- **`cubepi.middleware.compaction.summarizer.summarize()` takes`model: BoundModel`** instead of separate `provider: Provider, model: Model`@@ -616,7 +626,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0so its `chat` span lands as a child:```invoke_agent- └── cubepi.turn+ └── cubeloop.turn├── cubepi.compaction.summarize│ └── chat <summary-model>└── chat <main-model>@@ -706,7 +716,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0same `(provider, model)` pair as the agent's main.- The compaction summarizer's wrapper span now installs `turn_span` as theOTel current span, so `cubepi.compaction.summarize` lands as a child of- `cubepi.turn` instead of becoming an orphan root.+ `cubeloop.turn` instead of becoming an orphan root.### Removed@@ -735,7 +745,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **`MySQLCheckpointer`** — full-featured MySQL/MariaDB checkpointer withAlembic schema management, matching the Postgres implementation.- **Stream recording + `trace convert`** — `record_stream()` captures a raw- provider `MessageStream` to JSONL; `cubepi trace convert` replays the+ provider `MessageStream` to JSONL; `cubeloop trace convert` replays therecording as a structured trace. Useful for offline debugging and testingwithout live API calls.- **Trace CLI — run-metadata filtering** (`--meta` / `--show-meta`): filter@@ -767,7 +777,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0mapping (int budget / effort / enum), and the `max_tokens` field name. It nowdrives the OpenAI, OpenAI Responses, Anthropic, and DeepSeek providers, and isexported from the top-level package.-- **`cubepi trace` CLI** (install with the `trace-cli` extra): discover, list,+- **`cubeloop trace` CLI** (install with the `trace-cli` extra): discover, list,view, follow, and aggregate stats over local agent-run traces, with richrendering and run-id prefix matching.- **Tracing**: an OTLP exporter and a best-effort `trace()` scope helper. The@@ -799,23 +809,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- **[0.2.0]** - 2026-05-10 — see the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.2.0).- **[0.1.0]** - 2026-05-09 — initial release. See the [release notes](https://github.com/cubeplexai/cubepi/releases/tag/v0.1.0).-[Unreleased]: https://github.com/cubeplexai/cubepi/compare/v0.13.6...HEAD-[0.13.6]: https://github.com/cubeplexai/cubepi/compare/v0.13.5...v0.13.6-[0.13.5]: https://github.com/cubeplexai/cubepi/compare/v0.13.4...v0.13.5-[0.13.4]: https://github.com/cubeplexai/cubepi/compare/v0.13.3...v0.13.4-[0.13.3]: https://github.com/cubeplexai/cubepi/compare/v0.13.2...v0.13.3-[0.13.2]: https://github.com/cubeplexai/cubepi/compare/v0.13.1...v0.13.2-[0.13.1]: https://github.com/cubeplexai/cubepi/compare/v0.13.0...v0.13.1-[0.13.0]: https://github.com/cubeplexai/cubepi/compare/v0.12.0...v0.13.0-[0.12.0]: https://github.com/cubeplexai/cubepi/compare/v0.11.0...v0.12.0-[0.11.0]: https://github.com/cubeplexai/cubepi/compare/v0.10.0...v0.11.0-[0.10.0]: https://github.com/cubeplexai/cubepi/compare/v0.9.0...v0.10.0-[0.9.0]: https://github.com/cubeplexai/cubepi/compare/v0.8.0...v0.9.0-[0.8.0]: https://github.com/cubeplexai/cubepi/compare/v0.7.0...v0.8.0-[0.7.0]: https://github.com/cubeplexai/cubepi/compare/v0.6.0...v0.7.0-[0.6.0]: https://github.com/cubeplexai/cubepi/compare/v0.5.0...v0.6.0-[0.5.0]: https://github.com/cubeplexai/cubepi/compare/v0.4.0...v0.5.0-[0.4.0]: https://github.com/cubeplexai/cubepi/compare/v0.3.0...v0.4.0-[0.3.0]: https://github.com/cubeplexai/cubepi/compare/v0.2.0...v0.3.0-[0.2.0]: https://github.com/cubeplexai/cubepi/compare/v0.1.0...v0.2.0+[Unreleased]: https://github.com/cubeplexai/cubeloop/compare/v0.13.6...HEAD+[0.13.6]: https://github.com/cubeplexai/cubeloop/compare/v0.13.5...v0.13.6+[0.13.5]: https://github.com/cubeplexai/cubeloop/compare/v0.13.4...v0.13.5+[0.13.4]: https://github.com/cubeplexai/cubeloop/compare/v0.13.3...v0.13.4+[0.13.3]: https://github.com/cubeplexai/cubeloop/compare/v0.13.2...v0.13.3+[0.13.2]: https://github.com/cubeplexai/cubeloop/compare/v0.13.1...v0.13.2+[0.13.1]: https://github.com/cubeplexai/cubeloop/compare/v0.13.0...v0.13.1+[0.13.0]: https://github.com/cubeplexai/cubeloop/compare/v0.12.0...v0.13.0+[0.12.0]: https://github.com/cubeplexai/cubeloop/compare/v0.11.0...v0.12.0+[0.11.0]: https://github.com/cubeplexai/cubeloop/compare/v0.10.0...v0.11.0+[0.10.0]: https://github.com/cubeplexai/cubeloop/compare/v0.9.0...v0.10.0+[0.9.0]: https://github.com/cubeplexai/cubeloop/compare/v0.8.0...v0.9.0+[0.8.0]: https://github.com/cubeplexai/cubeloop/compare/v0.7.0...v0.8.0+[0.7.0]: https://github.com/cubeplexai/cubeloop/compare/v0.6.0...v0.7.0+[0.6.0]: https://github.com/cubeplexai/cubeloop/compare/v0.5.0...v0.6.0+[0.5.0]: https://github.com/cubeplexai/cubeloop/compare/v0.4.0...v0.5.0+[0.4.0]: https://github.com/cubeplexai/cubeloop/compare/v0.3.0...v0.4.0+[0.3.0]: https://github.com/cubeplexai/cubeloop/compare/v0.2.0...v0.3.0+[0.2.0]: https://github.com/cubeplexai/cubeloop/compare/v0.1.0...v0.2.0[0.1.0]: https://github.com/cubeplexai/cubepi/releases/tag/v0.1.0diff --git a/README.md b/README.mdindex 3d51e6e..d5a91f7 100644--- a/README.md+++ b/README.md@@ -1,26 +1,26 @@<p align="center">- <img src="https://raw.githubusercontent.com/cubeplexai/cubepi/main/website/static/img/brand/cubepi-social-preview.png" alt="CubePi" width="800">+ <img src="https://raw.githubusercontent.com/cubeplexai/cubeloop/main/website/static/img/brand/cubeloop-social-preview.png" alt="CubeLoop" width="800"></p>-[](https://github.com/cubeplexai/cubepi/actions/workflows/ci.yml)-[](https://codecov.io/gh/cubeplexai/cubepi)-[](https://pypi.org/project/cubepi/)-[](https://pypi.org/project/cubepi/)+[](https://github.com/cubeplexai/cubeloop/actions/workflows/ci.yml)+[](https://codecov.io/gh/cubeplexai/cubeloop)+[](https://pypi.org/project/cubeloop/)+[](https://pypi.org/project/cubeloop/)[](https://opensource.org/licenses/MIT)-[](https://cubepi.ai)-[](https://deepwiki.com/cubeplexai/cubepi)-[](https://skills.sh/cubeplexai/cubepi)+[](https://cubeloop.dev)+[](https://deepwiki.com/cubeplexai/cubeloop)+[](https://skills.sh/cubeplexai/cubeloop)-CubePi is a Pythonic, async-native agent framework designed for high performance, readability, and production-grade persistence. It provides a leaner alternative to graph-based agent runtimes by modeling agent logic as a linear while loop that developers can easily trace and debug.+CubeLoop is a Pythonic, async-native agent framework designed for high performance, readability, and production-grade persistence. It provides a leaner alternative to graph-based agent runtimes by modeling agent logic as a linear while loop that developers can easily trace and debug.-CubePi powers [CubePlex](https://github.com/cubeplexai/cubeplex), a cloud-native+CubeLoop powers [CubePlex](https://github.com/cubeplexai/cubeplex), a cloud-nativeplatform for managed agents in team workspaces — skills, shared memory, MCPtools, persistent sandboxes, governed access, and self-hosted deploy on DockerCompose or Kubernetes.-## Why CubePi+## Why CubeLoop-| | langgraph | CubePi |+| | langgraph | CubeLoop ||---|---|---|| **Abstraction** | Graph nodes + edges + channels — you model your agent as a state machine | Plain async functions — `run_agent_loop` is a while loop you can read in 5 minutes || **Streaming** | Callback-based, multiple handler types | `async for event in stream` — one pattern everywhere |@@ -34,23 +34,23 @@ Compose or Kubernetes.## Install```bash-pip install cubepi+pip install cubeloop# Optional extras-pip install cubepi[sqlite] # SQLite checkpointer-pip install cubepi[postgres] # Postgres checkpointer-pip install cubepi[mysql] # MySQL checkpointer-pip install cubepi[mcp] # MCP tool loaders-pip install cubepi[tracing] # OpenTelemetry tracing + metrics-pip install cubepi[tracing-otlp] # Adds the OTLP/HTTP span exporter-pip install cubepi[trace-cli] # `cubepi trace` terminal viewer+pip install cubeloop[sqlite] # SQLite checkpointer+pip install cubeloop[postgres] # Postgres checkpointer+pip install cubeloop[mysql] # MySQL checkpointer+pip install cubeloop[mcp] # MCP tool loaders+pip install cubeloop[tracing] # OpenTelemetry tracing + metrics+pip install cubeloop[tracing-otlp] # Adds the OTLP/HTTP span exporter+pip install cubeloop[trace-cli] # `cubeloop trace` terminal viewer```Or with [uv](https://github.com/astral-sh/uv):```bash-uv add cubepi-uv add cubepi[sqlite,postgres,mysql,mcp,tracing]+uv add cubeloop+uv add cubeloop[sqlite,postgres,mysql,mcp,tracing]```For local Git hooks that mirror CI, install `pre-commit` and enable the repo@@ -64,8 +64,8 @@ uvx pre-commit install```pythonimport asyncio-from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(provider_id="anthropic", api_key="sk-...")@@ -89,8 +89,8 @@ asyncio.run(agent.prompt("What's the weather in Tokyo?"))```For a guided tour of the architecture, browse the-[DeepWiki for this repo](https://deepwiki.com/cubeplexai/cubepi) or the-[Core Concepts guide](https://cubepi.ai/docs/getting-started/core-concepts).+[DeepWiki for this repo](https://deepwiki.com/cubeplexai/cubeloop) or the+[Core Concepts guide](https://cubeloop.dev/docs/getting-started/core-concepts).## Core Concepts@@ -99,9 +99,9 @@ For a guided tour of the architecture, browse theAbstract LLM interaction behind a `Provider` protocol. All providers return `MessageStream` — an async iterator of `StreamEvent`s.```python-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.openai import OpenAIProvider-from cubepi.providers import FauxProvider+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.openai import OpenAIProvider+from cubeloop.providers import FauxProvider# Real providersanthropic = AnthropicProvider(provider_id="anthropic", api_key="...")@@ -116,7 +116,7 @@ Use `FallbackBoundModel` to chain providers — on a rate limit, outage, orcontext-length error the next model in the chain is tried automatically:```python-from cubepi import FallbackBoundModel+from cubeloop import FallbackBoundModelmodel = FallbackBoundModel(chain=(@@ -134,7 +134,7 @@ typed parameters, the docstring becomes the description, and the frameworkhandles argument parsing, parallel execution, and error wrapping.```python-from cubepi import tool+from cubeloop import tool@toolasync def search(query: str) -> str:@@ -147,9 +147,9 @@ longhand `AgentTool(...)` is equivalent and fully supported:```pythonfrom pydantic import BaseModel-from cubepi import AgentTool-from cubepi.agent.types import AgentToolResult-from cubepi.providers.base import TextContent+from cubeloop import AgentTool+from cubeloop.agent.types import AgentToolResult+from cubeloop.providers.base import TextContentclass SearchParams(BaseModel):query: str@@ -171,8 +171,8 @@ search = AgentTool(Composable hooks that modify behavior without touching the core loop:```python-from cubepi import Middleware, compose_middleware-from cubepi.agent.types import BeforeToolCallResult+from cubeloop import Middleware, compose_middleware+from cubeloop.agent.types import BeforeToolCallResultclass LoggingMiddleware(Middleware):async def transform_context(self, messages, *, ctx, signal=None):@@ -209,8 +209,8 @@ consume significant context. Deferred tool groups hide schemas by default andlet the model expand them on demand:```python-from cubepi import Agent-from cubepi.deferred import DeferredToolGroup+from cubeloop import Agent+from cubeloop.deferred import DeferredToolGroup# load_github_tools is a zero-arg async callable returning list[AgentTool]# (e.g. wrap load_mcp_tools_stdio(...).tools — see the website guide).@@ -257,7 +257,7 @@ For advanced use (custom catalog header, cross-run replay), construct`DeferredToolsMiddleware` directly:```python-from cubepi.deferred import DeferredToolsMiddleware+from cubeloop.deferred import DeferredToolsMiddleware# Replay expansion state from a previous run (strategy is required and# must match the middleware's strategy)@@ -278,7 +278,7 @@ agent = Agent(Persist conversation state with append-only semantics:```python-from cubepi.checkpointer import (+from cubeloop.checkpointer import (MemoryCheckpointer,SQLiteCheckpointer,PostgresCheckpointer,@@ -303,8 +303,8 @@ async with MySQLCheckpointer("mysql://...") as cp:Postgres and MySQL never issue DDL at runtime — your app owns the schema viaAlembic. See the host-integration runbooks-([Postgres](cubepi/checkpointer/postgres/README.md) ·-[MySQL](cubepi/checkpointer/mysql/README.md)) and the runnable+([Postgres](cubeloop/checkpointer/postgres/README.md) ·+[MySQL](cubeloop/checkpointer/mysql/README.md)) and the runnable[`examples/`](examples/).### FauxProvider for Testing@@ -312,7 +312,7 @@ Alembic. See the host-integration runbooksShip your agent tests without API keys:```python-from cubepi.providers import FauxProvider, faux_text, faux_tool_call, faux_assistant_message+from cubeloop.providers import FauxProvider, faux_text, faux_tool_call, faux_assistant_messageprovider = FauxProvider(provider_id="faux")provider.set_responses([@@ -336,14 +336,14 @@ ingestible by Jaeger, Tempo, Honeycomb, Datadog, AWS X-Ray, or anyOTLP-compatible backend without custom instrumentation:```python-from cubepi.tracing import Tracer, tracing_context-from cubepi.tracing.exporters import JsonlSpanExporter+from cubeloop.tracing import Tracer, tracing_context+from cubeloop.tracing.exporters import JsonlSpanExporterasync with (Tracer(service_name="my-bot",agent_name="assistant",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],) as tracer,tracer.attached(agent),):@@ -357,14 +357,14 @@ Span tree per run:```trace└── invoke_agent 14425.8ms [0x1cd97cdb] ← one per agent.prompt()- ├── cubepi.turn 1283.1ms [0x5cfda93e] ← one per LLM round-trip+ ├── cubeloop.turn 1283.1ms [0x5cfda93e] ← one per LLM round-trip│ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]│ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]│ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested- │ └── cubepi.turn 9598.4ms [0x57c5cfc7]+ │ └── cubeloop.turn 9598.4ms [0x57c5cfc7]│ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]│ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]- └── cubepi.turn 491.9ms ERROR [0xce25f242]+ └── cubeloop.turn 491.9ms ERROR [0xce25f242]└── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]└── error: Error code: 400 - ... `tool_use` ids were found without`tool_result` blocks immediately after: call_01_...@@ -373,25 +373,25 @@ traceNo prompts / model outputs are recorded by default. Opt in with`Tracer(record_content=True)` plus a `redact` callback for PII. Pairwith `Meter(...)` for `gen_ai.client.operation.duration` / TTFC /-token-usage histograms. Full guide: https://cubepi.ai/docs/guides/tracing/overview+token-usage histograms. Full guide: https://cubeloop.dev/docs/guides/tracing/overview#### Inspecting traces from the terminal-With `JsonlSpanExporter` writing to `./cubepi-traces`, inspect runs with the-`cubepi trace` CLI (install the extra: `pip install cubepi[trace-cli]`). All-subcommands take `--dir` (default `./cubepi-traces`):+With `JsonlSpanExporter` writing to `./cubeloop-traces`, inspect runs with the+`cubeloop trace` CLI (install the extra: `pip install cubeloop[trace-cli]`). All+subcommands take `--dir` (default `./cubeloop-traces`):```bash-cubepi trace ls # recent runs, newest first; the `input`+cubeloop trace ls # recent runs, newest first; the `input`# column shows the user message + `status`-cubepi trace view <run_id> # render a run as a tree; errors print inline+cubeloop trace view <run_id> # render a run as a tree; errors print inline# under the failing span (no flag needed).# A unique run-id PREFIX is enough.-cubepi trace view <run> --content # also expand prompts / tool args / results-cubepi trace view <run> -v # expand ALL span attributes (verbose)-cubepi trace follow <run_id> # stream spans live as they complete-cubepi trace stats --by model # token / latency / error aggregates-cubepi trace stats --by tool --since 2026-01-01+cubeloop trace view <run> --content # also expand prompts / tool args / results+cubeloop trace view <run> -v # expand ALL span attributes (verbose)+cubeloop trace follow <run_id> # stream spans live as they complete+cubeloop trace stats --by model # token / latency / error aggregates+cubeloop trace stats --by tool --since 2026-01-01```Typical debugging flow: `ls` (find the run by its `input`), then@@ -405,11 +405,11 @@ is a subset of it. From trace fields, cache hit rate is`cache_read / input_tokens` (≤ 100%) — do **not** add `cache_read` to thedenominator.-Coding agents debugging cubepi/consumer apps can install the-[`cubepi-trace` skill](skills/cubepi-trace/SKILL.md):+Coding agents debugging cubeloop/consumer apps can install the+[`cubeloop-trace` skill](skills/cubeloop-trace/SKILL.md):```bash-npx skills add cubeplexai/cubepi@cubepi-trace -a claude-code+npx skills add cubeplexai/cubeloop@cubeloop-trace -a claude-code```## AI Agents@@ -419,8 +419,8 @@ with this repo:| Skill | Install | Purpose ||-------|---------|---------|-| `cubepi` | `npx skills add cubeplexai/cubepi@cubepi -a claude-code` | Build agents — API reference, tools, middleware, checkpointing, MCP, HITL |-| `cubepi-trace` | `npx skills add cubeplexai/cubepi@cubepi-trace -a claude-code` | Debug runs — inspect OTel spans, token counts, tool results, streaming failures |+| `cubeloop` | `npx skills add cubeplexai/cubeloop@cubeloop -a claude-code` | Build agents — API reference, tools, middleware, checkpointing, MCP, HITL |+| `cubeloop-trace` | `npx skills add cubeplexai/cubeloop@cubeloop-trace -a claude-code` | Debug runs — inspect OTel spans, token counts, tool results, streaming failures |## Requirements@@ -430,7 +430,7 @@ with this repo:## Credits-Architecture inspired by pi-agent-core (TypeScript); CubePi is an independent Python reimplementation with Pydantic v2, asyncio-native primitives, and built-in checkpointing.+Architecture inspired by pi-agent-core (TypeScript); CubeLoop is an independent Python reimplementation with Pydantic v2, asyncio-native primitives, and built-in checkpointing.## Licensediff --git a/codecov.yml b/codecov.ymlindex 7855480..6f2f819 100644--- a/codecov.yml+++ b/codecov.yml@@ -14,5 +14,5 @@ comment:require_changes: falseignore:- - "cubepi/cli/**"- - "cubepi/middleware/todo.py"+ - "cubeloop/cli/**"+ - "cubeloop/middleware/todo.py"diff --git a/compat/cubepi/README.md b/compat/cubepi/README.mdnew file mode 100644index 0000000..ac4d47d--- /dev/null+++ b/compat/cubepi/README.md@@ -0,0 +1,17 @@+# cubepi is now cubeloop++The `cubepi` PyPI package has been renamed to **cubeloop**.++```bash+pip install cubeloop+```++```python+from cubeloop import Agent, tool+```++This distribution is a transitional wrapper: it depends on `cubeloop==0.14.0`,+re-exports the public API, and aliases `cubepi.*` imports onto `cubeloop.*`.+Installing it prints a deprecation warning on first import.++See https://cubeloop.dev/docs/migration/from-cubepidiff --git a/compat/cubepi/cubepi/__init__.py b/compat/cubepi/cubepi/__init__.pynew file mode 100644index 0000000..39a857e--- /dev/null+++ b/compat/cubepi/cubepi/__init__.py@@ -0,0 +1,31 @@+"""Transitional alias for the renamed cubeloop package."""++from __future__ import annotations++import sys+import warnings++from cubepi._redirect import install as _install_redirect++_WARNING = (+ "WARNING: The 'cubepi' package has been renamed to 'cubeloop'.\n"+ "Install `cubeloop` and import from `cubeloop` instead.\n"+ "See https://cubeloop.dev/docs/migration/from-cubepi\n"+)++_install_redirect()++if not getattr(sys, "_cubepi_rename_warned", False):+ sys._cubepi_rename_warned = True # type: ignore[attr-defined]+ warnings.warn(+ "The 'cubepi' package has been renamed to 'cubeloop'. "+ "Install `cubeloop` and import from `cubeloop` instead. "+ "See https://cubeloop.dev/docs/migration/from-cubepi",+ DeprecationWarning,+ stacklevel=2,+ )+ print(_WARNING, file=sys.stderr, end="")++from cubeloop import * # noqa: E402,F403+from cubeloop import __all__ as __all__ # noqa: E402+from cubeloop import __version__ as __version__ # noqa: E402diff --git a/compat/cubepi/cubepi/__main__.py b/compat/cubepi/cubepi/__main__.pynew file mode 100644index 0000000..9d3ba2d--- /dev/null+++ b/compat/cubepi/cubepi/__main__.py@@ -0,0 +1,23 @@+"""`cubepi` console script — warn, then dispatch to cubeloop.cli."""++from __future__ import annotations++import sys+from collections.abc import Sequence++_WARNING = (+ "WARNING: The 'cubepi' package has been renamed to 'cubeloop'.\n"+ "Install `cubeloop` and import from `cubeloop` instead.\n"+ "See https://cubeloop.dev/docs/migration/from-cubepi\n"+)+++def main(argv: Sequence[str] | None = None) -> int:+ print(_WARNING, file=sys.stderr, end="")+ from cubeloop.cli.__main__ import main as _real++ return _real(argv)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/compat/cubepi/cubepi/_redirect.py b/compat/cubepi/cubepi/_redirect.pynew file mode 100644index 0000000..7b70121--- /dev/null+++ b/compat/cubepi/cubepi/_redirect.py@@ -0,0 +1,61 @@+"""On-demand cubepi.* → cubeloop.* import alias."""++from __future__ import annotations++import importlib+import importlib.abc+import importlib.machinery+import importlib.util+import sys+++class _AliasLoader(importlib.abc.Loader):+ def __init__(self, real_name: str) -> None:+ self.real_name = real_name++ def create_module(self, spec: importlib.machinery.ModuleSpec): # noqa: ARG002+ return importlib.import_module(self.real_name)++ def exec_module(self, module: object) -> None: # noqa: ARG002+ return None++ def get_code(self, fullname: str): # noqa: ARG002+ # runpy (`python -m cubepi.cli`) requires get_code; delegate to+ # cubeloop's real loader so aliased packages stay executable.+ spec = importlib.util.find_spec(self.real_name)+ if spec is None or spec.loader is None:+ return None+ getter = getattr(spec.loader, "get_code", None)+ if getter is None:+ return None+ return getter(self.real_name)+++class CubepiRedirectFinder(importlib.abc.MetaPathFinder):+ """Resolve cubepi.foo to the already-named cubeloop.foo module object."""++ def find_spec( # type: ignore[override]+ self,+ fullname: str,+ path: object, # noqa: ARG002+ target: object = None, # noqa: ARG002+ ) -> importlib.machinery.ModuleSpec | None:+ if not fullname.startswith("cubepi."):+ return None+ real_name = "cubeloop" + fullname[len("cubepi") :]+ real_spec = importlib.util.find_spec(real_name)+ if real_spec is None:+ return None+ spec = importlib.machinery.ModuleSpec(+ fullname,+ _AliasLoader(real_name),+ origin=real_spec.origin,+ is_package=real_spec.submodule_search_locations is not None,+ )+ spec.submodule_search_locations = real_spec.submodule_search_locations+ return spec+++def install() -> None:+ if not any(isinstance(f, CubepiRedirectFinder) for f in sys.meta_path):+ sys.meta_path.insert(0, CubepiRedirectFinder())diff --git a/compat/cubepi/pyproject.toml b/compat/cubepi/pyproject.tomlnew file mode 100644index 0000000..605754d--- /dev/null+++ b/compat/cubepi/pyproject.toml@@ -0,0 +1,43 @@+[project]+name = "cubepi"+version = "0.14.0"+description = "DEPRECATED: Cubepi has been renamed to cubeloop. This package is a transitional wrapper."+readme = "README.md"+license = "MIT"+requires-python = ">=3.11"+classifiers = [+ "Development Status :: 7 - Inactive",+ "Programming Language :: Python :: 3.11",+ "Programming Language :: Python :: 3.12",+ "Programming Language :: Python :: 3.13",+ "Programming Language :: Python :: 3.14",+]+dependencies = [+ "cubeloop==0.14.0",+]++[project.optional-dependencies]+sqlite = ["cubeloop[sqlite]==0.14.0"]+postgres = ["cubeloop[postgres]==0.14.0"]+mysql = ["cubeloop[mysql]==0.14.0"]+mcp = ["cubeloop[mcp]==0.14.0"]+tracing = ["cubeloop[tracing]==0.14.0"]+tracing-otlp = ["cubeloop[tracing-otlp]==0.14.0"]+trace-cli = ["cubeloop[trace-cli]==0.14.0"]++[project.scripts]+cubepi = "cubepi.__main__:main"++[project.urls]+Homepage = "https://cubeloop.dev"+Documentation = "https://cubeloop.dev/docs/migration/from-cubepi"++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["cubepi"]++[tool.uv.sources]+cubeloop = { workspace = true }diff --git a/cubepi/__init__.py b/cubeloop/__init__.pysimilarity index 88%rename from cubepi/__init__.pyrename to cubeloop/__init__.pyindex 125ee67..4982ab3 100644--- a/cubepi/__init__.py+++ b/cubeloop/__init__.py@@ -3,12 +3,12 @@from importlib.metadata import PackageNotFoundError, version as _pkg_versiontry:- __version__ = _pkg_version("cubepi")+ __version__ = _pkg_version("cubeloop")except PackageNotFoundError: # pragma: no cover — non-installed checkout__version__ = "0.0.0+unknown"-from cubepi.agent import (+from cubeloop.agent import (Agent,AgentState,AgentTool,@@ -17,8 +17,8 @@ from cubepi.agent import (run_agent_loop_continue,tool,)-from cubepi.middleware import Middleware, compose_middleware-from cubepi.providers import (+from cubeloop.middleware import Middleware, compose_middleware+from cubeloop.providers import (AssistantMessage,BaseProvider,BoundModel,@@ -42,7 +42,7 @@ from cubepi.providers import (is_synthetic_message,synthetic_user_message,)-from cubepi.errors import (+from cubeloop.errors import (ContentFiltered,ContextLengthExceeded,ModelNotFound,@@ -52,7 +52,7 @@ from cubepi.errors import (ProviderUnavailable,RateLimited,)-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,CapabilityWarning,PayloadPreview,@@ -62,7 +62,7 @@ from cubepi.providers.capability import (lint_capability,preview_payload,)-from cubepi.providers.images import (+from cubeloop.providers.images import (AssistantImages,BaseImagesProvider,ImagesAborted,@@ -74,7 +74,7 @@ from cubepi.providers.images import (ImagesProvider,SizeSpec,)-from cubepi.types import JsonObject, JsonValue, StructuredObject, StructuredValue+from cubeloop.types import JsonObject, JsonValue, StructuredObject, StructuredValue__all__ = ["__version__",diff --git a/cubepi/agent/__init__.py b/cubeloop/agent/__init__.pysimilarity index 79%rename from cubepi/agent/__init__.pyrename to cubeloop/agent/__init__.pyindex 34a0bb5..c8368f1 100644--- a/cubepi/agent/__init__.py+++ b/cubeloop/agent/__init__.py@@ -1,8 +1,8 @@-from cubepi.agent.agent import Agent, AgentState-from cubepi.agent.loop import run_agent_loop, run_agent_loop_continue-from cubepi.agent.tool_decorator import tool-from cubepi.agent.tools import execute_tool_calls-from cubepi.agent.types import (+from cubeloop.agent.agent import Agent, AgentState+from cubeloop.agent.loop import run_agent_loop, run_agent_loop_continue+from cubeloop.agent.tool_decorator import tool+from cubeloop.agent.tools import execute_tool_calls+from cubeloop.agent.types import (AfterToolCallContext,AfterToolCallResult,AgentContext,@@ -24,7 +24,7 @@ from cubepi.agent.types import (TurnEndEvent,TurnStartEvent,)-from cubepi.utils import emit_event+from cubeloop.utils import emit_event__all__ = ["Agent",diff --git a/cubepi/agent/_outcome.py b/cubeloop/agent/_outcome.pysimilarity index 100%rename from cubepi/agent/_outcome.pyrename to cubeloop/agent/_outcome.pydiff --git a/cubepi/agent/_tool_cycle.py b/cubeloop/agent/_tool_cycle.pysimilarity index 98%rename from cubepi/agent/_tool_cycle.pyrename to cubeloop/agent/_tool_cycle.pyindex 66c00a1..21f34ec 100644--- a/cubepi/agent/_tool_cycle.py+++ b/cubeloop/agent/_tool_cycle.py@@ -11,7 +11,7 @@ from __future__ import annotationsfrom collections import Counter-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,Message,ToolCall,diff --git a/cubepi/agent/agent.py b/cubeloop/agent/agent.pysimilarity index 96%rename from cubepi/agent/agent.pyrename to cubeloop/agent/agent.pyindex bed0ce5..3e941d7 100644--- a/cubepi/agent/agent.py+++ b/cubeloop/agent/agent.py@@ -7,20 +7,20 @@ from collections.abc import Sequencefrom dataclasses import dataclass, fieldfrom typing import TYPE_CHECKING, Callable, Generic, TypeVar-from cubepi.agent._outcome import RunOutcome-from cubepi.agent._tool_cycle import ToolCycleViolation, check_tool_cycle-from cubepi.agent.loop import (+from cubeloop.agent._outcome import RunOutcome+from cubeloop.agent._tool_cycle import ToolCycleViolation, check_tool_cycle+from cubeloop.agent.loop import (run_agent_loop,run_agent_loop_continue,run_agent_loop_resume,)-from cubepi.checkpointer.base import Checkpointer-from cubepi.checkpointer.exceptions import CompletionMarkerFailedError-from cubepi.hitl import HitlError, HitlRequest-from cubepi.hitl.channel import HitlChannel-from cubepi.hitl.exceptions import HitlDetached-from cubepi.middleware.base import Middleware, compose_middleware-from cubepi.agent.types import (+from cubeloop.checkpointer.base import Checkpointer+from cubeloop.checkpointer.exceptions import CompletionMarkerFailedError+from cubeloop.hitl import HitlError, HitlRequest+from cubeloop.hitl.channel import HitlChannel+from cubeloop.hitl.exceptions import HitlDetached+from cubeloop.middleware.base import Middleware, compose_middleware+from cubeloop.agent.types import (AgentContext,AgentEndEvent,AgentEvent,@@ -31,7 +31,7 @@ from cubepi.agent.types import (MessageStartEvent,TurnEndEvent,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BoundModel,Message,@@ -46,7 +46,7 @@ from cubepi.providers.base import (Usage,UserMessage,)-from cubepi.types import JsonObject, StructuredValue+from cubeloop.types import JsonObject, StructuredValueTMessage = TypeVar("TMessage")@@ -58,8 +58,8 @@ def _consume_control_exception(future: asyncio.Future[StructuredValue]) -> None:if TYPE_CHECKING:- from cubepi.deferred.types import DeferredStrategy, DeferredToolGroup- from cubepi.providers.fallback import FallbackBoundModel+ from cubeloop.deferred.types import DeferredStrategy, DeferredToolGroup+ from cubeloop.providers.fallback import FallbackBoundModeldef _deny_in_fork(tool: AgentTool) -> AgentTool:@@ -221,7 +221,7 @@ class Agent(Generic[TMessage]):if tools:self._state.tools = toolsif deferred_tool_groups:- from cubepi.deferred.middleware import DeferredToolsMiddleware+ from cubeloop.deferred.middleware import DeferredToolsMiddlewaredeferred_mw = DeferredToolsMiddleware(groups=deferred_tool_groups,@@ -233,7 +233,7 @@ class Agent(Generic[TMessage]):)middleware = [*(middleware or []), deferred_mw]middleware = middleware or []- # Retain the list so observers (e.g. cubepi.tracing.Recorder) can+ # Retain the list so observers (e.g. cubeloop.tracing.Recorder) can# walk it after construction — they need to reach attributes like# ``Middleware.providers()`` that aren't captured by the composed# hook callables below.@@ -402,7 +402,7 @@ class Agent(Generic[TMessage]):if pending is None:returnself._pending_suspension_event = None- from cubepi.agent.types import AgentSuspendedEvent+ from cubeloop.agent.types import AgentSuspendedEventawait self._process_event(AgentSuspendedEvent(pending_request=pending))@@ -563,7 +563,7 @@ class Agent(Generic[TMessage]):if self.checkpointer is None:raise RuntimeError("fork requires a checkpointer")if not self._run_aware:- from cubepi.checkpointer.exceptions import CheckpointerError+ from cubeloop.checkpointer.exceptions import CheckpointerErrorraise CheckpointerError("backend does not support fork; missing claim_run / mark_run_complete"@@ -586,7 +586,7 @@ class Agent(Generic[TMessage]):raise RuntimeError("fork_once requires a checkpointer")# Degraded-mode guardif not self._run_aware or not hasattr(self.checkpointer, "snapshot"):- from cubepi.checkpointer.exceptions import CheckpointerError+ from cubeloop.checkpointer.exceptions import CheckpointerErrorraise CheckpointerError("backend does not support fork_once; missing snapshot / "@@ -673,7 +673,7 @@ class Agent(Generic[TMessage]):)def _fork_once_span(self, *, src_thread_id: str, after_run_id: str):- """Emit a `cubepi.agent.fork_once` OTel span around the probe run.+ """Emit a `cubeloop.agent.fork_once` OTel span around the probe run.The opentelemetry dependency is part of the optional `tracing` extra;when it isn't installed we fall back to a no-op nullcontext so the@@ -685,12 +685,12 @@ class Agent(Generic[TMessage]):from contextlib import nullcontextreturn nullcontext()- tracer = trace.get_tracer("cubepi.agent")+ tracer = trace.get_tracer("cubeloop.agent")return tracer.start_as_current_span(- "cubepi.agent.fork_once",+ "cubeloop.agent.fork_once",attributes={- "cubepi.fork.src_thread_id": src_thread_id,- "cubepi.fork.after_run_id": after_run_id,+ "cubeloop.fork.src_thread_id": src_thread_id,+ "cubeloop.fork.after_run_id": after_run_id,},)@@ -765,7 +765,7 @@ class Agent(Generic[TMessage]):)async def _run_prompt(self, messages: list[Message]) -> None:- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run+ from cubeloop.providers.fallback import begin_fallback_run, end_fallback_runtoken = begin_fallback_run()try:@@ -799,7 +799,7 @@ class Agent(Generic[TMessage]):)async def _run_continuation(self) -> None:- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run+ from cubeloop.providers.fallback import begin_fallback_run, end_fallback_runtoken = begin_fallback_run()try:@@ -876,7 +876,7 @@ class Agent(Generic[TMessage]):async def respond(self, *, question_id: str | None = None, answer: StructuredValue) -> None:- from cubepi.hitl.exceptions import (+ from cubeloop.hitl.exceptions import (HitlNoPendingRequest,HitlStaleAnswer,)@@ -965,7 +965,7 @@ class Agent(Generic[TMessage]):tool_results + a terminal stop_reason="aborted" assistant messageand emits AgentAbortedEvent."""- from cubepi.agent.types import AgentAbortedEvent+ from cubeloop.agent.types import AgentAbortedEventif self._channel is None:raise HitlError("agent has no channel bound")@@ -1102,7 +1102,7 @@ class Agent(Generic[TMessage]):await self._process_event(AgentAbortedEvent(reason=reason))async def _run_hitl_resume(self) -> None:- from cubepi.providers.fallback import (+ from cubeloop.providers.fallback import (begin_fallback_run,end_fallback_run,get_active_index,diff --git a/cubepi/agent/loop.py b/cubeloop/agent/loop.pysimilarity index 98%rename from cubepi/agent/loop.pyrename to cubeloop/agent/loop.pyindex 4263f6a..1a57c05 100644--- a/cubepi/agent/loop.py+++ b/cubeloop/agent/loop.py@@ -3,8 +3,8 @@ from __future__ import annotationsimport asynciofrom typing import TYPE_CHECKING, Callable-from cubepi.agent.tools import execute_tool_calls-from cubepi.agent.types import (+from cubeloop.agent.tools import execute_tool_calls+from cubeloop.agent.types import (AgentContext,AgentEndEvent,AgentStartEvent,@@ -15,10 +15,10 @@ from cubepi.agent.types import (TurnEndEvent,TurnStartEvent,)-from cubepi.checkpointer.base import Checkpointer-from cubepi.hitl.exceptions import HitlAborted, HitlDetached-from cubepi.utils import emit_event-from cubepi.providers.base import (+from cubeloop.checkpointer.base import Checkpointer+from cubeloop.hitl.exceptions import HitlAborted, HitlDetached+from cubeloop.utils import emit_event+from cubeloop.providers.base import (AssistantMessage,BoundModel,Message,@@ -28,7 +28,7 @@ from cubepi.providers.base import ()if TYPE_CHECKING:- from cubepi.providers.fallback import FallbackBoundModel+ from cubeloop.providers.fallback import FallbackBoundModel_MAX_ON_RUN_END_CYCLES = 100@@ -251,7 +251,7 @@ async def _run_agent_loop_resume_body( # pragma: no cover — E2E testednew_messages: list,set_outcome: Callable[[str], None] | None = None,) -> list[Message]:- from cubepi.hitl.exceptions import HitlInconsistentState+ from cubeloop.hitl.exceptions import HitlInconsistentState# Sanity checkif not context.messages:diff --git a/cubepi/agent/tool_decorator.py b/cubeloop/agent/tool_decorator.pysimilarity index 98%rename from cubepi/agent/tool_decorator.pyrename to cubeloop/agent/tool_decorator.pyindex 4f0bf14..1df5820 100644--- a/cubepi/agent/tool_decorator.py+++ b/cubeloop/agent/tool_decorator.py@@ -8,7 +8,7 @@ arguments are injected only if the function asks for them, and the return valueis normalised so a tool can simply ``return "some text"``.```python-from cubepi import tool+from cubeloop import tool@tool@@ -34,8 +34,8 @@ from typing import (from pydantic import BaseModel, create_model-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import Content, TextContent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import Content, TextContent# Arguments the agent loop supplies when it calls a tool (see# cubepi/agent/tools.py). They are injected into the decorated function only ifdiff --git a/cubepi/agent/tools.py b/cubeloop/agent/tools.pysimilarity index 99%rename from cubepi/agent/tools.pyrename to cubeloop/agent/tools.pyindex cf53662..709b22f 100644--- a/cubepi/agent/tools.py+++ b/cubeloop/agent/tools.py@@ -9,9 +9,9 @@ from typing import Callablefrom pydantic import BaseModelfrom pydantic import ValidationError-from cubepi.hitl.exceptions import HitlControlException+from cubeloop.hitl.exceptions import HitlControlException-from cubepi.agent.types import (+from cubeloop.agent.types import (AfterToolCallContext,AgentContext,AgentTool,@@ -23,14 +23,14 @@ from cubepi.agent.types import (ToolExecutionStartEvent,ToolExecutionUpdateEvent,)-from cubepi.utils import emit_event-from cubepi.providers.base import (+from cubeloop.utils import emit_event+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,ToolResultMessage,)-from cubepi.types import JsonObject, StructuredObject, StructuredValue+from cubeloop.types import JsonObject, StructuredObject, StructuredValue@dataclass@@ -276,7 +276,7 @@ async def _execute_prepared(signal: asyncio.Event | None,emit_fn: Callable,) -> tuple[AgentToolResult, bool]:- from cubepi.hitl.channel import _in_custom_tool_var+ from cubeloop.hitl.channel import _in_custom_tool_varis_builtin = prepared.tool.hitl_builtintoken = None if is_builtin else _in_custom_tool_var.set(True)diff --git a/cubepi/agent/types.py b/cubeloop/agent/types.pysimilarity index 96%rename from cubepi/agent/types.pyrename to cubeloop/agent/types.pyindex 5b1922b..efe2c54 100644--- a/cubepi/agent/types.py+++ b/cubeloop/agent/types.py@@ -6,9 +6,9 @@ from typing import Awaitable, Callable, Generic, Literal, TypeVarfrom pydantic import BaseModel-from cubepi.hitl.binding import HitlBinding-from cubepi.hitl.types import HitlRequest-from cubepi.providers.base import (+from cubeloop.hitl.binding import HitlBinding+from cubeloop.hitl.types import HitlRequest+from cubeloop.providers.base import (AssistantMessage,Content,Message,@@ -17,7 +17,7 @@ from cubepi.providers.base import (ToolDefinition,ToolResultMessage,)-from cubepi.types import JsonObject, StructuredObject, StructuredValue+from cubeloop.types import JsonObject, StructuredObject, StructuredValueTParams = TypeVar("TParams", bound=BaseModel, covariant=True)TMessage = TypeVar("TMessage")diff --git a/cubepi/checkpointer/__init__.py b/cubeloop/checkpointer/__init__.pysimilarity index 57%rename from cubepi/checkpointer/__init__.pyrename to cubeloop/checkpointer/__init__.pyindex c2656a7..76ae7b8 100644--- a/cubepi/checkpointer/__init__.py+++ b/cubeloop/checkpointer/__init__.py@@ -1,18 +1,18 @@-from cubepi.checkpointer.base import Checkpointer, CheckpointData-from cubepi.checkpointer.memory import MemoryCheckpointer+from cubeloop.checkpointer.base import Checkpointer, CheckpointData+from cubeloop.checkpointer.memory import MemoryCheckpointerdef __getattr__(name: str) -> object:if name == "PostgresCheckpointer":- from cubepi.checkpointer.postgres.checkpointer import PostgresCheckpointer+ from cubeloop.checkpointer.postgres.checkpointer import PostgresCheckpointerreturn PostgresCheckpointerif name == "SQLiteCheckpointer":- from cubepi.checkpointer.sqlite import SQLiteCheckpointer+ from cubeloop.checkpointer.sqlite import SQLiteCheckpointerreturn SQLiteCheckpointerif name == "MySQLCheckpointer":- from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer+ from cubeloop.checkpointer.mysql.checkpointer import MySQLCheckpointerreturn MySQLCheckpointerraise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/cubepi/checkpointer/base.py b/cubeloop/checkpointer/base.pysimilarity index 96%rename from cubepi/checkpointer/base.pyrename to cubeloop/checkpointer/base.pyindex 7773cf9..aa2fa38 100644--- a/cubepi/checkpointer/base.py+++ b/cubeloop/checkpointer/base.py@@ -4,9 +4,9 @@ from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom typing import Protocol, runtime_checkable-from cubepi.hitl.types import HitlRequest-from cubepi.providers.base import Message-from cubepi.types import JsonObject, StructuredValue+from cubeloop.hitl.types import HitlRequest+from cubeloop.providers.base import Message+from cubeloop.types import JsonObject, StructuredValue@dataclassdiff --git a/cubepi/checkpointer/exceptions.py b/cubeloop/checkpointer/exceptions.pysimilarity index 96%rename from cubepi/checkpointer/exceptions.pyrename to cubeloop/checkpointer/exceptions.pyindex f783579..68e80f8 100644--- a/cubepi/checkpointer/exceptions.py+++ b/cubeloop/checkpointer/exceptions.py@@ -10,11 +10,11 @@ completion-marker failure."""-class CubepiSchemaError(Exception):+class CubeloopSchemaError(Exception):"""Base class for cubepi SQL checkpointer schema errors."""-class CubepiSchemaUninitialized(CubepiSchemaError):+class CubeloopSchemaUninitialized(CubeloopSchemaError):"""The cubepi_schema_version table is empty or missing.Typically means the host application's alembic upgrade hasn't been@@ -22,7 +22,7 @@ class CubepiSchemaUninitialized(CubepiSchemaError):"""-class CubepiSchemaMismatch(CubepiSchemaError):+class CubeloopSchemaMismatch(CubeloopSchemaError):"""The DB schema version doesn't match cubepi's expected version.Typically means the cubepi library was upgraded but the hostdiff --git a/cubepi/checkpointer/memory.py b/cubeloop/checkpointer/memory.pysimilarity index 97%rename from cubepi/checkpointer/memory.pyrename to cubeloop/checkpointer/memory.pyindex d6ae3f5..fba6fc5 100644--- a/cubepi/checkpointer/memory.py+++ b/cubeloop/checkpointer/memory.py@@ -6,8 +6,8 @@ import timefrom collections.abc import Iterablefrom dataclasses import dataclass-from cubepi.checkpointer.base import CheckpointData-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.base import CheckpointData+from cubeloop.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,@@ -15,9 +15,9 @@ from cubepi.checkpointer.exceptions import (ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.hitl.types import HitlRequest-from cubepi.providers.base import Message-from cubepi.types import JsonObject, StructuredValue+from cubeloop.hitl.types import HitlRequest+from cubeloop.providers.base import Message+from cubeloop.types import JsonObject, StructuredValue@dataclassdiff --git a/cubepi/checkpointer/mysql/README.md b/cubeloop/checkpointer/mysql/README.mdsimilarity index 60%rename from cubepi/checkpointer/mysql/README.mdrename to cubeloop/checkpointer/mysql/README.mdindex 21c3004..d5fcf96 100644--- a/cubepi/checkpointer/mysql/README.md+++ b/cubeloop/checkpointer/mysql/README.md@@ -3,10 +3,10 @@`MySQLCheckpointer` (aiomysql) is the MySQL counterpart of the Postgrescheckpointer — same model, MySQL-compatible types, and `KEY`partitioning on `thread_id`. **It never issues DDL at runtime** — your-application owns the schema lifecycle through Alembic, and cubepi only+application owns the schema lifecycle through Alembic, and cubeloop onlyreads and writes rows. Entering the async context manager(`async with MySQLCheckpointer(...)`) verifies the schema and raises-`CubepiSchemaUninitialized` / `CubepiSchemaMismatch` if the expected+`CubeloopSchemaUninitialized` / `CubeloopSchemaMismatch` if the expectedmigrations haven't been applied.Requires MySQL 8.0.13+ (JSON expression defaults) on InnoDB.@@ -14,13 +14,13 @@ Requires MySQL 8.0.13+ (JSON expression defaults) on InnoDB.Install with the extra:```bash-pip install 'cubepi[mysql]'+pip install 'cubeloop[mysql]'```## Using the checkpointer```python-from cubepi.checkpointer.mysql import MySQLCheckpointer+from cubeloop.checkpointer.mysql import MySQLCheckpointer# Entering the context manager connects the pool and verifies the schema.async with MySQLCheckpointer("mysql://user:pass@host:3306/db") as cp:@@ -37,19 +37,19 @@ parsed into `aiomysql.create_pool` kwargs. Schema verification happens onThe package re-exports the symbols Alembic wiring needs:```python-from cubepi.checkpointer.mysql import cubepi_metadata, EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.mysql import cubeloop_metadata, EXPECTED_SCHEMA_VERSION```| Symbol | Use ||---|---|-| `cubepi_metadata` | SQLAlchemy `MetaData` — set as Alembic `target_metadata` |-| `EXPECTED_SCHEMA_VERSION` | The version cubepi verifies on connect (currently `3`) |+| `cubeloop_metadata` | SQLAlchemy `MetaData` — set as Alembic `target_metadata` |+| `EXPECTED_SCHEMA_VERSION` | The version cubeloop verifies on connect (currently `6`) |The SQL helpers live in the `alembic_helpers` submodule:```python-from cubepi.checkpointer.mysql.alembic_helpers import (- messages_partition_clause, # the PARTITION BY KEY (...) clause for cubepi_messages+from cubeloop.checkpointer.mysql.alembic_helpers import (+ messages_partition_clause, # the PARTITION BY KEY (...) clause for cubeloop_messagesadd_pending_request_column_op, # v1→v2 column addwrite_schema_version_op, # returns two ';'-separated statements)@@ -57,48 +57,50 @@ from cubepi.checkpointer.mysql.alembic_helpers import (## Tables-`cubepi_metadata` defines three tables:+`cubeloop_metadata` defines the current (v6) tables:| Table | Purpose ||---|---|-| `cubepi_threads` | One row per thread; holds `pending_request JSON NULL` (HITL, v2+) |-| `cubepi_messages` | Append-only message log — `(thread_id, seq, role, metadata, payload, created_at)`, `PARTITION BY KEY (thread_id)` into 64 partitions |-| `cubepi_schema_version` | Single-row version marker verified on connect |+| `cubeloop_threads` | One row per thread; holds `pending_request JSON NULL` (HITL, v2+) |+| `cubeloop_messages` | Append-only message log — `(thread_id, seq, role, metadata, payload, created_at)`, `PARTITION BY KEY (thread_id)` into 64 partitions |+| `cubeloop_runs` | Per-run claim/completion (v4+) |+| `cubeloop_hitl_answers` | Durable HITL answers (v5+) |+| `cubeloop_schema_version` | Single-row version marker verified on connect |MySQL declares all partitions inline in the `CREATE TABLE` (unlike-Postgres, which uses one child table per partition). The `cubepi_messages`-table has **no foreign key** to `cubepi_threads` — MySQL forbids FKs on+Postgres, which uses one child table per partition). The `cubeloop_messages`+table has **no foreign key** to `cubeloop_threads` — MySQL forbids FKs onpartitioned tables.## Wiring Alembic (`env.py`)```python# alembic/env.py-from cubepi.checkpointer.mysql import cubepi_metadata+from cubeloop.checkpointer.mysql import cubeloop_metadata-target_metadata = cubepi_metadata+target_metadata = cubeloop_metadata# or, alongside your own models:-# target_metadata = [your_metadata, cubepi_metadata]+# target_metadata = [your_metadata, cubeloop_metadata]```## Autogenerate, and what to add by hand```bash-alembic revision --autogenerate -m "add cubepi checkpointer"+alembic revision --autogenerate -m "add cubeloop checkpointer"```Autogenerate emits `op.create_table(...)` for all three tables **with the-correct columns** (from `cubepi_metadata`). Two things to add by hand:+correct columns** (from `cubeloop_metadata`). Two things to add by hand:1. **KEY partitioning.** SQLAlchemy autogenerate cannot express MySQL`KEY` partitioning, so append the partition clause to the- `cubepi_messages` table. Keep the autogenerated column list and add+ `cubeloop_messages` table. Keep the autogenerated column list and addthe clause via `op.execute`:```python- from cubepi.checkpointer.mysql.alembic_helpers import messages_partition_clause+ from cubeloop.checkpointer.mysql.alembic_helpers import messages_partition_clause- op.execute("ALTER TABLE cubepi_messages " + messages_partition_clause())+ op.execute("ALTER TABLE cubeloop_messages " + messages_partition_clause())````KEY` (not `HASH`) is required because `thread_id` is a `VARCHAR` —@@ -109,27 +111,27 @@ correct columns** (from `cubepi_metadata`). Two things to add by hand:statement per call, so split before executing:```python- from cubepi.checkpointer.mysql.alembic_helpers import write_schema_version_op+ from cubeloop.checkpointer.mysql.alembic_helpers import write_schema_version_opfor stmt in write_schema_version_op().split(";"):if stmt.strip():op.execute(stmt)```-> Do not hand-trim the `cubepi_messages` columns. The checkpointer writes+> Do not hand-trim the `cubeloop_messages` columns. The checkpointer writes> and reads `(thread_id, seq, role, metadata, payload)`; dropping any of> them causes runtime SQL errors on the first append.## Upgrading schema versions-cubepi bumps `EXPECTED_SCHEMA_VERSION` when the schema changes; the-checkpointer refuses to connect if the row in `cubepi_schema_version`+CubeLoop bumps `EXPECTED_SCHEMA_VERSION` when the schema changes; the+checkpointer refuses to connect if the row in `cubeloop_schema_version`doesn't match. Each bump is one host migration.**v1 → v2** (HITL): adds `pending_request JSON NULL` to `cubepi_threads`.```python-from cubepi.checkpointer.mysql.alembic_helpers import (+from cubeloop.checkpointer.mysql.alembic_helpers import (add_pending_request_column_op,write_schema_version_op,)diff --git a/cubeloop/checkpointer/mysql/__init__.py b/cubeloop/checkpointer/mysql/__init__.pynew file mode 100644index 0000000..7a13c97--- /dev/null+++ b/cubeloop/checkpointer/mysql/__init__.py@@ -0,0 +1,27 @@+"""MySQLCheckpointer package.++Exceptions are available immediately; ``MySQLCheckpointer`` and model symbols+are added below once their modules exist.+"""++from cubeloop.checkpointer.mysql.checkpointer import MySQLCheckpointer+from cubeloop.checkpointer.mysql.exceptions import (+ CubeloopSchemaError,+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,+)+from cubeloop.checkpointer.mysql.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ cubeloop_metadata,+)++__all__ = [+ "MySQLCheckpointer",+ "CubeloopSchemaError",+ "CubeloopSchemaMismatch",+ "CubeloopSchemaUninitialized",+ "EXPECTED_SCHEMA_VERSION",+ "PARTITION_COUNT",+ "cubeloop_metadata",+]diff --git a/cubepi/checkpointer/mysql/alembic_helpers.py b/cubeloop/checkpointer/mysql/alembic_helpers.pysimilarity index 58%rename from cubepi/checkpointer/mysql/alembic_helpers.pyrename to cubeloop/checkpointer/mysql/alembic_helpers.pyindex 4c5efb4..1a218c8 100644--- a/cubepi/checkpointer/mysql/alembic_helpers.py+++ b/cubeloop/checkpointer/mysql/alembic_helpers.py@@ -1,6 +1,6 @@"""SQL helpers for host application alembic migrations (MySQL)."""-from cubepi.checkpointer.mysql.models import (+from cubeloop.checkpointer.mysql.models import (EXPECTED_SCHEMA_VERSION,PARTITION_COUNT,)@@ -80,21 +80,21 @@ def add_messages_run_id_column_op() -> str:def create_runs_table_op() -> str:- """Return SQL creating the partitioned ``cubepi_runs`` parent table.+ """Return SQL creating the partitioned ``cubeloop_runs`` parent table.- Call inside the host's alembic v3→v4 upgrade() via op.execute(). The- returned statement includes the KEY-partition clause inline. NO FK to- ``cubepi_threads`` — MySQL forbids FKs on partitioned tables.+ Current-schema factory (v6 names). Historical v3→v4 inlines the old+ cubepi_runs CREATE and must not call this helper. NO FK to+ ``cubeloop_threads`` — MySQL forbids FKs on partitioned tables."""return (- "CREATE TABLE cubepi_runs ("+ "CREATE TABLE cubeloop_runs ("" thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,"" run_id VARCHAR(255) NOT NULL,"" claimed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,"" completed_at TIMESTAMP NULL,"" completion_seq BIGINT NULL,"" PRIMARY KEY (thread_id, run_id),"- " KEY ix_cubepi_runs_thread_seq (thread_id, completion_seq)"+ " KEY ix_cubeloop_runs_thread_seq (thread_id, completion_seq)"") ENGINE=InnoDB " + runs_partition_clause())@@ -126,7 +126,20 @@ def upgrade_v3_to_v4_op() -> str:if stmt.strip():op.execute(stmt)"""- return f"{add_messages_run_id_column_op()} {create_runs_table_op()};"+ # Inline the pre-rename cubepi_runs CREATE. create_runs_table_op() now+ # emits cubeloop_runs names for fresh installs.+ legacy_runs = (+ "CREATE TABLE cubepi_runs ("+ " thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,"+ " run_id VARCHAR(255) NOT NULL,"+ " claimed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,"+ " completed_at TIMESTAMP NULL,"+ " completion_seq BIGINT NULL,"+ " PRIMARY KEY (thread_id, run_id),"+ " KEY ix_cubepi_runs_thread_seq (thread_id, completion_seq)"+ ") ENGINE=InnoDB " + runs_partition_clause()+ )+ return f"{add_messages_run_id_column_op()} {legacy_runs};"def create_hitl_answers_table_op() -> str:@@ -153,23 +166,84 @@ def upgrade_v4_to_v5_op() -> str:return create_hitl_answers_table_op() + ";"-def write_schema_version_op() -> str:- """Return SQL setting cubepi_schema_version to the current version.+def upgrade_v5_to_v6_op() -> str:+ """Rename cubepi_* tables to cubeloop_* in one atomic RENAME TABLE.- Clears any stale rows from prior cubepi versions then inserts the current- one. Idempotent. Call inside alembic upgrade() after CREATE TABLE- cubepi_schema_version.+ Includes cubepi_schema_version. KEY partitions ride with the table.- Returns two ';'-separated statements (DELETE then INSERT). MySQL/pymysql- executes a single statement per call, so split before executing::+ Returns ';'-joined standalone statements (SET / PREPARE / EXECUTE).+ Hosts must split the same way as ``write_schema_version_op``::++ for stmt in upgrade_v5_to_v6_op().split(";"):+ if stmt.strip():+ op.execute(stmt)++ Complete (no-op) iff both cubeloop_threads and cubeloop_schema_version+ already exist. If data tables moved but the version table did not,+ only the leftover version table is renamed. Requires a complete v5;+ missing cubepi_schema_version fails the whole rename.+ """+ rename_all = (+ "RENAME TABLE "+ "cubepi_threads TO cubeloop_threads, "+ "cubepi_messages TO cubeloop_messages, "+ "cubepi_runs TO cubeloop_runs, "+ "cubepi_hitl_answers TO cubeloop_hitl_answers, "+ "cubepi_schema_version TO cubeloop_schema_version"+ )+ rename_ver = "RENAME TABLE cubepi_schema_version TO cubeloop_schema_version"+ return (+ "SET @cp_new_th = ("+ "SELECT COUNT(*) FROM information_schema.tables "+ "WHERE table_schema = DATABASE() "+ "AND table_name = 'cubeloop_threads'); "+ "SET @cp_new_ver = ("+ "SELECT COUNT(*) FROM information_schema.tables "+ "WHERE table_schema = DATABASE() "+ "AND table_name = 'cubeloop_schema_version'); "+ "SET @cp_old_ver = ("+ "SELECT COUNT(*) FROM information_schema.tables "+ "WHERE table_schema = DATABASE() "+ "AND table_name = 'cubepi_schema_version'); "+ "SET @cp_sql = IF(@cp_new_th > 0 AND @cp_new_ver > 0, "+ "'DO 0', "+ "IF(@cp_new_th > 0 AND @cp_old_ver > 0, "+ f"'{rename_ver}', "+ f"'{rename_all}')); "+ "PREPARE cp_v6 FROM @cp_sql; "+ "EXECUTE cp_v6; "+ "DEALLOCATE PREPARE cp_v6;"+ )+++def write_schema_version_op() -> str:+ """Write EXPECTED_SCHEMA_VERSION to cubeloop_schema_version if that+ table exists, else to cubepi_schema_version.++ Returns ';'-joined **standalone** statements. Hosts must split::for stmt in write_schema_version_op().split(";"):if stmt.strip():op.execute(stmt)++ No compound IF/THEN — internal semicolons would break the split contract."""+ n = EXPECTED_SCHEMA_VERSIONreturn (- f"DELETE FROM cubepi_schema_version "- f"WHERE version <> {EXPECTED_SCHEMA_VERSION}; "- f"INSERT IGNORE INTO cubepi_schema_version (version) "- f"VALUES ({EXPECTED_SCHEMA_VERSION});"+ "SET @cp_ver_new = ("+ "SELECT COUNT(*) FROM information_schema.tables "+ "WHERE table_schema = DATABASE() "+ "AND table_name = 'cubeloop_schema_version'); "+ f"SET @cp_del = IF(@cp_ver_new > 0, "+ f"'DELETE FROM cubeloop_schema_version WHERE version <> {n}', "+ f"'DELETE FROM cubepi_schema_version WHERE version <> {n}'); "+ "PREPARE cp_stmt FROM @cp_del; "+ "EXECUTE cp_stmt; "+ "DEALLOCATE PREPARE cp_stmt; "+ f"SET @cp_ins = IF(@cp_ver_new > 0, "+ f"'INSERT IGNORE INTO cubeloop_schema_version (version) VALUES ({n})', "+ f"'INSERT IGNORE INTO cubepi_schema_version (version) VALUES ({n})'); "+ "PREPARE cp_stmt FROM @cp_ins; "+ "EXECUTE cp_stmt; "+ "DEALLOCATE PREPARE cp_stmt;")diff --git a/cubepi/checkpointer/mysql/checkpointer.py b/cubeloop/checkpointer/mysql/checkpointer.pysimilarity index 78%rename from cubepi/checkpointer/mysql/checkpointer.pyrename to cubeloop/checkpointer/mysql/checkpointer.pyindex a877a6f..ef69737 100644--- a/cubepi/checkpointer/mysql/checkpointer.py+++ b/cubeloop/checkpointer/mysql/checkpointer.py@@ -18,8 +18,8 @@ import msgpackimport pymysqlfrom pydantic import TypeAdapter-from cubepi.checkpointer.base import CheckpointData-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.base import CheckpointData+from cubeloop.checkpointer.exceptions import (CheckpointCorruptionError,RunAlreadyClaimedError,RunAlreadyCompletedError,@@ -28,19 +28,19 @@ from cubepi.checkpointer.exceptions import (ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.checkpointer.mysql.exceptions import (- CubepiSchemaMismatch,- CubepiSchemaUninitialized,+from cubeloop.checkpointer.mysql.exceptions import (+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,)-from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION-from cubepi.hitl.types import HitlRequest-from cubepi.providers.base import (+from cubeloop.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+from cubeloop.hitl.types import HitlRequest+from cubeloop.providers.base import (AssistantMessage,Message,ToolResultMessage,UserMessage,)-from cubepi.types import JsonObject, StructuredValue+from cubeloop.types import JsonObject, StructuredValue_STRUCTURED_VALUE_ADAPTER: TypeAdapter[Any] = TypeAdapter(StructuredValue)@@ -68,7 +68,7 @@ _ROLE_TO_CLS: dict[str, type[Message]] = {def _deserialize_row(thread_id: str, seq: int, role: str, metadata: Any, payload: Any) -> Message:- """Deserialize one cubepi_messages row; corruption raises typed."""+ """Deserialize one cubeloop_messages row; corruption raises typed."""try:cls = _ROLE_TO_CLS.get(role)if cls is None:@@ -80,7 +80,7 @@ def _deserialize_row(raise CheckpointCorruptionError(thread_id=thread_id,backend="mysql",- row_ref=f"cubepi_messages.seq={seq}",+ row_ref=f"cubeloop_messages.seq={seq}",cause=exc,) from exc@@ -175,53 +175,102 @@ class MySQLCheckpointer:assert self._pool is not Noneasync with self._pool.acquire() as conn:async with conn.cursor() as cur:- try:- await cur.execute(- "SELECT version FROM cubepi_schema_version LIMIT 1"+ row, missing = await self._select_version(+ cur, "cubeloop_schema_version"+ )+ if not missing:+ if row is None:+ raise CubeloopSchemaUninitialized(+ "cubeloop_schema_version table is empty. Host "+ "alembic migration must INSERT the current version "+ "(use write_schema_version_op())."+ )+ actual = row[0]+ if actual != EXPECTED_SCHEMA_VERSION:+ steps = ", ".join(+ f"upgrade_v{v}_to_v{v + 1}_op()"+ for v in range(actual, EXPECTED_SCHEMA_VERSION)+ )+ raise CubeloopSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=actual,+ hint=(+ "cubeloop was upgraded but host alembic is "+ f"behind. Generate a new alembic revision that "+ f"calls {steps} + write_schema_version_op() "+ "(see cubeloop.checkpointer.mysql.alembic_helpers) "+ "and run `alembic upgrade head` against this "+ "database."+ ),+ )+ return++ legacy, legacy_missing = await self._select_version(+ cur, "cubepi_schema_version"+ )+ if not legacy_missing:+ actual = 0 if legacy is None else int(legacy[0])+ raise CubeloopSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=actual,+ hint=(+ "Generate a new alembic revision that calls "+ "upgrade_v5_to_v6_op() + write_schema_version_op() "+ "(see cubeloop.checkpointer.mysql.alembic_helpers) "+ "and run `alembic upgrade head` against this "+ "database."+ ),)- row = await cur.fetchone()- except pymysql.err.Error as e:- # PyMySQL maps 1146 (ER_NO_SUCH_TABLE) to ProgrammingError but- # 1054 (ER_BAD_FIELD_ERROR) to OperationalError, so catch the- # common base and branch on the errno.- code = e.args[0] if e.args else None- if code in (_ER_NO_SUCH_TABLE, _ER_BAD_FIELD_ERROR):- raise CubepiSchemaUninitialized(- "cubepi tables not found or malformed. Run host "- "application's alembic upgrade."- ) from e- raise # pragma: no cover - non-schema DB errors propagate- 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())."- )- actual = row[0]- if actual != EXPECTED_SCHEMA_VERSION:- raise CubepiSchemaMismatch(- expected=EXPECTED_SCHEMA_VERSION,- actual=actual,- hint=(- "cubepi was upgraded but host alembic is behind. "- "Generate a new alembic revision that calls "- "add_run_id_column_op() + write_schema_version_op() "- "(see cubepi.checkpointer.mysql.alembic_helpers) "- "and run `alembic upgrade head` against this database."- ),- )++ await cur.execute(+ "SELECT COUNT(*) FROM information_schema.tables "+ "WHERE table_schema = DATABASE() "+ "AND table_name IN ('cubepi_threads', 'cubeloop_threads')"+ )+ count_row = await cur.fetchone()+ if count_row and count_row[0]:+ raise CubeloopSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=0,+ hint=(+ "data tables exist but schema_version is missing; "+ "cannot auto-classify. If tables are still cubepi_*, "+ "CREATE TABLE cubepi_schema_version and INSERT 5, "+ "then run upgrade_v5_to_v6_op(). Do not apply fresh "+ "v6 CREATE TABLE on existing data."+ ),+ )+ raise CubeloopSchemaUninitialized(+ "cubeloop tables not found. Run host application's alembic upgrade."+ )++ @staticmethod+ async def _select_version(+ cur: Any, table: str+ ) -> tuple[tuple[Any, ...] | None, bool]:+ """Return (row, missing). missing=True when the table does not exist."""+ try:+ await cur.execute(f"SELECT version FROM {table} LIMIT 1")+ row = await cur.fetchone()+ return row, False+ except pymysql.err.Error as e:+ code = e.args[0] if e.args else None+ if code in (_ER_NO_SUCH_TABLE, _ER_BAD_FIELD_ERROR):+ return None, True+ raiseasync def load(self, thread_id: str) -> CheckpointData | None:assert self._pool is not Noneasync with self._pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute(- "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "SELECT seq, role, metadata, payload FROM cubeloop_messages ""WHERE thread_id = %s ORDER BY seq",(thread_id,),)msg_rows = await cur.fetchall()await cur.execute(- "SELECT extra, parent_thread_id FROM cubepi_threads "+ "SELECT extra, parent_thread_id FROM cubeloop_threads ""WHERE thread_id = %s",(thread_id,),)@@ -261,12 +310,12 @@ class MySQLCheckpointer:# also swallow unrelated errors and emit a duplicate-key# warning when the row already exists.await cur.execute(- "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "INSERT INTO cubeloop_threads (thread_id) VALUES (%s) ""ON DUPLICATE KEY UPDATE thread_id = thread_id",(thread_id,),)await cur.execute(- "SELECT thread_id FROM cubepi_threads "+ "SELECT thread_id FROM cubeloop_threads ""WHERE thread_id = %s FOR UPDATE",(thread_id,),)@@ -274,7 +323,7 @@ class MySQLCheckpointer:if run_ids:placeholders = ", ".join(["%s"] * len(run_ids))await cur.execute(- f"SELECT run_id FROM cubepi_runs "+ f"SELECT run_id FROM cubeloop_runs "f"WHERE thread_id = %s "f"AND run_id IN ({placeholders}) "f"AND completed_at IS NOT NULL",@@ -287,7 +336,7 @@ class MySQLCheckpointer:f"append on completed run thread={thread_id} runs={bad}")await cur.execute(- "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "+ "SELECT COALESCE(MAX(seq), 0) FROM cubeloop_messages ""WHERE thread_id = %s",(thread_id,),)@@ -309,7 +358,7 @@ class MySQLCheckpointer:))await cur.executemany(- "INSERT INTO cubepi_messages "+ "INSERT INTO cubeloop_messages ""(thread_id, seq, role, metadata, payload, run_id) ""VALUES (%s, %s, %s, %s, %s, %s)",rows,@@ -322,9 +371,9 @@ class MySQLCheckpointer:async def claim_run(self, thread_id: str, run_id: str) -> None:"""Atomically claim a run_id on a thread.- Lazy-creates the cubepi_threads row, takes a per-thread FOR UPDATE+ Lazy-creates the cubeloop_threads row, takes a per-thread FOR UPDATElock to serialize concurrent claims for the same thread, then- checks cubepi_runs for an existing row before inserting. The+ checks cubeloop_runs for an existing row before inserting. Thepre-check matches the Postgres approach — using INSERT + catchingIntegrityError would also work, but a pre-SELECT lets usdistinguish in-flight vs completed cleanly without relying on the@@ -337,19 +386,19 @@ class MySQLCheckpointer:async with conn.cursor() as cur:# Lazy thread row creation (claim may precede any append).await cur.execute(- "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "INSERT INTO cubeloop_threads (thread_id) VALUES (%s) ""ON DUPLICATE KEY UPDATE thread_id = thread_id",(thread_id,),)# Per-thread fence: serializes claim_run/append/fork on# the same thread (matches Postgres's pg_advisory_xact_lock).await cur.execute(- "SELECT thread_id FROM cubepi_threads "+ "SELECT thread_id FROM cubeloop_threads ""WHERE thread_id = %s FOR UPDATE",(thread_id,),)await cur.execute(- "SELECT completed_at FROM cubepi_runs "+ "SELECT completed_at FROM cubeloop_runs ""WHERE thread_id = %s AND run_id = %s",(thread_id, run_id),)@@ -363,7 +412,7 @@ class MySQLCheckpointer:f"thread={thread_id} run={run_id} in flight")await cur.execute(- "INSERT INTO cubepi_runs (thread_id, run_id) VALUES (%s, %s)",+ "INSERT INTO cubeloop_runs (thread_id, run_id) VALUES (%s, %s)",(thread_id, run_id),)await conn.commit()@@ -385,12 +434,12 @@ class MySQLCheckpointer:try:async with conn.cursor() as cur:await cur.execute(- "SELECT thread_id FROM cubepi_threads "+ "SELECT thread_id FROM cubeloop_threads ""WHERE thread_id = %s FOR UPDATE",(thread_id,),)await cur.execute(- "SELECT completed_at FROM cubepi_runs "+ "SELECT completed_at FROM cubeloop_runs ""WHERE thread_id = %s AND run_id = %s",(thread_id, run_id),)@@ -404,13 +453,13 @@ class MySQLCheckpointer:return # idempotent successawait cur.execute("SELECT COALESCE(MAX(completion_seq), 0) + 1 "- "FROM cubepi_runs WHERE thread_id = %s "+ "FROM cubeloop_runs WHERE thread_id = %s ""AND completion_seq IS NOT NULL",(thread_id,),)(next_seq,) = await cur.fetchone()await cur.execute(- "UPDATE cubepi_runs SET completed_at = CURRENT_TIMESTAMP, "+ "UPDATE cubeloop_runs SET completed_at = CURRENT_TIMESTAMP, ""completion_seq = %s ""WHERE thread_id = %s AND run_id = %s",(next_seq, thread_id, run_id),@@ -433,7 +482,7 @@ class MySQLCheckpointer:async with self._pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute(- "SELECT pending_request, run_id FROM cubepi_threads "+ "SELECT pending_request, run_id FROM cubeloop_threads ""WHERE thread_id = %s",(thread_id,),)@@ -460,13 +509,13 @@ class MySQLCheckpointer:async with self._pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute(- "SELECT 1 FROM cubepi_threads WHERE thread_id = %s",+ "SELECT 1 FROM cubeloop_threads WHERE thread_id = %s",(thread_id,),)if await cur.fetchone() is None:raise ThreadNotFoundError(f"thread={thread_id}")await cur.execute(- "SELECT completion_seq FROM cubepi_runs "+ "SELECT completion_seq FROM cubeloop_runs ""WHERE thread_id = %s AND run_id = %s",(thread_id, after_run_id),)@@ -477,10 +526,10 @@ class MySQLCheckpointer:)cutoff = cutoff_row[0]await cur.execute(- "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "SELECT seq, role, metadata, payload FROM cubeloop_messages ""WHERE thread_id = %s AND ("" run_id IS NULL OR run_id IN ("- " SELECT run_id FROM cubepi_runs "+ " SELECT run_id FROM cubeloop_runs "" WHERE thread_id = %s "" AND completion_seq IS NOT NULL "" AND completion_seq <= %s"@@ -504,10 +553,10 @@ class MySQLCheckpointer:) -> None:"""Copy completed prefix of ``src_thread_id`` into ``new_thread_id``.- Threads-row first: the destination ``cubepi_threads`` row is+ Threads-row first: the destination ``cubeloop_threads`` row isinserted before the message + runs copies so callers see a- complete view if they probe mid-fork. There is no cubepi_runs ->- cubepi_threads FK on MySQL (partition limitation), but we keep+ complete view if they probe mid-fork. There is no cubeloop_runs ->+ cubeloop_threads FK on MySQL (partition limitation), but we keepthe same ordering for semantic parity with Postgres.Per-thread serialization: a ``SELECT … FOR UPDATE`` on the source@@ -522,7 +571,7 @@ class MySQLCheckpointer:async with conn.cursor() as cur:# Per-thread fence on the source thread.await cur.execute(- "SELECT thread_id FROM cubepi_threads "+ "SELECT thread_id FROM cubeloop_threads ""WHERE thread_id = %s FOR UPDATE",(src_thread_id,),)@@ -530,14 +579,14 @@ class MySQLCheckpointer:raise ThreadNotFoundError(f"thread={src_thread_id}")# Destination must not exist.await cur.execute(- "SELECT 1 FROM cubepi_threads WHERE thread_id = %s",+ "SELECT 1 FROM cubeloop_threads WHERE thread_id = %s",(new_thread_id,),)if await cur.fetchone() is not None:raise ThreadAlreadyExistsError(f"thread={new_thread_id}")# Cutoff: after_run_id must be completed on src.await cur.execute(- "SELECT completion_seq FROM cubepi_runs "+ "SELECT completion_seq FROM cubeloop_runs ""WHERE thread_id = %s AND run_id = %s",(src_thread_id, after_run_id),)@@ -549,7 +598,7 @@ class MySQLCheckpointer:cutoff = cutoff_row[0]# Build merged extra (carry parent's extra + fork metadata).await cur.execute(- "SELECT extra FROM cubepi_threads WHERE thread_id = %s",+ "SELECT extra FROM cubeloop_threads WHERE thread_id = %s",(src_thread_id,),)extra_row = await cur.fetchone()@@ -563,7 +612,7 @@ class MySQLCheckpointer:# with the Postgres FK-driven ordering, even though MySQL# has no FK on the partitioned messages/runs tables).await cur.execute(- "INSERT INTO cubepi_threads "+ "INSERT INTO cubeloop_threads ""(thread_id, parent_thread_id, forked_at_seq, extra) ""VALUES (%s, %s, %s, %s)",(@@ -575,13 +624,13 @@ class MySQLCheckpointer:)# Copy messages: legacy NULL run_id OR completed-at-cutoff.await cur.execute(- "INSERT INTO cubepi_messages "+ "INSERT INTO cubeloop_messages ""(thread_id, seq, role, metadata, payload, run_id) ""SELECT %s, seq, role, metadata, payload, run_id "- "FROM cubepi_messages "+ "FROM cubeloop_messages ""WHERE thread_id = %s AND ("" run_id IS NULL OR run_id IN ("- " SELECT run_id FROM cubepi_runs "+ " SELECT run_id FROM cubeloop_runs "" WHERE thread_id = %s "" AND completion_seq IS NOT NULL "" AND completion_seq <= %s"@@ -591,12 +640,12 @@ class MySQLCheckpointer:)# Copy completed runs satisfying the cutoff.await cur.execute(- "INSERT INTO cubepi_runs "+ "INSERT INTO cubeloop_runs ""(thread_id, run_id, claimed_at, completed_at, "" completion_seq) ""SELECT %s, run_id, claimed_at, completed_at, "" completion_seq "- "FROM cubepi_runs "+ "FROM cubeloop_runs ""WHERE thread_id = %s ""AND completion_seq IS NOT NULL ""AND completion_seq <= %s",@@ -618,12 +667,12 @@ class MySQLCheckpointer:# also swallow unrelated errors and emit a duplicate-key# warning when the row already exists.await cur.execute(- "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "INSERT INTO cubeloop_threads (thread_id) VALUES (%s) ""ON DUPLICATE KEY UPDATE thread_id = thread_id",(thread_id,),)await cur.execute(- "SELECT extra FROM cubepi_threads "+ "SELECT extra FROM cubeloop_threads ""WHERE thread_id = %s FOR UPDATE",(thread_id,),)@@ -631,7 +680,7 @@ class MySQLCheckpointer:current = _decode_json(row[0]) if row is not None else {}merged = {**current, **extra}await cur.execute(- "UPDATE cubepi_threads "+ "UPDATE cubeloop_threads ""SET extra = %s, updated_at = CURRENT_TIMESTAMP ""WHERE thread_id = %s",(json.dumps(merged), thread_id),@@ -663,13 +712,13 @@ class MySQLCheckpointer:try:async with conn.cursor() as cur:await cur.execute(- "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "INSERT INTO cubeloop_threads (thread_id) VALUES (%s) ""ON DUPLICATE KEY UPDATE thread_id = thread_id",(thread_id,),)if request is None:await cur.execute(- "UPDATE cubepi_threads "+ "UPDATE cubeloop_threads ""SET pending_request = NULL, run_id = NULL, ""updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",(thread_id,),@@ -677,7 +726,7 @@ class MySQLCheckpointer:else:payload = request.model_dump_json()await cur.execute(- "UPDATE cubepi_threads "+ "UPDATE cubeloop_threads ""SET pending_request = %s, run_id = %s, ""updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",(payload, run_id, thread_id),@@ -692,7 +741,7 @@ class MySQLCheckpointer:async with self._pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute(- "SELECT pending_request FROM cubepi_threads WHERE thread_id = %s",+ "SELECT pending_request FROM cubeloop_threads WHERE thread_id = %s",(thread_id,),)row = await cur.fetchone()@@ -717,7 +766,7 @@ class MySQLCheckpointer:async with self._pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute(- "SELECT run_id FROM cubepi_threads "+ "SELECT run_id FROM cubeloop_threads ""WHERE thread_id = %s AND pending_request IS NOT NULL",(thread_id,),)@@ -739,12 +788,12 @@ class MySQLCheckpointer:try:async with conn.cursor() as cur:await cur.execute(- "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "INSERT INTO cubeloop_threads (thread_id) VALUES (%s) ""ON DUPLICATE KEY UPDATE thread_id = thread_id",(thread_id,),)await cur.execute(- "INSERT INTO cubepi_hitl_answers "+ "INSERT INTO cubeloop_hitl_answers ""(thread_id, run_id, question_id, answer) ""VALUES (%s, %s, %s, %s) ""ON DUPLICATE KEY UPDATE "@@ -768,7 +817,7 @@ class MySQLCheckpointer:async with self._pool.acquire() as conn:async with conn.cursor() as cur:await cur.execute(- "SELECT answer FROM cubepi_hitl_answers "+ "SELECT answer FROM cubeloop_hitl_answers ""WHERE thread_id = %s AND run_id = %s AND question_id = %s",(thread_id, _run_key(run_id), question_id),)@@ -792,7 +841,7 @@ class MySQLCheckpointer:async with conn.cursor() as cur:if question_ids is None:await cur.execute(- "DELETE FROM cubepi_hitl_answers "+ "DELETE FROM cubeloop_hitl_answers ""WHERE thread_id = %s AND run_id = %s",(thread_id, run_key),)@@ -801,7 +850,7 @@ class MySQLCheckpointer:if qids:placeholders = ",".join("%s" for _ in qids)await cur.execute(- "DELETE FROM cubepi_hitl_answers "+ "DELETE FROM cubeloop_hitl_answers ""WHERE thread_id = %s AND run_id = %s "f"AND question_id IN ({placeholders})",(thread_id, run_key, *qids),diff --git a/cubeloop/checkpointer/mysql/exceptions.py b/cubeloop/checkpointer/mysql/exceptions.pynew file mode 100644index 0000000..4cd000c--- /dev/null+++ b/cubeloop/checkpointer/mysql/exceptions.py@@ -0,0 +1,19 @@+"""Schema exceptions for MySQLCheckpointer.++Re-exported from the backend-agnostic ``cubeloop.checkpointer.exceptions``.+Importing from there (rather than the Postgres package) keeps a single source+of truth without pulling in ``asyncpg``, so the ``cubepi[mysql]`` extra works+without the Postgres extra installed.+"""++from cubeloop.checkpointer.exceptions import (+ CubeloopSchemaError,+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,+)++__all__ = [+ "CubeloopSchemaError",+ "CubeloopSchemaMismatch",+ "CubeloopSchemaUninitialized",+]diff --git a/cubepi/checkpointer/mysql/models.py b/cubeloop/checkpointer/mysql/models.pysimilarity index 84%rename from cubepi/checkpointer/mysql/models.pyrename to cubeloop/checkpointer/mysql/models.pyindex 1988b01..7c79f4b 100644--- a/cubepi/checkpointer/mysql/models.py+++ b/cubeloop/checkpointer/mysql/models.py@@ -16,26 +16,26 @@ import sqlalchemy as safrom sqlalchemy.dialects.mysql import JSON, LONGBLOB, VARCHARfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column-EXPECTED_SCHEMA_VERSION = 5+EXPECTED_SCHEMA_VERSION = 6PARTITION_COUNT = 64-cubepi_metadata = sa.MetaData()+cubeloop_metadata = sa.MetaData()_TID = VARCHAR(255, collation="utf8mb4_bin")-class CubepiBase(DeclarativeBase):- metadata = cubepi_metadata+class CubeloopBase(DeclarativeBase):+ metadata = cubeloop_metadata-class CubepiThread(CubepiBase):- __tablename__ = "cubepi_threads"+class CubeloopThread(CubeloopBase):+ __tablename__ = "cubeloop_threads"__table_args__ = {"mysql_engine": "InnoDB"}thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)parent_thread_id: Mapped[str | None] = mapped_column(_TID,- sa.ForeignKey("cubepi_threads.thread_id"),+ sa.ForeignKey("cubeloop_threads.thread_id"),nullable=True,)forked_at_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)@@ -71,10 +71,10 @@ class CubepiThread(CubepiBase):)-class CubepiMessage(CubepiBase):- __tablename__ = "cubepi_messages"+class CubeloopMessage(CubeloopBase):+ __tablename__ = "cubeloop_messages"__table_args__ = (- sa.Index("ix_cubepi_messages_thread_run", "thread_id", "run_id"),+ sa.Index("ix_cubeloop_messages_thread_run", "thread_id", "run_id"),{"mysql_engine": "InnoDB"},)@@ -92,7 +92,7 @@ class CubepiMessage(CubepiBase):payload: Mapped[bytes] = mapped_column(LONGBLOB, nullable=False)# v4: opaque host-side run identifier stamped on each message. Lets# fork/snapshot include only messages from completed runs. VARCHAR(255)- # to match the cubepi_messages indexing convention (thread_id is also+ # to match the cubeloop_messages indexing convention (thread_id is also# VARCHAR(255) — keeps the composite index cardinality consistent).run_id: Mapped[str | None] = mapped_column(VARCHAR(255),@@ -105,19 +105,19 @@ class CubepiMessage(CubepiBase):)-class CubepiRun(CubepiBase):+class CubeloopRun(CubeloopBase):"""v4 per-run lifecycle row.Primary key (thread_id, run_id). KEY-partitioned by thread_id to match- cubepi_messages. NO FK to cubepi_threads — MySQL forbids FKs on+ cubeloop_messages. NO FK to cubeloop_threads — MySQL forbids FKs onpartitioned tables. The partition clause cannot be expressed inSQLAlchemy declarative and lives in``alembic_helpers.runs_partition_clause()``."""- __tablename__ = "cubepi_runs"+ __tablename__ = "cubeloop_runs"__table_args__ = (- sa.Index("ix_cubepi_runs_thread_seq", "thread_id", "completion_seq"),+ sa.Index("ix_cubeloop_runs_thread_seq", "thread_id", "completion_seq"),{"mysql_engine": "InnoDB"},)@@ -135,8 +135,8 @@ class CubepiRun(CubepiBase):completion_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)-class CubepiHitlAnswer(CubepiBase):- __tablename__ = "cubepi_hitl_answers"+class CubeloopHitlAnswer(CubeloopBase):+ __tablename__ = "cubeloop_hitl_answers"__table_args__ = {"mysql_engine": "InnoDB"}thread_id: Mapped[str] = mapped_column(_TID, primary_key=True)@@ -150,8 +150,8 @@ class CubepiHitlAnswer(CubepiBase):)-class CubepiSchemaVersion(CubepiBase):- __tablename__ = "cubepi_schema_version"+class CubeloopSchemaVersion(CubeloopBase):+ __tablename__ = "cubeloop_schema_version"__table_args__ = {"mysql_engine": "InnoDB"}version: Mapped[int] = mapped_column(sa.Integer, primary_key=True)diff --git a/cubepi/checkpointer/postgres/README.md b/cubeloop/checkpointer/postgres/README.mdsimilarity index 56%rename from cubepi/checkpointer/postgres/README.mdrename to cubeloop/checkpointer/postgres/README.mdindex d6e0ba2..a585811 100644--- a/cubepi/checkpointer/postgres/README.md+++ b/cubeloop/checkpointer/postgres/README.md@@ -2,22 +2,22 @@`PostgresCheckpointer` (asyncpg) persists agent state for multi-replica,high-concurrency deployments. **It never issues DDL at runtime** — your-application owns the schema lifecycle through Alembic, and cubepi only+application owns the schema lifecycle through Alembic, and cubeloop onlyreads and writes rows. Entering the async context manager(`async with PostgresCheckpointer(...)`) verifies the schema and raises-`CubepiSchemaUninitialized` / `CubepiSchemaMismatch` if the expected+`CubeloopSchemaUninitialized` / `CubeloopSchemaMismatch` if the expectedmigrations haven't been applied.Install with the extra:```bash-pip install 'cubepi[postgres]'+pip install 'cubeloop[postgres]'```## Using the checkpointer```python-from cubepi.checkpointer.postgres import PostgresCheckpointer+from cubeloop.checkpointer.postgres import PostgresCheckpointer# Entering the context manager connects the pool and verifies the schema.async with PostgresCheckpointer("postgresql://user:pass@host/db") as cp:@@ -33,96 +33,98 @@ Schema verification happens on `__aenter__`; it never creates tables.The package re-exports the symbols Alembic wiring needs:```python-from cubepi.checkpointer.postgres import cubepi_metadata, EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.postgres import cubeloop_metadata, EXPECTED_SCHEMA_VERSION```| Symbol | Use ||---|---|-| `cubepi_metadata` | SQLAlchemy `MetaData` — set as Alembic `target_metadata` |-| `EXPECTED_SCHEMA_VERSION` | The version cubepi verifies on connect (currently `3`) |+| `cubeloop_metadata` | SQLAlchemy `MetaData` — set as Alembic `target_metadata` |+| `EXPECTED_SCHEMA_VERSION` | The version cubeloop verifies on connect (currently `6`) |The SQL helpers live in the `alembic_helpers` submodule:```python-from cubepi.checkpointer.postgres.alembic_helpers import (- create_message_partitions_op, # DDL for the 64 hash partitions of cubepi_messages+from cubeloop.checkpointer.postgres.alembic_helpers import (+ create_message_partitions_op, # DDL for the 64 hash partitions of cubeloop_messagesadd_pending_request_column_op, # v1→v2 column add (idempotent, IF NOT EXISTS)- write_schema_version_op, # sets cubepi_schema_version to EXPECTED_SCHEMA_VERSION+ write_schema_version_op, # sets schema_version to EXPECTED_SCHEMA_VERSION)```## Tables-`cubepi_metadata` defines three tables:+`cubeloop_metadata` defines the current (v6) tables:| Table | Purpose ||---|---|-| `cubepi_threads` | One row per thread; holds `pending_request JSONB NULL` (HITL, v2+) |-| `cubepi_messages` | Append-only message log — `(thread_id, seq, role, metadata, payload, created_at)`, **HASH-partitioned** on `thread_id` into 64 partitions |-| `cubepi_schema_version` | Single-row version marker verified on connect |+| `cubeloop_threads` | One row per thread; holds `pending_request JSONB NULL` (HITL, v2+) |+| `cubeloop_messages` | Append-only message log — `(thread_id, seq, role, metadata, payload, created_at)`, **HASH-partitioned** on `thread_id` into 64 partitions |+| `cubeloop_runs` | Per-run claim/completion (v4+), HASH-partitioned |+| `cubeloop_hitl_answers` | Durable HITL answers (v5+) |+| `cubeloop_schema_version` | Single-row version marker verified on connect |## Wiring Alembic (`env.py`)-Point Alembic at cubepi's metadata so autogenerate sees the tables:+Point Alembic at cubeloop's metadata so autogenerate sees the tables:```python# alembic/env.py-from cubepi.checkpointer.postgres import cubepi_metadata+from cubeloop.checkpointer.postgres import cubeloop_metadata-target_metadata = cubepi_metadata+target_metadata = cubeloop_metadata# or, alongside your own models:-# target_metadata = [your_metadata, cubepi_metadata]+# target_metadata = [your_metadata, cubeloop_metadata]```## Autogenerate, and what to add by hand```bash-alembic revision --autogenerate -m "add cubepi checkpointer"+alembic revision --autogenerate -m "add cubeloop checkpointer"```Autogenerate emits `op.create_table(...)` for all three tables **with the-correct columns** (they come straight from `cubepi_metadata`). Two things+correct columns** (they come straight from `cubeloop_metadata`). Two thingsSQLAlchemy autogenerate does not reliably produce, so add them to thegenerated migration yourself:-1. **Child partitions.** `cubepi_messages` is HASH-partitioned on+1. **Child partitions.** `cubeloop_messages` is HASH-partitioned on`thread_id` (the model declares this via`__table_args__["postgresql_partition_by"]`). Keep the autogenerated- `create_table` for `cubepi_messages` — including all its columns — and+ `create_table` for `cubeloop_messages` — including all its columns — andmake sure it carries `postgresql_partition_by="HASH (thread_id)"`. The64 child partitions are not autogenerated; create them with the helper.-2. **The version row.** Autogenerate creates the `cubepi_schema_version`+2. **The version row.** Autogenerate creates the `cubeloop_schema_version`table but never inserts a row.```python-from cubepi.checkpointer.postgres.alembic_helpers import (+from cubeloop.checkpointer.postgres.alembic_helpers import (create_message_partitions_op,write_schema_version_op,)def upgrade():- # ... autogenerated create_table() for cubepi_threads,- # cubepi_schema_version, and cubepi_messages (keep ALL columns;- # ensure cubepi_messages has postgresql_partition_by="HASH (thread_id)") ...+ # ... autogenerated create_table() for cubeloop_threads,+ # cubeloop_schema_version, and cubeloop_messages (keep ALL columns;+ # ensure cubeloop_messages has postgresql_partition_by="HASH (thread_id)") ...op.execute(create_message_partitions_op()) # the 64 child partitionsop.execute(write_schema_version_op()) # record EXPECTED_SCHEMA_VERSION```-> Do not hand-trim the `cubepi_messages` columns. The checkpointer writes+> Do not hand-trim the `cubeloop_messages` columns. The checkpointer writes> and reads `(thread_id, seq, role, metadata, payload)`; dropping any of> them causes runtime SQL errors on the first append.## Upgrading schema versions-cubepi bumps `EXPECTED_SCHEMA_VERSION` when the schema changes; the-checkpointer refuses to connect if the row in `cubepi_schema_version`+CubeLoop bumps `EXPECTED_SCHEMA_VERSION` when the schema changes; the+checkpointer refuses to connect if the row in `cubeloop_schema_version`doesn't match. Each bump is one host migration.**v1 → v2** (HITL): adds `pending_request JSONB NULL` to `cubepi_threads`.```python-from cubepi.checkpointer.postgres.alembic_helpers import (+from cubeloop.checkpointer.postgres.alembic_helpers import (add_pending_request_column_op,write_schema_version_op,)@@ -138,7 +140,7 @@ def downgrade():````write_schema_version_op()` clears stale rows before inserting, so running-it after every cubepi upgrade keeps `cubepi_schema_version` single-valued.+it after every cubeloop upgrade keeps `cubepi_schema_version` single-valued.## See alsodiff --git a/cubeloop/checkpointer/postgres/__init__.py b/cubeloop/checkpointer/postgres/__init__.pynew file mode 100644index 0000000..767a3a2--- /dev/null+++ b/cubeloop/checkpointer/postgres/__init__.py@@ -0,0 +1,21 @@+from cubeloop.checkpointer.postgres.checkpointer import PostgresCheckpointer+from cubeloop.checkpointer.postgres.exceptions import (+ CubeloopSchemaError,+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,+)+from cubeloop.checkpointer.postgres.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+ cubeloop_metadata,+)++__all__ = [+ "PostgresCheckpointer",+ "CubeloopSchemaError",+ "CubeloopSchemaMismatch",+ "CubeloopSchemaUninitialized",+ "EXPECTED_SCHEMA_VERSION",+ "PARTITION_COUNT",+ "cubeloop_metadata",+]diff --git a/cubeloop/checkpointer/postgres/alembic_helpers.py b/cubeloop/checkpointer/postgres/alembic_helpers.pynew file mode 100644index 0000000..e46f513--- /dev/null+++ b/cubeloop/checkpointer/postgres/alembic_helpers.py@@ -0,0 +1,181 @@+"""SQL helpers for host application alembic migrations."""++from cubeloop.checkpointer.postgres.models import (+ EXPECTED_SCHEMA_VERSION,+ PARTITION_COUNT,+)+++def create_message_partitions_op() -> str:+ """Return SQL DDL creating all 64 child partitions of cubeloop_messages.++ Call inside an alembic upgrade() via op.execute(), AFTER the parent+ cubeloop_messages table has been created. Emits current (v6) names.+ """+ return "\n".join(+ f"CREATE TABLE cubeloop_messages_p{i:02d} "+ f"PARTITION OF cubeloop_messages "+ f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i});"+ for i in range(PARTITION_COUNT)+ )+++def add_pending_request_column_op() -> str:+ """Return SQL adding the v2 `pending_request` column to cubepi_threads.++ Historical helper: still targets the pre-rename table name. Call inside+ the host's alembic v1→v2 upgrade() via op.execute(). Idempotent under+ repeated execution via IF NOT EXISTS.+ """+ return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS pending_request JSONB"+++def add_run_id_column_op() -> str:+ """Return SQL adding the v3 `run_id` column to cubepi_threads.++ Historical helper: still targets the pre-rename table name.+ """+ return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS run_id TEXT"+++def create_runs_partitions_op() -> str:+ """Return SQL DDL creating all child partitions of cubeloop_runs.++ Current-schema factory (v6 names). Historical v3→v4 inlines the old+ cubepi_runs_pXX names and must not call this helper.+ """+ return "\n".join(+ f"CREATE TABLE cubeloop_runs_p{i:02d} "+ f"PARTITION OF cubeloop_runs "+ f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i});"+ for i in range(PARTITION_COUNT)+ )+++def upgrade_v3_to_v4_op() -> str:+ """Return SQL applying the v3→v4 schema changes.++ Historical helper: still emits cubepi_* names, including inlined+ cubepi_runs_pXX partitions (do not call create_runs_partitions_op()).+ """+ run_partitions = "\n".join(+ f"CREATE TABLE cubepi_runs_p{i:02d} "+ f"PARTITION OF cubepi_runs "+ f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i});"+ for i in range(PARTITION_COUNT)+ )+ parts = [+ "ALTER TABLE cubepi_messages ADD COLUMN IF NOT EXISTS run_id TEXT;",+ (+ "CREATE INDEX IF NOT EXISTS ix_cubepi_messages_thread_run "+ "ON cubepi_messages (thread_id, run_id);"+ ),+ (+ "CREATE TABLE IF NOT EXISTS cubepi_runs ("+ " thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) "+ "ON DELETE CASCADE,"+ " run_id TEXT NOT NULL,"+ " claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(),"+ " completed_at TIMESTAMPTZ,"+ " completion_seq BIGINT,"+ " PRIMARY KEY (thread_id, run_id)"+ ") PARTITION BY HASH (thread_id);"+ ),+ (+ "CREATE INDEX IF NOT EXISTS ix_cubepi_runs_thread_seq "+ "ON cubepi_runs (thread_id, completion_seq);"+ ),+ run_partitions,+ ]+ return "\n".join(parts)+++def upgrade_v4_to_v5_op() -> str:+ """Return SQL applying the v4->v5 schema changes.++ Historical helper: still emits cubepi_* names.+ """+ return (+ "CREATE TABLE IF NOT EXISTS cubepi_hitl_answers ("+ " thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) "+ "ON DELETE CASCADE,"+ " run_id TEXT NOT NULL,"+ " question_id TEXT NOT NULL,"+ " answer JSONB NOT NULL,"+ " answered_at TIMESTAMPTZ NOT NULL DEFAULT now(),"+ " PRIMARY KEY (thread_id, run_id, question_id)"+ ");"+ )+++def upgrade_v5_to_v6_op() -> str:+ """Rename cubepi_* tables/indexes/partitions to cubeloop_*.++ Complete (no-op) iff both cubeloop_threads and cubeloop_schema_version+ exist. If data tables already moved but the version table did not,+ rename the leftover. cubeloop_threads alone is not a no-op sentinel.++ Requires a complete v5 (including cubepi_schema_version). Missing+ version table makes the rename fail as a whole.+ """+ message_parts = "\n".join(+ f" ALTER TABLE cubepi_messages_p{i:02d} "+ f"RENAME TO cubeloop_messages_p{i:02d};"+ for i in range(PARTITION_COUNT)+ )+ run_parts = "\n".join(+ f" ALTER TABLE cubepi_runs_p{i:02d} RENAME TO cubeloop_runs_p{i:02d};"+ for i in range(PARTITION_COUNT)+ )+ return f"""+DO $$+BEGIN+ IF to_regclass('cubeloop_threads') IS NOT NULL+ AND to_regclass('cubeloop_schema_version') IS NOT NULL THEN+ RETURN;+ END IF;++ IF to_regclass('cubeloop_threads') IS NOT NULL+ AND to_regclass('cubepi_schema_version') IS NOT NULL THEN+ ALTER TABLE cubepi_schema_version RENAME TO cubeloop_schema_version;+ RETURN;+ END IF;++ ALTER TABLE cubepi_threads RENAME TO cubeloop_threads;+ ALTER TABLE cubepi_messages RENAME TO cubeloop_messages;+{message_parts}+ ALTER TABLE cubepi_runs RENAME TO cubeloop_runs;+{run_parts}+ ALTER TABLE cubepi_hitl_answers RENAME TO cubeloop_hitl_answers;+ ALTER TABLE cubepi_schema_version RENAME TO cubeloop_schema_version;+ ALTER INDEX IF EXISTS ix_cubepi_messages_metadata_gin+ RENAME TO ix_cubeloop_messages_metadata_gin;+ ALTER INDEX IF EXISTS ix_cubepi_messages_thread_run+ RENAME TO ix_cubeloop_messages_thread_run;+ ALTER INDEX IF EXISTS ix_cubepi_runs_thread_seq+ RENAME TO ix_cubeloop_runs_thread_seq;+END $$;+"""+++def write_schema_version_op() -> str:+ """Write EXPECTED_SCHEMA_VERSION to cubeloop_schema_version if that+ table exists, else to cubepi_schema_version.++ One ``DO $$`` block so asyncpg / Alembic send it as a single statement.+ """+ n = EXPECTED_SCHEMA_VERSION+ return f"""+DO $$+BEGIN+ IF to_regclass('cubeloop_schema_version') IS NOT NULL THEN+ DELETE FROM cubeloop_schema_version WHERE version <> {n};+ INSERT INTO cubeloop_schema_version (version) VALUES ({n})+ ON CONFLICT DO NOTHING;+ ELSE+ DELETE FROM cubepi_schema_version WHERE version <> {n};+ INSERT INTO cubepi_schema_version (version) VALUES ({n})+ ON CONFLICT DO NOTHING;+ END IF;+END $$;+"""diff --git a/cubepi/checkpointer/postgres/checkpointer.py b/cubeloop/checkpointer/postgres/checkpointer.pysimilarity index 80%rename from cubepi/checkpointer/postgres/checkpointer.pyrename to cubeloop/checkpointer/postgres/checkpointer.pyindex 7c6304b..3f5bf4e 100644--- a/cubepi/checkpointer/postgres/checkpointer.py+++ b/cubeloop/checkpointer/postgres/checkpointer.py@@ -14,8 +14,8 @@ import asyncpgimport msgpackfrom pydantic import TypeAdapter-from cubepi.checkpointer.base import CheckpointData-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.base import CheckpointData+from cubeloop.checkpointer.exceptions import (CheckpointCorruptionError,RunAlreadyClaimedError,RunAlreadyCompletedError,@@ -24,19 +24,19 @@ from cubepi.checkpointer.exceptions import (ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.checkpointer.postgres.exceptions import (- CubepiSchemaMismatch,- CubepiSchemaUninitialized,+from cubeloop.checkpointer.postgres.exceptions import (+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,)-from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION-from cubepi.hitl.types import HitlRequest-from cubepi.providers.base import (+from cubeloop.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION+from cubeloop.hitl.types import HitlRequest+from cubeloop.providers.base import (AssistantMessage,Message,ToolResultMessage,UserMessage,)-from cubepi.types import JsonObject, StructuredValue+from cubeloop.types import JsonObject, StructuredValue_STRUCTURED_VALUE_ADAPTER: TypeAdapter[Any] = TypeAdapter(StructuredValue)@@ -54,14 +54,29 @@ def _schema_mismatch_hint(actual: int, expected: int) -> str:"""steps = ", ".join(f"upgrade_v{v}_to_v{v + 1}_op()" for v in range(actual, expected))return (- "cubepi was upgraded but host alembic is behind. "+ "cubeloop was upgraded but host alembic is behind. "f"Generate a new alembic revision that calls {steps} + ""write_schema_version_op() (see "- "cubepi.checkpointer.postgres.alembic_helpers) and run "+ "cubeloop.checkpointer.postgres.alembic_helpers) and run ""`alembic upgrade head` against this database.")+_V5_TO_V6_HINT = (+ "Generate a new alembic revision that calls "+ "upgrade_v5_to_v6_op() + write_schema_version_op() "+ "(see cubeloop.checkpointer.postgres.alembic_helpers) and run "+ "`alembic upgrade head` against this database."+)++_MISSING_VERSION_TABLE_HINT = (+ "data tables exist but schema_version is missing; cannot auto-classify. "+ "If tables are still cubepi_*, CREATE TABLE cubepi_schema_version and "+ "INSERT 5, then run upgrade_v5_to_v6_op(). Do not apply fresh v6 "+ "CREATE TABLE on existing data."+)++def _serialize_structured_value(value: StructuredValue) -> str:return _STRUCTURED_VALUE_ADAPTER.dump_json(value).decode("utf-8")@@ -90,7 +105,7 @@ _ROLE_TO_CLS: dict[str, type[Message]] = {def _deserialize_row(thread_id: str, r: Any) -> Message:- """Deserialize one cubepi_messages row; corruption raises typed."""+ """Deserialize one cubeloop_messages row; corruption raises typed."""try:cls = _ROLE_TO_CLS.get(r["role"])if cls is None:@@ -107,7 +122,7 @@ def _deserialize_row(thread_id: str, r: Any) -> Message:raise CheckpointCorruptionError(thread_id=thread_id,backend="postgres",- row_ref=f"cubepi_messages.seq={r['seq']}",+ row_ref=f"cubeloop_messages.seq={r['seq']}",cause=exc,) from exc@@ -157,19 +172,42 @@ class PostgresCheckpointer:async with self._pool.acquire() as conn:try:row = await conn.fetchrow(- "SELECT version FROM cubepi_schema_version LIMIT 1"+ "SELECT version FROM cubeloop_schema_version LIMIT 1"+ )+ except asyncpg.UndefinedTableError:+ try:+ legacy = await conn.fetchrow(+ "SELECT version FROM cubepi_schema_version LIMIT 1"+ )+ except asyncpg.UndefinedTableError as e:+ has_data = await conn.fetchval(+ "SELECT to_regclass('cubepi_threads') IS NOT NULL "+ "OR to_regclass('cubeloop_threads') IS NOT NULL"+ )+ if has_data:+ raise CubeloopSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=0,+ hint=_MISSING_VERSION_TABLE_HINT,+ ) from e+ raise CubeloopSchemaUninitialized(+ "cubeloop tables not found. Run host application's "+ "alembic upgrade."+ ) from e+ actual = 0 if legacy is None else int(legacy["version"])+ raise CubeloopSchemaMismatch(+ expected=EXPECTED_SCHEMA_VERSION,+ actual=actual,+ hint=_V5_TO_V6_HINT,)- except asyncpg.UndefinedTableError as e:- raise CubepiSchemaUninitialized(- "cubepi tables not found. Run host application's alembic upgrade."- ) from eif row is None:- raise CubepiSchemaUninitialized(- "cubepi_schema_version table is empty. Host alembic migration "- "must INSERT the current version (use write_schema_version_op())."+ raise CubeloopSchemaUninitialized(+ "cubeloop_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(+ raise CubeloopSchemaMismatch(expected=EXPECTED_SCHEMA_VERSION,actual=row["version"],hint=_schema_mismatch_hint(row["version"], EXPECTED_SCHEMA_VERSION),@@ -179,12 +217,12 @@ class PostgresCheckpointer:assert self._pool is not Noneasync with self._pool.acquire() as conn:msg_rows = await conn.fetch(- "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "SELECT seq, role, metadata, payload FROM cubeloop_messages ""WHERE thread_id = $1 ORDER BY seq",thread_id,)extra_row = await conn.fetchrow(- "SELECT extra, parent_thread_id FROM cubepi_threads "+ "SELECT extra, parent_thread_id FROM cubeloop_threads ""WHERE thread_id = $1",thread_id,)@@ -226,14 +264,14 @@ class PostgresCheckpointer:)# Lazy thread row creationawait conn.execute(- "INSERT INTO cubepi_threads (thread_id) "+ "INSERT INTO cubeloop_threads (thread_id) ""VALUES ($1) ON CONFLICT DO NOTHING",thread_id,)# Pre-flight: reject append on any completed run_id.if run_ids:done_rows = await conn.fetch(- "SELECT run_id FROM cubepi_runs "+ "SELECT run_id FROM cubeloop_runs ""WHERE thread_id = $1 AND run_id = ANY($2::text[]) ""AND completed_at IS NOT NULL",thread_id,@@ -246,7 +284,7 @@ class PostgresCheckpointer:)last_seq = (await conn.fetchval(- "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "+ "SELECT COALESCE(MAX(seq), 0) FROM cubeloop_messages ""WHERE thread_id = $1",thread_id,)@@ -270,7 +308,7 @@ class PostgresCheckpointer:))await conn.executemany(- "INSERT INTO cubepi_messages "+ "INSERT INTO cubeloop_messages ""(thread_id, seq, role, metadata, payload, run_id) ""VALUES ($1, $2, $3, $4, $5, $6)",rows,@@ -286,7 +324,7 @@ class PostgresCheckpointer:)# Lazy thread row creation (claim may precede any append).await conn.execute(- "INSERT INTO cubepi_threads (thread_id) "+ "INSERT INTO cubeloop_threads (thread_id) ""VALUES ($1) ON CONFLICT (thread_id) DO NOTHING",thread_id,)@@ -294,7 +332,7 @@ class PostgresCheckpointer:# raise UniqueViolation (which would abort the txn before# we could distinguish in-flight vs completed).row = await conn.fetchrow(- "SELECT completed_at FROM cubepi_runs "+ "SELECT completed_at FROM cubeloop_runs ""WHERE thread_id = $1 AND run_id = $2",thread_id,run_id,@@ -308,7 +346,7 @@ class PostgresCheckpointer:f"thread={thread_id} run={run_id} in flight")await conn.execute(- "INSERT INTO cubepi_runs (thread_id, run_id) VALUES ($1, $2)",+ "INSERT INTO cubeloop_runs (thread_id, run_id) VALUES ($1, $2)",thread_id,run_id,)@@ -322,7 +360,7 @@ class PostgresCheckpointer:thread_id,)row = await conn.fetchrow(- "SELECT completed_at FROM cubepi_runs "+ "SELECT completed_at FROM cubeloop_runs ""WHERE thread_id = $1 AND run_id = $2",thread_id,run_id,@@ -335,12 +373,12 @@ class PostgresCheckpointer:return # idempotent successnext_seq = await conn.fetchval("SELECT COALESCE(MAX(completion_seq), 0) + 1 "- "FROM cubepi_runs WHERE thread_id = $1 "+ "FROM cubeloop_runs WHERE thread_id = $1 ""AND completion_seq IS NOT NULL",thread_id,)await conn.execute(- "UPDATE cubepi_runs SET completed_at = now(), "+ "UPDATE cubeloop_runs SET completed_at = now(), ""completion_seq = $3 ""WHERE thread_id = $1 AND run_id = $2",thread_id,@@ -354,7 +392,7 @@ class PostgresCheckpointer:assert self._pool is not Noneasync with self._pool.acquire() as conn:row = await conn.fetchrow(- "SELECT pending_request, run_id FROM cubepi_threads "+ "SELECT pending_request, run_id FROM cubeloop_threads ""WHERE thread_id = $1",thread_id,)@@ -372,13 +410,13 @@ class PostgresCheckpointer:async with self._pool.acquire() as conn:# Source thread must exist.t_row = await conn.fetchrow(- "SELECT 1 FROM cubepi_threads WHERE thread_id = $1",+ "SELECT 1 FROM cubeloop_threads WHERE thread_id = $1",thread_id,)if t_row is None:raise ThreadNotFoundError(f"thread={thread_id}")cutoff = await conn.fetchval(- "SELECT completion_seq FROM cubepi_runs "+ "SELECT completion_seq FROM cubeloop_runs ""WHERE thread_id = $1 AND run_id = $2",thread_id,after_run_id,@@ -388,10 +426,10 @@ class PostgresCheckpointer:f"thread={thread_id} run={after_run_id} not completed")rows = await conn.fetch(- "SELECT seq, role, metadata, payload FROM cubepi_messages "+ "SELECT seq, role, metadata, payload FROM cubeloop_messages ""WHERE thread_id = $1 AND ("" run_id IS NULL OR run_id IN ("- " SELECT run_id FROM cubepi_runs "+ " SELECT run_id FROM cubeloop_runs "" WHERE thread_id = $1 "" AND completion_seq IS NOT NULL "" AND completion_seq <= $2"@@ -423,21 +461,21 @@ class PostgresCheckpointer:# / claim_run / save_extra / save_pending_request — so its# presence is the canonical "thread exists" gate).t_row = await conn.fetchrow(- "SELECT 1 FROM cubepi_threads WHERE thread_id = $1",+ "SELECT 1 FROM cubeloop_threads WHERE thread_id = $1",src_thread_id,)if t_row is None:raise ThreadNotFoundError(f"thread={src_thread_id}")# Destination must not exist.dst_row = await conn.fetchrow(- "SELECT 1 FROM cubepi_threads WHERE thread_id = $1",+ "SELECT 1 FROM cubeloop_threads WHERE thread_id = $1",new_thread_id,)if dst_row is not None:raise ThreadAlreadyExistsError(f"thread={new_thread_id}")# Cutoff: after_run_id must be completed on src.cutoff = await conn.fetchval(- "SELECT completion_seq FROM cubepi_runs "+ "SELECT completion_seq FROM cubeloop_runs ""WHERE thread_id = $1 AND run_id = $2",src_thread_id,after_run_id,@@ -448,7 +486,7 @@ class PostgresCheckpointer:)# Build merged extra (carry parent's extra + fork metadata).src_extra_row = await conn.fetchrow(- "SELECT extra FROM cubepi_threads WHERE thread_id = $1",+ "SELECT extra FROM cubeloop_threads WHERE thread_id = $1",src_thread_id,)raw_extra = (@@ -461,9 +499,9 @@ class PostgresCheckpointer:if metadata is not None:base_extra["fork"] = json.loads(json.dumps(metadata))# INSERT destination threads row first to satisfy the- # cubepi_messages / cubepi_runs FKs on subsequent copies.+ # cubeloop_messages / cubeloop_runs FKs on subsequent copies.await conn.execute(- "INSERT INTO cubepi_threads "+ "INSERT INTO cubeloop_threads ""(thread_id, parent_thread_id, forked_at_seq, extra) ""VALUES ($1, $2, $3, $4::jsonb)",new_thread_id,@@ -474,13 +512,13 @@ class PostgresCheckpointer:# Copy messages whose run is NULL (legacy prefix) or completed# at or before cutoff. Preserve seq from the source.await conn.execute(- "INSERT INTO cubepi_messages "+ "INSERT INTO cubeloop_messages ""(thread_id, seq, role, metadata, payload, run_id) ""SELECT $1, seq, role, metadata, payload, run_id "- "FROM cubepi_messages "+ "FROM cubeloop_messages ""WHERE thread_id = $2 AND ("" run_id IS NULL OR run_id IN ("- " SELECT run_id FROM cubepi_runs "+ " SELECT run_id FROM cubeloop_runs "" WHERE thread_id = $2 "" AND completion_seq IS NOT NULL "" AND completion_seq <= $3"@@ -492,10 +530,10 @@ class PostgresCheckpointer:)# Copy completed runs satisfying the cutoff.await conn.execute(- "INSERT INTO cubepi_runs "+ "INSERT INTO cubeloop_runs ""(thread_id, run_id, claimed_at, completed_at, completion_seq) ""SELECT $1, run_id, claimed_at, completed_at, completion_seq "- "FROM cubepi_runs "+ "FROM cubeloop_runs ""WHERE thread_id = $2 ""AND completion_seq IS NOT NULL ""AND completion_seq <= $3",@@ -508,10 +546,10 @@ class PostgresCheckpointer:assert self._pool is not Noneasync with self._pool.acquire() as conn:await conn.execute(- "INSERT INTO cubepi_threads (thread_id, extra, updated_at) "+ "INSERT INTO cubeloop_threads (thread_id, extra, updated_at) ""VALUES ($1, $2::jsonb, now()) ""ON CONFLICT (thread_id) DO UPDATE "- "SET extra = cubepi_threads.extra || EXCLUDED.extra, "+ "SET extra = cubeloop_threads.extra || EXCLUDED.extra, "" updated_at = now()",thread_id,json.dumps(extra),@@ -538,13 +576,13 @@ class PostgresCheckpointer:async with conn.transaction():# Ensure thread row exists (lazy creation matches save_extra path).await conn.execute(- "INSERT INTO cubepi_threads (thread_id) "+ "INSERT INTO cubeloop_threads (thread_id) ""VALUES ($1) ON CONFLICT DO NOTHING",thread_id,)if request is None:await conn.execute(- "UPDATE cubepi_threads "+ "UPDATE cubeloop_threads ""SET pending_request = NULL, run_id = NULL, ""updated_at = now() WHERE thread_id = $1",thread_id,@@ -552,7 +590,7 @@ class PostgresCheckpointer:else:payload = request.model_dump_json()await conn.execute(- "UPDATE cubepi_threads "+ "UPDATE cubeloop_threads ""SET pending_request = $2::jsonb, run_id = $3, ""updated_at = now() WHERE thread_id = $1",thread_id,@@ -564,7 +602,7 @@ class PostgresCheckpointer:assert self._pool is not Noneasync with self._pool.acquire() as conn:row = await conn.fetchrow(- "SELECT pending_request FROM cubepi_threads WHERE thread_id = $1",+ "SELECT pending_request FROM cubeloop_threads WHERE thread_id = $1",thread_id,)if row is None or row["pending_request"] is None:@@ -586,7 +624,7 @@ class PostgresCheckpointer:assert self._pool is not Noneasync with self._pool.acquire() as conn:row = await conn.fetchrow(- "SELECT run_id FROM cubepi_threads "+ "SELECT run_id FROM cubeloop_threads ""WHERE thread_id = $1 AND pending_request IS NOT NULL",thread_id,)@@ -605,12 +643,12 @@ class PostgresCheckpointer:async with self._pool.acquire() as conn:async with conn.transaction():await conn.execute(- "INSERT INTO cubepi_threads (thread_id) "+ "INSERT INTO cubeloop_threads (thread_id) ""VALUES ($1) ON CONFLICT DO NOTHING",thread_id,)await conn.execute(- "INSERT INTO cubepi_hitl_answers "+ "INSERT INTO cubeloop_hitl_answers ""(thread_id, run_id, question_id, answer) ""VALUES ($1, $2, $3, $4::jsonb) ""ON CONFLICT (thread_id, run_id, question_id) DO UPDATE "@@ -631,7 +669,7 @@ class PostgresCheckpointer:assert self._pool is not Noneasync with self._pool.acquire() as conn:row = await conn.fetchrow(- "SELECT answer FROM cubepi_hitl_answers "+ "SELECT answer FROM cubeloop_hitl_answers ""WHERE thread_id = $1 AND run_id = $2 AND question_id = $3",thread_id,_run_key(run_id),@@ -653,7 +691,7 @@ class PostgresCheckpointer:async with self._pool.acquire() as conn:if question_ids is None:await conn.execute(- "DELETE FROM cubepi_hitl_answers "+ "DELETE FROM cubeloop_hitl_answers ""WHERE thread_id = $1 AND run_id = $2",thread_id,run_key,@@ -663,7 +701,7 @@ class PostgresCheckpointer:if not qids:returnawait conn.execute(- "DELETE FROM cubepi_hitl_answers "+ "DELETE FROM cubeloop_hitl_answers ""WHERE thread_id = $1 AND run_id = $2 ""AND question_id = ANY($3::text[])",thread_id,diff --git a/cubeloop/checkpointer/postgres/exceptions.py b/cubeloop/checkpointer/postgres/exceptions.pynew file mode 100644index 0000000..a046520--- /dev/null+++ b/cubeloop/checkpointer/postgres/exceptions.py@@ -0,0 +1,17 @@+"""Exceptions raised by PostgresCheckpointer schema verification.++Re-exported from the backend-agnostic ``cubeloop.checkpointer.exceptions`` so+the same classes are shared with the MySQL checkpointer.+"""++from cubeloop.checkpointer.exceptions import (+ CubeloopSchemaError,+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,+)++__all__ = [+ "CubeloopSchemaError",+ "CubeloopSchemaMismatch",+ "CubeloopSchemaUninitialized",+]diff --git a/cubepi/checkpointer/postgres/models.py b/cubeloop/checkpointer/postgres/models.pysimilarity index 80%rename from cubepi/checkpointer/postgres/models.pyrename to cubeloop/checkpointer/postgres/models.pyindex ed8a516..fcc4edb 100644--- a/cubepi/checkpointer/postgres/models.py+++ b/cubeloop/checkpointer/postgres/models.py@@ -15,23 +15,23 @@ import sqlalchemy as safrom sqlalchemy.dialects.postgresql import JSONBfrom sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column-EXPECTED_SCHEMA_VERSION = 5+EXPECTED_SCHEMA_VERSION = 6PARTITION_COUNT = 64-cubepi_metadata = sa.MetaData()+cubeloop_metadata = sa.MetaData()-class CubepiBase(DeclarativeBase):- metadata = cubepi_metadata+class CubeloopBase(DeclarativeBase):+ metadata = cubeloop_metadata-class CubepiThread(CubepiBase):- __tablename__ = "cubepi_threads"+class CubeloopThread(CubeloopBase):+ __tablename__ = "cubeloop_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"),+ sa.ForeignKey("cubeloop_threads.thread_id"),nullable=True,)forked_at_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)@@ -66,22 +66,22 @@ class CubepiThread(CubepiBase):)-class CubepiMessage(CubepiBase):- __tablename__ = "cubepi_messages"+class CubeloopMessage(CubeloopBase):+ __tablename__ = "cubeloop_messages"__table_args__ = (sa.Index(- "ix_cubepi_messages_metadata_gin",+ "ix_cubeloop_messages_metadata_gin","metadata",postgresql_using="gin",postgresql_ops={"metadata": "jsonb_path_ops"},),- sa.Index("ix_cubepi_messages_thread_run", "thread_id", "run_id"),+ sa.Index("ix_cubeloop_messages_thread_run", "thread_id", "run_id"),{"postgresql_partition_by": "HASH (thread_id)"},)thread_id: Mapped[str] = mapped_column(sa.Text,- sa.ForeignKey("cubepi_threads.thread_id", ondelete="CASCADE"),+ sa.ForeignKey("cubeloop_threads.thread_id", ondelete="CASCADE"),primary_key=True,)seq: Mapped[int] = mapped_column(sa.BigInteger, primary_key=True)@@ -106,15 +106,15 @@ class CubepiMessage(CubepiBase):)-class CubepiRun(CubepiBase):- __tablename__ = "cubepi_runs"+class CubeloopRun(CubeloopBase):+ __tablename__ = "cubeloop_runs"__table_args__ = (- sa.Index("ix_cubepi_runs_thread_seq", "thread_id", "completion_seq"),+ sa.Index("ix_cubeloop_runs_thread_seq", "thread_id", "completion_seq"),{"postgresql_partition_by": "HASH (thread_id)"},)thread_id: Mapped[str] = mapped_column(sa.Text,- sa.ForeignKey("cubepi_threads.thread_id", ondelete="CASCADE"),+ sa.ForeignKey("cubeloop_threads.thread_id", ondelete="CASCADE"),primary_key=True,)run_id: Mapped[str] = mapped_column(sa.Text, primary_key=True)@@ -129,12 +129,12 @@ class CubepiRun(CubepiBase):completion_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)-class CubepiHitlAnswer(CubepiBase):- __tablename__ = "cubepi_hitl_answers"+class CubeloopHitlAnswer(CubeloopBase):+ __tablename__ = "cubeloop_hitl_answers"thread_id: Mapped[str] = mapped_column(sa.Text,- sa.ForeignKey("cubepi_threads.thread_id", ondelete="CASCADE"),+ sa.ForeignKey("cubeloop_threads.thread_id", ondelete="CASCADE"),primary_key=True,)run_id: Mapped[str] = mapped_column(sa.Text, primary_key=True)@@ -147,7 +147,7 @@ class CubepiHitlAnswer(CubepiBase):)-class CubepiSchemaVersion(CubepiBase):- __tablename__ = "cubepi_schema_version"+class CubeloopSchemaVersion(CubeloopBase):+ __tablename__ = "cubeloop_schema_version"version: Mapped[int] = mapped_column(sa.Integer, primary_key=True)diff --git a/cubepi/checkpointer/sqlite.py b/cubeloop/checkpointer/sqlite.pysimilarity index 98%rename from cubepi/checkpointer/sqlite.pyrename to cubeloop/checkpointer/sqlite.pyindex 8d54a3c..6f6f4a9 100644--- a/cubepi/checkpointer/sqlite.py+++ b/cubeloop/checkpointer/sqlite.py@@ -9,8 +9,8 @@ from typing import Any, AsyncIterator, castimport aiosqlitefrom pydantic import TypeAdapter-from cubepi.checkpointer.base import CheckpointData-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.base import CheckpointData+from cubeloop.checkpointer.exceptions import (CheckpointCorruptionError,CheckpointerLockTimeoutError,RunAlreadyClaimedError,@@ -20,14 +20,14 @@ from cubepi.checkpointer.exceptions import (ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.hitl.types import HitlRequest-from cubepi.providers.base import (+from cubeloop.hitl.types import HitlRequest+from cubeloop.providers.base import (AssistantMessage,Message,ToolResultMessage,UserMessage,)-from cubepi.types import JsonObject, StructuredValue+from cubeloop.types import JsonObject, StructuredValue_STRUCTURED_VALUE_ADAPTER: TypeAdapter[Any] = TypeAdapter(StructuredValue)diff --git a/cubeloop/cli/__init__.py b/cubeloop/cli/__init__.pynew file mode 100644index 0000000..cdaa4c5--- /dev/null+++ b/cubeloop/cli/__init__.py@@ -0,0 +1 @@+"""cubeloop command-line interface."""diff --git a/cubepi/cli/__main__.py b/cubeloop/cli/__main__.pysimilarity index 74%rename from cubepi/cli/__main__.pyrename to cubeloop/cli/__main__.pyindex 096a95e..b277243 100644--- a/cubepi/cli/__main__.py+++ b/cubeloop/cli/__main__.py@@ -1,4 +1,4 @@-"""Entry point for the ``cubepi`` console script."""+"""Entry point for the ``cubeloop`` console script."""from __future__ import annotations@@ -6,11 +6,11 @@ import argparseimport sysfrom collections.abc import Sequence-from cubepi.cli.trace import commands as trace_commands+from cubeloop.cli.trace import commands as trace_commandsdef build_parser() -> argparse.ArgumentParser:- parser = argparse.ArgumentParser(prog="cubepi")+ parser = argparse.ArgumentParser(prog="cubeloop")sub = parser.add_subparsers(dest="group", required=True)trace_commands.register(sub)return parser@@ -23,7 +23,7 @@ def main(argv: Sequence[str] | None = None) -> int:if handler is None:parser.print_help()return 2- from cubepi.cli.trace.render import RichMissingError+ from cubeloop.cli.trace.render import RichMissingErrortry:return handler(args)diff --git a/cubeloop/cli/trace/__init__.py b/cubeloop/cli/trace/__init__.pynew file mode 100644index 0000000..876120b--- /dev/null+++ b/cubeloop/cli/trace/__init__.py@@ -0,0 +1 @@+"""`cubeloop trace` — read JSONL spans written by JsonlSpanExporter."""diff --git a/cubepi/cli/trace/commands.py b/cubeloop/cli/trace/commands.pysimilarity index 94%rename from cubepi/cli/trace/commands.pyrename to cubeloop/cli/trace/commands.pyindex 2d8434f..de2e789 100644--- a/cubepi/cli/trace/commands.py+++ b/cubeloop/cli/trace/commands.py@@ -1,17 +1,17 @@-"""argparse wiring for `cubepi trace`."""+"""argparse wiring for `cubeloop trace`."""from __future__ import annotationsimport argparsefrom pathlib import Path-from cubepi.cli.trace import loader, render, stats-from cubepi.cli.trace.follow import follow_run-from cubepi.cli.trace.model import build_forest+from cubeloop.cli.trace import loader, render, stats+from cubeloop.cli.trace.follow import follow_run+from cubeloop.cli.trace.model import build_forestdef register(subparsers: "argparse._SubParsersAction") -> None:- trace = subparsers.add_parser("trace", help="inspect cubepi JSONL traces")+ trace = subparsers.add_parser("trace", help="inspect cubeloop JSONL traces")trace_sub = trace.add_subparsers(dest="trace_cmd", required=True)p_ls = trace_sub.add_parser("ls", help="list recent runs")@@ -48,7 +48,7 @@ def register(subparsers: "argparse._SubParsersAction") -> None:)p_follow.set_defaults(handler=cmd_follow)- from cubepi.cli.trace.convert import cmd_convert+ from cubeloop.cli.trace.convert import cmd_convertp_convert = trace_sub.add_parser("convert", help="reconstruct API request body from a recorded chat span"@@ -89,7 +89,7 @@ def _add_dir(parser: argparse.ArgumentParser) -> None:parser.add_argument("--dir",default=str(loader.DEFAULT_DIR),- help="traces directory (default: ./cubepi-traces)",+ help="traces directory (default: ./cubeloop-traces)",)diff --git a/cubepi/cli/trace/convert.py b/cubeloop/cli/trace/convert.pysimilarity index 98%rename from cubepi/cli/trace/convert.pyrename to cubeloop/cli/trace/convert.pyindex 791dad9..1d6835b 100644--- a/cubepi/cli/trace/convert.py+++ b/cubeloop/cli/trace/convert.py@@ -1,4 +1,4 @@-"""cubepi trace convert — reconstruct an API request body from a recorded chat span."""+"""cubeloop trace convert — reconstruct an API request body from a recorded chat span."""from __future__ import annotations@@ -7,8 +7,8 @@ import jsonfrom pathlib import Pathfrom typing import Any-from cubepi.cli.trace import loader-from cubepi.tracing import schema+from cubeloop.cli.trace import loader+from cubeloop.tracing import schemadef cmd_convert(args: argparse.Namespace) -> int:diff --git a/cubepi/cli/trace/follow.py b/cubeloop/cli/trace/follow.pysimilarity index 98%rename from cubepi/cli/trace/follow.pyrename to cubeloop/cli/trace/follow.pyindex 3fc7dde..8a3779f 100644--- a/cubepi/cli/trace/follow.py+++ b/cubeloop/cli/trace/follow.py@@ -14,7 +14,7 @@ from collections.abc import Callablefrom pathlib import Pathfrom typing import Any-from cubepi.cli.trace.model import Span+from cubeloop.cli.trace.model import Spandef iter_new_spans(path: Path, state: dict[str, Any]):diff --git a/cubepi/cli/trace/loader.py b/cubeloop/cli/trace/loader.pysimilarity index 92%rename from cubepi/cli/trace/loader.pyrename to cubeloop/cli/trace/loader.pyindex 44c3bbd..2e732ee 100644--- a/cubepi/cli/trace/loader.py+++ b/cubeloop/cli/trace/loader.py@@ -7,16 +7,14 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom pathlib import Path-from cubepi.cli.trace.model import Span-from cubepi.tracing import schema+from cubeloop.cli.trace.model import Span+from cubeloop.tracing import schema-DEFAULT_DIR = Path("./cubepi-traces")+DEFAULT_DIR = Path("./cubeloop-traces")_MIN = datetime.min.replace(tzinfo=timezone.utc)-# Run-scoped metadata is stamped by the recorder as ``cubepi.metadata.<key>``-# attributes on the root invoke_agent span (set via-# ``cubepi.tracing.tracing_context(metadata=...)``).-_META_PREFIX = "cubepi.metadata."+# Run-scoped metadata is stamped as ``cubeloop.metadata.<key>`` (0.13: cubepi.metadata.*).+_META_PREFIXES = ("cubeloop.metadata.", "cubepi.metadata.")def _root_span(spans: list[Span]) -> Span | None:@@ -27,16 +25,18 @@ def _root_span(spans: list[Span]) -> Span | None:def _run_metadata(spans: list[Span]) -> dict[str, str]:- """The ``cubepi.metadata.*`` attributes off the trace's root span, with the+ """The ``cubeloop.metadata.*`` attributes off the trace's root span, with theprefix stripped and values stringified. Empty when none were recorded."""root = _root_span(spans)if root is None:return {}- return {- k[len(_META_PREFIX) :]: str(v)- for k, v in root.attributes.items()- if k.startswith(_META_PREFIX)- }+ out: dict[str, str] = {}+ for k, v in root.attributes.items():+ for prefix in _META_PREFIXES:+ if k.startswith(prefix):+ out[k[len(prefix) :]] = str(v)+ break+ return outdef _meta_matches(have: dict[str, str], want: dict[str, str]) -> bool:@@ -92,7 +92,7 @@ def resolve_run(arg: str, directory: Path) -> list[Path]:f"trace prefix {arg!r} is ambiguous under {directory}: matches {candidates}")raise RunResolutionError(- f"no trace file for trace {arg!r} under {directory} (try `cubepi trace ls`)"+ f"no trace file for trace {arg!r} under {directory} (try `cubeloop trace ls`)")diff --git a/cubepi/cli/trace/model.py b/cubeloop/cli/trace/model.pysimilarity index 92%rename from cubepi/cli/trace/model.pyrename to cubeloop/cli/trace/model.pyindex 0f4d426..4656d6f 100644--- a/cubepi/cli/trace/model.py+++ b/cubeloop/cli/trace/model.py@@ -6,7 +6,7 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom typing import Any-from cubepi.tracing import schema+from cubeloop.tracing import schema_EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)@@ -94,21 +94,22 @@ class Span:@propertydef is_aborted(self) -> bool:- # The recorder sets a boolean cubepi.aborted attribute (and also an- # error.type="cubepi.aborted" string). The boolean is the canonical+ # The recorder sets a boolean cubeloop.aborted attribute (and also an+ # error.type="cubeloop.aborted" string). The boolean is the canonical# signal; OTel status stays UNSET for aborts, so don't gate on status.- return self.attributes.get(schema.CUBEPI_ABORTED) is True+ return schema.is_aborted_attrs(self.attributes)@propertydef run_id(self) -> str | None:- return self.attributes.get(schema.CUBEPI_RUN_ID)+ value = schema.attr(self.attributes, schema.CUBELOOP_RUN_ID)+ return None if value is None else str(value)@propertydef operation(self) -> str | None:"""gen_ai.operation.name — the reliable span classifier.Span *names* carry suffixes ("chat <model>", "execute_tool <tool>"),- so classify on this attribute, not on ``name``. The cubepi.turn span+ so classify on this attribute, not on ``name``. The cubeloop.turn spanhas no operation name."""return self.attributes.get(schema.GEN_AI_OPERATION_NAME)diff --git a/cubepi/cli/trace/render.py b/cubeloop/cli/trace/render.pysimilarity index 95%rename from cubepi/cli/trace/render.pyrename to cubeloop/cli/trace/render.pyindex 267bb2d..c5629b9 100644--- a/cubepi/cli/trace/render.py+++ b/cubeloop/cli/trace/render.py@@ -6,10 +6,10 @@ from __future__ import annotationsimport jsonfrom typing import TYPE_CHECKING-from cubepi.cli.trace.loader import RunSummary-from cubepi.cli.trace.model import Span, TreeNode-from cubepi.cli.trace.stats import StatRow-from cubepi.tracing import schema+from cubeloop.cli.trace.loader import RunSummary+from cubeloop.cli.trace.model import Span, TreeNode+from cubeloop.cli.trace.stats import StatRow+from cubeloop.tracing import schemaif TYPE_CHECKING: # pragma: no coverfrom rich.console import Console@@ -24,7 +24,7 @@ def _require_rich() -> None:import rich # noqa: F401except ImportError as exc: # pragma: no coverraise RichMissingError(- "this command needs rich. Install it via: pip install cubepi[trace-cli]"+ "this command needs rich. Install it via: pip install cubeloop[trace-cli]") from exc@@ -132,7 +132,7 @@ def render_runs(runs: list[RunSummary], show_meta: list[str] | None = None) -> Nshow_meta = show_meta or []console = _console()- table = Table(title="cubepi runs")+ table = Table(title="cubeloop runs")for col in ("started", "trace_id", "spans", "status", "duration"):table.add_column(col)for key in show_meta:diff --git a/cubepi/cli/trace/stats.py b/cubeloop/cli/trace/stats.pysimilarity index 97%rename from cubepi/cli/trace/stats.pyrename to cubeloop/cli/trace/stats.pyindex ea97b00..37999b2 100644--- a/cubepi/cli/trace/stats.py+++ b/cubeloop/cli/trace/stats.py@@ -4,8 +4,8 @@ from __future__ import annotationsfrom dataclasses import dataclass-from cubepi.cli.trace.model import Span-from cubepi.tracing import schema+from cubeloop.cli.trace.model import Span+from cubeloop.tracing import schema@dataclassdiff --git a/cubepi/deferred/__init__.py b/cubeloop/deferred/__init__.pysimilarity index 55%rename from cubepi/deferred/__init__.pyrename to cubeloop/deferred/__init__.pyindex 88189d8..a3d2f4b 100644--- a/cubepi/deferred/__init__.py+++ b/cubeloop/deferred/__init__.py@@ -1,7 +1,7 @@"""Deferred tool groups — progressive tool disclosure primitive."""-from cubepi.deferred.middleware import DeferredToolsMiddleware, ResumedState-from cubepi.deferred.types import DeferredStrategy, DeferredToolGroup+from cubeloop.deferred.middleware import DeferredToolsMiddleware, ResumedState+from cubeloop.deferred.types import DeferredStrategy, DeferredToolGroup__all__ = ["DeferredStrategy",diff --git a/cubepi/deferred/_catalog.py b/cubeloop/deferred/_catalog.pysimilarity index 97%rename from cubepi/deferred/_catalog.pyrename to cubeloop/deferred/_catalog.pyindex c4f3ffc..66137f5 100644--- a/cubepi/deferred/_catalog.py+++ b/cubeloop/deferred/_catalog.py@@ -1,6 +1,6 @@from __future__ import annotations-from cubepi.deferred.types import DeferredToolGroup+from cubeloop.deferred.types import DeferredToolGroupDEFAULT_CATALOG_HEADER = ("# Deferred tool groups\n"diff --git a/cubepi/deferred/_dispatch_tool.py b/cubeloop/deferred/_dispatch_tool.pysimilarity index 93%rename from cubepi/deferred/_dispatch_tool.pyrename to cubeloop/deferred/_dispatch_tool.pyindex 937e2b5..186a73d 100644--- a/cubepi/deferred/_dispatch_tool.py+++ b/cubeloop/deferred/_dispatch_tool.py@@ -6,9 +6,9 @@ from typing import Anyfrom pydantic import BaseModel, Field-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import TextContent-from cubepi.types import StructuredValue+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import TextContent+from cubeloop.types import StructuredValueDISPATCH_TOOL_NAME = "deferred_tool_call"diff --git a/cubepi/deferred/_expand_tool.py b/cubeloop/deferred/_expand_tool.pysimilarity index 93%rename from cubepi/deferred/_expand_tool.pyrename to cubeloop/deferred/_expand_tool.pyindex 7fa219f..ae030e1 100644--- a/cubepi/deferred/_expand_tool.py+++ b/cubeloop/deferred/_expand_tool.py@@ -6,9 +6,9 @@ from collections.abc import Awaitable, Callablefrom pydantic import BaseModel, Field-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import TextContent-from cubepi.types import StructuredValue+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import TextContent+from cubeloop.types import StructuredValueTOOL_NAME = "load_tools"diff --git a/cubepi/deferred/middleware.py b/cubeloop/deferred/middleware.pysimilarity index 98%rename from cubepi/deferred/middleware.pyrename to cubeloop/deferred/middleware.pyindex 9ed702d..c939433 100644--- a/cubepi/deferred/middleware.py+++ b/cubeloop/deferred/middleware.py@@ -27,30 +27,30 @@ from collections.abc import Callablefrom dataclasses import dataclass, replacefrom typing import Any-from cubepi.agent.types import (+from cubeloop.agent.types import (AfterToolCallContext,AfterToolCallResult,AgentContext,AgentTool,)-from cubepi.deferred._catalog import (+from cubeloop.deferred._catalog import (DEFAULT_CATALOG_HEADER,DEFAULT_DISPATCH_CATALOG_HEADER,render_catalog,render_static_catalog,)-from cubepi.deferred._dispatch_tool import (+from cubeloop.deferred._dispatch_tool import (DISPATCH_TOOL_NAME,_make_deferred_tool_call,)-from cubepi.deferred._expand_tool import (+from cubeloop.deferred._expand_tool import (TOOL_NAME,LoadToolsOutput,_make_load_tools,)-from cubepi.deferred.types import DeferredStrategy, DeferredToolGroup-from cubepi.middleware.base import Middleware-from cubepi.providers.base import ToolCall+from cubeloop.deferred.types import DeferredStrategy, DeferredToolGroup+from cubeloop.middleware.base import Middleware+from cubeloop.providers.base import ToolCall@dataclassdiff --git a/cubepi/deferred/types.py b/cubeloop/deferred/types.pysimilarity index 95%rename from cubepi/deferred/types.pyrename to cubeloop/deferred/types.pyindex 8308d50..faf1133 100644--- a/cubepi/deferred/types.py+++ b/cubeloop/deferred/types.py@@ -4,7 +4,7 @@ from collections.abc import Awaitable, Callablefrom dataclasses import dataclassfrom typing import Literal-from cubepi.agent.types import AgentTool+from cubeloop.agent.types import AgentTool# "dispatch" (default): static tools array + system prompt; schemas delivered# via load_tools results; calls routed through the deferred_tool_calldiff --git a/cubepi/errors.py b/cubeloop/errors.pysimilarity index 98%rename from cubepi/errors.pyrename to cubeloop/errors.pyindex e87be65..0785049 100644--- a/cubepi/errors.py+++ b/cubeloop/errors.py@@ -1,7 +1,7 @@"""Typed provider errors.cubepi providers catch raw SDK exceptions and re-raise as one of these-subclasses, so downstream callers can ``except cubepi.errors.X`` instead+subclasses, so downstream callers can ``except cubeloop.errors.X`` insteadof pattern-matching on SDK-specific strings or status codes.Adding a new subclass: add it at the bottom of the file (never reorder)@@ -14,14 +14,14 @@ import mathimport refrom typing import NoReturn, Protocol-from cubepi.providers.base import Message+from cubeloop.providers.base import Messageclass _ClassifyTarget(Protocol):"""Structural type for the `model` parameter of `classify_and_raise`.- Both `cubepi.providers.base.Model` and- `cubepi.providers.images.types.ImagesModel` satisfy it; `context_window`+ Both `cubeloop.providers.base.Model` and+ `cubeloop.providers.images.types.ImagesModel` satisfy it; `context_window`is read with a getattr fallback so image models (which don't have it)skip the token-budget heuristic cleanly."""diff --git a/cubepi/hitl/__init__.py b/cubeloop/hitl/__init__.pysimilarity index 77%rename from cubepi/hitl/__init__.pyrename to cubeloop/hitl/__init__.pyindex e8632a3..e7f9d53 100644--- a/cubepi/hitl/__init__.py+++ b/cubeloop/hitl/__init__.py@@ -3,7 +3,7 @@See dev/specs/2026-05-28-hitl-channel.md for the full design."""-from cubepi.hitl.exceptions import (+from cubeloop.hitl.exceptions import (HitlAborted,HitlCancelled,HitlConcurrencyError,@@ -17,17 +17,17 @@ from cubepi.hitl.exceptions import (HitlStaleAnswer,HitlTimedOut,)-from cubepi.hitl.policy import (+from cubeloop.hitl.policy import (Approve,ApprovalDecision,AskUser,Deny,)-from cubepi.hitl.ask_user import AskUserParams, ask_user_tool-from cubepi.hitl.channel import CheckpointedChannel, HitlChannel, InMemoryChannel-from cubepi.hitl.testing import NoopChannel, ScriptedChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware, ConfirmToolCallMiddleware-from cubepi.hitl.types import (+from cubeloop.hitl.ask_user import AskUserParams, ask_user_tool+from cubeloop.hitl.channel import CheckpointedChannel, HitlChannel, InMemoryChannel+from cubeloop.hitl.testing import NoopChannel, ScriptedChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware, ConfirmToolCallMiddleware+from cubeloop.hitl.types import (ApproveAnswer,ApproveRequest,AskRequest,diff --git a/cubepi/hitl/_trace.py b/cubeloop/hitl/_trace.pysimilarity index 94%rename from cubepi/hitl/_trace.pyrename to cubeloop/hitl/_trace.pyindex 74da111..54e2abc 100644--- a/cubepi/hitl/_trace.py+++ b/cubeloop/hitl/_trace.py@@ -26,7 +26,7 @@ def hitl_span(kind: str, **attrs):yield _NullSpan()returntrace = cast(Any, otel_trace)- tracer = trace.get_tracer("cubepi.hitl")+ tracer = trace.get_tracer("cubeloop.hitl")with tracer.start_as_current_span(f"hitl.{kind}") as span:for k, v in attrs.items():if v is not None:diff --git a/cubepi/hitl/ask_user.py b/cubeloop/hitl/ask_user.pysimilarity index 91%rename from cubepi/hitl/ask_user.pyrename to cubeloop/hitl/ask_user.pyindex 05b0095..989ae6c 100644--- a/cubepi/hitl/ask_user.py+++ b/cubeloop/hitl/ask_user.py@@ -7,12 +7,12 @@ from typing import castfrom pydantic import BaseModel-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.hitl.binding import HitlBinding-from cubepi.hitl.channel import CheckpointedChannel, HitlChannel-from cubepi.hitl.types import Option, Question-from cubepi.providers.base import TextContent-from cubepi.types import StructuredObject, StructuredValue+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.hitl.binding import HitlBinding+from cubeloop.hitl.channel import CheckpointedChannel, HitlChannel+from cubeloop.hitl.types import Option, Question+from cubeloop.providers.base import TextContent+from cubeloop.types import StructuredObject, StructuredValueclass _OptionDef(BaseModel):@@ -67,7 +67,7 @@ def ask_user_tool(channel: HitlChannel) -> AgentTool[AskUserParams]:on_update: Callable[[StructuredValue], None] | None = None,) -> AgentToolResult:del call_id, on_update- from cubepi.hitl.exceptions import HitlCancelled, HitlTimedOut+ from cubeloop.hitl.exceptions import HitlCancelled, HitlTimedOutquestions = [Question(diff --git a/cubepi/hitl/binding.py b/cubeloop/hitl/binding.pysimilarity index 100%rename from cubepi/hitl/binding.pyrename to cubeloop/hitl/binding.pydiff --git a/cubepi/hitl/channel.py b/cubeloop/hitl/channel.pysimilarity index 96%rename from cubepi/hitl/channel.pyrename to cubeloop/hitl/channel.pyindex 962d0de..4eaa8e3 100644--- a/cubepi/hitl/channel.py+++ b/cubeloop/hitl/channel.py@@ -8,15 +8,15 @@ import timefrom typing import Any, AsyncIterator, Protocol, TypeAliasfrom typing import cast-from cubepi.checkpointer.base import Checkpointer-from cubepi.hitl.exceptions import (+from cubeloop.checkpointer.base import Checkpointer+from cubeloop.hitl.exceptions import (HitlAborted,HitlCancelled,HitlConcurrencyError,HitlStaleAnswer,HitlTimedOut,)-from cubepi.hitl.types import (+from cubeloop.hitl.types import (ApproveAnswer,ApproveRequest,AskRequest,@@ -25,7 +25,7 @@ from cubepi.hitl.types import (HitlRequest,Question,)-from cubepi.types import JsonObject, StructuredValue+from cubeloop.types import JsonObject, StructuredValue# Sentinel default for the per-call `timeout` kwarg on confirm/approve/ask.@@ -42,7 +42,7 @@ TimeoutArg: TypeAlias = float | None | _UseDefaultTimeout# ContextVar used by CheckpointedChannel to enforce the "do not ask HITL# from inside a custom tool body" durability guard. Set by-# cubepi.agent.tools._execute_prepared for non-builtin tools; the guard fires+# cubeloop.agent.tools._execute_prepared for non-builtin tools; the guard fires# in CheckpointedChannel._on_pending_set when the var is True and# allow_inside_custom_tool=False._in_custom_tool_var: contextvars.ContextVar[bool] = contextvars.ContextVar(@@ -196,7 +196,7 @@ class _BaseChannel:signal: asyncio.Event | None,question_id: str,) -> StructuredValue:- from cubepi.hitl._trace import hitl_span+ from cubeloop.hitl._trace import hitl_spankind = payload.kindeffective_timeout: float | None = (@@ -234,7 +234,7 @@ class _BaseChannel:from_resume = Trueoutcome = _outcome_from_answer(kind, ans)if self._emit is not None:- from cubepi.agent.types import HitlAnswerEvent+ from cubeloop.agent.types import HitlAnswerEventawait self._emit_event(HitlAnswerEvent(question_id=question_id, answer=ans)@@ -247,7 +247,7 @@ class _BaseChannel:from_resume = Trueoutcome = _outcome_from_answer(kind, ans)if self._emit is not None:- from cubepi.agent.types import HitlAnswerEvent+ from cubeloop.agent.types import HitlAnswerEventawait self._emit_event(HitlAnswerEvent(question_id=question_id, answer=ans)@@ -353,7 +353,7 @@ class _BaseChannel:q.put_nowait(req)# Emit event — guard avoids importing not-yet-defined event types.if self._emit is not None: # pragma: no cover — integration tested- from cubepi.agent.types import HitlRequestEvent # avoid circular+ from cubeloop.agent.types import HitlRequestEvent # avoid circularawait self._emit_event(HitlRequestEvent(request=req))@@ -385,7 +385,7 @@ class _BaseChannel:if self._future is not None and not self._future.done():self._future.set_result(answer)if self._emit is not None: # pragma: no cover — integration tested- from cubepi.agent.types import HitlAnswerEvent # avoid circular+ from cubeloop.agent.types import HitlAnswerEvent # avoid circularawait self._emit_event(HitlAnswerEvent(question_id=question_id, answer=answer)@@ -400,7 +400,7 @@ class _BaseChannel:if self._future is not None and not self._future.done():self._future.set_exception(HitlCancelled(reason))if self._emit is not None: # pragma: no cover — integration tested- from cubepi.agent.types import HitlAnswerEvent # avoid circular+ from cubeloop.agent.types import HitlAnswerEvent # avoid circularawait self._emit_event(HitlAnswerEvent(question_id=question_id, answer=None, cancelled=True)@@ -520,7 +520,7 @@ def _normalize_answer(payload: HitlPayload, ans: StructuredValue) -> StructuredVdef _outcome_from_exception(exc: BaseException) -> str:- from cubepi.hitl.exceptions import (+ from cubeloop.hitl.exceptions import (HitlAborted,HitlCancelled,HitlDetached,@@ -585,7 +585,7 @@ class CheckpointedChannel(_BaseChannel):and hasattr(checkpointer, "load_hitl_answer")and hasattr(checkpointer, "clear_hitl_answers")):- from cubepi.hitl.exceptions import HitlError+ from cubeloop.hitl.exceptions import HitlErrorraise HitlError("CheckpointedChannel requires a checkpointer with "@@ -619,7 +619,7 @@ class CheckpointedChannel(_BaseChannel):async def _on_pending_set(self, req: HitlRequest) -> None:if _in_custom_tool_var.get() and not self._allow_inside_custom_tool:- from cubepi.hitl.exceptions import HitlDurabilityNotGuaranteed+ from cubeloop.hitl.exceptions import HitlDurabilityNotGuaranteedraise HitlDurabilityNotGuaranteed("CheckpointedChannel called from inside a custom tool body. "@@ -648,7 +648,7 @@ class CheckpointedChannel(_BaseChannel):*,exc: BaseException | None = None,) -> None:- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedif isinstance(exc, HitlDetached):returndiff --git a/cubepi/hitl/exceptions.py b/cubeloop/hitl/exceptions.pysimilarity index 92%rename from cubepi/hitl/exceptions.pyrename to cubeloop/hitl/exceptions.pyindex d1dc2c8..3eab0f4 100644--- a/cubepi/hitl/exceptions.py+++ b/cubeloop/hitl/exceptions.py@@ -3,14 +3,14 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Sequenceif TYPE_CHECKING: # pragma: no cover- from cubepi.providers.base import ToolResultMessage+ from cubeloop.providers.base import ToolResultMessageclass HitlControlException(BaseException):"""Base for HITL control-flow exceptions.Inherits BaseException so existing `except Exception:` handlers in- cubepi.agent.tools._prepare_tool_call and _execute_prepared do NOT+ cubeloop.agent.tools._prepare_tool_call and _execute_prepared do NOTswallow these — mirrors asyncio.CancelledError.``partial_tool_results``: ToolResultMessages of sibling tool calls indiff --git a/cubepi/hitl/middleware.py b/cubeloop/hitl/middleware.pysimilarity index 91%rename from cubepi/hitl/middleware.pyrename to cubeloop/hitl/middleware.pyindex b2487d9..883b482 100644--- a/cubepi/hitl/middleware.py+++ b/cubeloop/hitl/middleware.py@@ -5,13 +5,13 @@ from typing import Awaitable, Callable, Iterable, Protocol, Union, castfrom pydantic import BaseModel-from cubepi.agent.types import BeforeToolCallContext, BeforeToolCallResult-from cubepi.hitl.binding import HitlBinding-from cubepi.hitl.channel import CheckpointedChannel, HitlChannel-from cubepi.hitl.exceptions import HitlCancelled, HitlTimedOut-from cubepi.hitl.policy import Approve, ApprovalDecision, AskUser, Deny-from cubepi.middleware.base import Middleware-from cubepi.types import JsonObject, StructuredObject+from cubeloop.agent.types import BeforeToolCallContext, BeforeToolCallResult+from cubeloop.hitl.binding import HitlBinding+from cubeloop.hitl.channel import CheckpointedChannel, HitlChannel+from cubeloop.hitl.exceptions import HitlCancelled, HitlTimedOut+from cubeloop.hitl.policy import Approve, ApprovalDecision, AskUser, Deny+from cubeloop.middleware.base import Middleware+from cubeloop.types import JsonObject, StructuredObjectclass _VarsObject(Protocol):diff --git a/cubepi/hitl/policy.py b/cubeloop/hitl/policy.pysimilarity index 91%rename from cubepi/hitl/policy.pyrename to cubeloop/hitl/policy.pyindex 8901d64..b838393 100644--- a/cubepi/hitl/policy.py+++ b/cubeloop/hitl/policy.py@@ -3,7 +3,7 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Union-from cubepi.types import JsonObject+from cubeloop.types import JsonObject@dataclass(frozen=True)diff --git a/cubepi/hitl/testing.py b/cubeloop/hitl/testing.pysimilarity index 88%rename from cubepi/hitl/testing.pyrename to cubeloop/hitl/testing.pyindex 79da995..ec30db6 100644--- a/cubepi/hitl/testing.py+++ b/cubeloop/hitl/testing.py@@ -3,10 +3,10 @@ from __future__ import annotationsimport timefrom typing import Callable, Union-from cubepi.hitl.channel import _BaseChannel, _USE_DEFAULT_TIMEOUT-from cubepi.hitl.exceptions import HitlError-from cubepi.hitl.types import HitlRequest-from cubepi.types import StructuredValue+from cubeloop.hitl.channel import _BaseChannel, _USE_DEFAULT_TIMEOUT+from cubeloop.hitl.exceptions import HitlError+from cubeloop.hitl.types import HitlRequest+from cubeloop.types import StructuredValueclass ScriptedChannel(_BaseChannel):@@ -52,7 +52,7 @@ class NoopChannel(_BaseChannel):"""Auto-approves everything. Useful for subagents in tests."""async def _await_answer(self, payload, timeout, signal, question_id):- from cubepi.hitl.types import ApproveAnswer+ from cubeloop.hitl.types import ApproveAnswerkind = payload.kindif kind == "approve":diff --git a/cubepi/hitl/types.py b/cubeloop/hitl/types.pysimilarity index 96%rename from cubepi/hitl/types.pyrename to cubeloop/hitl/types.pyindex a55b186..0d78a65 100644--- a/cubepi/hitl/types.py+++ b/cubeloop/hitl/types.py@@ -4,7 +4,7 @@ from typing import Literal, Unionfrom pydantic import BaseModel, Field-from cubepi.types import JsonObject+from cubeloop.types import JsonObjectclass Option(BaseModel):diff --git a/cubepi/mcp/__init__.py b/cubeloop/mcp/__init__.pysimilarity index 65%rename from cubepi/mcp/__init__.pyrename to cubeloop/mcp/__init__.pyindex 2d59f81..4ddde2a 100644--- a/cubepi/mcp/__init__.py+++ b/cubeloop/mcp/__init__.py@@ -3,9 +3,9 @@cubepi[mcp] extra required."""-from cubepi.mcp.http_loader import load_mcp_tools_http-from cubepi.mcp.stdio_loader import load_mcp_tools_stdio-from cubepi.mcp.types import (+from cubeloop.mcp.http_loader import load_mcp_tools_http+from cubeloop.mcp.stdio_loader import load_mcp_tools_stdio+from cubeloop.mcp.types import (MCPDiscoveryResult,MCPIcon,MCPServerInfo,diff --git a/cubepi/mcp/_adapter.py b/cubeloop/mcp/_adapter.pysimilarity index 94%rename from cubepi/mcp/_adapter.pyrename to cubeloop/mcp/_adapter.pyindex 705550a..7b28c07 100644--- a/cubepi/mcp/_adapter.py+++ b/cubeloop/mcp/_adapter.py@@ -1,4 +1,4 @@-"""MCP tool descriptor → cubepi.AgentTool adapter."""+"""MCP tool descriptor → cubeloop.AgentTool adapter."""from __future__ import annotations@@ -7,9 +7,9 @@ from typing import Any, Awaitable, Callable, Literalfrom pydantic import BaseModel, Field, create_model-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.mcp._tracing import mark_span_mcp_error, mcp_client_span-from cubepi.providers.base import Content, ImageContent, TextContent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.mcp._tracing import mark_span_mcp_error, mcp_client_span+from cubeloop.providers.base import Content, ImageContent, TextContentdef mcp_schema_to_pydantic_model(@@ -19,7 +19,7 @@ def mcp_schema_to_pydantic_model() -> type[BaseModel]:"""Convert an MCP JSON-Schema inputSchema to a Pydantic model class.- cubepi.AgentTool requires `parameters: type[BaseModel]`. We synthesize+ cubeloop.AgentTool requires `parameters: type[BaseModel]`. We synthesizea model from the schema's top-level properties.Type coverage: string/integer/number/boolean/array/object. Nested@@ -111,7 +111,7 @@ def make_mcp_agent_tool(protocol_version: str | None = None,session_id: str | None = None,) -> AgentTool:- """Build a cubepi.AgentTool wrapping an MCP tool call.+ """Build a cubeloop.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 normalized to:@@ -157,7 +157,7 @@ def make_mcp_agent_tool(if result is _ABORTED_SENTINEL:# Cooperative abort fired while the MCP RPC was in# flight. Mark the CLIENT span aborted (Status UNSET,- # cubepi.aborted=true) so the trace shows the+ # cubeloop.aborted=true) so the trace shows the# interruption, then return a synthetic tool result.# Returning rather than raising preserves the agent# lifecycle that non-MCP provider aborts use: the@@ -171,8 +171,8 @@ def make_mcp_agent_tool(# round-1 follow-up on PR #88).if span is not None:try:- span.set_attribute("cubepi.aborted", True)- span.set_attribute("error.type", "cubepi.aborted")+ span.set_attribute("cubeloop.aborted", True)+ span.set_attribute("error.type", "cubeloop.aborted")except Exception:passreturn AgentToolResult(@@ -182,7 +182,7 @@ def make_mcp_agent_tool(# MCP server-reported tool failure (``isError: true``): the# JSON-RPC call succeeded but the tool's logic failed. Mark# the CLIENT span ERROR so backends count it as a failure,- # matching the cubepi.tool.is_error treatment for non-MCP+ # matching the cubeloop.tool.is_error treatment for non-MCP# tool spans.if result.get("isError"):mark_span_mcp_error(span, "MCP server returned isError")diff --git a/cubepi/mcp/_tracing.py b/cubeloop/mcp/_tracing.pysimilarity index 96%rename from cubepi/mcp/_tracing.pyrename to cubeloop/mcp/_tracing.pyindex 0c798e4..7f1ecee 100644--- a/cubepi/mcp/_tracing.py+++ b/cubeloop/mcp/_tracing.py@@ -55,7 +55,7 @@ except ImportError: # pragma: no cover — exercised only without the extra.StatusCode = None-# When :class:`cubepi.tracing.Tracer` is attached to an agent it+# When :class:`cubeloop.tracing.Tracer` is attached to an agent it# pushes its private :class:`TracerProvider` onto this stack. Without# any registration, ``_otel_trace.get_tracer`` falls back to the OTel# global default — which is a no-op provider unless the caller also@@ -72,7 +72,7 @@ def register_provider(provider: Any, *, record_content: bool = False) -> object:"""Push ``provider`` and its content policy onto the routing stack.Returns an opaque token that :func:`unregister_provider` uses to remove- this exact entry. Called by :meth:`cubepi.tracing.Tracer.attach`.+ this exact entry. Called by :meth:`cubeloop.tracing.Tracer.attach`."""token = object()_provider_stack.append((token, provider, record_content))@@ -244,7 +244,7 @@ def _current_span_via_registered() -> Any:# Public attribute name constants — duplicated from-# cubepi.tracing.schema so this module can be imported without the+# cubeloop.tracing.schema so this module can be imported without the# tracing extra installed. Keep in sync._MCP_METHOD_NAME = "mcp.method.name"_MCP_SESSION_ID = "mcp.session.id"@@ -254,7 +254,7 @@ _GEN_AI_OPERATION_NAME = "gen_ai.operation.name"_SERVER_ADDRESS = "server.address"_SERVER_PORT = "server.port"_ERROR_TYPE = "error.type"-_SCOPE_NAME = "cubepi.mcp"+_SCOPE_NAME = "cubeloop.mcp"@asynccontextmanager@@ -347,10 +347,10 @@ async def mcp_client_span(span.set_attribute(_ERROR_TYPE, error_type)# Cancellation is a control signal, not a failure — match the# convention from the chat / turn / invoke_agent spans: leave- # Status UNSET and mark cubepi.aborted=true, do NOT record an+ # Status UNSET and mark cubeloop.aborted=true, do NOT record an# exception event.- if error_type == "cubepi.aborted":- span.set_attribute("cubepi.aborted", True)+ if error_type == "cubeloop.aborted":+ span.set_attribute("cubeloop.aborted", True)else:description = (str(exc)[:256] if record_content else "mcp client error"@@ -416,12 +416,12 @@ def current_traceparent() -> str | None:def _error_type_for(exc: BaseException) -> str:- """Local error.type derivation. Mirrors cubepi.tracing.errors but+ """Local error.type derivation. Mirrors cubeloop.tracing.errors butre-implemented here so the MCP module has no hard tracing dep."""import asyncioif isinstance(exc, asyncio.CancelledError):- return "cubepi.aborted"+ return "cubeloop.aborted"if isinstance(exc, (asyncio.TimeoutError, TimeoutError)):return "timeout"if isinstance(exc, ConnectionError):diff --git a/cubepi/mcp/http_loader.py b/cubeloop/mcp/http_loader.pysimilarity index 97%rename from cubepi/mcp/http_loader.pyrename to cubeloop/mcp/http_loader.pyindex 361e618..9e7b8ad 100644--- a/cubepi/mcp/http_loader.py+++ b/cubeloop/mcp/http_loader.py@@ -8,8 +8,8 @@ from contextlib import asynccontextmanagerfrom datetime import timedeltafrom typing import Any, Callable, Literal-from cubepi.mcp._adapter import make_mcp_agent_tool-from cubepi.mcp.types import (+from cubeloop.mcp._adapter import make_mcp_agent_tool+from cubeloop.mcp.types import (MCPDiscoveryResult,server_info_from_init_result,tool_info_from_desc,@@ -86,7 +86,7 @@ def _stamp_session_id(session_id: str | None) -> None:"""Attach ``mcp.session.id`` to the current OTel span if both theid and ``opentelemetry`` are present.- The CLIENT span was opened by ``cubepi.mcp._adapter._execute``+ The CLIENT span was opened by ``cubeloop.mcp._adapter._execute``via ``mcp_client_span``; ``use_span`` makes it the current spanwhile ``call_remote`` runs, so reading ``get_current_span()``inside the loader's call path resolves to the right span. No-op@@ -147,13 +147,13 @@ async def load_mcp_tools_http("""async def _call_remote(tool_name: str, args: dict[str, Any]) -> dict[str, Any]:- # When an MCP CLIENT span is current (cubepi.mcp._adapter wraps+ # When an MCP CLIENT span is current (cubeloop.mcp._adapter wraps# this call in ``mcp_client_span``), propagate the W3C# ``traceparent`` header so an instrumented MCP server can# continue the trace. The helper returns None when no recording# span is active or OTel isn't installed; merge so caller-# supplied headers aren't clobbered.- from cubepi.mcp._tracing import current_traceparent+ from cubeloop.mcp._tracing import current_traceparentcall_headers = headerstp = current_traceparent()diff --git a/cubepi/mcp/stdio_loader.py b/cubeloop/mcp/stdio_loader.pysimilarity index 97%rename from cubepi/mcp/stdio_loader.pyrename to cubeloop/mcp/stdio_loader.pyindex 07e9185..1a3cb12 100644--- a/cubepi/mcp/stdio_loader.py+++ b/cubeloop/mcp/stdio_loader.py@@ -5,8 +5,8 @@ from __future__ import annotationsimport asynciofrom typing import Any-from cubepi.mcp._adapter import make_mcp_agent_tool-from cubepi.mcp.types import (+from cubeloop.mcp._adapter import make_mcp_agent_tool+from cubeloop.mcp.types import (MCPDiscoveryResult,server_info_from_init_result,tool_info_from_desc,diff --git a/cubepi/mcp/types.py b/cubeloop/mcp/types.pysimilarity index 98%rename from cubepi/mcp/types.pyrename to cubeloop/mcp/types.pyindex c1d6d98..930071e 100644--- a/cubepi/mcp/types.py+++ b/cubeloop/mcp/types.py@@ -4,7 +4,7 @@ from __future__ import annotationsfrom dataclasses import dataclass, field-from cubepi.agent.types import AgentTool+from cubeloop.agent.types import AgentTool@dataclass(frozen=True)diff --git a/cubeloop/middleware/__init__.py b/cubeloop/middleware/__init__.pynew file mode 100644index 0000000..a9feea5--- /dev/null+++ b/cubeloop/middleware/__init__.py@@ -0,0 +1,61 @@+from __future__ import annotations++from typing import Any++from cubeloop.middleware.base import Middleware, TurnAction, compose_middleware++__all__ = [+ "CompactionMiddleware",+ "CompactionState",+ "GoalMiddleware",+ "ToolResultCompressor",+ "Middleware",+ "SubagentMiddleware",+ "SubagentRequest",+ "SubagentResult",+ "SubagentSpec",+ "Todo",+ "TodoGuardBlocked",+ "TodoGuardType",+ "TodoListMiddleware",+ "TurnAction",+ "WriteTodosInput",+ "WRITE_TODOS_SYSTEM_PROMPT",+ "WRITE_TODOS_TOOL_DESCRIPTION",+ "compose_middleware",+]++_LAZY = {+ "CompactionMiddleware": ("cubeloop.middleware.compaction", "CompactionMiddleware"),+ "CompactionState": ("cubeloop.middleware.compaction", "CompactionState"),+ "ToolResultCompressor": ("cubeloop.middleware.compaction", "ToolResultCompressor"),+ "GoalMiddleware": ("cubeloop.middleware.goal", "GoalMiddleware"),+ "SubagentMiddleware": ("cubeloop.middleware.subagents", "SubagentMiddleware"),+ "SubagentRequest": ("cubeloop.middleware.subagents", "SubagentRequest"),+ "SubagentResult": ("cubeloop.middleware.subagents", "SubagentResult"),+ "SubagentSpec": ("cubeloop.middleware.subagents", "SubagentSpec"),+ "Todo": ("cubeloop.middleware.todo", "Todo"),+ "TodoGuardBlocked": ("cubeloop.middleware.todo", "TodoGuardBlocked"),+ "TodoGuardType": ("cubeloop.middleware.todo", "TodoGuardType"),+ "TodoListMiddleware": ("cubeloop.middleware.todo", "TodoListMiddleware"),+ "WriteTodosInput": ("cubeloop.middleware.todo", "WriteTodosInput"),+ "WRITE_TODOS_SYSTEM_PROMPT": (+ "cubeloop.middleware.todo",+ "WRITE_TODOS_SYSTEM_PROMPT",+ ),+ "WRITE_TODOS_TOOL_DESCRIPTION": (+ "cubeloop.middleware.todo",+ "WRITE_TODOS_TOOL_DESCRIPTION",+ ),+}+++def __getattr__(name: str) -> Any:+ try:+ module_name, attr = _LAZY[name]+ except KeyError:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None+ import importlib++ module = importlib.import_module(module_name)+ return getattr(module, attr)diff --git a/cubepi/middleware/base.py b/cubeloop/middleware/base.pysimilarity index 97%rename from cubepi/middleware/base.pyrename to cubeloop/middleware/base.pyindex 6828cce..d66a169 100644--- a/cubepi/middleware/base.py+++ b/cubeloop/middleware/base.py@@ -5,16 +5,16 @@ from typing import Callable, Iterable, Literalimport asyncio-from cubepi.agent.types import (+from cubeloop.agent.types import (AfterToolCallContext,AfterToolCallResult,AgentContext,BeforeToolCallContext,BeforeToolCallResult,)-from cubepi.hitl.binding import HitlBinding-from cubepi.providers.base import AssistantMessage, BoundModel, Message, ToolCall-from cubepi.types import JsonObject, StructuredObject+from cubeloop.hitl.binding import HitlBinding+from cubeloop.providers.base import AssistantMessage, BoundModel, Message, ToolCall+from cubeloop.types import JsonObject, StructuredObject@dataclass@@ -118,7 +118,7 @@ class Middleware:bound model.Each entry is a ``BoundModel`` — the same handle the user gets from- ``provider.model(...)``. ``cubepi.tracing.Recorder`` uses these to:+ ``provider.model(...)``. ``cubeloop.tracing.Recorder`` uses these to:* Subscribe listeners on any provider the recorder isn't alreadywatching, so the resulting calls show up in the trace treediff --git a/cubepi/middleware/compaction/__init__.py b/cubeloop/middleware/compaction/__init__.pysimilarity index 96%rename from cubepi/middleware/compaction/__init__.pyrename to cubeloop/middleware/compaction/__init__.pyindex eacc609..3cbf2d9 100644--- a/cubepi/middleware/compaction/__init__.py+++ b/cubeloop/middleware/compaction/__init__.py@@ -6,24 +6,27 @@ from typing import Anyfrom pydantic import ValidationError-from cubepi.agent.types import AgentContext-from cubepi.middleware.base import Middleware-from cubepi.middleware.compaction.boundary import (+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.base import Middleware+from cubeloop.middleware.compaction.boundary import (safe_boundary,tail_start_by_tokens,)-from cubepi.middleware.compaction.pruner import ToolResultCompressor, prune_tool_results-from cubepi.middleware.compaction.state import (+from cubeloop.middleware.compaction.pruner import (+ ToolResultCompressor,+ prune_tool_results,+)+from cubeloop.middleware.compaction.state import (CompactionState,PreservedToolResult,message_refs,)-from cubepi.middleware.compaction.summarizer import (+from cubeloop.middleware.compaction.summarizer import (build_fallback_summary,summarize,)-from cubepi.middleware.compaction.tokens import approx_tokens, real_context_estimate-from cubepi.providers.base import (+from cubeloop.middleware.compaction.tokens import approx_tokens, real_context_estimate+from cubeloop.providers.base import (BoundModel,Message,UserMessage,@@ -395,7 +398,7 @@ class CompactionMiddleware(Middleware):return resultdef extra_llm_calls(self) -> tuple[BoundModel, ...]:- # Surface the bound summary model so ``cubepi.tracing.Recorder`` can+ # Surface the bound summary model so ``cubeloop.tracing.Recorder`` can# both subscribe its listeners (the summarizer's chat span lands in# the trace) AND identify the summary call by spec — important when# the summary model's provider is the same instance as the agent'sdiff --git a/cubepi/middleware/compaction/boundary.py b/cubeloop/middleware/compaction/boundary.pysimilarity index 97%rename from cubepi/middleware/compaction/boundary.pyrename to cubeloop/middleware/compaction/boundary.pyindex 9383044..edc2e1d 100644--- a/cubepi/middleware/compaction/boundary.py+++ b/cubeloop/middleware/compaction/boundary.py@@ -1,7 +1,7 @@from __future__ import annotations-from cubepi.middleware.compaction.tokens import approx_tokens-from cubepi.providers.base import (+from cubeloop.middleware.compaction.tokens import approx_tokens+from cubeloop.providers.base import (AssistantMessage,Message,ToolCall,diff --git a/cubepi/middleware/compaction/pruner.py b/cubeloop/middleware/compaction/pruner.pysimilarity index 96%rename from cubepi/middleware/compaction/pruner.pyrename to cubeloop/middleware/compaction/pruner.pyindex 9178103..b3d559e 100644--- a/cubepi/middleware/compaction/pruner.py+++ b/cubeloop/middleware/compaction/pruner.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom collections.abc import Callable-from cubepi.providers.base import Message, TextContent, ToolResultMessage+from cubeloop.providers.base import Message, TextContent, ToolResultMessage_PRUNE_KEEP_CHARS = 120diff --git a/cubepi/middleware/compaction/state.py b/cubeloop/middleware/compaction/state.pysimilarity index 96%rename from cubepi/middleware/compaction/state.pyrename to cubeloop/middleware/compaction/state.pyindex fa70cc2..c6b2262 100644--- a/cubepi/middleware/compaction/state.py+++ b/cubeloop/middleware/compaction/state.py@@ -5,7 +5,7 @@ import jsonfrom pydantic import BaseModel, Field-from cubepi.providers.base import Message+from cubeloop.providers.base import Messageclass PreservedToolResult(BaseModel):diff --git a/cubepi/middleware/compaction/summarizer.py b/cubeloop/middleware/compaction/summarizer.pysimilarity index 98%rename from cubepi/middleware/compaction/summarizer.pyrename to cubeloop/middleware/compaction/summarizer.pyindex 7051475..3bd3d4d 100644--- a/cubepi/middleware/compaction/summarizer.py+++ b/cubeloop/middleware/compaction/summarizer.py@@ -3,9 +3,9 @@ from __future__ import annotationsimport asyncioimport json-from cubepi.middleware.compaction.state import CompactionState, message_refs-from cubepi.middleware.compaction.tokens import approx_tokens-from cubepi.providers.base import (+from cubeloop.middleware.compaction.state import CompactionState, message_refs+from cubeloop.middleware.compaction.tokens import approx_tokens+from cubeloop.providers.base import (AssistantMessage,BoundModel,Message,diff --git a/cubepi/middleware/compaction/tokens.py b/cubeloop/middleware/compaction/tokens.pysimilarity index 98%rename from cubepi/middleware/compaction/tokens.pyrename to cubeloop/middleware/compaction/tokens.pyindex db575bf..348572c 100644--- a/cubepi/middleware/compaction/tokens.py+++ b/cubeloop/middleware/compaction/tokens.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport json-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,Message,TextContent,diff --git a/cubepi/middleware/goal.py b/cubeloop/middleware/goal.pysimilarity index 97%rename from cubepi/middleware/goal.pyrename to cubeloop/middleware/goal.pyindex f6211c1..0af8285 100644--- a/cubepi/middleware/goal.py+++ b/cubeloop/middleware/goal.py@@ -13,9 +13,9 @@ from typing import Anyfrom pydantic import BaseModel-from cubepi.agent.types import AgentContext-from cubepi.middleware.base import Middleware-from cubepi.providers.base import (+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.base import Middleware+from cubeloop.providers.base import (BoundModel,Message,TextContent,diff --git a/cubepi/middleware/subagents.py b/cubeloop/middleware/subagents.pysimilarity index 97%rename from cubepi/middleware/subagents.pyrename to cubeloop/middleware/subagents.pyindex aae537f..335a880 100644--- a/cubepi/middleware/subagents.py+++ b/cubeloop/middleware/subagents.py@@ -10,11 +10,11 @@ from typing import Protocol, castfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentEvent, AgentTool, AgentToolResult-from cubepi.middleware.base import Middleware-from cubepi.providers.base import AssistantMessage, BoundModel, TextContent-from cubepi.types import StructuredValue+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentEvent, AgentTool, AgentToolResult+from cubeloop.middleware.base import Middleware+from cubeloop.providers.base import AssistantMessage, BoundModel, TextContent+from cubeloop.types import StructuredValuelogger = logging.getLogger(__name__)diff --git a/cubepi/middleware/todo.py b/cubeloop/middleware/todo.pysimilarity index 99%rename from cubepi/middleware/todo.pyrename to cubeloop/middleware/todo.pyindex 68ff597..af6701d 100644--- a/cubepi/middleware/todo.py+++ b/cubeloop/middleware/todo.py@@ -30,15 +30,15 @@ from typing import Any, Literal, TypeAlias, castfrom typing_extensions import TypedDict-from cubepi.agent.types import (+from cubeloop.agent.types import (AfterToolCallContext,AfterToolCallResult,AgentContext,AgentTool,AgentToolResult,)-from cubepi.middleware.base import Middleware, TurnAction-from cubepi.providers.base import (+from cubeloop.middleware.base import Middleware, TurnAction+from cubeloop.providers.base import (synthetic_user_message,AssistantMessage,Message,@@ -46,7 +46,7 @@ from cubepi.providers.base import (ToolCall,UserMessage,)-from cubepi.types import StructuredValue+from cubeloop.types import StructuredValuefrom pydantic import BaseModel# ---------------------------------------------------------------------------diff --git a/cubepi/providers/__init__.py b/cubeloop/providers/__init__.pysimilarity index 83%rename from cubepi/providers/__init__.pyrename to cubeloop/providers/__init__.pyindex c95595c..8bf71b3 100644--- a/cubepi/providers/__init__.py+++ b/cubeloop/providers/__init__.py@@ -1,4 +1,4 @@-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,BoundModel,@@ -33,7 +33,7 @@ from cubepi.providers.base import (chain_providers,collect_agent_providers,)-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,CapabilityWarning,PayloadPreview,@@ -43,36 +43,36 @@ from cubepi.providers.capability import (lint_capability,preview_payload,)-from cubepi.providers.faux import (+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_text,faux_thinking,faux_tool_call,)-from cubepi.providers.fallback import (+from cubeloop.providers.fallback import (DEFAULT_TRIGGER_ERRORS,FallbackBoundModel,)-from cubepi.providers.models import models_are_equal-from cubepi.providers.reasoning_profiles import get_capability_profile+from cubeloop.providers.models import models_are_equal+from cubeloop.providers.reasoning_profiles import get_capability_profile# Lazy imports for optional providersdef get_anthropic_provider():- from cubepi.providers.anthropic import AnthropicProvider+ from cubeloop.providers.anthropic import AnthropicProviderreturn AnthropicProviderdef get_openai_provider():- from cubepi.providers.openai import OpenAIProvider+ from cubeloop.providers.openai import OpenAIProviderreturn OpenAIProviderdef get_openai_responses_provider():- from cubepi.providers.openai_responses import OpenAIResponsesProvider+ from cubeloop.providers.openai_responses import OpenAIResponsesProviderreturn OpenAIResponsesProviderdiff --git a/cubepi/providers/anthropic.py b/cubeloop/providers/anthropic.pysimilarity index 99%rename from cubepi/providers/anthropic.pyrename to cubeloop/providers/anthropic.pyindex 2f72696..3197765 100644--- a/cubepi/providers/anthropic.py+++ b/cubeloop/providers/anthropic.py@@ -5,7 +5,7 @@ import jsonimport timefrom typing import Any, Literal, Protocol, runtime_checkable-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,ImageContent,@@ -30,12 +30,12 @@ from cubepi.providers.base import (invoke_on_response,typed_error_event,)-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,apply_reasoning_control,apply_temperature,)-from cubepi.providers.reasoning_profiles import get_capability_profile+from cubeloop.providers.reasoning_profiles import get_capability_profileCacheRetention = Literal["short", "long", "none"]@@ -271,7 +271,7 @@ class AnthropicProvider(BaseProvider):await self._emit(ms, StreamEvent(type="done"), model)ms.set_result(result)except Exception as _sdk_exc:- from cubepi.errors import classify_and_raise+ from cubeloop.errors import classify_and_raiseclassify_and_raise(_sdk_exc, model=model, messages=messages)diff --git a/cubepi/providers/base.py b/cubeloop/providers/base.pysimilarity index 98%rename from cubepi/providers/base.pyrename to cubeloop/providers/base.pyindex 232e35e..8da2820 100644--- a/cubepi/providers/base.py+++ b/cubeloop/providers/base.py@@ -18,7 +18,7 @@ from typing import (from pydantic import BaseModel, ConfigDict, Field-from cubepi.types import JsonObject, StructuredValue+from cubeloop.types import JsonObject, StructuredValueBaseModelT = TypeVar("BaseModelT", bound=BaseModel)@@ -267,7 +267,7 @@ def typed_error_event() -> StreamEvent:"""Build a typed error ``StreamEvent`` from a classified exception."""- from cubepi.errors import annotate_error_event+ from cubeloop.errors import annotate_error_eventfields = annotate_error_event(exc, fallback_message=error_message)error_type = fields.get("error_type")@@ -622,7 +622,7 @@ async def _safe_run_coroutine(cb: Callable, coro: Any) -> None:def _log_listener_exception(cb: Callable, exc: BaseException) -> None:- logging.getLogger("cubepi.providers").warning(+ logging.getLogger("cubeloop.providers").warning("cubepi provider listener %r raised; swallowed", cb, exc_info=exc)@@ -705,7 +705,7 @@ class BaseProvider:Built-in providers (Anthropic, OpenAI, OpenAI Responses, Faux) inheritfrom this class to gain the persistent listener registry used by- ``cubepi.tracing`` and other observers. User-defined providers should+ ``cubeloop.tracing`` and other observers. User-defined providers shouldinherit from ``BaseProvider`` unless they implement the full ``Provider``protocol themselves.@@ -996,7 +996,7 @@ def chain_providers(model: object) -> list["BaseProvider"]:Walks a model's ``chain`` (FallbackBoundModel-like) or its single``.provider`` (plain BoundModel-like). Uses duck typing on ``.chain`` to- avoid importing :mod:`cubepi.providers.fallback` into this base module —+ avoid importing :mod:`cubeloop.providers.fallback` into this base module —``fallback`` already depends on ``base``, so the reverse import wouldcycle.@@ -1011,8 +1011,8 @@ def chain_providers(model: object) -> list["BaseProvider"]:For plain bound models, returns ``[model.provider]`` if it is a``BaseProvider``. For ``None`` or any other input, returns ``[]``.- Used by :meth:`cubepi.tracing.recorder.Recorder.attach` and- :meth:`cubepi.tracing.meter.Meter.attach` to subscribe to every leg of a+ Used by :meth:`cubeloop.tracing.recorder.Recorder.attach` and+ :meth:`cubeloop.tracing.meter.Meter.attach` to subscribe to every leg of afallback chain so post-failover provider events land in the trace /metric stream."""@@ -1025,8 +1025,8 @@ def chain_providers(model: object) -> list["BaseProvider"]:for idx, bm in enumerate(chain):p = getattr(bm, "provider", None)if not isinstance(p, BaseProvider):- logging.getLogger("cubepi.providers.base").warning(- "cubepi.providers.base.chain_providers: chain[%d] provider "+ logging.getLogger("cubeloop.providers.base").warning(+ "cubeloop.providers.base.chain_providers: chain[%d] provider ""%s is not a BaseProvider; tracing/metrics will skip this leg",idx,type(p).__name__,@@ -1047,8 +1047,8 @@ def collect_agent_providers(agent: Any) -> list["BaseProvider"]:Walks ``agent._model`` via :func:`chain_providers` and falls back to apublic ``provider`` attribute on the agent for legacy code paths. Used- by both :meth:`cubepi.tracing.recorder.Recorder.attach` and- :meth:`cubepi.tracing.meter.Meter.attach` to dedupe the prelude that+ by both :meth:`cubeloop.tracing.recorder.Recorder.attach` and+ :meth:`cubeloop.tracing.meter.Meter.attach` to dedupe the prelude thatfinds providers to subscribe to."""model = getattr(agent, "_model", None)diff --git a/cubepi/providers/capability.py b/cubeloop/providers/capability.pysimilarity index 99%rename from cubepi/providers/capability.pyrename to cubeloop/providers/capability.pyindex 007daa2..6f59d29 100644--- a/cubepi/providers/capability.py+++ b/cubeloop/providers/capability.py@@ -10,7 +10,7 @@ from typing import Any, Literalfrom pydantic import BaseModel, Field, model_validator-from cubepi.providers.base import (+from cubeloop.providers.base import (Model,ReasoningControl,ReasoningEffort,diff --git a/cubepi/providers/fallback.py b/cubeloop/providers/fallback.pysimilarity index 97%rename from cubepi/providers/fallback.pyrename to cubeloop/providers/fallback.pyindex d0f56ea..39cabb3 100644--- a/cubepi/providers/fallback.py+++ b/cubeloop/providers/fallback.py@@ -8,7 +8,7 @@ import timefrom dataclasses import dataclassfrom typing import Any, Awaitable, Callable-from cubepi.errors import (+from cubeloop.errors import (ContentFiltered,ContextLengthExceeded,ProviderBadRequest,@@ -17,7 +17,7 @@ from cubepi.errors import (RateLimited,error_from_stream_fields,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BoundModel,Message,@@ -34,7 +34,7 @@ from cubepi.providers.base import ()-_log = logging.getLogger("cubepi.providers.fallback")+_log = logging.getLogger("cubeloop.providers.fallback")DEFAULT_RETRY_ERRORS: frozenset[type[ProviderError]] = frozenset(@@ -250,7 +250,7 @@ class FallbackBoundModel:else "none (exhausted)")_log.warning(- "cubepi.providers.fallback: failover triggered "+ "cubeloop.providers.fallback: failover triggered ""failed=%s → next=%s reason=%s attempt=%s/%s",failed_label,next_label,@@ -265,7 +265,7 @@ class FallbackBoundModel:await resultexcept Exception as cb_exc: # noqa: BLE001_log.warning(- "cubepi.providers.fallback: on_failover callback raised; swallowed: %s",+ "cubeloop.providers.fallback: on_failover callback raised; swallowed: %s",cb_exc,)@@ -277,7 +277,7 @@ class FallbackBoundModel:wait_s: float,) -> None:_log.info(- "cubepi.providers.fallback: same-model retry model=%s/%s "+ "cubeloop.providers.fallback: same-model retry model=%s/%s ""attempt=%s/%s wait=%.2fs reason=%s",failed.spec.provider_id,failed.spec.id,@@ -293,7 +293,7 @@ class FallbackBoundModel:await resultexcept Exception as cb_exc: # noqa: BLE001_log.warning(- "cubepi.providers.fallback: on_retry callback raised; swallowed: %s",+ "cubeloop.providers.fallback: on_retry callback raised; swallowed: %s",cb_exc,)@@ -589,9 +589,9 @@ class FallbackBoundModel:return "raise"-# ``chain_providers`` lives in :mod:`cubepi.providers.base` so the tracing /+# ``chain_providers`` lives in :mod:`cubeloop.providers.base` so the tracing /# meter modules can import it without pulling in this fallback module. The-# import above re-exports it under ``cubepi.providers.fallback.chain_providers``+# import above re-exports it under ``cubeloop.providers.fallback.chain_providers``# for back-compat with existing call sites.__all__ = ["DEFAULT_RETRY_ERRORS",diff --git a/cubepi/providers/faux.py b/cubeloop/providers/faux.pysimilarity index 99%rename from cubepi/providers/faux.pyrename to cubeloop/providers/faux.pyindex d50c9cb..efb5e32 100644--- a/cubepi/providers/faux.py+++ b/cubeloop/providers/faux.py@@ -7,7 +7,7 @@ import mathimport timefrom typing import Any, Awaitable, Callable, cast-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,Content,diff --git a/cubepi/providers/images/__init__.py b/cubeloop/providers/images/__init__.pysimilarity index 66%rename from cubepi/providers/images/__init__.pyrename to cubeloop/providers/images/__init__.pyindex 43418bd..f4360f8 100644--- a/cubepi/providers/images/__init__.py+++ b/cubeloop/providers/images/__init__.py@@ -1,16 +1,16 @@"""Image generation providers — public exports."""-from cubepi.providers.images.base import (+from cubeloop.providers.images.base import (BaseImagesProvider,ImagesProvider,)-from cubepi.providers.images.capability import (+from cubeloop.providers.images.capability import (ImagesCapabilityDescriptor,SizeSpec,)-from cubepi.providers.images.faux import FauxImagesProvider-from cubepi.providers.images.openai_images import OpenAIImagesProvider-from cubepi.providers.images.types import (+from cubeloop.providers.images.faux import FauxImagesProvider+from cubeloop.providers.images.openai_images import OpenAIImagesProvider+from cubeloop.providers.images.types import (AssistantImages,ImagesAborted,ImagesContext,diff --git a/cubepi/providers/images/base.py b/cubeloop/providers/images/base.pysimilarity index 97%rename from cubepi/providers/images/base.pyrename to cubeloop/providers/images/base.pyindex e337f40..1f31c30 100644--- a/cubepi/providers/images/base.py+++ b/cubeloop/providers/images/base.py@@ -3,13 +3,13 @@ from __future__ import annotationsimport copyfrom typing import Any, Callable, Literal, Protocol, runtime_checkable-from cubepi.providers.base import (+from cubeloop.providers.base import (OnRequestCallback,OnResponseBodyCallback,_detach,)-from cubepi.providers.images.capability import ImagesCapabilityDescriptor-from cubepi.providers.images.types import (+from cubeloop.providers.images.capability import ImagesCapabilityDescriptor+from cubeloop.providers.images.types import (AssistantImages,ImagesContext,ImagesCost,@@ -67,7 +67,7 @@ class ImagesProvider(Protocol):class BaseImagesProvider:"""Concrete base class for built-in and user-defined image providers.- Mirrors the role of :class:`cubepi.providers.base.BaseProvider` in chat:+ Mirrors the role of :class:`cubeloop.providers.base.BaseProvider` in chat:holds ``provider_id``, exposes a ``.model(...)`` factory that propagatesit onto :class:`ImagesModel`, and runs request/response observerregistries. Image is one-shot (no streamed chunks), so there is nodiff --git a/cubepi/providers/images/capability.py b/cubeloop/providers/images/capability.pysimilarity index 100%rename from cubepi/providers/images/capability.pyrename to cubeloop/providers/images/capability.pydiff --git a/cubepi/providers/images/faux.py b/cubeloop/providers/images/faux.pysimilarity index 94%rename from cubepi/providers/images/faux.pyrename to cubeloop/providers/images/faux.pyindex 904f4ad..de67df2 100644--- a/cubepi/providers/images/faux.py+++ b/cubeloop/providers/images/faux.py@@ -1,13 +1,13 @@from __future__ import annotations-from cubepi.errors import ProviderError-from cubepi.providers.base import (+from cubeloop.errors import ProviderError+from cubeloop.providers.base import (ImageContent,_fire_request_listeners,_fire_response_listeners,)-from cubepi.providers.images.base import BaseImagesProvider-from cubepi.providers.images.types import (+from cubeloop.providers.images.base import BaseImagesProvider+from cubeloop.providers.images.types import (AssistantImages,ImagesAborted,ImagesContext,diff --git a/cubepi/providers/images/openai_images.py b/cubeloop/providers/images/openai_images.pysimilarity index 97%rename from cubepi/providers/images/openai_images.pyrename to cubeloop/providers/images/openai_images.pyindex f131507..90cce4e 100644--- a/cubepi/providers/images/openai_images.py+++ b/cubeloop/providers/images/openai_images.py@@ -5,8 +5,8 @@ import base64import iofrom typing import Any-from cubepi.errors import classify_and_raise-from cubepi.providers.base import (+from cubeloop.errors import classify_and_raise+from cubeloop.providers.base import (ImageContent,OnPayloadCallback,ProviderResponse,@@ -16,9 +16,9 @@ from cubepi.providers.base import (invoke_on_payload,invoke_on_response,)-from cubepi.providers.images.base import BaseImagesProvider-from cubepi.providers.images.capability import ImagesCapabilityDescriptor-from cubepi.providers.images.types import (+from cubeloop.providers.images.base import BaseImagesProvider+from cubeloop.providers.images.capability import ImagesCapabilityDescriptor+from cubeloop.providers.images.types import (AssistantImages,ImagesAborted,ImagesContext,diff --git a/cubepi/providers/images/types.py b/cubeloop/providers/images/types.pysimilarity index 96%rename from cubepi/providers/images/types.pyrename to cubeloop/providers/images/types.pyindex 61eb52f..3220d41 100644--- a/cubepi/providers/images/types.py+++ b/cubeloop/providers/images/types.py@@ -5,14 +5,14 @@ from typing import Any, Literalfrom pydantic import BaseModel, ConfigDict, Field-from cubepi.providers.base import (+from cubeloop.providers.base import (ImageContent,OnPayloadCallback,OnResponseCallback,ProviderResponse,TextContent,)-from cubepi.types import JsonObject+from cubeloop.types import JsonObject# Re-exported so the ``OnResponseCallback`` forward reference to# ``ProviderResponse`` can be resolved when pydantic builds ``ImagesOptions``@@ -108,7 +108,7 @@ class ImagesOptions(BaseModel):class AssistantImages(BaseModel):"""Response from a successful or aborted image generation call.- Failures raise ``cubepi.errors.ProviderError`` subclasses; they never+ Failures raise ``cubeloop.errors.ProviderError`` subclasses; they neverappear as a ``stop_reason``. ``stop_reason="aborted"`` is produced when``ImagesOptions.signal`` fires mid-call."""diff --git a/cubepi/providers/models.py b/cubeloop/providers/models.pysimilarity index 89%rename from cubepi/providers/models.pyrename to cubeloop/providers/models.pyindex 01d7bca..4388850 100644--- a/cubepi/providers/models.py+++ b/cubeloop/providers/models.py@@ -1,6 +1,6 @@from __future__ import annotations-from cubepi.providers.base import Model+from cubeloop.providers.base import Modeldef models_are_equal(a: Model | None, b: Model | None) -> bool:diff --git a/cubepi/providers/openai.py b/cubeloop/providers/openai.pysimilarity index 99%rename from cubepi/providers/openai.pyrename to cubeloop/providers/openai.pyindex aa39fc6..a454197 100644--- a/cubepi/providers/openai.py+++ b/cubeloop/providers/openai.py@@ -5,14 +5,14 @@ import jsonimport timefrom typing import Any-from cubepi.utils.json_parse import parse_streaming_json+from cubeloop.utils.json_parse import parse_streaming_json-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,apply_reasoning_control,apply_temperature,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,ImageContent,@@ -37,7 +37,7 @@ from cubepi.providers.base import (invoke_on_response,typed_error_event,)-from cubepi.providers.reasoning_profiles import get_capability_profile+from cubeloop.providers.reasoning_profiles import get_capability_profileclass OpenAIProvider(BaseProvider):@@ -177,7 +177,7 @@ class OpenAIProvider(BaseProvider):try:response = await self._client.chat.completions.create(**kwargs)except Exception as _sdk_exc:- from cubepi.errors import classify_and_raise+ from cubeloop.errors import classify_and_raiseclassify_and_raise(_sdk_exc, model=model, messages=messages)@@ -526,7 +526,7 @@ class OpenAIProvider(BaseProvider):# try/except didn't catch — async-for-chunk iteration errors# (mid-stream connection drops, timeouts) arrive here raw.if isinstance(e, Exception):- from cubepi.errors import classify_and_raise+ from cubeloop.errors import classify_and_raisetry:classify_and_raise(e, model=model, messages=messages)diff --git a/cubepi/providers/openai_responses.py b/cubeloop/providers/openai_responses.pysimilarity index 99%rename from cubepi/providers/openai_responses.pyrename to cubeloop/providers/openai_responses.pyindex 8e804bc..bf6b89c 100644--- a/cubepi/providers/openai_responses.py+++ b/cubeloop/providers/openai_responses.py@@ -5,7 +5,7 @@ import jsonimport timefrom typing import Any-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,ImageContent,@@ -30,12 +30,12 @@ from cubepi.providers.base import (invoke_on_response,typed_error_event,)-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,apply_reasoning_control,apply_temperature,)-from cubepi.providers.reasoning_profiles import get_capability_profile+from cubeloop.providers.reasoning_profiles import get_capability_profileclass OpenAIResponsesProvider(BaseProvider):@@ -165,7 +165,7 @@ class OpenAIResponsesProvider(BaseProvider):try:response = await self._client.responses.create(**kwargs)except Exception as _sdk_exc:- from cubepi.errors import classify_and_raise+ from cubeloop.errors import classify_and_raiseclassify_and_raise(_sdk_exc, model=model, messages=messages)@@ -563,7 +563,7 @@ class OpenAIResponsesProvider(BaseProvider):# try/except didn't catch — async-for-event iteration errors# arrive here raw.if isinstance(e, Exception):- from cubepi.errors import classify_and_raise+ from cubeloop.errors import classify_and_raisetry:classify_and_raise(e, model=model, messages=messages)diff --git a/cubepi/providers/reasoning_profiles.py b/cubeloop/providers/reasoning_profiles.pysimilarity index 95%rename from cubepi/providers/reasoning_profiles.pyrename to cubeloop/providers/reasoning_profiles.pyindex 287ccfd..f12610e 100644--- a/cubepi/providers/reasoning_profiles.py+++ b/cubeloop/providers/reasoning_profiles.py@@ -2,8 +2,8 @@ from __future__ import annotationsfrom typing import Any-from cubepi.providers.base import ReasoningEffort, ReasoningSummary-from cubepi.providers.capability import CapabilityDescriptor, ReasoningCapability+from cubeloop.providers.base import ReasoningEffort, ReasoningSummary+from cubeloop.providers.capability import CapabilityDescriptor, ReasoningCapability_OPENAI_EFFORT_VALUES: dict[ReasoningEffort, str] = {diff --git a/cubepi/py.typed b/cubeloop/py.typedsimilarity index 100%rename from cubepi/py.typedrename to cubeloop/py.typeddiff --git a/cubepi/tracing/__init__.py b/cubeloop/tracing/__init__.pysimilarity index 59%rename from cubepi/tracing/__init__.pyrename to cubeloop/tracing/__init__.pyindex 8ce311e..5e2768e 100644--- a/cubepi/tracing/__init__.py+++ b/cubeloop/tracing/__init__.py@@ -1,6 +1,6 @@-"""cubepi.tracing — OpenTelemetry-compatible observability for cubepi agents.+"""cubeloop.tracing — OpenTelemetry-compatible observability for cubepi agents.-Build a :class:`Tracer`, attach it to an :class:`~cubepi.agent.Agent`, and+Build a :class:`Tracer`, attach it to an :class:`~cubeloop.agent.Agent`, andspans will flow to whichever :class:`~opentelemetry.sdk.trace.export.SpanExporter`implementations you configure (e.g. :class:`JsonlSpanExporter` for localfiles, or the OTLP exporter shipped with ``opentelemetry-exporter-otlp-proto-http``).@@ -9,7 +9,7 @@ The heavyweight members (:class:`Tracer`, :class:`Meter`,:class:`JsonlSpanExporter`, :func:`tracing_context`, ``SCHEMA_URL``) requirethe optional ``opentelemetry-sdk`` dependency; install with``pip install cubepi[tracing]``. They are imported lazily so that pure-metadata-submodules such as :mod:`cubepi.tracing.schema` remain importable without the+submodules such as :mod:`cubeloop.tracing.schema` remain importable without theSDK (used by the ``cubepi trace`` CLI)."""@@ -27,19 +27,19 @@ __all__ = []if TYPE_CHECKING: # pragma: no cover- from cubepi.tracing.context import tracing_context- from cubepi.tracing.exporters import JsonlSpanExporter- from cubepi.tracing.meter import Meter- from cubepi.tracing.schema import SCHEMA_URL- from cubepi.tracing.tracer import Tracer, trace+ from cubeloop.tracing.context import tracing_context+ from cubeloop.tracing.exporters import JsonlSpanExporter+ from cubeloop.tracing.meter import Meter+ from cubeloop.tracing.schema import SCHEMA_URL+ from cubeloop.tracing.tracer import Tracer, trace_LAZY = {- "tracing_context": ("cubepi.tracing.context", "tracing_context"),- "JsonlSpanExporter": ("cubepi.tracing.exporters", "JsonlSpanExporter"),- "Meter": ("cubepi.tracing.meter", "Meter"),- "SCHEMA_URL": ("cubepi.tracing.schema", "SCHEMA_URL"),- "Tracer": ("cubepi.tracing.tracer", "Tracer"),- "trace": ("cubepi.tracing.tracer", "trace"),+ "tracing_context": ("cubeloop.tracing.context", "tracing_context"),+ "JsonlSpanExporter": ("cubeloop.tracing.exporters", "JsonlSpanExporter"),+ "Meter": ("cubeloop.tracing.meter", "Meter"),+ "SCHEMA_URL": ("cubeloop.tracing.schema", "SCHEMA_URL"),+ "Tracer": ("cubeloop.tracing.tracer", "Tracer"),+ "trace": ("cubeloop.tracing.tracer", "trace"),}@@ -52,7 +52,7 @@ def __getattr__(name: str) -> Any:import opentelemetry.sdk.trace # noqa: F401except ImportError as exc: # pragma: no cover — only without the extra.raise ImportError(- "cubepi.tracing requires the 'opentelemetry-sdk' package. "+ "cubeloop.tracing requires the 'opentelemetry-sdk' package. ""Install it via: pip install cubepi[tracing]") from excimport importlibdiff --git a/cubepi/tracing/content.py b/cubeloop/tracing/content.pysimilarity index 99%rename from cubepi/tracing/content.pyrename to cubeloop/tracing/content.pyindex 4ea2da2..fc7706c 100644--- a/cubepi/tracing/content.py+++ b/cubeloop/tracing/content.py@@ -13,7 +13,7 @@ from __future__ import annotationsimport jsonfrom typing import Any-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,Message,TextContent,diff --git a/cubepi/tracing/context.py b/cubeloop/tracing/context.pysimilarity index 74%rename from cubepi/tracing/context.pyrename to cubeloop/tracing/context.pyindex c727646..9b2e563 100644--- a/cubepi/tracing/context.py+++ b/cubeloop/tracing/context.py@@ -1,21 +1,21 @@-"""Per-run tagging / metadata context for cubepi.tracing.+"""Per-run tagging / metadata context for cubeloop.tracing.Sets a contextvar-scoped ``tags`` / ``metadata`` payload that the-:class:`~cubepi.tracing.recorder.Recorder` reads on ``AgentStartEvent``+:class:`~cubeloop.tracing.recorder.Recorder` reads on ``AgentStartEvent``and stamps onto the ``invoke_agent`` span. Inspired by LangSmith's``langsmith.run_helpers.tracing_context`` (same contextvar mechanism).Namespacing:-- Tags use a single attribute ``cubepi.tags`` (tuple of strings).-- User metadata is namespaced under ``cubepi.metadata.*`` so that- recorder-owned schema keys (``cubepi.run_id``,- ``cubepi.turn.index``, …) can never be overridden by+- Tags use a single attribute ``cubeloop.tags`` (tuple of strings).+- User metadata is namespaced under ``cubeloop.metadata.*`` so that+ recorder-owned schema keys (``cubeloop.run_id``,+ ``cubeloop.turn.index``, …) can never be overridden bycaller-supplied values.Usage::- from cubepi.tracing import tracing_context+ from cubeloop.tracing import tracing_contextasync with tracer.attached(agent):with tracing_context(tags=["beta-arm"], metadata={"user_id": "u-42"}):@@ -25,8 +25,8 @@ Usage::Resulting ``invoke_agent`` span attributes:-- ``cubepi.tags`` = ``("beta-arm",)``-- ``cubepi.metadata.user_id`` = ``"u-42"``+- ``cubeloop.tags`` = ``("beta-arm",)``+- ``cubeloop.metadata.user_id`` = ``"u-42"``Multiple nested ``tracing_context`` blocks merge: inner tags areappended, inner metadata keys override outer ones (last-write-wins).@@ -40,11 +40,11 @@ from typing import Any, Iterator_run_metadata: contextvars.ContextVar[dict[str, Any]] = contextvars.ContextVar(- "cubepi.tracing.run_metadata", default={}+ "cubeloop.tracing.run_metadata", default={})_run_tags: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar(- "cubepi.tracing.run_tags", default=()+ "cubeloop.tracing.run_tags", default=())@@ -59,12 +59,12 @@ def tracing_context(The recorder reads these contextvars on ``AgentStartEvent`` andstamps them on the ``invoke_agent`` span as:- - ``cubepi.tags`` — tuple of strings (OTel attribute type)+ - ``cubeloop.tags`` — tuple of strings (OTel attribute type)- one attribute per metadata key, namespaced under- ``cubepi.metadata.*`` (e.g. ``metadata={"user_id": "u-42"}`` →- ``cubepi.metadata.user_id = "u-42"``). The dedicated+ ``cubeloop.metadata.*`` (e.g. ``metadata={"user_id": "u-42"}`` →+ ``cubeloop.metadata.user_id = "u-42"``). The dedicatedsub-namespace keeps recorder-owned schema keys- (``cubepi.run_id``, ``cubepi.turn.index``, …) safe from+ (``cubeloop.run_id``, ``cubeloop.turn.index``, …) safe fromcaller-supplied collisions.The contextvar nature means this works for concurrent agents:@@ -95,7 +95,7 @@ def tracing_context(def _current_tags() -> tuple[str, ...]:"""Internal: return the active tag tuple for the current task.- Called by :class:`~cubepi.tracing.recorder.Recorder` on+ Called by :class:`~cubeloop.tracing.recorder.Recorder` on``_on_agent_start``; not part of the public API."""return _run_tags.get()diff --git a/cubepi/tracing/errors.py b/cubeloop/tracing/errors.pysimilarity index 90%rename from cubepi/tracing/errors.pyrename to cubeloop/tracing/errors.pyindex 30c618f..e77fb54 100644--- a/cubepi/tracing/errors.py+++ b/cubeloop/tracing/errors.py@@ -8,7 +8,7 @@ The OTel GenAI semantic convention does NOT prescribe a closed enum for- Provider client class raised → fully-qualified Python class name- Network timeout → ``"timeout"``- Connection refused → ``"connection_error"``-- Agent aborted → ``"cubepi.aborted"``+- Agent aborted → ``"cubeloop.aborted"``- Tool / business error → exception class name"""@@ -17,14 +17,14 @@ from __future__ import annotationsimport asyncio-def cubepi_error_type_for(exc: BaseException) -> str:+def cubeloop_error_type_for(exc: BaseException) -> str:"""Derive an ``error.type`` value for a thrown exception.Cheap and best-effort; observers should rely on the``gen_ai.client.operation.exception`` event for full details."""if isinstance(exc, asyncio.CancelledError):- return "cubepi.aborted"+ return "cubeloop.aborted"if isinstance(exc, asyncio.TimeoutError):return "timeout"if isinstance(exc, TimeoutError): # builtin in 3.11+diff --git a/cubepi/tracing/exporters/__init__.py b/cubeloop/tracing/exporters/__init__.pysimilarity index 83%rename from cubepi/tracing/exporters/__init__.pyrename to cubeloop/tracing/exporters/__init__.pyindex 5de8b1f..c4f4785 100644--- a/cubepi/tracing/exporters/__init__.py+++ b/cubeloop/tracing/exporters/__init__.py@@ -1,17 +1,17 @@-"""Span exporter implementations for cubepi.tracing.+"""Span exporter implementations for cubeloop.tracing.JsonlSpanExporter is always available (depends only on the SDK).OTLPSpanExporter is re-exported from``opentelemetry-exporter-otlp-proto-http`` when the ``tracing-otlp``optional dependency is installed. Without that extra, accessing-``cubepi.tracing.exporters.OTLPSpanExporter`` raises ``ImportError``+``cubeloop.tracing.exporters.OTLPSpanExporter`` raises ``ImportError``with an actionable install hint."""from __future__ import annotations-from cubepi.tracing.exporters.jsonl import JsonlSpanExporter+from cubeloop.tracing.exporters.jsonl import JsonlSpanExporter__all__ = ["JsonlSpanExporter", "OTLPSpanExporter"]diff --git a/cubepi/tracing/exporters/jsonl.py b/cubeloop/tracing/exporters/jsonl.pysimilarity index 95%rename from cubepi/tracing/exporters/jsonl.pyrename to cubeloop/tracing/exporters/jsonl.pyindex 5967470..12ae47e 100644--- a/cubepi/tracing/exporters/jsonl.py+++ b/cubeloop/tracing/exporters/jsonl.py@@ -25,7 +25,7 @@ class JsonlSpanExporter(SpanExporter):Files: ``<directory>/<YYYY-MM-DD>/<trace_id>.jsonl``, one file per traceso the parent run and any nested subagent runs (same trace_id, different- ``cubepi.run_id``) land together. The date used for the subdirectory is+ ``cubeloop.run_id``) land together. The date used for the subdirectory isthe span's start time (UTC). The ``trace_id`` is the span's 32-hex traceid; spans without a context fall back to ``"unknown-trace"``.@@ -34,7 +34,7 @@ class JsonlSpanExporter(SpanExporter):def __init__(self,- directory: str | os.PathLike[str] = "./cubepi-traces",+ directory: str | os.PathLike[str] = "./cubeloop-traces",) -> None:self._directory = Path(directory)self._shutdown = False@@ -86,7 +86,7 @@ class JsonlSpanExporter(SpanExporter):else:date_dir = datetime.now(tz=timezone.utc).strftime("%Y-%m-%d")ctx = span.get_span_context()- # Use is_valid (matches cubepi.mcp._tracing / http_loader convention):+ # Use is_valid (matches cubeloop.mcp._tracing / http_loader convention):# guards trace_id != 0 idiomatically; invalid contexts → unknown-trace.trace_id = (format(ctx.trace_id, "032x")diff --git a/cubepi/tracing/meter.py b/cubeloop/tracing/meter.pysimilarity index 97%rename from cubepi/tracing/meter.pyrename to cubeloop/tracing/meter.pyindex 36762cf..2dade29 100644--- a/cubepi/tracing/meter.py+++ b/cubeloop/tracing/meter.py@@ -1,6 +1,6 @@-"""``Meter`` — OTel histograms for cubepi.tracing.+"""``Meter`` — OTel histograms for cubeloop.tracing.-Mirrors :class:`cubepi.tracing.tracer.Tracer` in shape: construct once,+Mirrors :class:`cubeloop.tracing.tracer.Tracer` in shape: construct once,``attach(agent)`` to wire metrics emission to the agent's event stream+ provider listeners.@@ -29,8 +29,8 @@ from opentelemetry.sdk.metrics.export import ()from opentelemetry.sdk.resources import Resource-import cubepi-from cubepi.tracing.schema import (+import cubeloop+from cubeloop.tracing.schema import (GEN_AI_OPERATION_NAME,GEN_AI_PROVIDER_NAME,GEN_AI_REQUEST_MODEL,@@ -44,8 +44,8 @@ from cubepi.tracing.schema import ()if TYPE_CHECKING:- from cubepi.agent.agent import Agent- from cubepi.providers.base import Model+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import Model#: Recommended GenAI metric bucket boundaries per the semconv spec@@ -77,7 +77,7 @@ class Meter:Example::- from cubepi.tracing import Tracer, Meter+ from cubeloop.tracing import Tracer, Meterfrom opentelemetry.exporter.otlp.proto.http.metric_exporter import (OTLPMetricExporter,)@@ -112,7 +112,7 @@ class Meter:self._provider = MeterProvider(resource=self._resource, metric_readers=readers)self._otel_meter = self._provider.get_meter(name=SCOPE_NAME,- version=cubepi.__version__,+ version=cubeloop.__version__,schema_url=SCHEMA_URL,)self._duration_hist = self._otel_meter.create_histogram(@@ -153,7 +153,7 @@ class Meter:overwrote the first agent's ``_chat_open_ns`` / ``_chat_attrs``before its response landed)."""- from cubepi.providers.base import BaseProvider, collect_agent_providers+ from cubeloop.providers.base import BaseProvider, collect_agent_providersstate = _MeterState()diff --git a/cubepi/tracing/recorder.py b/cubeloop/tracing/recorder.pysimilarity index 92%rename from cubepi/tracing/recorder.pyrename to cubeloop/tracing/recorder.pyindex dfd964b..0ebec36 100644--- a/cubepi/tracing/recorder.py+++ b/cubeloop/tracing/recorder.py@@ -4,7 +4,7 @@ OpenTelemetry spans.Span hierarchy::invoke_agent <agent_name> [INTERNAL]- └── cubepi.turn [INTERNAL]+ └── cubeloop.turn [INTERNAL]├── chat <model> [CLIENT] (lifetime: provider listeners)└── execute_tool <tool_name> [INTERNAL]@@ -31,7 +31,7 @@ from typing import IO, TYPE_CHECKING, Any, Callablefrom opentelemetry import tracefrom opentelemetry.trace import SpanKind, Status, StatusCode-from cubepi.agent.types import (+from cubeloop.agent.types import (AgentEndEvent,AgentStartEvent,AgentSuspendedEvent,@@ -42,7 +42,7 @@ from cubepi.agent.types import (ToolExecutionEndEvent,ToolExecutionStartEvent,)-from cubepi.providers.base import (+from cubeloop.providers.base import (BaseProvider,StreamEvent,ToolCall,@@ -50,33 +50,33 @@ from cubepi.providers.base import (UserMessage,collect_agent_providers,)-from cubepi.tracing.content import (+from cubeloop.tracing.content import (messages_to_semconv,serialize_for_attribute,system_instructions_to_semconv,tool_definitions_to_semconv,)-from cubepi.tracing.errors import cubepi_error_type_for-from cubepi.tracing.schema import (- CUBEPI_ABORTED,- CUBEPI_AGENT_SYSTEM_PROMPT_SHA256,- CUBEPI_AGENT_TOOLS,- CUBEPI_INPUT_MESSAGES_COUNT,- CUBEPI_LLM_RAW_REQUEST,- CUBEPI_LLM_RAW_RESPONSE,- CUBEPI_LLM_THINKING_LEVEL,- CUBEPI_OUTPUT_MESSAGES_COUNT,- CUBEPI_RUN_ID,- CUBEPI_RUN_OUTCOME,- CUBEPI_TOOL_BLOCK_REASON,- CUBEPI_TOOL_BLOCKED_BY_HOOK,- CUBEPI_TOOL_EXECUTION_MODE,- CUBEPI_TOOL_IS_ERROR,- CUBEPI_TOOL_TERMINATE,- CUBEPI_TURN_INDEX,- CUBEPI_TURN_STOP_REASON,- CUBEPI_TURN_TERMINATED_BY_TOOL,- CUBEPI_TURN_TOOL_CALLS_COUNT,+from cubeloop.tracing.errors import cubeloop_error_type_for+from cubeloop.tracing.schema import (+ CUBELOOP_ABORTED,+ CUBELOOP_AGENT_SYSTEM_PROMPT_SHA256,+ CUBELOOP_AGENT_TOOLS,+ CUBELOOP_INPUT_MESSAGES_COUNT,+ CUBELOOP_LLM_RAW_REQUEST,+ CUBELOOP_LLM_RAW_RESPONSE,+ CUBELOOP_LLM_THINKING_LEVEL,+ CUBELOOP_OUTPUT_MESSAGES_COUNT,+ CUBELOOP_RUN_ID,+ CUBELOOP_RUN_OUTCOME,+ CUBELOOP_TOOL_BLOCK_REASON,+ CUBELOOP_TOOL_BLOCKED_BY_HOOK,+ CUBELOOP_TOOL_EXECUTION_MODE,+ CUBELOOP_TOOL_IS_ERROR,+ CUBELOOP_TOOL_TERMINATE,+ CUBELOOP_TURN_INDEX,+ CUBELOOP_TURN_STOP_REASON,+ CUBELOOP_TURN_TERMINATED_BY_TOOL,+ CUBELOOP_TURN_TOOL_CALLS_COUNT,ERROR_TYPE,EVENT_GEN_AI_EXCEPTION,GEN_AI_INPUT_MESSAGES,@@ -120,9 +120,9 @@ from cubepi.tracing.schema import ()if TYPE_CHECKING:- from cubepi.agent.agent import Agent- from cubepi.providers.base import Model- from cubepi.tracing.tracer import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import Model+ from cubeloop.tracing.tracer import Tracer# Per-task "active run" gate. A provider instance shared by a parent@@ -134,7 +134,7 @@ if TYPE_CHECKING:# its run owns the current asyncio task, and the provider listeners act# only when the active run matches their own run._active_run: contextvars.ContextVar[object | None] = contextvars.ContextVar(- "cubepi.tracing.active_run", default=None+ "cubeloop.tracing.active_run", default=None)@@ -151,7 +151,7 @@ class _RunState:chat_first_chunk_recorded: bool = Falsetool_spans: dict[str, Any] = field(default_factory=dict)# contextvars.Token per tool_call_id, returned by- # ``cubepi.mcp._tracing.register_tool_span``. Passed back on+ # ``cubeloop.mcp._tracing.register_tool_span``. Passed back on# ``unregister_tool_span`` to restore the prior contextvar state.tool_span_tokens: dict[str, Any] = field(default_factory=dict)# Caller-supplied extra attrs for this run (set via run_scope, future).@@ -458,7 +458,7 @@ class Recorder:``Exception`` path*. ``asyncio.CancelledError`` inherits from``BaseException`` and bypasses that handler, so a run cancelledwhile an MCP tool was in flight leaves the registration alive- in :mod:`cubepi.mcp._tracing._active_entries`. Repeated aborts+ in :mod:`cubeloop.mcp._tracing._active_entries`. Repeated abortswould leak parent-span/provider pairs for the lifetime of theprocess.@@ -470,7 +470,7 @@ class Recorder:if run is None or not run.tool_span_tokens:returntry:- from cubepi.mcp import _tracing as _mcp_tracing+ from cubeloop.mcp import _tracing as _mcp_tracingexcept ImportError: # pragma: no cover — mcp module always presentrun.tool_span_tokens.clear()return@@ -500,7 +500,7 @@ class Recorder:def _close_open_spans(self, run: "_RunState | None") -> None:"""End any spans still open on ``run``.- Normal flow ends ``execute_tool`` / ``chat`` / ``cubepi.turn`` /+ Normal flow ends ``execute_tool`` / ``chat`` / ``cubeloop.turn`` /``invoke_agent`` spans in their respective event handlers. But``asyncio.CancelledError`` bypasses cubepi's agent-loop``except Exception`` handler — no ``ToolExecutionEnd`` /@@ -509,7 +509,7 @@ class Recorder:never exports them: cancelled runs simply disappear from thebackend (codex overall-review BLOCKING).- Each span gets ``cubepi.aborted=true`` + ``error.type`` so the+ Each span gets ``cubeloop.aborted=true`` + ``error.type`` so thebackend sees the run was interrupted rather than silentlysucceeding. Status is left UNSET — cancellation isn't afailure.@@ -518,16 +518,16 @@ class Recorder:returnfor span in list(run.tool_spans.values()):try:- span.set_attribute(CUBEPI_ABORTED, True)- span.set_attribute(ERROR_TYPE, "cubepi.aborted")+ span.set_attribute(CUBELOOP_ABORTED, True)+ span.set_attribute(ERROR_TYPE, "cubeloop.aborted")span.end()except Exception:passrun.tool_spans.clear()if run.chat_span is not None:try:- run.chat_span.set_attribute(CUBEPI_ABORTED, True)- run.chat_span.set_attribute(ERROR_TYPE, "cubepi.aborted")+ run.chat_span.set_attribute(CUBELOOP_ABORTED, True)+ run.chat_span.set_attribute(ERROR_TYPE, "cubeloop.aborted")run.chat_span.end()except Exception:pass@@ -536,14 +536,14 @@ class Recorder:run.chat_first_chunk_recorded = Falseif run.turn_span is not None:try:- run.turn_span.set_attribute(CUBEPI_ABORTED, True)+ run.turn_span.set_attribute(CUBELOOP_ABORTED, True)run.turn_span.end()except Exception:passrun.turn_span = Noneif run.agent_span is not None:try:- run.agent_span.set_attribute(CUBEPI_ABORTED, True)+ run.agent_span.set_attribute(CUBELOOP_ABORTED, True)run.agent_span.end()except Exception:pass@@ -591,9 +591,9 @@ class Recorder:parent_ctx = Nonetry:# TODO(tracing): relocate this "current tool span" helper out of- # cubepi.mcp._tracing — it now serves generic nested agents, not+ # cubeloop.mcp._tracing — it now serves generic nested agents, not# just MCP clients.- from cubepi.mcp import _tracing as _mcp_tracing+ from cubeloop.mcp import _tracing as _mcp_tracingentry = _mcp_tracing._get_tool_span_entry()if entry is not None:@@ -607,7 +607,7 @@ class Recorder:context=parent_ctx,attributes={GEN_AI_OPERATION_NAME: OP_INVOKE_AGENT,- CUBEPI_RUN_ID: run_id,+ CUBELOOP_RUN_ID: run_id,# gen_ai.provider.name is required by semconv; we set a# placeholder here and overwrite at the first chat span# with the actual provider id.@@ -632,23 +632,23 @@ class Recorder:# the same provider instance).self._active_run_token = _active_run.set(self._run)- # Stamp any tags / metadata set via ``cubepi.tracing.tracing_context``+ # Stamp any tags / metadata set via ``cubeloop.tracing.tracing_context``# for this run. Per-task contextvar scoping means concurrent# agents each see their own values; nested ``tracing_context``# blocks merge before reaching here.#- # User metadata is namespaced under ``cubepi.metadata.*`` so+ # User metadata is namespaced under ``cubeloop.metadata.*`` so# that keys like ``run_id`` / ``turn_index`` / ``agent.tools``- # — which the recorder owns under ``cubepi.*`` — can never be+ # — which the recorder owns under ``cubeloop.*`` — can never be# overwritten by caller-supplied values. Reserved cubepi- # schema keys (especially ``cubepi.run_id``, a per-span filtering+ # schema keys (especially ``cubeloop.run_id``, a per-span filtering# attribute) must stay recorder-controlled (codex P2 on PR #92).try:- from cubepi.tracing.context import _current_metadata, _current_tags+ from cubeloop.tracing.context import _current_metadata, _current_tagstags = _current_tags()if tags:- span.set_attribute("cubepi.tags", tags)+ span.set_attribute("cubeloop.tags", tags)metadata = _current_metadata()for key, value in metadata.items():# OTel attribute values are limited to scalar primitives@@ -656,7 +656,7 @@ class Recorder:# dropped here — better to lose one tag than corrupt the# whole span.try:- span.set_attribute(f"cubepi.metadata.{key}", value)+ span.set_attribute(f"cubeloop.metadata.{key}", value)except (TypeError, ValueError):passexcept ImportError: # pragma: no cover — context module always available@@ -702,14 +702,14 @@ class Recorder:returnfor span in list(run.tool_spans.values()):try:- span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")+ span.set_attribute(CUBELOOP_RUN_OUTCOME, "suspended")span.end()except Exception:passrun.tool_spans.clear()if run.chat_span is not None:try:- run.chat_span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")+ run.chat_span.set_attribute(CUBELOOP_RUN_OUTCOME, "suspended")run.chat_span.end()except Exception:pass@@ -718,14 +718,14 @@ class Recorder:run.chat_first_chunk_recorded = Falseif run.turn_span is not None:try:- run.turn_span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")+ run.turn_span.set_attribute(CUBELOOP_RUN_OUTCOME, "suspended")run.turn_span.end()except Exception:passrun.turn_span = None- run.agent_span.set_attribute(CUBEPI_RUN_OUTCOME, "suspended")+ run.agent_span.set_attribute(CUBELOOP_RUN_OUTCOME, "suspended")run.agent_span.set_attribute(- CUBEPI_OUTPUT_MESSAGES_COUNT, len(run.output_messages)+ CUBELOOP_OUTPUT_MESSAGES_COUNT, len(run.output_messages))run.agent_span.end()self._sweep_tool_span_tokens(run)@@ -744,7 +744,7 @@ class Recorder:returnrun.new_message_count = len(event.messages)run.agent_span.set_attribute(- CUBEPI_OUTPUT_MESSAGES_COUNT, run.new_message_count+ CUBELOOP_OUTPUT_MESSAGES_COUNT, run.new_message_count)if self._record_content:if run.system_prompt:@@ -786,7 +786,7 @@ class Recorder:self._run = None# ------------------------------------------------------------------- # cubepi.turn+ # cubeloop.turn# ------------------------------------------------------------------def _on_turn_start(self) -> None:@@ -800,11 +800,11 @@ class Recorder:kind=SpanKind.INTERNAL,context=ctx,attributes={- CUBEPI_TURN_INDEX: run.turn_index,+ CUBELOOP_TURN_INDEX: run.turn_index,# Propagate run_id so every child span carries it —# OTel does NOT inherit attributes from parent spans. It's a# filtering attribute; the JSONL exporter shards by trace_id.- CUBEPI_RUN_ID: run.run_id,+ CUBELOOP_RUN_ID: run.run_id,},)run.turn_terminated_by_tool = False@@ -829,15 +829,15 @@ class Recorder:# record the cubepi-normalized stop_reason on the turn span.stop_reason = getattr(msg, "stop_reason", None)if stop_reason:- run.turn_span.set_attribute(CUBEPI_TURN_STOP_REASON, stop_reason)+ run.turn_span.set_attribute(CUBELOOP_TURN_STOP_REASON, stop_reason)tool_calls_count = sum(1for c in getattr(msg, "content", [])if getattr(c, "type", "") == "tool_call")- run.turn_span.set_attribute(CUBEPI_TURN_TOOL_CALLS_COUNT, tool_calls_count)+ run.turn_span.set_attribute(CUBELOOP_TURN_TOOL_CALLS_COUNT, tool_calls_count)if run.turn_terminated_by_tool:- run.turn_span.set_attribute(CUBEPI_TURN_TERMINATED_BY_TOOL, True)+ run.turn_span.set_attribute(CUBELOOP_TURN_TERMINATED_BY_TOOL, True)# Content: record per-turn input/output messages if enabled.if self._record_content:if run.turn_input_messages:@@ -854,7 +854,7 @@ class Recorder:)# Error handling on the turn: if assistant message stopped with# "error", mark turn ERROR. Abort path leaves UNSET + sets- # cubepi.aborted on the invoke_agent root.+ # cubeloop.aborted on the invoke_agent root.if stop_reason == "error":err_msg = ((getattr(msg, "error_message", None) or "model error")@@ -862,10 +862,10 @@ class Recorder:else "model error")run.turn_span.set_status(Status(StatusCode.ERROR, err_msg[:256]))- run.turn_span.set_attribute(ERROR_TYPE, "cubepi.error")+ run.turn_span.set_attribute(ERROR_TYPE, "cubeloop.error")elif stop_reason == "aborted":- run.turn_span.set_attribute(CUBEPI_ABORTED, True)- run.agent_span.set_attribute(CUBEPI_ABORTED, True)+ run.turn_span.set_attribute(CUBELOOP_ABORTED, True)+ run.agent_span.set_attribute(CUBELOOP_ABORTED, True)run.turn_span.end()run.turn_span = None@@ -885,7 +885,7 @@ class Recorder:GEN_AI_TOOL_TYPE: "function",# Record run_id as a span attribute (for filtering); the JSONL# exporter now shards by trace_id, not run_id.- CUBEPI_RUN_ID: run.run_id,+ CUBELOOP_RUN_ID: run.run_id,}# NOTE: gen_ai.tool.call.arguments is opt-in content recorded# after start_span so the redaction hook can run before the@@ -896,7 +896,7 @@ class Recorder:if tool_obj.description:attrs[GEN_AI_TOOL_DESCRIPTION] = tool_obj.descriptionmode = tool_obj.execution_mode or "parallel"- attrs[CUBEPI_TOOL_EXECUTION_MODE] = mode+ attrs[CUBELOOP_TOOL_EXECUTION_MODE] = modespan = self._tracer.otel_tracer.start_span(name=f"{SPAN_NAME_EXECUTE_TOOL} {event.tool_name}",kind=SpanKind.INTERNAL,@@ -905,7 +905,7 @@ class Recorder:)run.tool_spans[event.tool_call_id] = span# Expose this execute_tool span (and its owning provider) to- # ``cubepi.mcp._tracing`` via a per-task contextvar so an MCP+ # ``cubeloop.mcp._tracing`` via a per-task contextvar so an MCP# tool call running inside the AgentTool body inherits the# right parent. Per-task scoping avoids the global-dict# collision when concurrent agents reuse the same tool_call_id@@ -913,7 +913,7 @@ class Recorder:# conversation — codex round-8). The recorder stashes the# contextvar reset token on _RunState to undo on exec_end.try:- from cubepi.mcp import _tracing as _mcp_tracing+ from cubeloop.mcp import _tracing as _mcp_tracingcv_token = _mcp_tracing.register_tool_span(event.tool_call_id,@@ -936,31 +936,31 @@ class Recorder:span = run.tool_spans.pop(event.tool_call_id, None)cv_token = run.tool_span_tokens.pop(event.tool_call_id, None)try:- from cubepi.mcp import _tracing as _mcp_tracing+ from cubeloop.mcp import _tracing as _mcp_tracing_mcp_tracing.unregister_tool_span(cv_token)except ImportError: # pragma: no cover — mcp module always presentpassif span is None:return- span.set_attribute(CUBEPI_TOOL_IS_ERROR, event.is_error)+ span.set_attribute(CUBELOOP_TOOL_IS_ERROR, event.is_error)if self._record_content and event.result is not None:self._set_content_attr(span, GEN_AI_TOOL_CALL_RESULT, _coerce_dict(event.result))if event.terminate:- span.set_attribute(CUBEPI_TOOL_TERMINATE, True)+ span.set_attribute(CUBELOOP_TOOL_TERMINATE, True)run.turn_terminated_by_tool = Trueif event.blocked_by_hook:- span.set_attribute(CUBEPI_TOOL_BLOCKED_BY_HOOK, True)+ span.set_attribute(CUBELOOP_TOOL_BLOCKED_BY_HOOK, True)if event.block_reason is not None:- span.set_attribute(CUBEPI_TOOL_BLOCK_REASON, event.block_reason)+ span.set_attribute(CUBELOOP_TOOL_BLOCK_REASON, event.block_reason)if event.is_error:span.set_status(Status(StatusCode.ERROR, "tool error"))err_type = (- "cubepi.tool.blocked_by_hook"+ "cubeloop.tool.blocked_by_hook"if event.blocked_by_hook- else "cubepi.tool.error"+ else "cubeloop.tool.error")span.set_attribute(ERROR_TYPE, err_type)span.end()@@ -980,10 +980,10 @@ class Recorder:# when ``record_content=True``).if isinstance(msg, (UserMessage, ToolResultMessage)):run.agent_span.set_attribute(- CUBEPI_INPUT_MESSAGES_COUNT,+ CUBELOOP_INPUT_MESSAGES_COUNT,int((run.agent_span.attributes or {}).get(- CUBEPI_INPUT_MESSAGES_COUNT, 0+ CUBELOOP_INPUT_MESSAGES_COUNT, 0))+ 1,@@ -1032,7 +1032,7 @@ class Recorder:GEN_AI_REQUEST_STREAM: True,# Record run_id as a span attribute (for filtering); the JSONL# exporter now shards by trace_id, not run_id.- CUBEPI_RUN_ID: run.run_id,+ CUBELOOP_RUN_ID: run.run_id,}# Pull StreamOptions-derived params from the payload where the# provider exposed them as final kwargs.@@ -1054,16 +1054,16 @@ class Recorder:if payload.get("service_tier"):attrs[OPENAI_REQUEST_SERVICE_TIER] = payload["service_tier"]- # Thinking level on cubepi.* namespace.+ # Thinking level on cubeloop.* namespace.thinking = payload.get("thinking")if isinstance(thinking, dict) and thinking.get("type") == "enabled":- attrs[CUBEPI_LLM_THINKING_LEVEL] = "on"+ attrs[CUBELOOP_LLM_THINKING_LEVEL] = "on"elif thinking is None and (payload.get("reasoning", {}).get("effort")if payload.get("reasoning")else None):- attrs[CUBEPI_LLM_THINKING_LEVEL] = payload["reasoning"]["effort"]+ attrs[CUBELOOP_LLM_THINKING_LEVEL] = payload["reasoning"]["effort"]# Root ``invoke_agent`` span carries attribution for the agent# invocation as a whole — provider name, system prompt hash, tool@@ -1090,7 +1090,7 @@ class Recorder:tools = payload.get("tools")if isinstance(tools, list) and tools:run.agent_span.set_attribute(- CUBEPI_AGENT_TOOLS, [_safe_tool_name(t) for t in tools]+ CUBELOOP_AGENT_TOOLS, [_safe_tool_name(t) for t in tools])chat_span = self._tracer.otel_tracer.start_span(@@ -1128,7 +1128,7 @@ class Recorder:run.chat_tool_definitions = tool_defsself._set_content_attr(chat_span, GEN_AI_TOOL_DEFINITIONS, tool_defs)# Raw wire payload — large; gated by record_content.- self._set_content_attr(chat_span, CUBEPI_LLM_RAW_REQUEST, payload)+ self._set_content_attr(chat_span, CUBELOOP_LLM_RAW_REQUEST, payload)def _on_provider_chunk(self, event: StreamEvent, model: "Model") -> None:del model@@ -1248,7 +1248,7 @@ class Recorder:# itself (provider-shaped). Record both the raw# response (JSON dict) for backends that prefer it,# and the normalized output messages where derivable.- self._set_content_attr(span, CUBEPI_LLM_RAW_RESPONSE, body)+ self._set_content_attr(span, CUBELOOP_LLM_RAW_RESPONSE, body)output_message = _derive_output_message_from_body(body)if output_message:self._set_content_attr(@@ -1260,8 +1260,8 @@ class Recorder:# Mark the chat span aborted in that case so it matches# the contract for hard cancels.if body is not None and _body_is_aborted(body):- span.set_attribute(CUBEPI_ABORTED, True)- span.set_attribute(ERROR_TYPE, "cubepi.aborted")+ span.set_attribute(CUBELOOP_ABORTED, True)+ span.set_attribute(ERROR_TYPE, "cubeloop.aborted")if exc is None and body is None and self._agent_signal_is_set():# Provider abort branches (anthropic/openai/openai_responses)@@ -1271,7 +1271,7 @@ class Recorder:# inspect, so without this branch the chat span would close# UNSET — out of sync with the turn/root which TurnEnd# marks aborted. Match the cancellation contract: leave- # Status UNSET, set cubepi.aborted + error.type.+ # Status UNSET, set cubeloop.aborted + error.type.## Gate on ``agent._active_signal.is_set()`` so we don't# mistake provider-side non-abort fallbacks for aborts:@@ -1280,21 +1280,21 @@ class Recorder:# firing response listeners with body=None / exc=None# — a successful (if incomplete) completion that must# NOT be marked aborted (codex P2 follow-up on PR #87).- span.set_attribute(CUBEPI_ABORTED, True)- span.set_attribute(ERROR_TYPE, "cubepi.aborted")+ span.set_attribute(CUBELOOP_ABORTED, True)+ span.set_attribute(ERROR_TYPE, "cubeloop.aborted")elif exc is None:# Healthy completion — leave Status UNSET per OTel guidance.passelif _is_cancelled_error(exc):# Hard cancel: not a failure. Mark and leave UNSET.- span.set_attribute(CUBEPI_ABORTED, True)- span.set_attribute(ERROR_TYPE, "cubepi.aborted")+ span.set_attribute(CUBELOOP_ABORTED, True)+ span.set_attribute(ERROR_TYPE, "cubeloop.aborted")else:description = (str(exc)[:256] if self._record_content else "provider error")span.set_status(Status(StatusCode.ERROR, description))- span.set_attribute(ERROR_TYPE, cubepi_error_type_for(exc))+ span.set_attribute(ERROR_TYPE, cubeloop_error_type_for(exc))exception_attrs = {"exception.type": type(exc).__name__}if self._record_content:exception_attrs.update(@@ -1476,13 +1476,13 @@ class Recorder:span.set_attribute(GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, reasoning)def _maybe_record_system_prompt_hash(self, payload: dict, run: _RunState) -> None:- if (run.agent_span.attributes or {}).get(CUBEPI_AGENT_SYSTEM_PROMPT_SHA256):+ if (run.agent_span.attributes or {}).get(CUBELOOP_AGENT_SYSTEM_PROMPT_SHA256):returntext = _extract_system_prompt(payload)if not text:returndigest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]- run.agent_span.set_attribute(CUBEPI_AGENT_SYSTEM_PROMPT_SHA256, digest)+ run.agent_span.set_attribute(CUBELOOP_AGENT_SYSTEM_PROMPT_SHA256, digest)def _derive_output_message_from_body(body: dict) -> list[dict[str, Any]] | None:@@ -1642,7 +1642,7 @@ def _safe_tool_name(t: Any) -> str:Three shapes seen in the wild:- - Anthropic / cubepi.AgentTool: top-level ``{"name": ...}``+ - Anthropic / cubeloop.AgentTool: top-level ``{"name": ...}``- OpenAI Responses: top-level ``{"name": ..., "type": "function"}``- OpenAI Chat: nested ``{"type": "function", "function": {"name": ...}}``diff --git a/cubepi/tracing/schema.py b/cubeloop/tracing/schema.pysimilarity index 68%rename from cubepi/tracing/schema.pyrename to cubeloop/tracing/schema.pyindex dc369af..c5cef15 100644--- a/cubepi/tracing/schema.py+++ b/cubeloop/tracing/schema.py@@ -2,7 +2,7 @@Align with OpenTelemetry GenAI Semantic Conventions v1.41.0(https://opentelemetry.io/docs/specs/semconv/gen-ai/). Anything cubepi--specific lives under the ``cubepi.*`` namespace per the OTel-recommended+specific lives under the ``cubeloop.*`` namespace per the OTel-recommendedvendor-extension pattern."""@@ -96,47 +96,77 @@ EVENT_GEN_AI_EXCEPTION = "gen_ai.client.operation.exception"# ---------------------------------------------------------------------------# Per-run identity-CUBEPI_RUN_ID = "cubepi.run_id"-CUBEPI_THREAD_ID = "cubepi.thread_id"+CUBELOOP_RUN_ID = "cubeloop.run_id"+CUBELOOP_THREAD_ID = "cubeloop.thread_id"# Root span helpers-CUBEPI_AGENT_TOOLS = "cubepi.agent.tools"-CUBEPI_AGENT_SYSTEM_PROMPT_SHA256 = "cubepi.agent.system_prompt.sha256"-CUBEPI_INPUT_MESSAGES_COUNT = "cubepi.input.messages.count"-CUBEPI_OUTPUT_MESSAGES_COUNT = "cubepi.output.messages.count"-CUBEPI_RUN_OUTCOME = "cubepi.run.outcome"-CUBEPI_ABORTED = "cubepi.aborted"--# Turn span attributes (cubepi.turn span — no gen_ai.operation.name)-CUBEPI_TURN_INDEX = "cubepi.turn.index"-CUBEPI_TURN_STOP_REASON = "cubepi.turn.stop_reason"-CUBEPI_TURN_TOOL_CALLS_COUNT = "cubepi.turn.tool_calls.count"-CUBEPI_TURN_TERMINATED_BY_TOOL = "cubepi.turn.terminated_by_tool"+CUBELOOP_AGENT_TOOLS = "cubeloop.agent.tools"+CUBELOOP_AGENT_SYSTEM_PROMPT_SHA256 = "cubeloop.agent.system_prompt.sha256"+CUBELOOP_INPUT_MESSAGES_COUNT = "cubeloop.input.messages.count"+CUBELOOP_OUTPUT_MESSAGES_COUNT = "cubeloop.output.messages.count"+CUBELOOP_RUN_OUTCOME = "cubeloop.run.outcome"+CUBELOOP_ABORTED = "cubeloop.aborted"++# Turn span attributes (cubeloop.turn span — no gen_ai.operation.name)+CUBELOOP_TURN_INDEX = "cubeloop.turn.index"+CUBELOOP_TURN_STOP_REASON = "cubeloop.turn.stop_reason"+CUBELOOP_TURN_TOOL_CALLS_COUNT = "cubeloop.turn.tool_calls.count"+CUBELOOP_TURN_TERMINATED_BY_TOOL = "cubeloop.turn.terminated_by_tool"# Chat span — provider-side LLM call-CUBEPI_LLM_THINKING_LEVEL = "cubepi.llm.thinking_level"-CUBEPI_LLM_RAW_REQUEST = "cubepi.llm.raw_request"-CUBEPI_LLM_RAW_RESPONSE = "cubepi.llm.raw_response"+CUBELOOP_LLM_THINKING_LEVEL = "cubeloop.llm.thinking_level"+CUBELOOP_LLM_RAW_REQUEST = "cubeloop.llm.raw_request"+CUBELOOP_LLM_RAW_RESPONSE = "cubeloop.llm.raw_response"# Tool span-CUBEPI_TOOL_EXECUTION_MODE = "cubepi.tool.execution_mode"-CUBEPI_TOOL_IS_ERROR = "cubepi.tool.is_error"-CUBEPI_TOOL_TERMINATE = "cubepi.tool.terminate"-CUBEPI_TOOL_BLOCKED_BY_HOOK = "cubepi.tool.blocked_by_hook"-CUBEPI_TOOL_BLOCK_REASON = "cubepi.tool.block_reason"+CUBELOOP_TOOL_EXECUTION_MODE = "cubeloop.tool.execution_mode"+CUBELOOP_TOOL_IS_ERROR = "cubeloop.tool.is_error"+CUBELOOP_TOOL_TERMINATE = "cubeloop.tool.terminate"+CUBELOOP_TOOL_BLOCKED_BY_HOOK = "cubeloop.tool.blocked_by_hook"+CUBELOOP_TOOL_BLOCK_REASON = "cubeloop.tool.block_reason"# Span names (NOT semconv keys — these are name templates)SPAN_NAME_INVOKE_AGENT = "invoke_agent"-SPAN_NAME_TURN = "cubepi.turn"+SPAN_NAME_TURN = "cubeloop.turn"SPAN_NAME_CHAT = "chat"SPAN_NAME_EXECUTE_TOOL = "execute_tool"# Instrumentation scope identity-SCOPE_NAME = "cubepi.tracing"+SCOPE_NAME = "cubeloop.tracing"++# Legacy 0.13 keys — CLI dual-read only. Writers emit cubeloop.* exclusively.+_LEGACY_PREFIX = "cubepi."+CUBELOOP_TAGS = "cubeloop.tags"+CUBELOOP_METADATA_PREFIX = "cubeloop.metadata."+CUBELOOP_ONESHOT_OPERATION = "cubeloop.oneshot.operation"+ERROR_TYPE_ABORTED = "cubeloop.aborted"+ERROR_TYPE_ABORTED_LEGACY = "cubepi.aborted"+SPAN_NAME_TURN_LEGACY = "cubepi.turn"+++def attr(attributes: dict[str, object] | None, key: str) -> object | None:+ """Read ``key``, falling back to the cubepi.* spelling for 0.13 JSONL."""+ if not attributes:+ return None+ if key in attributes:+ return attributes[key]+ if key.startswith("cubeloop."):+ return attributes.get("cubepi." + key[len("cubeloop.") :])+ return None+++def is_aborted_attrs(attributes: dict[str, object] | None) -> bool:+ """True if the boolean abort flag or error.type says aborted (either namespace)."""+ if not attributes:+ return False+ if attr(attributes, CUBELOOP_ABORTED) is True:+ return True+ err = attributes.get("error.type")+ return err in {ERROR_TYPE_ABORTED, ERROR_TYPE_ABORTED_LEGACY}# ----------------------------------------------------------------------------# Provider name mapping (cubepi.Model.provider → gen_ai.provider.name)+# Provider name mapping (cubeloop.Model.provider → gen_ai.provider.name)# ---------------------------------------------------------------------------#: Cubepi providers identify themselves with short strings ondiff --git a/cubepi/tracing/tracer.py b/cubeloop/tracing/tracer.pysimilarity index 93%rename from cubepi/tracing/tracer.pyrename to cubeloop/tracing/tracer.pyindex a5969a2..fd6f091 100644--- a/cubepi/tracing/tracer.py+++ b/cubeloop/tracing/tracer.py@@ -26,12 +26,12 @@ from opentelemetry.trace import (set_span_in_context,)-import cubepi-from cubepi.tracing.schema import SCHEMA_URL, SCOPE_NAME+import cubeloop+from cubeloop.tracing.schema import SCHEMA_URL, SCOPE_NAMEif TYPE_CHECKING:- from cubepi.agent.agent import Agent- from cubepi.providers.base import BoundModel, Message+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import BoundModel, Messageclass _OneShotSession:@@ -64,10 +64,10 @@ class _OneShotSession:"""import asyncio as _asyncio- from cubepi.providers.base import (+ from cubeloop.providers.base import (StreamOptions as _StreamOptions,)- from cubepi.providers.base import (+ from cubeloop.providers.base import (TextContent as _TextContent,)@@ -123,13 +123,13 @@ class Tracer:-------::- from cubepi.tracing import Tracer- from cubepi.tracing.exporters import JsonlSpanExporter+ from cubeloop.tracing import Tracer+ from cubeloop.tracing.exporters import JsonlSpanExportertracer = Tracer(service_name="my-bot",agent_name="coding-agent",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],)detach = tracer.attach(agent)try:@@ -186,7 +186,7 @@ class Tracer:self._otel_tracer = self._provider.get_tracer(instrumenting_module_name=SCOPE_NAME,- instrumenting_library_version=cubepi.__version__,+ instrumenting_library_version=cubeloop.__version__,schema_url=SCHEMA_URL,)self._shutdown = False@@ -257,13 +257,13 @@ class Tracer:MAJOR).Also registers this Tracer's private TracerProvider with- :mod:`cubepi.mcp._tracing` so MCP CLIENT spans flow through+ :mod:`cubeloop.mcp._tracing` so MCP CLIENT spans flow throughthe same exporters — without this step, the MCP module fallsback to the OTel global default (a no-op provider when thecaller didn't separately call ``trace.set_tracer_provider``).The detach callable unregisters."""- from cubepi.tracing.recorder import Recorder+ from cubeloop.tracing.recorder import Recorderrecorder = Recorder(self,@@ -286,7 +286,7 @@ class Tracer:mcp_token: object | None = Nonemcp_tracing: Any | None = Nonetry:- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp import _tracing as mcp_tracingassert mcp_tracing is not Nonemcp_token = mcp_tracing.register_provider(@@ -458,15 +458,15 @@ class Tracer:listeners for the duration of the block, producing a ``chat`` childspan automatically when :meth:`_OneShotSession.generate` is called.- ``metadata`` keys are stamped as ``cubepi.metadata.<key>`` attributes on+ ``metadata`` keys are stamped as ``cubeloop.metadata.<key>`` attributes onthe root span and are queryable with``cubepi trace ls --meta <key>=<value>``.``operation`` is recorded in two places:- - ``cubepi.oneshot.operation`` — for span introspection and dashboards.- - ``cubepi.metadata.oneshot_operation`` — so the CLI ``--meta`` filter- (which only reads ``cubepi.metadata.*`` attributes) can reach it::+ - ``cubeloop.oneshot.operation`` — for span introspection and dashboards.+ - ``cubeloop.metadata.oneshot_operation`` — so the CLI ``--meta`` filter+ (which only reads ``cubeloop.metadata.*`` attributes) can reach it::uv run cubepi trace ls --meta oneshot_operation=consolidate_memoryuv run cubepi trace ls --meta conversation_id=conv-123@@ -486,10 +486,10 @@ class Tracer:"""from opentelemetry.trace import SpanKind- from cubepi.providers.base import BaseProvider as _BaseProvider- from cubepi.tracing.recorder import Recorder, _RunState, _active_run- from cubepi.tracing.schema import (- CUBEPI_RUN_ID,+ from cubeloop.providers.base import BaseProvider as _BaseProvider+ from cubeloop.tracing.recorder import Recorder, _RunState, _active_run+ from cubeloop.tracing.schema import (+ CUBELOOP_RUN_ID,GEN_AI_OPERATION_NAME,GEN_AI_PROVIDER_NAME,OP_INVOKE_AGENT,@@ -504,9 +504,9 @@ class Tracer:root_attrs: dict[str, Any] = {GEN_AI_OPERATION_NAME: OP_INVOKE_AGENT,- CUBEPI_RUN_ID: run_id,+ CUBELOOP_RUN_ID: run_id,GEN_AI_PROVIDER_NAME: "cubepi",- "cubepi.oneshot.operation": operation,+ "cubeloop.oneshot.operation": operation,}# User metadata first, then reserved keys, so a caller-supplied# ``oneshot_operation`` key in ``metadata`` can't shadow the one@@ -514,11 +514,11 @@ class Tracer:# ``cubepi trace ls --meta oneshot_operation=...`` filter depends# on).for k, v in (metadata or {}).items():- root_attrs[f"cubepi.metadata.{k}"] = v- # Also expose operation under cubepi.metadata.* so the+ root_attrs[f"cubeloop.metadata.{k}"] = v+ # Also expose operation under cubeloop.metadata.* so the# `cubepi trace ls --meta oneshot_operation=...` filter works- # (the CLI's --meta filter only reads cubepi.metadata.* attrs).- root_attrs["cubepi.metadata.oneshot_operation"] = operation+ # (the CLI's --meta filter only reads cubeloop.metadata.* attrs).+ root_attrs["cubeloop.metadata.oneshot_operation"] = operationroot_span = self._otel_tracer.start_span(name=SPAN_NAME_INVOKE_AGENT,@@ -527,7 +527,7 @@ class Tracer:)# _RunState with turn_span = root_span so chat spans nest directly- # under the root (no cubepi.turn wrapper — one-shot has no loop).+ # under the root (no cubeloop.turn wrapper — one-shot has no loop).run = _RunState(run_id=run_id,agent_span=root_span,@@ -602,18 +602,18 @@ class Tracer:# reads status off the root) lists this run as an error# instead of a successful invoke_agent. Mirrors what the# agent path does on turn-level errors. Cancellation is- # tracked as cubepi.aborted (UNSET status, semconv-aligned)+ # tracked as cubeloop.aborted (UNSET status, semconv-aligned)# rather than ERROR.try:from opentelemetry.trace import Status, StatusCode- from cubepi.tracing.schema import CUBEPI_ABORTED, ERROR_TYPE+ from cubeloop.tracing.schema import CUBELOOP_ABORTED, ERROR_TYPEimport asyncio as _asyncio_for_cancelif isinstance(_exc, _asyncio_for_cancel.CancelledError):- root_span.set_attribute(CUBEPI_ABORTED, True)- root_span.set_attribute(ERROR_TYPE, "cubepi.aborted")+ root_span.set_attribute(CUBELOOP_ABORTED, True)+ root_span.set_attribute(ERROR_TYPE, "cubeloop.aborted")else:description = str(_exc)[:256] if do_record else "oneshot error"root_span.set_status(Status(StatusCode.ERROR, description))@@ -645,10 +645,10 @@ class Tracer:# exist for one-shot (no tool execution path).if run.chat_span is not None:try:- from cubepi.tracing.schema import CUBEPI_ABORTED, ERROR_TYPE+ from cubeloop.tracing.schema import CUBELOOP_ABORTED, ERROR_TYPE- run.chat_span.set_attribute(CUBEPI_ABORTED, True)- run.chat_span.set_attribute(ERROR_TYPE, "cubepi.aborted")+ run.chat_span.set_attribute(CUBELOOP_ABORTED, True)+ run.chat_span.set_attribute(ERROR_TYPE, "cubeloop.aborted")run.chat_span.end()except Exception: # pragma: no cover — defensivepass@@ -660,11 +660,11 @@ class Tracer:# ``gen_ai.input.messages`` off the root.if do_record:try:- from cubepi.tracing.content import (+ from cubeloop.tracing.content import (messages_to_semconv,system_instructions_to_semconv,)- from cubepi.tracing.schema import (+ from cubeloop.tracing.schema import (GEN_AI_INPUT_MESSAGES,GEN_AI_OUTPUT_MESSAGES,GEN_AI_SYSTEM_INSTRUCTIONS,@@ -864,7 +864,7 @@ def _log_tracing_warning(message: str, exc: BaseException) -> None:route these records through it. The log call itself is guarded so a raisinglogging handler can't defeat the best-effort guarantee."""try:- logging.getLogger("cubepi.tracing").warning(+ logging.getLogger("cubeloop.tracing").warning("cubepi tracing: %s", message, exc_info=exc)except Exception: # noqa: BLE001 — logging must never break the run # pragma: no coverdiff --git a/cubepi/types.py b/cubeloop/types.pysimilarity index 100%rename from cubepi/types.pyrename to cubeloop/types.pydiff --git a/cubeloop/utils/__init__.py b/cubeloop/utils/__init__.pynew file mode 100644index 0000000..fd3808b--- /dev/null+++ b/cubeloop/utils/__init__.py@@ -0,0 +1,6 @@+"""cubeloop.utils — utility modules."""++from cubeloop.utils.emit import emit_event+from cubeloop.utils.json_parse import parse_streaming_json, repair_json++__all__ = ["emit_event", "parse_streaming_json", "repair_json"]diff --git a/cubepi/utils/emit.py b/cubeloop/utils/emit.pysimilarity index 100%rename from cubepi/utils/emit.pyrename to cubeloop/utils/emit.pydiff --git a/cubepi/utils/json_parse.py b/cubeloop/utils/json_parse.pysimilarity index 100%rename from cubepi/utils/json_parse.pyrename to cubeloop/utils/json_parse.pydiff --git a/cubepi/checkpointer/mysql/__init__.py b/cubepi/checkpointer/mysql/__init__.pydeleted file mode 100644index 7531aed..0000000--- a/cubepi/checkpointer/mysql/__init__.py+++ /dev/null@@ -1,27 +0,0 @@-"""MySQLCheckpointer package.--Exceptions are available immediately; ``MySQLCheckpointer`` and model symbols-are added below once their modules exist.-"""--from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer-from cubepi.checkpointer.mysql.exceptions import (- CubepiSchemaError,- CubepiSchemaMismatch,- CubepiSchemaUninitialized,-)-from cubepi.checkpointer.mysql.models import (- EXPECTED_SCHEMA_VERSION,- PARTITION_COUNT,- cubepi_metadata,-)--__all__ = [- "MySQLCheckpointer",- "CubepiSchemaError",- "CubepiSchemaMismatch",- "CubepiSchemaUninitialized",- "EXPECTED_SCHEMA_VERSION",- "PARTITION_COUNT",- "cubepi_metadata",-]diff --git a/cubepi/checkpointer/mysql/exceptions.py b/cubepi/checkpointer/mysql/exceptions.pydeleted file mode 100644index d8834cf..0000000--- a/cubepi/checkpointer/mysql/exceptions.py+++ /dev/null@@ -1,19 +0,0 @@-"""Schema exceptions for MySQLCheckpointer.--Re-exported from the backend-agnostic ``cubepi.checkpointer.exceptions``.-Importing from there (rather than the Postgres package) keeps a single source-of truth without pulling in ``asyncpg``, so the ``cubepi[mysql]`` extra works-without the Postgres extra installed.-"""--from cubepi.checkpointer.exceptions import (- CubepiSchemaError,- CubepiSchemaMismatch,- CubepiSchemaUninitialized,-)--__all__ = [- "CubepiSchemaError",- "CubepiSchemaMismatch",- "CubepiSchemaUninitialized",-]diff --git a/cubepi/checkpointer/postgres/__init__.py b/cubepi/checkpointer/postgres/__init__.pydeleted file mode 100644index 3b8bdad..0000000--- a/cubepi/checkpointer/postgres/__init__.py+++ /dev/null@@ -1,21 +0,0 @@-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",-]diff --git a/cubepi/checkpointer/postgres/alembic_helpers.py b/cubepi/checkpointer/postgres/alembic_helpers.pydeleted file mode 100644index 1a013f9..0000000--- a/cubepi/checkpointer/postgres/alembic_helpers.py+++ /dev/null@@ -1,132 +0,0 @@-"""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() 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 add_pending_request_column_op() -> str:- """Return SQL adding the v2 `pending_request` column to cubepi_threads.-- Call inside the host's alembic v1→v2 upgrade() via op.execute(). The new- column is JSONB NULL. Idempotent under repeated execution via IF NOT EXISTS.- Hosts must also bump `cubepi_schema_version` via write_schema_version_op()."""- return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS pending_request JSONB"---def add_run_id_column_op() -> str:- """Return SQL adding the v3 `run_id` column to cubepi_threads.-- Call inside the host's alembic v2→v3 upgrade() via op.execute(). The new- column is TEXT NULL — it carries an opaque host-side identifier (e.g. the- cubebox run_id) persisted atomically with `pending_request`. Idempotent- under repeated execution via IF NOT EXISTS. Hosts must also bump- `cubepi_schema_version` via write_schema_version_op() (EXPECTED_SCHEMA_VERSION- is now 3)."""- return "ALTER TABLE cubepi_threads ADD COLUMN IF NOT EXISTS run_id TEXT"---def create_runs_partitions_op() -> str:- """Return SQL DDL creating all child partitions of cubepi_runs.-- Call inside an alembic upgrade() via op.execute(), AFTER the parent- cubepi_runs partitioned table has been created. Uses the same- PARTITION_COUNT as cubepi_messages.- """- return "\n".join(- f"CREATE TABLE cubepi_runs_p{i:02d} "- f"PARTITION OF cubepi_runs "- f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i});"- for i in range(PARTITION_COUNT)- )---def upgrade_v3_to_v4_op() -> str:- """Return SQL applying the v3→v4 schema changes.-- Adds the `run_id` column + index to `cubepi_messages` and creates- the partitioned `cubepi_runs` parent table with its child- partitions. Hosts must also bump `cubepi_schema_version` via- write_schema_version_op() (EXPECTED_SCHEMA_VERSION is now 4).-- Call inside the host's alembic v3→v4 upgrade() via op.execute().- Idempotent under repeated execution via IF NOT EXISTS guards.- """- parts = [- "ALTER TABLE cubepi_messages ADD COLUMN IF NOT EXISTS run_id TEXT;",- (- "CREATE INDEX IF NOT EXISTS ix_cubepi_messages_thread_run "- "ON cubepi_messages (thread_id, run_id);"- ),- (- "CREATE TABLE IF NOT EXISTS cubepi_runs ("- " thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) "- "ON DELETE CASCADE,"- " run_id TEXT NOT NULL,"- " claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(),"- " completed_at TIMESTAMPTZ,"- " completion_seq BIGINT,"- " PRIMARY KEY (thread_id, run_id)"- ") PARTITION BY HASH (thread_id);"- ),- (- "CREATE INDEX IF NOT EXISTS ix_cubepi_runs_thread_seq "- "ON cubepi_runs (thread_id, completion_seq);"- ),- create_runs_partitions_op(),- ]- return "\n".join(parts)---def upgrade_v4_to_v5_op() -> str:- """Return SQL applying the v4->v5 schema changes.-- Creates the durable HITL answer ledger table. Hosts must also bump- `cubepi_schema_version` via write_schema_version_op()- (EXPECTED_SCHEMA_VERSION is now 5).- """- return (- "CREATE TABLE IF NOT EXISTS cubepi_hitl_answers ("- " thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) "- "ON DELETE CASCADE,"- " run_id TEXT NOT NULL,"- " question_id TEXT NOT NULL,"- " answer JSONB NOT NULL,"- " answered_at TIMESTAMPTZ NOT NULL DEFAULT now(),"- " PRIMARY KEY (thread_id, run_id, question_id)"- ");"- )---def write_schema_version_op() -> str:- """Return SQL setting cubepi_schema_version to the current version.-- Call inside alembic upgrade() after CREATE TABLE cubepi_schema_version.-- Atomically clears any stale rows (from prior cubepi versions) and writes- the current version. ``version`` is the primary key, so a plain INSERT- would leave older rows in place and ``_verify_schema`` (which does- ``SELECT version ... LIMIT 1``) could read a stale value and falsely- report CubepiSchemaMismatch. Idempotent under repeated execution.- """- return (- f"DELETE FROM cubepi_schema_version "- f"WHERE version <> {EXPECTED_SCHEMA_VERSION}; "- f"INSERT INTO cubepi_schema_version (version) "- f"VALUES ({EXPECTED_SCHEMA_VERSION}) ON CONFLICT DO NOTHING;"- )diff --git a/cubepi/checkpointer/postgres/exceptions.py b/cubepi/checkpointer/postgres/exceptions.pydeleted file mode 100644index cbd27b8..0000000--- a/cubepi/checkpointer/postgres/exceptions.py+++ /dev/null@@ -1,17 +0,0 @@-"""Exceptions raised by PostgresCheckpointer schema verification.--Re-exported from the backend-agnostic ``cubepi.checkpointer.exceptions`` so-the same classes are shared with the MySQL checkpointer.-"""--from cubepi.checkpointer.exceptions import (- CubepiSchemaError,- CubepiSchemaMismatch,- CubepiSchemaUninitialized,-)--__all__ = [- "CubepiSchemaError",- "CubepiSchemaMismatch",- "CubepiSchemaUninitialized",-]diff --git a/cubepi/cli/__init__.py b/cubepi/cli/__init__.pydeleted file mode 100644index b69f07f..0000000--- a/cubepi/cli/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""cubepi command-line interface."""diff --git a/cubepi/cli/trace/__init__.py b/cubepi/cli/trace/__init__.pydeleted file mode 100644index f5abb76..0000000--- a/cubepi/cli/trace/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""`cubepi trace` — read JSONL spans written by JsonlSpanExporter."""diff --git a/cubepi/middleware/__init__.py b/cubepi/middleware/__init__.pydeleted file mode 100644index bd48371..0000000--- a/cubepi/middleware/__init__.py+++ /dev/null@@ -1,61 +0,0 @@-from __future__ import annotations--from typing import Any--from cubepi.middleware.base import Middleware, TurnAction, compose_middleware--__all__ = [- "CompactionMiddleware",- "CompactionState",- "GoalMiddleware",- "ToolResultCompressor",- "Middleware",- "SubagentMiddleware",- "SubagentRequest",- "SubagentResult",- "SubagentSpec",- "Todo",- "TodoGuardBlocked",- "TodoGuardType",- "TodoListMiddleware",- "TurnAction",- "WriteTodosInput",- "WRITE_TODOS_SYSTEM_PROMPT",- "WRITE_TODOS_TOOL_DESCRIPTION",- "compose_middleware",-]--_LAZY = {- "CompactionMiddleware": ("cubepi.middleware.compaction", "CompactionMiddleware"),- "CompactionState": ("cubepi.middleware.compaction", "CompactionState"),- "ToolResultCompressor": ("cubepi.middleware.compaction", "ToolResultCompressor"),- "GoalMiddleware": ("cubepi.middleware.goal", "GoalMiddleware"),- "SubagentMiddleware": ("cubepi.middleware.subagents", "SubagentMiddleware"),- "SubagentRequest": ("cubepi.middleware.subagents", "SubagentRequest"),- "SubagentResult": ("cubepi.middleware.subagents", "SubagentResult"),- "SubagentSpec": ("cubepi.middleware.subagents", "SubagentSpec"),- "Todo": ("cubepi.middleware.todo", "Todo"),- "TodoGuardBlocked": ("cubepi.middleware.todo", "TodoGuardBlocked"),- "TodoGuardType": ("cubepi.middleware.todo", "TodoGuardType"),- "TodoListMiddleware": ("cubepi.middleware.todo", "TodoListMiddleware"),- "WriteTodosInput": ("cubepi.middleware.todo", "WriteTodosInput"),- "WRITE_TODOS_SYSTEM_PROMPT": (- "cubepi.middleware.todo",- "WRITE_TODOS_SYSTEM_PROMPT",- ),- "WRITE_TODOS_TOOL_DESCRIPTION": (- "cubepi.middleware.todo",- "WRITE_TODOS_TOOL_DESCRIPTION",- ),-}---def __getattr__(name: str) -> Any:- try:- module_name, attr = _LAZY[name]- except KeyError:- raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None- import importlib-- module = importlib.import_module(module_name)- return getattr(module, attr)diff --git a/cubepi/utils/__init__.py b/cubepi/utils/__init__.pydeleted file mode 100644index d7db47c..0000000--- a/cubepi/utils/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""cubepi.utils — utility modules."""--from cubepi.utils.emit import emit_event-from cubepi.utils.json_parse import parse_streaming_json, repair_json--__all__ = ["emit_event", "parse_streaming_json", "repair_json"]diff --git a/dev/plans/2026-09-09-rename-cubeloop.md b/dev/plans/2026-09-09-rename-cubeloop.mdnew file mode 100644index 0000000..3cb2532--- /dev/null+++ b/dev/plans/2026-09-09-rename-cubeloop.md@@ -0,0 +1,418 @@+# Rename CubePi → CubeLoop — Implementation Plan++**Goal:** Rebrand the library to CubeLoop / `cubeloop` in 0.14.0: package tree, imports, CLI, OTel vendor namespace, Postgres/MySQL table names, current docs, and a transitional `cubepi` PyPI shim. GitHub repo is renamed in place (not a new repo). Canonical site is `https://cubeloop.dev`.++**Spec:** [`dev/specs/2026-09-09-rename-cubeloop.md`](../specs/2026-09-09-rename-cubeloop.md)++**Architecture:** One source tree (`cubeloop/`). A second hatchling project at `compat/cubepi/` publishes the shim wheel. Schema v6 is a `RENAME TABLE` (PG/MySQL only). Tracing writes `cubeloop.*` and the CLI reads both namespaces.++**Tech stack:** Python 3.11+, hatchling, uv workspace, pytest, ruff, mypy, Docusaurus current docs (EN + zh-Hans).++Work in `.worktrees/2026-09-09-rename-cubeloop` on branch `2026-09-09-rename-cubeloop`. Never commit to `main`.++---++## Do not touch++These stay CubePi — they document what already shipped:++- `website/versioned_docs/**`+- `website/versioned_sidebars/**`+- `website/i18n/zh-Hans/docusaurus-plugin-content-docs/version-*`+- Historical `CHANGELOG.md` sections (`## [0.13.6]` and older). Add new text under `[Unreleased]` only.+- `dev/specs/**` and `dev/plans/**` except this pair.+- SQLite table names (`messages`, `runs`, `thread_extra`, …).+- Git history.++A bulk `cubepi` → `cubeloop` replace that hits those trees is a bug.++---++## File structure++- **Move** `cubepi/` → `cubeloop/`+- **Move** `skills/cubepi/` → `skills/cubeloop/`, `skills/cubepi-trace/` → `skills/cubeloop-trace/`+- **Move** `website/static/img/brand/cubepi-*` → `cubeloop-*` (same artwork)+- **Create** `compat/cubepi/` (shim distribution)+- **Create** `website/docs/migration/from-cubepi.md` + zh-Hans mirror+- **Create** `tests/compat/test_cubepi_shim.py`+- **Create** `tests/cli/trace/fixtures/` (0.13 JSONL + 0.14 JSONL)+- **Modify** `pyproject.toml`, `uv.lock`, `.pre-commit-config.yaml`, `codecov.yml`, `AGENTS.md`, `CLAUDE.md`, `README.md`+- **Modify** `.github/workflows/{ci,docs,publish}.yml`+- **Modify** checkpointer models / runtime SQL / alembic helpers (PG + MySQL)+- **Modify** `cubeloop/tracing/schema.py` and every writer of `cubepi.*` attributes+- **Modify** current docs, `website/src/**`, `docusaurus.config.ts`, `sidebars.ts`, `website/static/_worker.js`, `website/scripts/build_api_reference.py`+- **Modify** examples, tests (except frozen historical schema SQL that still creates `cubepi_*` as a v5 fixture)++---++## Task 1: Mechanical package-tree rename++Do the filesystem move and import-path rewrite **before** identifier/table/OTel string changes, so the suite can go green on `import cubeloop` while names are still `Cubepi*` / `cubepi_*`.++- [ ] `git mv cubepi cubeloop`+- [ ] `git mv skills/cubepi skills/cubeloop`+- [ ] `git mv skills/cubepi-trace skills/cubeloop-trace`+- [ ] `git mv website/static/img/brand/cubepi-logo.svg website/static/img/brand/cubeloop-logo.svg` (and `.png`, `cubepi-social-preview.svg` / `.png`)+- [ ] Update `pyproject.toml`:+ - `name = "cubeloop"`+ - version `0.14.0` (this PR *is* the breaking 0.14 surface; tag comes later)+ - URLs → `https://cubeloop.dev`, `https://github.com/cubeplexai/cubeloop`+ - `[project.scripts] cubeloop = "cubeloop.cli.__main__:main"`+ - `[tool.mypy] files = ["cubeloop"]`+ - `[tool.hatch.build.targets.wheel] packages = ["cubeloop"]`+ - `[tool.uv.workspace] members = ["compat/cubepi"]` (member lands in Task 5; can add the table now or then)+- [ ] Rewrite imports in **allowed** paths only:++Allowed: `cubeloop/`, `tests/`, `examples/`, `website/docs/`, `website/src/`, `website/scripts/`, `website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/`, `website/docusaurus.config.ts`, `website/sidebars.ts`, `website/static/_worker.js`, `README.md`, `AGENTS.md`, `CLAUDE.md`, `.github/`, `.pre-commit-config.yaml`, `codecov.yml`, `skills/`.++Replace, in order (longest first):++1. `from cubepi` / `import cubepi` → `cubeloop`+2. `"cubepi/` path segments in CI/mypy/ruff/codecov (`cubepi/cli/**` → `cubeloop/cli/**`)+3. Do **not** yet rewrite `cubepi_threads`, `cubepi.run_id`, `CubepiSchemaError`, `CUBEPI_*` — those are later tasks.++- [ ] `uv lock && uv sync --all-extras --dev`+- [ ] CI workflow: `--cov=cubeloop`, `import cubeloop`, ruff/mypy paths, docs.yml `cubepi/**` → `cubeloop/**` and the API-mdx guard `cubepi-*.mdx` → `cubeloop-*.mdx`+- [ ] `website/scripts/build_api_reference.py`: `MODULES` tuples `cubeloop.*`; generated page ids `cubeloop-agent` etc.+- [ ] `website/sidebars.ts` current API ids `api/cubeloop-agent` …+- [ ] `website/docs/api/index.mdx` + zh-Hans current mirror++Green bar for this task is “the tree imports as cubeloop”:++```bash+uv run python -c "import cubeloop; print(cubeloop.__all__)"+uv run ruff check cubeloop/ tests/+uv run ruff format --check cubeloop/ tests/+uv run mypy cubeloop+uv run pytest tests/test_init.py tests/test_package.py tests/cli/test_entrypoint.py -q+```++Expect remaining failures only where tests still assert the string `"cubepi"` as a table/attr/package name. Do not “fix” those by reverting the import path.++---++## Task 2: Public Python identifiers++- [ ] `CubepiSchemaError` / `Uninitialized` / `Mismatch` → `Cubeloop*` in `cubeloop/checkpointer/exceptions.py` and the PG/MySQL re-exports+- [ ] ORM: `cubepi_metadata` → `cubeloop_metadata`; `CubepiBase` / `CubepiThread` / `CubepiMessage` / `CubepiRun` / `CubepiHitlAnswer` / `CubepiSchemaVersion` → `Cubeloop*`+- [ ] Tracing constants: `CUBEPI_RUN_ID` → `CUBELOOP_RUN_ID` (and the rest). **Leave the string values as `cubepi.*` until Task 4** so Task 2 is a pure identifier rename.+- [ ] `_pkg_version("cubeloop")`+- [ ] Logger / tracer *names* that are Python logging namespaces can wait for Task 4 (they are OTel/log vendor strings).+- [ ] cubeloop does **not** keep `Cubepi*` aliases. The shim is the compatibility layer.++```bash+uv run pytest tests/checkpointer/test_init.py tests/checkpointer/test_exceptions.py tests/test_init.py -q+```++---++## Task 3: Schema v5 → v6 (Postgres + MySQL)++`EXPECTED_SCHEMA_VERSION = 6`. Runtime SQL and current-schema helpers use `cubeloop_*`. Historical v1–v5 helpers keep emitting `cubepi_*` because they run against databases that still have those names.++### 3.1 Footgun — do not “fix” old helpers by renaming their SQL++Today `upgrade_v3_to_v4_op()` calls `create_runs_partitions_op()`. After this task `create_runs_partitions_op()` must emit `cubeloop_runs_pXX PARTITION OF cubeloop_runs`. If the v3→v4 helper still calls it, a v3 database will try to partition a table that does not exist yet.++- [ ] Inline the **old** `cubepi_runs_pXX` / `cubepi_messages_pXX` DDL into `upgrade_v3_to_v4_op` (and any other historical helper that currently delegates to a current-schema factory).+- [ ] Point `create_message_partitions_op` / `create_runs_partitions_op` (Postgres) and the current MySQL CREATE helpers at **new** names, for fresh installs.++`write_schema_version_op()` must **not** hardcode only `cubeloop_schema_version`. Hosts copy `op.execute(write_schema_version_op())` into each already-shipped Alembic revision. After 0.14 those revisions still run against `cubepi_schema_version` when a fresh DB replays history.++Return dialect SQL that writes `EXPECTED_SCHEMA_VERSION` to `cubeloop_schema_version` if that table exists, else to `cubepi_schema_version`.++- Postgres: one `DO $$ … $$` block (single statement).+- MySQL: **must** remain a `;`-joined list of standalone statements. Hosts do `for stmt in write_schema_version_op().split(";"): op.execute(stmt)`. Do not emit `BEGIN`/`IF`/`THEN` compound SQL. Use `SET @cp_ver_new = (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'cubeloop_schema_version')`, then `SET @cp_del = IF(@cp_ver_new > 0, 'DELETE FROM cubeloop_schema_version WHERE version <> N', 'DELETE FROM cubepi_schema_version WHERE version <> N')`, then `PREPARE` / `EXECUTE` / `DEALLOCATE PREPARE`, then the same for `INSERT IGNORE`. Tests execute via that split loop, not `cursor.execute(whole_string)`.++`upgrade_v5_to_v6_op()` only renames, including the version table. The host then calls `write_schema_version_op()`, which now hits the new table.++Do **not** change historical helpers to call `write_schema_version_op` themselves.++### 3.2 Postgres `upgrade_v5_to_v6_op()`++Rename, in one helper:++| Old | New |+|---|---|+| `cubepi_threads` | `cubeloop_threads` |+| `cubepi_messages` + `cubepi_messages_p00`…`p63` | `cubeloop_messages` + matching `pXX` |+| `cubepi_runs` + `cubepi_runs_p00`…`p63` | `cubeloop_runs` + matching `pXX` |+| `cubepi_hitl_answers` | `cubeloop_hitl_answers` |+| `cubepi_schema_version` | `cubeloop_schema_version` |+| `ix_cubepi_*` (the three we named) | `ix_cubeloop_*` |++`ALTER TABLE … RENAME TO` on a partitioned parent does **not** rename children — loop `PARTITION_COUNT`. Auto-generated PK/FK constraint names may keep `cubepi_*`; do not chase them unless a test asserts the name.++Idempotency (Postgres): complete iff `cubeloop_threads` **and** `cubeloop_schema_version` both exist. `cubeloop_threads` alone is not a no-op sentinel.++### 3.3 MySQL `upgrade_v5_to_v6_op()`++One `RENAME TABLE a TO a2, b TO b2, …` covering **all** v5 tables including `cubepi_schema_version`. KEY partitions ride with the table. Do not rename the version table in a second statement.++Same complete-state idempotency as Postgres. Missing `cubepi_schema_version` makes the atomic rename fail as a whole; `_verify_schema` step 3 explains recovery. Do not split this helper on `;` — it is one statement.++### 3.4 Runtime SQL++Every string in `cubeloop/checkpointer/postgres/checkpointer.py` and `mysql/checkpointer.py` (`FROM cubepi_messages`, `INSERT INTO cubepi_threads`, mismatch hint text) uses the new names. `_schema_mismatch_hint` must name `upgrade_v5_to_v6_op()` when `actual < 6`. MySQL's current hint still says `add_run_id_column_op()` — replace it with the same step-list helper Postgres uses.++`_verify_schema` (both backends):++1. SELECT from `cubeloop_schema_version`. If the table exists, compare to 6.+2. If the new table is missing (`UndefinedTable` / MySQL 1146): SELECT `cubepi_schema_version`. If **that** exists (any stored version, including 6), raise `CubeloopSchemaMismatch(expected=6, actual=<row>)` with a hint that only names `upgrade_v5_to_v6_op()` + `write_schema_version_op()`.+3. If neither version table exists but `cubepi_threads` or `cubeloop_threads` does → `CubeloopSchemaMismatch(expected=6, actual=0)` with a “version table missing, do not CREATE fresh v6 on live data” hint (migrate guide recovery: insert version 5 then v5→v6).+4. If neither version table nor data tables exist → `CubeloopSchemaUninitialized`.++A host who deploys 0.14 before the v6 Alembic revision must not see “tables not found”.++### 3.5 Tests++Split fixtures. Today's `_setup_schema` CREATEs `cubepi_*` then calls `add_pending_request_column_op`, `create_message_partitions_op`, `upgrade_v3_to_v4_op`, `upgrade_v4_to_v5_op`, `write_schema_version_op`. After Task 3.1 those historical helpers still emit `cubepi_*` while current partition factories emit `cubeloop_*`. Do **not** “just rename the CREATE TABLE” and keep calling the old helpers.++- [ ] **Fresh-v6 builder**: one canonical v6 DDL source (same SQL the backend README / examples ship) + current `create_message_partitions_op` / `create_runs_partitions_op`. No historical helpers. Assert it matches example DDL (string or information_schema).+- [ ] **Historical-v5 builder**: keep creating `cubepi_*` and calling the frozen v1–v5 helpers; `write_schema_version_op` lands version 6-or-5 in `cubepi_schema_version` (because the new table does not exist yet). Used only as the input to v5→v6 tests and as the unmigrated-v5 mismatch case.+- [ ] **Full-chain replay test** (PG + MySQL): start empty, run the documented helper sequence a host would copy (v1-shaped CREATE + pending_request + run_id + partitions + v3→v4 + v4→v5 + write + **v5→v6** + write). Then open the checkpointer and round-trip a message. This is the test that catches `write_schema_version_op` targeting the wrong table.+- [ ] `test_expected_schema_version_is_5` → `…_is_6`; mismatch-hint tests include v5→v6+- [ ] **Keep** v2/v3 fixture SQL as `CREATE TABLE cubepi_schema_version …`. Update asserted `expected=6`. Unmigrated v5 (historical-v5 builder, no v6 helper) raises `CubeloopSchemaMismatch`, **not** Uninitialized.+- [ ] New tests (PG + MySQL):+ 1. historical-v5 + `upgrade_v5_to_v6_op` + `write_schema_version_op` → checkpointer enters, message round-trips.+ 2. Helper is idempotent on an already-v6 database (both `cubeloop_threads` and `cubeloop_schema_version` present).+ 3. `information_schema` shows `cubeloop_threads` / `cubeloop_messages` / `cubeloop_runs` / `cubeloop_hitl_answers` / `cubeloop_schema_version`; old names are gone.+ 4. Data tables present, no version table → mismatch `actual=0`, not Uninitialized.+ 5. MySQL `write_schema_version_op()` split-and-execute loop (README contract) succeeds on both a v5-named and a v6-named version table.+- [ ] Env readers: `CUBELOOP_TEST_PG_DSN` then fallback `CUBEPI_TEST_PG_DSN` (same for MySQL / MCP HTTP / example DSNs). CI env keys become `CUBELOOP_*`. Ephemeral DB names `cubepi_test_*` / `cubepi_example_*` → `cubeloop_test_*` / `cubeloop_example_*`.+- [ ] Examples + backend READMEs: v6 CREATE TABLE under new names, plus a short “existing v5 DB: call `upgrade_v5_to_v6_op`” note.++```bash+uv run pytest tests/checkpointer/ -v+```++SQLite tests must stay green with **no** table rename.++---++## Task 4: OTel vendor namespace++### 4.1 Write path — cubeloop only++Start from `rg -n "cubepi\\." cubeloop/` after Task 1, not from schema.py alone. Change **string values** (constants already renamed in Task 2) **and** every remaining literal/f-string.++Schema constants plus the 0.13.6 leftovers the first inventory missed:++```+cubepi.run_id / cubepi.thread_id / cubepi.agent.* / cubepi.turn.* / cubepi.llm.* / cubepi.tool.*+cubepi.run.outcome / cubepi.aborted+cubepi.turn (span name)+SCOPE_NAME cubepi.tracing+cubepi.metadata.<key>+cubepi.oneshot.operation+cubepi.tags+cubepi.fork.src_thread_id / cubepi.fork.after_run_id+cubepi.agent.fork_once (span name)+error.type cubepi.aborted / cubepi.error / cubepi.tool.error+cubepi_error_type_for() → "cubeloop.aborted"+ContextVars cubepi.tracing.run_metadata / run_tags / active_run+```++Also the non-schema literals (grep `"cubepi` in `cubeloop/` after Task 1):++| File | Old | New |+|---|---|---|+| `mcp/_tracing.py` | `_SCOPE_NAME = "cubepi.mcp"`, `error.type = "cubepi.aborted"` | `cubeloop.mcp` / `cubeloop.aborted` |+| `hitl/_trace.py` | `get_tracer("cubepi.hitl")` | `cubeloop.hitl` |+| `agent/agent.py` | `get_tracer("cubepi.agent")`, span `cubepi.agent.fork_once` | `cubeloop.agent` / `cubeloop.agent.fork_once` |+| `providers/base.py` | logger `"cubepi.providers"` | `cubeloop.providers` |+| `cli/trace/loader.py` | `_META_PREFIX = "cubepi.metadata."` | dual-read, see 4.2 |+| `cli/trace/render.py` | title `"cubepi runs"` | `"cubeloop runs"` |+| `cli/__main__.py` | `prog="cubepi"` | `prog="cubeloop"` |+| `cli/trace/loader.py` | `DEFAULT_DIR = Path("./cubepi-traces")` | `./cubeloop-traces` |++No dual-write. `gen_ai.*` unchanged.++Add schema constants for the metadata prefix and oneshot operation if they are currently ad-hoc f-strings — they should live next to the other `CUBELOOP_*` keys.++### 4.2 Read path — both namespaces++CLI (and any in-process reader that keys off schema constants) accepts old and new:++- Span name `cubepi.turn` **or** `cubeloop.turn`+- Attribute lookup: try `cubeloop.run_id`, fall back to `cubepi.run_id` (same for tags, fork attrs, outcome, metadata prefix, oneshot)+- Abort is **not** a plain key fallback. `Span.is_aborted` today reads only the boolean. Treat as aborted if `cubeloop.aborted` or `cubepi.aborted` is true **or** `error.type` is `cubeloop.aborted` or `cubepi.aborted`.++Helper: `schema.attr(attrs, CUBELOOP_RUN_ID)` for ordinary keys. Abort stays a dedicated predicate so `error.type` is not forgotten. Do not scatter `or attrs.get("cubepi…")` in every call site.++### 4.3 Tests++- [ ] `tests/tracing/test_lazy_import.py`: `CUBELOOP_RUN_ID == "cubeloop.run_id"` still imports without OpenTelemetry+- [ ] Existing tracing tests assert new keys (`cubeloop.tags`, fork attrs, `error.type` values, oneshot)+- [ ] New CLI tests with fixtures:+ - `v013_cubepi.jsonl` — `cubepi.turn`, `cubepi.run_id`, `cubepi.metadata.user_id`, `cubepi.tags`+ - `v013_abort_boolean.jsonl` — `cubepi.aborted=true`+ - `v013_abort_error_type_only.jsonl` — `error.type="cubepi.aborted"` and **no** boolean (must still show aborted)+ - `v013_fork.jsonl` / `v013_oneshot.jsonl`+ - `v014_cubeloop.jsonl` — new keys only+ - `cubeloop trace view` renders both generations; `ls --meta` matches both prefixes+- [ ] `rg "cubepi\\." cubeloop/` is empty except comments that quote the old name in the migrate guide / dual-read fallback table in schema.py++```bash+uv run pytest tests/tracing/ tests/cli/ tests/mcp/test_adapter.py -v+```++---++## Task 5: `cubepi` shim distribution++`compat/cubepi/` is a second hatchling project in the uv workspace.++```+compat/cubepi/+ pyproject.toml+ README.md # deprecation banner; classifier Inactive+ cubepi/+ __init__.py # warn + re-export cubeloop public API+ _redirect.py # MetaPathFinder: cubepi.* → cubeloop.* on demand+ __main__.py # warn, dispatch to cubeloop.cli+```++`pyproject.toml`:++- `name = "cubepi"`, `version = "0.14.0"` (keep in lockstep with root; exact pin, not a range)+- `dependencies = ["cubeloop==0.14.0"]`+- extras forward 1:1: `sqlite = ["cubeloop[sqlite]==0.14.0"]` (same for postgres, mysql, mcp, tracing, tracing-otlp, trace-cli)+- `[project.scripts] cubepi = "cubepi.__main__:main"`+- `[tool.uv.sources] cubeloop = { workspace = true }` so local `uv sync` uses the workspace package; `uv build` must emit the PyPI pin in the wheel metadata (verify with `unzip -p dist/cubepi-*.whl '*.dist-info/METADATA' | grep Requires-Dist`)++### 5.1 Import redirect++`cubepi/__init__.py` must **not** `sys.modules['cubepi'] = cubeloop` (breaks relative imports inside cubeloop). A finder that only writes `sys.modules` and returns `None` is also insufficient: `from cubepi.providers.anthropic import …` has to resolve `cubepi.providers` first, and with no `ModuleSpec` import falls through to a missing physical package.++Ship a `MetaPathFinder` + alias `Loader`:++1. `import cubepi` loads the shim `__init__.py` (finder ignores the root name).+2. `__init__.py` prints the spec warning to **stderr once per process**, emits `DeprecationWarning`, then `from cubeloop import *` and copies `__all__` / `__version__`.+3. Finder matches `fullname.startswith("cubepi.")`. `find_spec` returns `ModuleSpec(fullname, AliasLoader(real_name), origin=real.origin, is_package=…)`. Package specs set `submodule_search_locations`.+4. `AliasLoader.create_module` returns `importlib.import_module(real_name)` — the **same object** already in `sys.modules[real_name]`. `exec_module` is a no-op. cubeloop relative imports keep `__name__` under `cubeloop.*`.+5. Do **not** `walk_packages` / eagerly import `cubeloop.tracing` (lazy OTel import must survive `from cubepi.tracing import schema`).++PEP 517 wheels cannot print during `pip install`. Do not add a `.pth` that prints on every interpreter start. Do not raise in `setup()`.++### 5.2 Tests (`tests/compat/test_cubepi_shim.py`)++- [ ] `import cubepi` captures stderr containing `renamed to 'cubeloop'` and a `DeprecationWarning`+- [ ] `cubepi.Agent is cubeloop.Agent`+- [ ] `from cubepi.providers.anthropic import AnthropicProvider` is the cubeloop class+- [ ] `from cubepi.checkpointer.postgres import PostgresCheckpointer` works+- [ ] Subprocess with OpenTelemetry hidden: `from cubepi.tracing import schema` succeeds (lazy)+- [ ] `python -m cubepi trace --help` exits 0 and prints the warning on stderr+- [ ] Second `import cubepi` in the same process does not reprint the stderr banner++Workspace tests are not enough (they resolve `cubeloop` via the live project). Task 8 adds a clean-venv wheel smoke.++```bash+uv run pytest tests/compat/ -v+```++---++## Task 6: Current docs, site, skills, changelog++Allowed trees only (see Do not touch).++- [ ] `CubePi` → `CubeLoop`, `cubepi` → `cubeloop`, `cubepi.ai` → `cubeloop.dev`, `cubeplexai/cubepi` → `cubeplexai/cubeloop` in:+ - `README.md`, `AGENTS.md`, `CLAUDE.md`+ - `website/docs/**`, `website/src/**`, `website/docusaurus.config.ts` (`title`, `url`, `projectName`, logos, editUrl, keywords)+ - `website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/**`+ - `website/static/_worker.js`: `cubeloop.pages.dev` → `cubeloop.dev`+ - `examples/**`, `skills/cubeloop/**`, `skills/cubeloop-trace/**` (frontmatter `name: cubeloop` / `cubeloop-trace`)+ - checkpointer READMEs+- [ ] New page `website/docs/migration/from-cubepi.md` (+ zh-Hans current):+ - `pip install cubeloop` / import map+ - shim: `pip install -U cubepi` still works, warns, re-exports+ - alembic v5→v6 (`upgrade_v5_to_v6_op`)+ - OTel attribute map + “CLI still reads old JSONL”+ - env var map+ - GitHub redirect+- [ ] Add it to `website/sidebars.ts` Migration category+- [ ] `CHANGELOG.md` `[Unreleased]`: breaking rename, shim, schema v6, OTel namespace. Do not edit older sections. Compare-URL footer can wait for the GitHub rename; use `cubeplexai/cubeloop` now (redirects after rename).+- [ ] `dev/runbooks/cut-doc-version.md`: s/CubePi/CubeLoop/ and s/cubepi/cubeloop/ in the **runbook prose** (it is operational, not a frozen snapshot).++```bash+cd website && pnpm build && pnpm test+```++If browser tools are available, open `/docs/migration/from-cubepi`, `/docs/getting-started/installation`, and the homepage; check desktop + mobile. Frozen `/docs/0.13/` must still say CubePi.++---++## Task 7: Publish workflow++`.github/workflows/publish.yml` currently `uv build`s one dist.++- [ ] Build **both** wheels + sdists into `dist/`:+ 1. root → `cubeloop-0.14.0-*`+ 2. workspace member `cubepi` → `cubepi-0.14.0-*`+- [ ] Upload the whole `dist/` to TestPyPI then PyPI. Set `skip-existing: true` on both `pypa/gh-action-pypi-publish` steps so a partial TestPyPI attempt (cubeloop uploaded, cubepi rejected) can be retried without hitting “file already exists”.+- [ ] Document in the workflow comment (or a short `dev/runbooks/rename-github-and-pypi.md`) the out-of-repo steps — they are **not** this PR:++ 1. Land this PR on `main`.+ 2. Rename GitHub repo `cubepi` → `cubeloop` (Settings → Rename). Do not create a new repo.+ 3. Cloudflare: custom domain `cubeloop.dev`; 301 `cubepi.ai` → `cubeloop.dev`; Pages GitHub connection.+ 4. **PyPI and TestPyPI**: create project `cubeloop` + OIDC publisher for `cubeplexai/cubeloop` on **both** indexes (workflow `publish.yml`, matching environment names). Update the existing `cubepi` publisher's repository name on both indexes after the GitHub rename. Verify publisher identity before tagging.+ 5. Tag `v0.14.0`.+ 6. Cut docs version 0.14 per `cut-doc-version.md` **after** current/ is CubeLoop.++---++## Task 8: Verify++```bash+uv sync --all-extras --dev+uv run ruff check cubeloop/ tests/ compat/cubepi/+uv run ruff format --check cubeloop/ tests/ compat/cubepi/+uv run mypy cubeloop+uv run pytest tests/ -v+cd website && pnpm build && pnpm test+```++Sanity greps (must be empty except Do-not-touch trees and the migrate page / CHANGELOG Unreleased / shim / historical alembic SQL):++```bash+# Current library must not import cubepi+rg -n "from cubepi|import cubepi" cubeloop tests examples website/docs website/src \+ website/scripts website/i18n/zh-Hans/docusaurus-plugin-content-docs/current \+ README.md AGENTS.md CLAUDE.md skills --glob '!**/migration/from-cubepi.md'++# Current schema helpers / runtime SQL must not still write cubepi_* table names+# (historical upgrade_vN helpers and v2/v3 fixtures MAY still contain cubepi_*)+rg -n "INSERT INTO cubepi_|FROM cubepi_|CREATE TABLE cubepi_" cubeloop/checkpointer --glob '*checkpointer.py'+```++`uv build` at repo root and `uv build` for the cubepi member; inspect METADATA for the exact `Requires-Dist: cubeloop==0.14.0`.++Clean-venv wheel smoke (cwd **outside** the checkout). Use the host `uv`, not a venv-local `uv` (there isn’t one). `--no-index` cannot resolve `anthropic` / `pydantic` / `sqlalchemy` / `asyncpg`; pin only our two wheels from `dist/` and let the package index fill the rest:++```bash+REPO=/home/chris/cubepi/.worktrees/2026-09-09-rename-cubeloop+uv venv /tmp/cubeloop-smoke+uv pip install --python /tmp/cubeloop-smoke/bin/python \+ --find-links "$REPO/dist" \+ 'cubeloop==0.14.0' 'cubepi[postgres]==0.14.0'+cd /tmp+/tmp/cubeloop-smoke/bin/python -c "import cubeloop, cubepi; from cubepi.providers.anthropic import AnthropicProvider; from cubepi.tracing import schema; import sqlalchemy, asyncpg"+/tmp/cubeloop-smoke/bin/python -m cubepi trace --help+```++Hide OpenTelemetry in a subprocess for the `from cubepi.tracing import schema` assertion. This is the test that catches path-deps, missing shim files, and extras that do not forward. Use `--find-links` without `--no-index` so third-party wheels still come from PyPI; `--find-links` prefers the local cubeloop/cubepi artifacts when versions match.++---++## Out of scope (do not do in this PR)++- Yanking `cubepi` 0.13.x+- Failing `pip install cubepi` (sklearn brownout)+- Dual-writing OTel keys+- Rewriting versioned docs or old CHANGELOG entries+- New logo artwork+- Opening a second GitHub repository+- Actually renaming the GitHub repo / DNS / PyPI publishers (runbook only)+- Tagging 0.14.0 / cutting `version-0.14` docsdiff --git a/dev/runbooks/cut-doc-version.md b/dev/runbooks/cut-doc-version.mdindex 331e521..ea6a65f 100644--- a/dev/runbooks/cut-doc-version.md+++ b/dev/runbooks/cut-doc-version.md@@ -75,7 +75,7 @@ them before running the cut, not after the build fails.### 1. Run `pnpm apiref` **before** `docusaurus docs:version`-`website/docs/api/cubepi-*.mdx` is gitignored (only `index.mdx` is committed)+`website/docs/api/cubeloop-*.mdx` is gitignored (only `index.mdx` is committed)because it's regenerated from Python source on every build by `pnpm apiref`(wired into `prebuild`/`prestart`). If you cut without running `apiref`first, the snapshot copies an empty `api/` directory, the next build fails@@ -149,11 +149,11 @@ at section indices (`overview` pages) rather than specific subpages.### 6. Don't commit generated API mdx into `current/`-CI has a guard that fails the build if `website/docs/api/cubepi-*.mdx` is+CI has a guard that fails the build if `website/docs/api/cubeloop-*.mdx` ispresent in a commit (only `index.mdx` is allowed). The snapshot is allowedto contain them because the path is different(`versioned_docs/version-X.Y/api/`). If your local cut accidentally staged-`website/docs/api/cubepi-*.mdx`, unstage them — they regenerate on every+`website/docs/api/cubeloop-*.mdx`, unstage them — they regenerate on everybuild.### 7. `versions.json` order matters@@ -242,10 +242,10 @@ When promoting `[Unreleased]` → `[X.Y.0] - YYYY-MM-DD`, also patch thelink block at the bottom of `CHANGELOG.md`:```diff--[Unreleased]: https://github.com/cubeplexai/cubepi/compare/v(X.Y-1).0...HEAD-+[Unreleased]: https://github.com/cubeplexai/cubepi/compare/vX.Y.0...HEAD-+[X.Y.0]: https://github.com/cubeplexai/cubepi/compare/v(X.Y-1).0...vX.Y.0- [(X.Y-1).0]: https://github.com/cubeplexai/cubepi/compare/v(X.Y-2).0...v(X.Y-1).0+-[Unreleased]: https://github.com/cubeplexai/cubeloop/compare/v(X.Y-1).0...HEAD++[Unreleased]: https://github.com/cubeplexai/cubeloop/compare/vX.Y.0...HEAD++[X.Y.0]: https://github.com/cubeplexai/cubeloop/compare/v(X.Y-1).0...vX.Y.0+ [(X.Y-1).0]: https://github.com/cubeplexai/cubeloop/compare/v(X.Y-2).0...v(X.Y-1).0```Verify before commit — every `## [N.M.0]` heading must have a matchingdiff --git a/dev/runbooks/rename-github-and-pypi.md b/dev/runbooks/rename-github-and-pypi.mdnew file mode 100644index 0000000..bf99eb5--- /dev/null+++ b/dev/runbooks/rename-github-and-pypi.md@@ -0,0 +1,63 @@+# GitHub rename and PyPI publishers++Out-of-repo cutover for CubePi → CubeLoop. The code PR does **not** do+these steps; this runbook is the checklist after that PR lands (and the+parts already done before merge).++Do **not** open a second GitHub repository. GitHub's in-place rename+keeps issues, PRs, stars, Actions history, and redirects+`github.com/cubeplexai/cubepi` → `github.com/cubeplexai/cubeloop`.++## Already done (before the 0.14 PR)++These landed during the cutover window and do not need repeating:++| Item | Status |+|---|---|+| GitHub repo rename `cubeplexai/cubepi` → `cubeplexai/cubeloop` | Done |+| Cloudflare Pages custom domains `cubeloop.dev` / `www.cubeloop.dev` on project `cubepi` | Done (project name stays `cubepi`) |+| Zone Single Redirect: `cubepi.ai` / `www.cubepi.ai` → `https://cubeloop.dev${uri}` 301 | Done |+| `cubepi.pages.dev` path 301s (except Pages' built-in `/` alias) via `_worker.js` | Done in this PR |+| Google Search Console change of address `cubepi.ai` → `cubeloop.dev` | Done |+| GA4 stream URL / authorized domains; PostHog authorized URLs | Done |+| PyPI pending Trusted Publisher for **new** project `cubeloop` | Done: repo `cubeplexai/cubeloop`, workflow `publish.yml`, environment `pypi` |++The Cloudflare Pages project is still named `cubepi`. Leave it.+`docs.yml` `projectName: cubepi` is correct.++## After the code PR merges++1. **Confirm GitHub redirects.** `git clone https://github.com/cubeplexai/cubepi.git` should land in `cubeloop`. Update local remotes if they still say `cubepi.git` (`git remote set-url origin https://github.com/cubeplexai/cubeloop.git`).+2. **Cloudflare Pages GitHub connection.** If Pages is wired to the GitHub repo (this project is Direct Upload via `pages-action`, so usually nothing to change). After merge, the next `docs.yml` deploy on `main` publishes CubeLoop current docs to `cubeloop.dev`.+3. **Submit sitemaps** on the Search Console property `cubeloop.dev`:+ - `sitemap.xml`+ - `zh-Hans/sitemap.xml`+ Do this **after** the CubeLoop docs deploy, not before — live sitemaps still listed `cubepi.ai` URLs until then.+4. **PyPI / TestPyPI publishers** (verify before tagging):+ - **New project `cubeloop`:** pending publisher must match `Repository: cubeplexai/cubeloop`, `Workflow: publish.yml`, `Environment: pypi`. First successful upload **creates** the project; there is no "New project" button.+ - **TestPyPI** is a separate account: https://test.pypi.org/manage/account/publishing/ — same workflow/environment names, environment `testpypi`.+ - **Existing `cubepi`:** after the GitHub rename, edit the publisher at https://pypi.org/manage/project/cubepi/settings/publishing/ so the repository is `cubeplexai/cubeloop` (not `cubepi`). Same on TestPyPI.+5. **Tag `v0.14.0`.** `publish.yml` builds both dists (`uv build` + `uv build --package cubepi`) and uploads the whole `dist/` to TestPyPI then PyPI with `skip-existing: true`. A partial TestPyPI attempt can be retried.+6. **Smoke from a clean machine** (not the worktree):+ ```bash+ pip install cubeloop+ python -c "import cubeloop; print(cubeloop.__version__)"+ pip install -U cubepi+ python -c "import cubepi" # DeprecationWarning + stderr banner+ ```+ Both indexes must have **both** files before calling the cut done. The shim's `Requires-Dist: cubeloop==0.14.0` will fail if only `cubepi` uploaded.+7. **Cut docs version 0.14** per [`cut-doc-version.md`](cut-doc-version.md) **after** `website/docs/` current is CubeLoop, so `version-0.14` is born as CubeLoop. Do not snapshot 0.13-branded current/.++## Do not++- Yank `cubepi` 0.13.x.+- Fail `pip install cubepi` (the 0.14 shim must keep working).+- Create `github.com/cubeplexai/cubeloop` as a new empty repo.+- Rename the Cloudflare Pages project (would change `cubepi.pages.dev`).+- Edit `website/versioned_docs/` or old CHANGELOG sections.++## Related++- Spec: `dev/specs/2026-09-09-rename-cubeloop.md`+- Plan: `dev/plans/2026-09-09-rename-cubeloop.md`+- Migrate page: `website/docs/migration/from-cubepi.md`diff --git a/dev/specs/2026-09-09-rename-cubeloop.md b/dev/specs/2026-09-09-rename-cubeloop.mdnew file mode 100644index 0000000..d5a6619--- /dev/null+++ b/dev/specs/2026-09-09-rename-cubeloop.md@@ -0,0 +1,351 @@+# Rename CubePi → CubeLoop++- **Date**: 2026-09-09+- **Status**: Approved for implementation+- **Branch / worktree**: `2026-09-09-rename-cubeloop` → `.worktrees/2026-09-09-rename-cubeloop`+- **Related**: release runbook in this spec §9; docs versioning [`dev/runbooks/cut-doc-version.md`](../runbooks/cut-doc-version.md)++## Confirmed with the user++| Decision | Choice |+|---|---|+| Display name | CubeLoop |+| PyPI / import / CLI | `cubeloop` |+| Domain | `cubeloop.dev` (newly registered) |+| GitHub | Rename `cubeplexai/cubepi` in place to `cubeplexai/cubeloop`. Do **not** create a second repository. |+| Dual package | Yes. `cubepi` continues on PyPI as a transitional meta-package that depends on `cubeloop` and warns. |+| SQL table names | Rename (`cubepi_*` → `cubeloop_*`) with a schema migration. |+| OTel vendor namespace | Rename (`cubepi.*` → `cubeloop.*`). |+| Historical snapshots | Frozen `versioned_docs` / old CHANGELOG entries / old `dev/specs` stay as CubePi — they document what shipped. |++## 1. Motivation++The project is rebranding from CubePi to CubeLoop. The current public identity (`cubepi` on PyPI, `from cubepi import …`, `cubepi.ai`, `cubeplexai/cubepi`) has to move together. Leaving any of those on the old name after the rest have moved creates a split identity that is worse than a clean break.++This is a breaking 0.x release (proposed **0.14.0**), not a 1.0.++## 2. Identity map++| Surface | Before | After |+|---|---|---|+| Display | CubePi | CubeLoop |+| PyPI project | `cubepi` | `cubeloop` (real). `cubepi` stays as the shim. |+| Import root | `cubepi` | `cubeloop` |+| Source tree | `cubepi/` | `cubeloop/` |+| Console script | `cubepi` | `cubeloop`. Shim also keeps `cubepi` as a wrapper. |+| Docs / homepage | `https://cubepi.ai` | `https://cubeloop.dev` |+| GitHub | `https://github.com/cubeplexai/cubepi` | `https://github.com/cubeplexai/cubeloop` |+| Trace dir default | `./cubepi-traces` | `./cubeloop-traces` |+| Skills | `cubepi`, `cubepi-trace` | `cubeloop`, `cubeloop-trace` |+| OTel scope | `cubepi.tracing` | `cubeloop.tracing` |+| OTel vendor attrs | `cubepi.run_id`, `cubepi.turn`, … | `cubeloop.run_id`, `cubeloop.turn`, … |+| SQL tables (PG/MySQL) | `cubepi_threads`, `cubepi_messages`, … | `cubeloop_threads`, `cubeloop_messages`, … |+| SQLAlchemy metadata | `cubepi_metadata` | `cubeloop_metadata` |+| Schema exceptions | `CubepiSchemaError` hierarchy | `CubeloopSchemaError` hierarchy |+| Env vars | `CUBEPI_*` | `CUBELOOP_*` (old names accepted for one 0.x window) |++Out of scope for this rename:++- New logo / visual identity (rename the files; keep the existing artwork unless new assets are supplied).+- Rewriting frozen versioned docs (0.3–0.13) or historical CHANGELOG entries.+- Creating a new GitHub repository.+- Yanking `cubepi` 0.13.x from PyPI.++## 3. Dual package (the `cubepi` shim)++### 3.1 Why a second distribution++Users who already have `cubepi` in a lockfile will `pip install -U cubepi` (or uv/poetry equivalent) and expect *something* to happen. Publishing only `cubeloop` leaves those lockfiles on 0.13.x forever.++Prior art:++- **sklearn on PyPI** (scikit-learn/sklearn-pypi-package) is an empty distribution that depends on `scikit-learn`. That works because the real wheel already provides the `sklearn` import path. cubepi cannot copy this blindly: after the rename the real wheel provides `cubeloop`, not `cubepi`.+- sklearn later switched the dummy to a **brownout that fails install**. We do **not** fail install in 0.14. We warn, pull in `cubeloop`, and keep old imports working for a transition window.+- **Pillow** ships the `PIL` import path inside the same wheel. We cannot do that as the long-term shape (the import path is part of the new name), but the shim's job is the same idea for one 0.x window.++Divergence: cubepi's import path **is** the PyPI name, so an empty dependency-only wheel would make `import cubepi` raise `ModuleNotFoundError` after a successful install. That is worse than a warning. The shim is therefore a **tiny alias package**, not a zero-file meta-package.++### 3.2 Shape of the `cubepi` 0.14+ distribution++Lives in this repo at `compat/cubepi/` (own `pyproject.toml`). The root project becomes `cubeloop`.++- `requires-python` matches cubeloop.+- Version is **exactly** the cubeloop version (pin `cubeloop==0.14.0`, not a range). Version skew between the two wheels is a bug.+- Optional extras are forwarded: `cubepi[sqlite]` → `cubeloop[sqlite]==<same>`, same for `postgres`, `mysql`, `mcp`, `tracing`, `tracing-otlp`, `trace-cli`.+- Classifier `Development Status :: 7 - Inactive`.+- PyPI description / README is a deprecation banner pointing at `pip install cubeloop` and https://cubeloop.dev.++The wheel contains:++1. `cubepi/__init__.py` — warn + public re-export of `cubeloop`.+2. An on-demand import redirect so deep imports keep working:+ `from cubepi.providers.anthropic import AnthropicProvider` loads the cubeloop module of the same suffix.+3. Console script `cubepi` → prints the same warning to stderr, then dispatches to `cubeloop.cli`.++The redirect is a `MetaPathFinder` **plus an alias `Loader`**, not a finder that only mutates `sys.modules` and returns `None`. Python resolves `cubepi.providers` before `cubepi.providers.anthropic`; if the finder does not return a `ModuleSpec` with a loader, import falls through to a missing physical package and deep imports fail.++Required shape:++- Finder matches only `fullname.startswith("cubepi.")` (the root `cubepi` package is the shim on disk).+- `find_spec` returns a `ModuleSpec(fullname, AliasLoader(real_name), origin=…, is_package=…)`.+- `AliasLoader.create_module` returns `importlib.import_module("cubeloop" + suffix)` — the **same object** as `sys.modules[real_name]`, so cubeloop's relative imports keep using `__name__ == "cubeloop…"` .+- `exec_module` is a no-op (module already executed under the real name).+- Package specs set `submodule_search_locations` so further children can be found.+- Do not `walk_packages` / eagerly import `cubeloop.tracing`. `from cubepi.tracing import schema` must still work without OpenTelemetry.++Do not assign `sys.modules["cubepi"] = cubeloop`.++### 3.3 The install-time warning++PEP 517 wheels do not run `setup.py` at install time. A print inside `setup()` only fires when building from an sdist, and `uv build` publishes a wheel, so **a true pip-install print is not reliable**. sklearn's dummy eventually failed install by raising in `setup()`; that is a brownout, not a warning, and it only works for sdist installs.++Warning surfaces we actually ship:++| When | How |+|---|---|+| Browsing PyPI | Banner README + Inactive classifier. |+| First `import cubepi` | `DeprecationWarning` **and** one stderr line (warnings are often filtered). |+| `cubepi` CLI | Same stderr line, then the cubeloop CLI. |+| Resolver | `cubepi==0.14.0` depending on `cubeloop==0.14.0` is visible in the lock. |++Do not install a `.pth` that prints on every Python startup.++The stderr / warning text:++```text+WARNING: The 'cubepi' package has been renamed to 'cubeloop'.+Install `cubeloop` and import from `cubeloop` instead.+See https://cubeloop.dev/docs/migration/from-cubepi+```++### 3.4 Shim lifetime++Keep the shim for the rest of 0.x. Removal (or a sklearn-style install brownout) is a later, explicit decision — not part of 0.14.++### 3.5 Publishing both wheels++`.github/workflows/publish.yml` builds two dists from the same tag:++1. root project → `cubeloop`+2. `compat/cubepi` → `cubepi`++PyPI trusted publishing is per project **and per index**. The publish workflow uploads to TestPyPI first, then PyPI. Before tagging:++- Register `cubeloop` on **both** pypi.org and test.pypi.org, each with an OIDC publisher for `cubeplexai/cubeloop` (workflow `publish.yml`, matching environment names).+- After the GitHub repo rename, update the existing `cubepi` publisher's repository name on **both** indexes to `cubeplexai/cubeloop`.++Partial upload: wheels are immutable. If TestPyPI accepts `cubeloop` and then rejects `cubepi` (missing publisher), a retry of the same version fails on the already-uploaded file. The publish action must set `skip-existing: true` (or an equivalent idempotent retry) so a completed file is skipped and the missing one can be uploaded. Document the same for a human `twine` recovery.++A post-build smoke test (clean venv, `--no-index --find-links dist`, cwd outside the checkout) is required before we trust the two wheels: `import cubeloop`, `import cubepi` (warns), a deep import, `from cubepi.tracing import schema` without OpenTelemetry, `python -m cubepi trace --help`, and `cubepi[postgres]` pulling sqlalchemy/asyncpg.++## 4. Library rename++### 4.1 Package tree and Python names++`git mv cubepi cubeloop`. Every `from cubepi…` / `import cubepi…` in library code, tests, examples, website scripts, and current docs becomes `cubeloop`.++Public identifiers that embed the old name:++| Old | New |+|---|---|+| `cubepi_metadata` | `cubeloop_metadata` |+| `CubepiBase`, `CubepiThread`, `CubepiMessage`, `CubepiRun`, `CubepiHitlAnswer`, `CubepiSchemaVersion` | `Cubeloop*` |+| `CubepiSchemaError`, `CubepiSchemaUninitialized`, `CubepiSchemaMismatch` | `CubeloopSchemaError`, `CubeloopSchemaUninitialized`, `CubeloopSchemaMismatch` |+| `CUBEPI_*` tracing constants | `CUBELOOP_*` |+| `_pkg_version("cubepi")` | `_pkg_version("cubeloop")` |++cubeloop itself does **not** keep the old Python names. The shim is the compatibility layer.++### 4.2 CLI++`[project.scripts] cubeloop = "cubeloop.cli.__main__:main"`.++Default JSONL directory: `./cubeloop-traces`. `--dir` is unchanged. No automatic fallback to `./cubepi-traces`.++### 4.3 Env vars++| Old | New |+|---|---|+| `CUBEPI_TEST_PG_DSN` | `CUBELOOP_TEST_PG_DSN` |+| `CUBEPI_TEST_MYSQL_DSN` | `CUBELOOP_TEST_MYSQL_DSN` |+| `CUBEPI_TEST_MCP_HTTP_URL` | `CUBELOOP_TEST_MCP_HTTP_URL` |+| `CUBEPI_PG_DSN` (examples) | `CUBELOOP_PG_DSN` |+| `CUBEPI_MYSQL_DSN` (examples) | `CUBELOOP_MYSQL_DSN` |+| `CUBEPI_DOCS_SOURCE_REF` | `CUBELOOP_DOCS_SOURCE_REF` |++Readers accept the old name if the new one is unset, for the rest of 0.x. CI and docs print the new name.++## 5. Checkpointer schema v5 → v6++`EXPECTED_SCHEMA_VERSION` becomes 6. Hosts apply `upgrade_v5_to_v6_op()` (Postgres and MySQL each get one) and then `write_schema_version_op()`.++### 5.0 Runtime verification (unmigrated v5)++0.14 `_verify_schema` SELECTs `cubeloop_schema_version`. A v5 database still has only `cubepi_schema_version`. Treating “new table missing” as `CubeloopSchemaUninitialized` / “tables not found” is the wrong diagnosis — the host needs `upgrade_v5_to_v6_op()`, not a greenfield CREATE.++Verification order:++1. `cubeloop_schema_version` present → compare `version` to 6 (today’s path). Mismatch hint names every `upgrade_vN_to_v{N+1}_op()` still required, including v5→v6.+2. Else `cubepi_schema_version` present → `CubeloopSchemaMismatch(expected=6, actual=<that row>)` with a hint that **only** names `upgrade_v5_to_v6_op()` + `write_schema_version_op()`. Do this even if the stored number is already 6 (a host who replayed live `write_schema_version_op()` before the rename).+3. Else if `cubepi_threads` or `cubeloop_threads` exists → not an empty database. Raise `CubeloopSchemaMismatch(expected=6, actual=0)` with a hint that the version table is missing so the schema cannot be auto-classified. Recovery (migrate guide): if the data tables are still `cubepi_*`, `CREATE TABLE cubepi_schema_version` and `INSERT 5`, then run `upgrade_v5_to_v6_op()`. Do **not** apply fresh v6 CREATE TABLE on top of existing data.+4. Else → `CubeloopSchemaUninitialized`.++Do not SELECT the legacy version table except as this diagnostic.++### 5.0.1 `write_schema_version_op()` must not assume the new table++Hosts copy `op.execute(write_schema_version_op())` into **each** Alembic revision (documented pattern). After 0.14 those old revisions still run against `cubepi_schema_version` when someone provisions a fresh DB by replaying history. If the helper is rewritten to only touch `cubeloop_schema_version`, replay dies in the v4→v5 revision, before v6 can rename.++`write_schema_version_op()` writes `EXPECTED_SCHEMA_VERSION` to `cubeloop_schema_version` if that table exists, else to `cubepi_schema_version`. `upgrade_v5_to_v6_op()` only renames; the host then calls `write_schema_version_op()`, which now sees the new table.++Dialect constraints:++- **Postgres:** one `DO $$ … $$` block is fine (`asyncpg` / Alembic `op.execute` send it as a single statement).+- **MySQL:** the documented contract is `for stmt in write_schema_version_op().split(";"): op.execute(stmt)`. A compound `IF` / stored procedure **cannot** be used — internal semicolons get split into invalid fragments. Return a `;`-joined sequence of **standalone** statements only, e.g. `SET @cp_ver_new = (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'cubeloop_schema_version')`, then `SET @cp_del = IF(@cp_ver_new > 0, 'DELETE FROM cubeloop_schema_version WHERE version <> N', 'DELETE FROM cubepi_schema_version WHERE version <> N')`, then `PREPARE` / `EXECUTE` / `DEALLOCATE PREPARE`, then the same for `INSERT IGNORE`. No statement in that string contains a nested `;`. Tests must split-and-execute exactly as the README does.++Historical v1–v5 DDL helpers keep emitting `cubepi_*` names. A 0.14 test must replay that full helper chain (not only a pre-built v5 snapshot) through v6 and then open the checkpointer.++### 5.1 Postgres++Rename parent tables, 64 message partitions, 64 run partitions, indexes, and the schema-version table:++| Old | New |+|---|---|+| `cubepi_threads` | `cubeloop_threads` |+| `cubepi_messages` (+ `cubepi_messages_p00`…`p63`) | `cubeloop_messages` (+ `cubeloop_messages_p00`…`p63`) |+| `cubepi_runs` (+ `cubepi_runs_p00`…`p63`) | `cubeloop_runs` (+ same partition suffix) |+| `cubepi_hitl_answers` | `cubeloop_hitl_answers` |+| `cubepi_schema_version` | `cubeloop_schema_version` |+| `ix_cubepi_*` | `ix_cubeloop_*` |++PostgreSQL `ALTER TABLE … RENAME TO` on a partitioned parent does **not** rename children. The helper must rename each partition. FKs follow the referenced table automatically.++Fresh installs create `cubeloop_*` names only. `create_message_partitions_op` / `create_runs_partitions_op` emit the new names.++Idempotency is **complete only when both** `cubeloop_threads` and `cubeloop_schema_version` exist. `cubeloop_threads` alone is not a no-op sentinel (that is the half-renamed failure mode). If data tables are already `cubeloop_*` but `cubepi_schema_version` still exists, rename the remaining objects. If neither new nor old data tables exist, this is not a v5→v6 path.++### 5.2 MySQL++One `RENAME TABLE a TO a2, b TO b2, …` statement covering **every** v5 table including `cubepi_schema_version`. Indexes and KEY partitions ride with the table. A second statement for the version table is forbidden: if it fails after data tables already moved, retry sees `cubeloop_threads` and would no-op under a naive sentinel.++The helper assumes a complete v5 (data + version table). If `cubepi_schema_version` is missing, the atomic rename fails as a whole — `_verify_schema` step 3 tells the operator to create the version table first. Same complete-state idempotency as Postgres.++### 5.3 SQLite — do not rename++SQLite already uses generic names (`messages`, `runs`, `thread_extra`, `thread_pending_request`, `thread_hitl_answers`). There is no `cubepi_` prefix to update, and renaming those files' internal tables would churn local DBs for no brand value.++This is a deliberate divergence from "rename every table": SQLite was never branded.++### 5.4 Host-managed DDL++Examples (`examples/checkpointing_postgres.py`, `examples/checkpointing_mysql.py`) and the backend READMEs ship the v6 CREATE TABLE statements under the new names, plus the v5→v6 rename helper for existing databases. Applications that copy-pasted v5 DDL must run the helper (or equivalent `RENAME TABLE`) before opening 0.14.++## 6. Tracing++### 6.1 Write path++Every cubepi-vendor identifier on the write path changes. Implementation starts from a grep of `cubepi.` in `cubeloop/` (after the tree rename), not from the schema.py constant list alone. Inventory that exists in 0.13.6 and **must** move:++| Kind | Old | New |+|---|---|---|+| Attr constants in `schema.py` | `cubepi.run_id`, `cubepi.thread_id`, `cubepi.agent.*`, `cubepi.turn.*`, `cubepi.llm.*`, `cubepi.tool.*`, `cubepi.run.outcome`, `cubepi.aborted`, counts | `cubeloop.*` same suffix |+| Span name | `cubepi.turn` | `cubeloop.turn` |+| Scope | `cubepi.tracing` | `cubeloop.tracing` |+| Ad-hoc attrs | `cubepi.tags`, `cubepi.metadata.<key>`, `cubepi.oneshot.operation`, `cubepi.fork.src_thread_id`, `cubepi.fork.after_run_id` | `cubeloop.*` |+| Span name | `cubepi.agent.fork_once` | `cubeloop.agent.fork_once` |+| `error.type` values | `cubepi.aborted`, `cubepi.error`, `cubepi.tool.error` | `cubeloop.aborted` / `.error` / `.tool.error` |+| Tracer scopes | `cubepi.mcp`, `cubepi.hitl`, `cubepi.agent` | `cubeloop.*` |+| Loggers | `cubepi.providers`, `cubepi.providers.base`, `cubepi.providers.fallback`, `cubepi.tracing` | `cubeloop.*` |+| ContextVars | `cubepi.tracing.run_metadata`, `cubepi.tracing.run_tags`, `cubepi.tracing.active_run` | `cubeloop.tracing.*` |+| Helper | `cubepi_error_type_for` → `"cubepi.aborted"` | `cubeloop_error_type_for` → `"cubeloop.aborted"` |++Promote every ad-hoc f-string / literal onto schema constants. No dual-write. `gen_ai.*` is unchanged.++### 6.2 Read path (`cubeloop trace`)++JSONL from ≤0.13 still has `cubepi.*` keys. Readers accept **both** namespaces. New files are cubeloop-only.++A generic `schema.attr(attrs, NEW_KEY)` (try new, then old) is not enough for abort: `Span.is_aborted` today reads only the boolean `cubepi.aborted`. Some 0.13 spans (and MCP adapter paths) also stamp `error.type="cubepi.aborted"`; treat as aborted if **either** boolean (`cubeloop.aborted` or `cubepi.aborted`) is true **or** `error.type` is `cubeloop.aborted` or `cubepi.aborted`. Metadata prefix, oneshot, tags, fork attrs, and span name `cubepi.turn` all dual-read.++This is the one place dual-read is required. Host dashboards are their migration.++## 7. Docs, site, brand files++### 7.1 Current docs (this PR)++Rename throughout:++- `website/docs/**` (EN current)+- `website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/**`+- `website/src/**`, `docusaurus.config.ts`, compare pages, FAQ, changelog page+- `README.md`, `AGENTS.md` / `CLAUDE.md`, `examples/**`, `skills/**`+- `website/static/_worker.js`: production hostname `cubeloop.pages.dev` → `cubeloop.dev`++Add `website/docs/migration/from-cubepi.md` (and zh-Hans current): install `cubeloop`, import map, alembic v5→v6, OTel attribute map, shim warning, GitHub redirect. Put it in the existing Migration sidebar category.++A feature without docs is not done; the migrate page is the user-facing docs for this change.++### 7.2 Frozen history — do not rewrite++`website/versioned_docs/version-0.3` … `version-0.13` and their zh-Hans mirrors stay CubePi. They are snapshots of released versions.++Optional, small, allowed: a one-line banner on those versions ("CubePi was renamed to CubeLoop in 0.14; this snapshot documents the `cubepi` package.") if Docusaurus version config supports it without editing hundreds of md files. Do not search-replace the snapshots.++`CHANGELOG.md`: add a 0.14.0 section that describes the rename. Do not rewrite older sections. Update the `[Unreleased]` / compare URLs to the new GitHub path once the repo is renamed.++`dev/specs/**` and `dev/plans/**` from before this date stay as written.++### 7.3 Brand files++Rename `website/static/img/brand/cubepi-*` → `cubeloop-*`. Same artwork. Social preview alt text / Open Graph titles become CubeLoop.++### 7.4 Domain++- Canonical site: `https://cubeloop.dev`+- Cloudflare Pages custom domain: `cubeloop.dev`+- `cubepi.ai` (and `www`) **301** to the matching `cubeloop.dev` path. Existing `_worker.js` already 301s `cubepi.pages.dev` → the custom domain; after the cut it 301s `cubeloop.pages.dev` → `cubeloop.dev`. The cubepi.ai → cubeloop.dev redirect is DNS/Cloudflare config, not this repo.++## 8. GitHub rename (in place)++GitHub's rename keeps issues, PRs, stars, Actions history, and redirects `github.com/cubeplexai/cubepi` → `…/cubeloop` (git clone of the old URL keeps working).++Things that do **not** follow automatically and must be updated in the same release window:++- This repo's URLs in `pyproject.toml`, README badges, `docusaurus.config.ts` `editUrl`, CHANGELOG compare links, skills install lines.+- PyPI trusted publisher repository name (both `cubepi` and the new `cubeloop` project).+- Codecov project (usually follows; verify the badge).+- Cloudflare Pages GitHub connection.+- skills.sh / DeepWiki entries that key on `cubeplexai/cubepi`.++Do **not** open a new empty repository and push. That would split issues and break the redirect.++## 9. Release order++The code PR can land on `main` while the GitHub repo is still named `cubepi`, but then README/docs URLs 404 until the rename. Coordinate as one cut:++1. Land this work on `main` (package tree, shim, schema v6, current docs, migrate guide).+2. **Immediately** rename the GitHub repository `cubepi` → `cubeloop`.+3. Point `cubeloop.dev` at the Pages project; 301 `cubepi.ai` → `cubeloop.dev`.+4. Update **PyPI and TestPyPI** trusted publishers; first-time-create `cubeloop` on both indexes. Confirm workflow name + environment match `publish.yml`.+5. Tag `v0.14.0`. Publish uploads both dists; `skip-existing: true` so a partial TestPyPI attempt can be retried. User-install of the shim needs cubeloop on the same index — TestPyPI/PyPI both must have both files before we call the cut done.+6. Verify from a clean machine: `pip install cubeloop` and `pip install -U cubepi` both yield importable cubeloop; the latter warns on `import cubepi`.++Docs version snapshot for 0.14 follows [`cut-doc-version.md`](../runbooks/cut-doc-version.md) **after** the current tree is CubeLoop, so `version-0.14` is born as CubeLoop.++## 10. Testing++- Full existing suite after the tree rename (pytest, ruff, mypy) against `cubeloop/`.+- Shim tests in `tests/compat/`: `import cubepi` warns; `from cubepi import Agent` is `cubeloop.Agent`; `from cubepi.providers.anthropic import AnthropicProvider` resolves; `from cubepi.tracing import schema` is still lazy. Plus a **clean-venv wheel smoke** (Task 8) — workspace tests are not sufficient.+- Schema v6: a **fresh-v6** fixture (canonical new DDL only, no historical helpers); a **historical-v5** fixture (old names + old helpers) that then runs `upgrade_v5_to_v6_op`; a **full helper-chain replay** from v1-shaped CREATE through v6; unmigrated v5 raises `CubeloopSchemaMismatch` not Uninitialized; helper is idempotent.+- Trace CLI fixtures: 0.13 JSONL covering `cubepi.turn`, `cubepi.run_id`, `cubepi.metadata.*`, `cubepi.tags`, fork attrs, oneshot, boolean abort, and `error.type="cubepi.aborted"` without the boolean; 0.14 JSONL uses only `cubeloop.*`.+- Examples and `tests/checkpointer/test_examples.py` use `CUBELOOP_*_DSN` (old env still accepted).++## 11. Non-goals++- 1.0 version jump.+- Failing `pip install cubepi` (sklearn brownout) in this release.+- Dual-writing OTel attributes.+- Renaming SQLite table names.+- Rewriting versioned docs or git history.+- A new GitHub repository.+- Redesigning the logo.diff --git a/examples/README.md b/examples/README.mdindex 361d508..83cc088 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,6 +1,6 @@# Examples-Runnable scripts demonstrating CubePi features.+Runnable scripts demonstrating CubeLoop features.Run any example with `uv`:@@ -33,12 +33,12 @@ when both are set.| Example | What it shows | Extra deps ||---|---|---|| [`weather_agent.py`](weather_agent.py) | Tool calling, streaming output, Ctrl-C cancellation | `httpx` |-| [`persistent_chat.py`](persistent_chat.py) | SQLite-backed chat that survives restarts | `cubepi[sqlite]` |+| [`persistent_chat.py`](persistent_chat.py) | SQLite-backed chat that survives restarts | `cubeloop[sqlite]` || [`multi_provider_failover.py`](multi_provider_failover.py) | Automatic failover between providers on error | — || [`ask_user_form.py`](ask_user_form.py) | HITL multi-question form via `ask_user_tool` | — || [`sandbox_confirm.py`](sandbox_confirm.py) | `ApprovalPolicyMiddleware` — auto-allow, deny, or confirm tool calls | — |-| [`resumable_tasks.py`](resumable_tasks.py) | Crash-resilient tasks with idempotent tools and checkpointing | `cubepi[sqlite]` |-| [`postgres_fastapi.py`](postgres_fastapi.py) | Production HTTP service: FastAPI + SSE streaming + Postgres | `cubepi[postgres]` `fastapi` `uvicorn[standard]` `sse-starlette` |+| [`resumable_tasks.py`](resumable_tasks.py) | Crash-resilient tasks with idempotent tools and checkpointing | `cubeloop[sqlite]` |+| [`postgres_fastapi.py`](postgres_fastapi.py) | Production HTTP service: FastAPI + SSE streaming + Postgres | `cubeloop[postgres]` `fastapi` `uvicorn[standard]` `sse-starlette` |### weather_agent.py@@ -56,7 +56,7 @@ uv run python examples/persistent_chat.py bob# Different thread, clean slate.```-Requires: `cubepi[sqlite]`+Requires: `cubeloop[sqlite]`### multi_provider_failover.py@@ -96,15 +96,15 @@ uv run python examples/resumable_tasks.py job-1```Items already processed are skipped on resume (idempotent tool backed by-a file-based job store in `/tmp/cubepi-jobs/`).+a file-based job store in `/tmp/cubeloop-jobs/`).-Requires: `cubepi[sqlite]`+Requires: `cubeloop[sqlite]`### postgres_fastapi.py```bashuv sync --extra postgres-export DATABASE_URL=postgresql://user:pass@localhost/cubepi+export DATABASE_URL=postgresql://user:pass@localhost/cubeloopuv run --with fastapi --with "uvicorn[standard]" --with sse-starlette \uvicorn examples.postgres_fastapi:app --reload --port 8000@@ -124,18 +124,18 @@ Both use `FauxProvider` (no API key needed) and create a **throwaway database**that is dropped on exit — safe to re-run against a dev server.```bash-CUBEPI_PG_DSN=postgresql://user:pass@host:5432/dbname \+CUBELOOP_PG_DSN=postgresql://user:pass@host:5432/dbname \uv run python examples/checkpointing_postgres.py-CUBEPI_MYSQL_DSN=mysql://user:pass@host:3306/dbname \+CUBELOOP_MYSQL_DSN=mysql://user:pass@host:3306/dbname \uv run python examples/checkpointing_mysql.py```-Each script bootstraps the CubePi schema inline so it runs standalone, but in+Each script bootstraps the CubeLoop schema inline so it runs standalone, but inproduction the schema is owned by your host application's Alembic migration.See the host-integration runbooks for the migration recipe and version-upgrade flow:-- [`cubepi/checkpointer/postgres/README.md`](../cubepi/checkpointer/postgres/README.md)-- [`cubepi/checkpointer/mysql/README.md`](../cubepi/checkpointer/mysql/README.md)+- [`cubeloop/checkpointer/postgres/README.md`](../cubeloop/checkpointer/postgres/README.md)+- [`cubeloop/checkpointer/mysql/README.md`](../cubeloop/checkpointer/mysql/README.md)- User guides: [Postgres](../website/docs/guides/checkpointing/postgres.md) ·[MySQL](../website/docs/guides/checkpointing/mysql.md)diff --git a/examples/_provider.py b/examples/_provider.pyindex 97e843d..f12fb80 100644--- a/examples/_provider.py+++ b/examples/_provider.py@@ -22,13 +22,13 @@ _anthropic_key = os.environ.get("ANTHROPIC_API_KEY")_openai_key = os.environ.get("OPENAI_API_KEY")if _anthropic_key:- from cubepi.providers.anthropic import AnthropicProvider+ from cubeloop.providers.anthropic import AnthropicProvider_base_url = os.environ.get("ANTHROPIC_BASE_URL") or Noneprovider = AnthropicProvider(api_key=_anthropic_key, base_url=_base_url)MODEL_ID = os.environ.get("MODEL", "claude-sonnet-4-6")elif _openai_key:- from cubepi.providers.openai import OpenAIProvider+ from cubeloop.providers.openai import OpenAIProvider_base_url = os.environ.get("OPENAI_BASE_URL") or Noneprovider = OpenAIProvider(api_key=_openai_key, base_url=_base_url)diff --git a/examples/ask_user_form.py b/examples/ask_user_form.pyindex 6ce949d..6c725d2 100644--- a/examples/ask_user_form.py+++ b/examples/ask_user_form.py@@ -13,8 +13,8 @@ Set ANTHROPIC_API_KEY or OPENAI_API_KEY before running (see _provider.py).import asyncio-from cubepi import Agent-from cubepi.hitl import InMemoryChannel, ask_user_tool+from cubeloop import Agent+from cubeloop.hitl import InMemoryChannel, ask_user_toolfrom _provider import MODEL_ID, providerdiff --git a/examples/checkpointing_mysql.py b/examples/checkpointing_mysql.pyindex 9981f98..e4af062 100644--- a/examples/checkpointing_mysql.py+++ b/examples/checkpointing_mysql.py@@ -3,7 +3,7 @@This is a runnable, end-to-end example of `MySQLCheckpointer`. It uses`FauxProvider`, so it needs no API key — only a reachable MySQL 8.0.13+.- CUBEPI_MYSQL_DSN=mysql://user:pass@host:3306/dbname \+ CUBELOOP_MYSQL_DSN=mysql://user:pass@host:3306/dbname \uv run python examples/checkpointing_mysql.pyDefaults to `mysql://root:root@localhost:3306/mysql`.@@ -28,76 +28,80 @@ import secretsimport aiomysql-from cubepi.agent.agent import Agent-from cubepi.checkpointer.mysql import MySQLCheckpointer-from cubepi.checkpointer.mysql.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.mysql import MySQLCheckpointer+from cubeloop.checkpointer.mysql.alembic_helpers import (+ create_runs_table_op,messages_partition_clause,- upgrade_v3_to_v4_op,write_schema_version_op,)-from cubepi.checkpointer.mysql.checkpointer import _parse_dsn-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.checkpointer.mysql.checkpointer import _parse_dsn+from cubeloop.providers.faux import FauxProvider, faux_assistant_messageADMIN_DSN = os.environ.get(- "CUBEPI_MYSQL_DSN",- "mysql://root:root@localhost:3306/mysql",+ "CUBELOOP_MYSQL_DSN",+ os.environ.get(+ "CUBEPI_MYSQL_DSN",+ "mysql://root:root@localhost:3306/mysql",+ ),)THREAD_ID = "user-42"async def bootstrap_schema(dsn: str) -> None:- """Create the cubepi v2 schema.+ """Create the cubeloop v6 schema.- In a real deployment this is your Alembic migration. The columns come- straight from `cubepi_metadata`; only the KEY partitioning and the- schema-version row are added by hand (autogenerate can't model them).- See cubepi/checkpointer/mysql/README.md for the migration recipe.+ In a real deployment this is your Alembic migration. Existing v5+ databases should call upgrade_v5_to_v6_op() instead of this CREATE."""conn = await aiomysql.connect(autocommit=True, **_parse_dsn(dsn))try:async with conn.cursor() as cur:await cur.execute("""- CREATE TABLE cubepi_threads (+ CREATE TABLE cubeloop_threads (thread_id VARCHAR(255) COLLATE utf8mb4_bin PRIMARY KEY,parent_thread_id VARCHAR(255) COLLATE utf8mb4_bin NULL,forked_at_seq BIGINT NULL,extra JSON NOT NULL DEFAULT (JSON_OBJECT()),+ pending_request JSON NULL,+ run_id VARCHAR(64) NULL,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMP,CONSTRAINT fk_parent FOREIGN KEY (parent_thread_id)- REFERENCES cubepi_threads (thread_id)+ REFERENCES cubeloop_threads (thread_id)) ENGINE=InnoDB""")- await cur.execute(add_pending_request_column_op()) # v1 -> v2 column- await cur.execute(add_run_id_column_op()) # v2 -> v3 columnawait cur.execute("""- CREATE TABLE cubepi_messages (+ CREATE TABLE cubeloop_messages (thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,seq BIGINT NOT NULL,role VARCHAR(32) NOT NULL,metadata JSON NOT NULL DEFAULT (JSON_OBJECT()),payload LONGBLOB NOT NULL,+ run_id VARCHAR(255) NULL,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (thread_id, seq)+ PRIMARY KEY (thread_id, seq),+ KEY ix_cubeloop_messages_thread_run (thread_id, run_id)) ENGINE=InnoDB """- + messages_partition_clause() # PARTITION BY KEY (thread_id)+ + messages_partition_clause())await cur.execute(- "CREATE TABLE cubepi_schema_version (version INT PRIMARY KEY) "+ "CREATE TABLE cubeloop_schema_version (version INT PRIMARY KEY) ""ENGINE=InnoDB")- # v3 -> v4: run_id on cubepi_messages + cubepi_runs partitioned table.- # upgrade_v3_to_v4_op() returns multiple ';'-separated statements;- # MySQL runs one per call, so split before executing.- for stmt in upgrade_v3_to_v4_op().split(";"):- if stmt.strip():- await cur.execute(stmt)- # write_schema_version_op() returns two ';'-separated statements;- # MySQL runs one per call, so split before executing.+ await cur.execute(create_runs_table_op())+ await cur.execute("""+ CREATE TABLE cubeloop_hitl_answers (+ thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ run_id VARCHAR(255) NOT NULL,+ question_id VARCHAR(255) NOT NULL,+ answer JSON NOT NULL,+ answered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (thread_id, run_id, question_id)+ ) ENGINE=InnoDB+ """)for stmt in write_schema_version_op().split(";"):if stmt.strip():await cur.execute(stmt)@@ -126,7 +130,7 @@ def transcript(messages) -> list[str]:async def main() -> None:# Throwaway DB so the example is safe to re-run.- db_name = f"cubepi_example_{secrets.token_hex(5)}"+ db_name = f"cubeloop_example_{secrets.token_hex(5)}"admin_cfg = _parse_dsn(ADMIN_DSN)admin = await aiomysql.connect(autocommit=True, **admin_cfg)try:diff --git a/examples/checkpointing_postgres.py b/examples/checkpointing_postgres.pyindex a75cb26..378557e 100644--- a/examples/checkpointing_postgres.py+++ b/examples/checkpointing_postgres.py@@ -3,7 +3,7 @@This is a runnable, end-to-end example of `PostgresCheckpointer`. It uses`FauxProvider`, so it needs no API key — only a reachable Postgres.- CUBEPI_PG_DSN=postgresql://user:pass@host:5432/dbname \+ CUBELOOP_PG_DSN=postgresql://user:pass@host:5432/dbname \uv run python examples/checkpointing_postgres.pyDefaults to `postgresql://postgres:postgres@localhost:5432/postgres`.@@ -28,69 +28,90 @@ import secretsimport asyncpg-from cubepi.agent.agent import Agent-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.checkpointer.postgres.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.checkpointer.postgres.alembic_helpers import (create_message_partitions_op,- upgrade_v3_to_v4_op,+ create_runs_partitions_op,write_schema_version_op,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.faux import FauxProvider, faux_assistant_messageADMIN_DSN = os.environ.get(- "CUBEPI_PG_DSN",- "postgresql://postgres:postgres@localhost:5432/postgres",+ "CUBELOOP_PG_DSN",+ os.environ.get(+ "CUBEPI_PG_DSN",+ "postgresql://postgres:postgres@localhost:5432/postgres",+ ),)THREAD_ID = "user-42"async def bootstrap_schema(dsn: str) -> None:- """Create the cubepi v2 schema.+ """Create the cubeloop v6 schema.- In a real deployment this is your Alembic migration. The columns come- straight from `cubepi_metadata`; only the partitioning and the- schema-version row are added by hand (autogenerate can't model them).- See cubepi/checkpointer/postgres/README.md for the migration recipe.+ In a real deployment this is your Alembic migration. Existing v5+ databases should call upgrade_v5_to_v6_op() instead of this CREATE."""conn = await asyncpg.connect(dsn)try:await conn.execute("""- CREATE TABLE cubepi_threads (+ CREATE TABLE cubeloop_threads (thread_id TEXT PRIMARY KEY,- parent_thread_id TEXT REFERENCES cubepi_threads(thread_id),+ parent_thread_id TEXT REFERENCES cubeloop_threads(thread_id),forked_at_seq BIGINT,extra JSONB NOT NULL DEFAULT '{}'::jsonb,+ pending_request JSONB,+ run_id TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),updated_at TIMESTAMPTZ NOT NULL DEFAULT now());""")- await conn.execute(add_pending_request_column_op()) # v1 -> v2 column- await conn.execute(add_run_id_column_op()) # v2 -> v3 columnawait conn.execute("""- CREATE TABLE cubepi_messages (+ CREATE TABLE cubeloop_messages (thread_id TEXT NOT NULL- REFERENCES cubepi_threads(thread_id) ON DELETE CASCADE,+ REFERENCES cubeloop_threads(thread_id) ON DELETE CASCADE,seq BIGINT NOT NULL,role TEXT NOT NULL,metadata JSONB NOT NULL DEFAULT '{}'::jsonb,payload BYTEA NOT NULL,+ run_id TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (thread_id, seq)) PARTITION BY HASH (thread_id);""")- await conn.execute(create_message_partitions_op()) # 64 child partitions+ 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);+ CREATE INDEX ix_cubeloop_messages_metadata_gin+ ON cubeloop_messages USING GIN (metadata jsonb_path_ops);""")- await conn.execute(- "CREATE TABLE cubepi_schema_version (version INTEGER PRIMARY KEY);"- )- # v3 -> v4: run_id on cubepi_messages + cubepi_runs partitioned table.- await conn.execute(upgrade_v3_to_v4_op())- await conn.execute(write_schema_version_op()) # record EXPECTED_SCHEMA_VERSION+ await conn.execute("""+ CREATE TABLE cubeloop_schema_version (version INTEGER PRIMARY KEY);+ """)+ await conn.execute("""+ CREATE TABLE cubeloop_runs (+ thread_id TEXT NOT NULL REFERENCES cubeloop_threads(thread_id)+ ON DELETE CASCADE,+ run_id TEXT NOT NULL,+ claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ completed_at TIMESTAMPTZ,+ completion_seq BIGINT,+ PRIMARY KEY (thread_id, run_id)+ ) PARTITION BY HASH (thread_id);+ """)+ await conn.execute(create_runs_partitions_op())+ await conn.execute("""+ CREATE TABLE cubeloop_hitl_answers (+ thread_id TEXT NOT NULL REFERENCES cubeloop_threads(thread_id)+ ON DELETE CASCADE,+ run_id TEXT NOT NULL,+ question_id TEXT NOT NULL,+ answer JSONB NOT NULL,+ answered_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (thread_id, run_id, question_id)+ );+ """)+ await conn.execute(write_schema_version_op())finally:await conn.close()@@ -116,7 +137,7 @@ def transcript(messages) -> list[str]:async def main() -> None:# Throwaway DB so the example is safe to re-run.- db_name = f"cubepi_example_{secrets.token_hex(5)}"+ db_name = f"cubeloop_example_{secrets.token_hex(5)}"admin = await asyncpg.connect(ADMIN_DSN)try:await admin.execute(f'CREATE DATABASE "{db_name}"')diff --git a/examples/multi_provider_failover.py b/examples/multi_provider_failover.pyindex bcc3648..d7db833 100644--- a/examples/multi_provider_failover.py+++ b/examples/multi_provider_failover.py@@ -15,17 +15,17 @@ from __future__ import annotationsimport asyncioimport os-from cubepi import Agent, FallbackBoundModel-from cubepi.errors import (+from cubeloop import Agent, FallbackBoundModel+from cubeloop.errors import (ContextLengthExceeded,ProviderAuthFailed,ProviderBadRequest,ProviderUnavailable,RateLimited,)-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.base import BoundModel-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.base import BoundModel+from cubeloop.providers.openai import OpenAIProviderfrom _provider import MODEL_ID, providerdiff --git a/examples/persistent_chat.py b/examples/persistent_chat.pyindex d8bea88..7844a19 100644--- a/examples/persistent_chat.py+++ b/examples/persistent_chat.py@@ -19,8 +19,8 @@ Set ANTHROPIC_API_KEY or OPENAI_API_KEY before running (see _provider.py).import asyncioimport sys-from cubepi import Agent-from cubepi.checkpointer import SQLiteCheckpointer+from cubeloop import Agent+from cubeloop.checkpointer import SQLiteCheckpointerfrom _provider import MODEL_ID, providerdiff --git a/examples/postgres_fastapi.py b/examples/postgres_fastapi.pyindex 6c21150..2447851 100644--- a/examples/postgres_fastapi.py+++ b/examples/postgres_fastapi.py@@ -27,8 +27,8 @@ from fastapi import FastAPI, Dependsfrom pydantic import BaseModelfrom sse_starlette.sse import EventSourceResponse-from cubepi import Agent-from cubepi.checkpointer import PostgresCheckpointer+from cubeloop import Agent+from cubeloop.checkpointer import PostgresCheckpointer# Works both when run as a script (python examples/postgres_fastapi.py) and# when loaded as a package by uvicorn (uvicorn examples.postgres_fastapi:app).diff --git a/examples/resumable_tasks.py b/examples/resumable_tasks.pyindex 3392d61..5795004 100644--- a/examples/resumable_tasks.py+++ b/examples/resumable_tasks.py@@ -20,8 +20,8 @@ import osimport sysfrom pathlib import Path-from cubepi import Agent, AgentToolResult, TextContent, tool-from cubepi.checkpointer import SQLiteCheckpointer+from cubeloop import Agent, AgentToolResult, TextContent, tool+from cubeloop.checkpointer import SQLiteCheckpointerfrom _provider import MODEL_ID, provider@@ -89,7 +89,7 @@ async def main(thread_id: str, start: bool) -> None:last_type = type(last).__name__ if last else "none"print(f"Resuming thread {thread_id!r} ({len(agent.state.messages)} messages, last={last_type})")if last_type == "AssistantMessage":- from cubepi.providers.base import ToolCall+ from cubeloop.providers.base import ToolCallhas_pending_tools = any(isinstance(c, ToolCall) for c in last.content)if not has_pending_tools:# Run completed normally — no pending tool calls to execute.diff --git a/examples/sandbox_confirm.py b/examples/sandbox_confirm.pyindex 483bf41..8a81fab 100644--- a/examples/sandbox_confirm.py+++ b/examples/sandbox_confirm.py@@ -12,8 +12,8 @@ Set ANTHROPIC_API_KEY or OPENAI_API_KEY before running (see _provider.py).import asynciofrom pydantic import BaseModel-from cubepi import Agent, AgentToolResult, TextContent, tool-from cubepi.hitl import (+from cubeloop import Agent, AgentToolResult, TextContent, tool+from cubeloop.hitl import (Approve,AskUser,Deny,diff --git a/examples/weather_agent.py b/examples/weather_agent.pyindex 78207e1..4438d01 100644--- a/examples/weather_agent.py+++ b/examples/weather_agent.py@@ -15,7 +15,7 @@ from typing import Annotatedimport httpxfrom pydantic import Field-from cubepi import Agent, AgentToolResult, TextContent, tool+from cubeloop import Agent, AgentToolResult, TextContent, toolfrom _provider import MODEL_ID, providerdiff --git a/pyproject.toml b/pyproject.tomlindex fd02703..f4d1a01 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -1,6 +1,6 @@[project]-name = "cubepi"-version = "0.13.6"+name = "cubeloop"+version = "0.14.0"description = "Pythonic async-native agent framework"readme = "README.md"license = "MIT"@@ -22,11 +22,11 @@ dependencies = [][project.urls]-Homepage = "https://cubepi.ai"-Documentation = "https://cubepi.ai/docs"-Repository = "https://github.com/cubeplexai/cubepi"-Changelog = "https://cubepi.ai/changelog"-Issues = "https://github.com/cubeplexai/cubepi/issues"+Homepage = "https://cubeloop.dev"+Documentation = "https://cubeloop.dev/docs"+Repository = "https://github.com/cubeplexai/cubeloop"+Changelog = "https://cubeloop.dev/changelog"+Issues = "https://github.com/cubeplexai/cubeloop/issues"[project.optional-dependencies]sqlite = [@@ -62,7 +62,7 @@ trace-cli = [][project.scripts]-cubepi = "cubepi.cli.__main__:main"+cubeloop = "cubeloop.cli.__main__:main"[dependency-groups]dev = [@@ -78,15 +78,19 @@ dev = ["ruff>=0.15.12","sqlalchemy>=2.0","mypy>=2.1.0",+ "cubepi",]+[tool.uv.sources]+cubepi = { workspace = true }+[tool.pytest.ini_options]asyncio_mode = "auto"testpaths = ["tests", "website/scripts/tests"][tool.mypy]python_version = "3.11"-files = ["cubepi"]+files = ["cubeloop"]ignore_missing_imports = truewarn_redundant_casts = truewarn_unused_ignores = true@@ -96,4 +100,7 @@ requires = ["hatchling"]build-backend = "hatchling.build"[tool.hatch.build.targets.wheel]-packages = ["cubepi"]+packages = ["cubeloop"]++[tool.uv.workspace]+members = ["compat/cubepi"]diff --git a/skills/cubepi-trace/SKILL.md b/skills/cubeloop-trace/SKILL.mdsimilarity index 75%rename from skills/cubepi-trace/SKILL.mdrename to skills/cubeloop-trace/SKILL.mdindex 61d47f3..9fc5b7a 100644--- a/skills/cubepi-trace/SKILL.md+++ b/skills/cubeloop-trace/SKILL.md@@ -1,12 +1,12 @@----name: cubepi-trace-description: Use when debugging a cubepi/cubebox agent run — a missing final reply, a tool that misbehaved, a 4xx from the model, wrong token/cache numbers, or "why did the agent do that?". Reads the JSONL traces cubepi writes per run via the `cubepi trace` CLI (ls / view / follow / stats) to inspect the span tree, errors, tool inputs/outputs, and token usage. Triggers on phrases like "查一下这个 run", "trace 一下", "为什么最后一轮没回复", "工具结果不对", "看 trace".+name: cubeloop-trace+description: Use when debugging a cubeloop/cubebox agent run — a missing final reply, a tool that misbehaved, a 4xx from the model, wrong token/cache numbers, or "why did the agent do that?". Reads the JSONL traces cubeloop writes per run via the `cubeloop trace` CLI (ls / view / follow / stats) to inspect the span tree, errors, tool inputs/outputs, and token usage. Triggers on phrases like "查一下这个 run", "trace 一下", "为什么最后一轮没回复", "工具结果不对", "看 trace".----# Debugging cubepi runs with `cubepi trace`+# Debugging CubeLoop runs with `cubeloop trace`-cubepi can record every agent run as an OpenTelemetry span tree, written to-local JSONL files. The `cubepi trace` CLI reads those files so you can see+cubeloop can record every agent run as an OpenTelemetry span tree, written to+local JSONL files. The `cubeloop trace` CLI reads those files so you can seeexactly what happened inside a run without re-running it: which LLM calls andtool calls fired, in what order, what each returned, where it errored, and thetoken/cache counts. Reach for this **before** guessing at a bug.@@ -30,7 +30,7 @@ Tracing must be **on** and **recording content** for the run you want toinspect. In cubebox it's config-driven (dynaconf):- `tracing.enabled: true`-- `tracing.directory: ./cubepi-traces` (default; relative to the backend cwd)+- `tracing.directory: ./cubeloop-traces` (default; relative to the backend cwd)- `tracing.record_content: true` (needed to see prompts / tool args / results;off = you get the span tree and timings but no content)@@ -40,17 +40,17 @@ cubebox's `config.development` already enables this. Files land at`<directory>/<YYYY-MM-DD>/<trace_id>.jsonl` — sharded by `trace_id`, so onefile holds the whole trace, including any nested subagent runs (they inheritthe parent's trace). A trace that crosses UTC midnight is split across two date-dirs; the CLI merges them. (`cubepi.run_id` is still recorded as a per-span+dirs; the CLI merges them. (`cubeloop.run_id` is still recorded as a per-spanattribute if you need to distinguish individual runs within a trace.)Run the CLI from the cubebox backend dir so it picks up the venv that has-cubepi installed (the `trace-cli` extra provides it):+cubeloop installed (the `trace-cli` extra provides it):```bash-uv run cubepi trace --help+uv run cubeloop trace --help```-`--dir` defaults to `./cubepi-traces`; pass `--dir <path>` if your traces live+`--dir` defaults to `./cubeloop-traces`; pass `--dir <path>` if your traces liveelsewhere (e.g. a worktree).## The fast path (this is 90% of debugging)@@ -59,11 +59,11 @@ elsewhere (e.g. a worktree).# 1. List recent traces, newest first. The `trace_id` column is the id you# pass to `view`; the `input` column shows the user's message so you can# find the right one; `status` flags errors.-uv run cubepi trace ls+uv run cubeloop trace ls# 2. View one trace as a span tree. A trace id PREFIX is enough (ls truncates# ids). Errors are printed inline under the failing span — no flags needed.-uv run cubepi trace view 1cd97cdb+uv run cubeloop trace view 1cd97cdb````view` output looks like (each node ends with a short `span_id` for locating@@ -72,23 +72,23 @@ the raw span in the JSONL):```trace└── invoke_agent 14425.8ms [0x1cd97cdb]- ├── cubepi.turn 1283.1ms [0x5cfda93e]+ ├── cubeloop.turn 1283.1ms [0x5cfda93e]│ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]│ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]│ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested- │ └── cubepi.turn 9598.4ms [0x57c5cfc7]+ │ └── cubeloop.turn 9598.4ms [0x57c5cfc7]│ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]│ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]- └── cubepi.turn 491.9ms ERROR [0xce25f242]+ └── cubeloop.turn 491.9ms ERROR [0xce25f242]└── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]└── error: Error code: 400 - ... `tool_use` ids were found without`tool_result` blocks immediately after: call_01_...```-Read the tree top-down: `invoke_agent` (one run) → `cubepi.turn` (one agent+Read the tree top-down: `invoke_agent` (one run) → `cubeloop.turn` (one agentloop turn) → `chat <model>` (an LLM call, with `tok <input>/<output>`) and`execute_tool <name>` (a tool call). A **subagent** appears as-`execute_tool subagent` with the subagent's own `invoke_agent → cubepi.turn →+`execute_tool subagent` with the subagent's own `invoke_agent → cubeloop.turn →…` nested directly beneath it — its chat and tool spans live inside thatsubtree, not flat under the parent turn. The `[0x…]` suffix is the span_id(grep it in the raw JSONL to inspect that exact span). An `ERROR` marker plus@@ -99,35 +99,35 @@ the inline `error:` line usually tells you the root cause directly.```bash# Expand the actual gen_ai content (prompts, tool args, tool results) —# useful when the error isn't enough and you need to see what was sent.-uv run cubepi trace view <run> --content+uv run cubeloop trace view <run> --content# Expand ALL span attributes (verbose; includes full request bodies/tool# schemas — large). Use when --content isn't enough.-uv run cubepi trace view <run> -v+uv run cubeloop trace view <run> -v# Watch a run live as spans complete (poll). Good for a run in progress.-uv run cubepi trace follow <run>+uv run cubeloop trace follow <run># Aggregate across runs: latency p50/p95, error rate, tokens — by model or tool.-uv run cubepi trace stats --by model-uv run cubepi trace stats --by tool --since 2026-05-20+uv run cubeloop trace stats --by model+uv run cubeloop trace stats --by tool --since 2026-05-20# Filter by run metadata (cubebox stamps conversation_id / user_id / org_id /# workspace_id on the root span). Repeatable = AND, exact match. Works on# `ls` and `stats` — find all traces for a conversation, or that user's stats.-uv run cubepi trace ls --meta conversation_id=conv_123-uv run cubepi trace ls --meta user_id=usr_9 --meta org_id=org_1-uv run cubepi trace stats --by model --meta user_id=usr_9+uv run cubeloop trace ls --meta conversation_id=conv_123+uv run cubeloop trace ls --meta user_id=usr_9 --meta org_id=org_1+uv run cubeloop trace stats --by model --meta user_id=usr_9# Show metadata as ls columns (display, not filter):-uv run cubepi trace ls --show-meta conversation_id,user_id+uv run cubeloop trace ls --show-meta conversation_id,user_id```## Tracing one-shot LLM calls (`Tracer.oneshot`)`Tracer.oneshot()` instruments a single prompt→text LLM call (no agent loop)and writes it as a full `invoke_agent` trace. Cubebox uses this for background-tasks like memory consolidation. The span tree is flat — no `cubepi.turn`+tasks like memory consolidation. The span tree is flat — no `cubeloop.turn`wrapper since there's no loop:```@@ -137,21 +137,21 @@ trace```The root span carries:-- `cubepi.oneshot.operation` — the operation name (e.g. `"consolidate_memory"`)-- `cubepi.metadata.*` — caller-supplied metadata (e.g. `conversation_id`)+- `cubeloop.oneshot.operation` — the operation name (e.g. `"consolidate_memory"`)+- `cubeloop.metadata.*` — caller-supplied metadata (e.g. `conversation_id`)Find oneshot traces by operation or conversation:```bash-# All consolidation runs (operation is exposed as cubepi.metadata.oneshot_operation-# so the --meta filter can reach it; cubepi.oneshot.operation is also set for dashboards)-uv run cubepi trace ls --meta oneshot_operation=consolidate_memory+# All consolidation runs (operation is exposed as cubeloop.metadata.oneshot_operation+# so the --meta filter can reach it; cubeloop.oneshot.operation is also set for dashboards)+uv run cubeloop trace ls --meta oneshot_operation=consolidate_memory# Oneshot traces for a specific conversation (alongside its agent runs)-uv run cubepi trace ls --meta conversation_id=conv-1fwZQ8u3ZDukx3+uv run cubeloop trace ls --meta conversation_id=conv-1fwZQ8u3ZDukx3# Stats on consolidation token usage-uv run cubepi trace stats --by model --meta oneshot_operation=consolidate_memory+uv run cubeloop trace stats --by model --meta oneshot_operation=consolidate_memory```Cubebox wires this in `run_manager.py`; the consolidation pass calls:@@ -179,16 +179,16 @@ reconstruct the request body from a recorded `chat` span (requires```bash# Reconstruct the last LLM call as an OpenAI JSON body-uv run cubepi trace convert <run_id>+uv run cubeloop trace convert <run_id># Pick a specific call by span_id prefix (copy [0x…] from `view`)-uv run cubepi trace convert <run_id> --span 0xbb7eb1+uv run cubeloop trace convert <run_id> --span 0xbb7eb1# Shell-executable curl (uses $BASE_URL / $API_KEY env vars)-uv run cubepi trace convert <run_id> --span 0xbb7eb1 --format curl+uv run cubeloop trace convert <run_id> --span 0xbb7eb1 --format curl# Anthropic Messages API shape-uv run cubepi trace convert <run_id> --format anthropic+uv run cubeloop trace convert <run_id> --format anthropic```The `[0x…]` suffix from each `chat` node in `view` output is the span_id — paste@@ -201,7 +201,7 @@ arguments, duplicate tool executions, truncated output — enable stream recordiin the tracer:```python-Tracer(record_content=True, record_stream=True, stream_dir="./cubepi-traces", …)+Tracer(record_content=True, record_stream=True, stream_dir="./cubeloop-traces", …)```This writes `<stream_dir>/<run_id>.stream.jsonl` — one JSON line per raw@@ -209,10 +209,10 @@ This writes `<stream_dir>/<run_id>.stream.jsonl` — one JSON line per raw```bash# See all toolcall events for a run-grep '"type": "toolcall' cubepi-traces/<date>/<run_id>.stream.jsonl | python -m json.tool+grep '"type": "toolcall' cubeloop-traces/<date>/<run_id>.stream.jsonl | python -m json.tool# Check for duplicate toolcall_end (double finish_reason bug pattern):-grep '"toolcall_end"' cubepi-traces/<date>/<run_id>.stream.jsonl | wc -l # expect 1+grep '"toolcall_end"' cubeloop-traces/<date>/<run_id>.stream.jsonl | wc -l # expect 1```Key fields: `t` (elapsed seconds), `type`, `ci` (content index), `accumulated`@@ -257,7 +257,7 @@ Mind the convention — it differs between the trace and cubebox's UI:- **Find the trace** by the `input` column in `ls` rather than guessing ids.- **Subagent missing from the tree?** It should nest under`execute_tool subagent`. If a subagent's spans look absent, confirm the run- was recorded with a cubepi new enough to shard by `trace_id` (older runs+ was recorded with a cubeloop new enough to shard by `trace_id` (older runssharded by `run_id`, so a subagent's spans landed in a separate file).- **Backend vs frontend**: the trace shows what the backend/agent did. If thetrace shows correct data but the UI is wrong, the bug is in the frontend@@ -265,6 +265,6 @@ Mind the convention — it differs between the trace and cubebox's UI:## Source and contributing-Skill source and cubepi source: https://github.com/cubeplexai/cubepi+Skill source and CubeLoop source: https://github.com/cubeplexai/cubeloopIf the docs or skill are unclear, read the source — it's the authoritative reference.-Bugs or missing coverage: open an issue or PR at https://github.com/cubeplexai/cubepi/issues+Bugs or missing coverage: open an issue or PR at https://github.com/cubeplexai/cubeloop/issuesdiff --git a/skills/cubepi/SKILL.md b/skills/cubeloop/SKILL.mdsimilarity index 68%rename from skills/cubepi/SKILL.mdrename to skills/cubeloop/SKILL.mdindex f9f8091..fcf3130 100644--- a/skills/cubepi/SKILL.md+++ b/skills/cubeloop/SKILL.md@@ -1,17 +1,17 @@----name: cubepi-description: Use when building, extending, or debugging agents with the CubePi framework. Covers the Agent API, providers, tools, middleware, checkpointing, MCP integration, and HITL. References the cubepi-trace skill for run debugging.+name: cubeloop+description: Use when building, extending, or debugging agents with the CubeLoop framework. Covers the Agent API, providers, tools, middleware, checkpointing, MCP integration, and HITL. References the cubeloop-trace skill for run debugging.----# Building agents with CubePi+# Building agents with CubeLoop-CubePi is a Pythonic, async-native agent framework. The agent loop is a plain+CubeLoop is a Pythonic, async-native agent framework. The agent loop is a plain`while` loop — no graph nodes, no state machines. You can read the full runtimein a few minutes.-**Docs:** https://cubepi.ai/docs-**Source:** https://github.com/cubeplexai/cubepi-**Issues / PRs:** https://github.com/cubeplexai/cubepi/issues+**Docs:** https://cubeloop.dev/docs+**Source:** https://github.com/cubeplexai/cubeloop+**Issues / PRs:** https://github.com/cubeplexai/cubeloop/issuesIf anything in the docs is unclear or missing, read the source directly — thecode is the authoritative reference. If you hit a bug or find a gap, open an@@ -20,11 +20,11 @@ issue or PR on the repo.## Install```bash-pip install cubepi # core-pip install cubepi[mcp] # MCP tool loaders-pip install cubepi[tracing,trace-cli] # OpenTelemetry + cubepi trace CLI-pip install cubepi[sqlite] # SQLite checkpointer-pip install cubepi[postgres] # Postgres checkpointer+pip install cubeloop # core+pip install cubeloop[mcp] # MCP tool loaders+pip install cubeloop[tracing,trace-cli] # OpenTelemetry + cubeloop trace CLI+pip install cubeloop[sqlite] # SQLite checkpointer+pip install cubeloop[postgres] # Postgres checkpointer```## Core concepts@@ -32,9 +32,9 @@ pip install cubepi[postgres] # Postgres checkpointer### Agent + Provider + Model```python-from cubepi import Agent, AgentTool, Model-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.openai import OpenAIProvider+from cubeloop import Agent, AgentTool, Model+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.openai import OpenAIProviderprovider = AnthropicProvider(provider_id="anthropic") # or OpenAIProvider(provider_id="openai")model = Model(id="claude-opus-4-5-20251001")@@ -48,8 +48,8 @@ await agent.wait_for_idle()```pythonfrom pydantic import BaseModel-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import TextContent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import TextContentclass SearchInput(BaseModel):query: str@@ -62,7 +62,7 @@ tool = AgentTool(name="search", description="Search the web", parameters=SearchIagent = Agent(..., tools=[tool])```-Full tool docs: https://cubepi.ai/docs/guides/tools+Full tool docs: https://cubeloop.dev/docs/guides/tools### Streaming responses@@ -74,7 +74,7 @@ async for event in agent.stream("What is 2+2?"):Event types: `text_delta`, `thinking_delta`, `toolcall_start`, `toolcall_delta`,`toolcall_end`, `message_start`, `message_end`. Full reference:-https://cubepi.ai/docs/guides/streaming+https://cubeloop.dev/docs/guides/streaming### Middleware@@ -82,7 +82,7 @@ Eight typed hooks. Subclass `Middleware`, override the hooks you need, pass instto `Agent(middleware=[...])`:```python-from cubepi import Middleware+from cubeloop import Middlewareclass MyMiddleware(Middleware):async def transform_context(self, messages, *, ctx, signal=None):@@ -120,12 +120,12 @@ agent = Agent(..., middleware=[MyMiddleware()])| `should_stop_after_turn` | Each turn boundary | Any True stops || `on_run_end` | Once after all turns, before agent_end | Messages concatenate |-Full docs: https://cubepi.ai/docs/guides/middleware+Full docs: https://cubeloop.dev/docs/guides/middleware### Checkpointing```python-from cubepi.checkpointer.sqlite import SqliteCheckpointer+from cubeloop.checkpointer.sqlite import SqliteCheckpointercheckpointer = await SqliteCheckpointer.create("./state.db")agent = Agent(..., checkpointer=checkpointer)@@ -135,42 +135,42 @@ await agent.resume(conversation_id="conv_123")await agent.prompt("Continue from where we left off")```-Full docs: https://cubepi.ai/docs/guides/checkpointing+Full docs: https://cubeloop.dev/docs/guides/checkpointing### MCP tools```python-from cubepi.mcp import MCPToolLoader+from cubeloop.mcp import MCPToolLoaderloader = MCPToolLoader(server_url="http://localhost:8080")tools = await loader.load()agent = Agent(..., tools=tools)```-Full docs: https://cubepi.ai/docs/guides/mcp+Full docs: https://cubeloop.dev/docs/guides/mcp### Human-in-the-loop (HITL)Use `before_tool_call` middleware to intercept and approve tool calls, or usethe built-in `ApprovalPolicyMiddleware` for policy-driven approval:-Full docs: https://cubepi.ai/docs/guides/hitl+Full docs: https://cubeloop.dev/docs/guides/hitl## Debugging runs-Install the `cubepi-trace` skill — it gives you the full protocol for+Install the `cubeloop-trace` skill — it gives you the full protocol forinspecting recorded OTel spans without re-running the agent:```bash-npx skills add cubeplexai/cubepi@cubepi-trace -a claude-code+npx skills add cubeplexai/cubeloop@cubeloop-trace -a claude-code```-The skill covers `cubepi trace ls / view / follow / stats / convert`, token+The skill covers `cubeloop trace ls / view / follow / stats / convert`, tokenand cache-rate conventions, and streaming failure debugging.## Getting help-- **Docs:** https://cubepi.ai/docs-- **Source:** https://github.com/cubeplexai/cubepi (read it — it's short)-- **Issues:** https://github.com/cubeplexai/cubepi/issues+- **Docs:** https://cubeloop.dev/docs+- **Source:** https://github.com/cubeplexai/cubeloop (read it — it's short)+- **Issues:** https://github.com/cubeplexai/cubeloop/issues- **PRs welcome** for bugs, missing docs, or new provider supportdiff --git a/tests/agent/test_agent.py b/tests/agent/test_agent.pyindex cecec14..4e407aa 100644--- a/tests/agent/test_agent.py+++ b/tests/agent/test_agent.py@@ -2,17 +2,17 @@ import asyncioimport pytest-from cubepi.agent.agent import Agent, _MessageQueue-from cubepi.agent.types import AgentTool-from cubepi.middleware.base import Middleware-from cubepi.providers.base import (+from cubeloop.agent.agent import Agent, _MessageQueue+from cubeloop.agent.types import AgentTool+from cubeloop.middleware.base import Middleware+from cubeloop.providers.base import (AssistantMessage,Model,ReasoningControl,TextContent,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.faux import FauxProvider, faux_assistant_messagefrom pydantic import BaseModel@@ -235,7 +235,7 @@ class TestAgentPromptGuards:provider = FauxProvider(provider_id="faux")async def slow_stream(*args, **kwargs):- from cubepi.providers.base import MessageStream, StreamEvent+ from cubeloop.providers.base import MessageStream, StreamEventms = MessageStream()@@ -269,7 +269,7 @@ class TestAgentPromptGuards:provider = FauxProvider(provider_id="faux")async def slow_stream(*args, **kwargs):- from cubepi.providers.base import MessageStream, StreamEvent+ from cubeloop.providers.base import MessageStream, StreamEventms = MessageStream()@@ -447,7 +447,7 @@ class TestAgentAbortSignal:provider = FauxProvider(provider_id="faux")async def slow_stream(*args, **kwargs):- from cubepi.providers.base import MessageStream, StreamEvent+ from cubeloop.providers.base import MessageStream, StreamEventms = MessageStream()@@ -489,7 +489,7 @@ class TestAgentWaitForIdle:provider = FauxProvider(provider_id="faux")async def slow_stream(*args, **kwargs):- from cubepi.providers.base import MessageStream, StreamEvent+ from cubeloop.providers.base import MessageStream, StreamEventms = MessageStream()diff --git a/tests/agent/test_agent_claim_run.py b/tests/agent/test_agent_claim_run.pyindex e99080b..f40fc1c 100644--- a/tests/agent/test_agent_claim_run.py+++ b/tests/agent/test_agent_claim_run.py@@ -2,14 +2,14 @@ import asyncioimport pytest-from cubepi.agent.agent import Agent-from cubepi.checkpointer.exceptions import (+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,)-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import FauxProviderdef _ok_faux() -> FauxProvider:@@ -93,7 +93,7 @@ async def test_resume_claims_run_and_stamps_messages():treat NULL as legacy / always-copy) would copy them into forks evenif the resumed work is still in flight or later abandoned."""- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.base import TextContent, UserMessagecp = MemoryCheckpointer()a = _agent(checkpointer=cp, thread_id="t")@@ -122,7 +122,7 @@ async def test_resume_claims_run_and_stamps_messages():@pytest.mark.asyncioasync def test_resume_auto_generates_run_id_when_not_supplied():"""resume() without an explicit run_id auto-generates one."""- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.base import TextContent, UserMessagecp = MemoryCheckpointer()a = _agent(checkpointer=cp, thread_id="t")@@ -141,7 +141,7 @@ async def test_resume_precondition_failure_does_not_claim():must NOT call claim_run — otherwise a dangling claimed run wouldblock re-resume with the same run_id."""- from cubepi.providers.base import AssistantMessage, TextContent+ from cubeloop.providers.base import AssistantMessage, TextContentcp = MemoryCheckpointer()a = _agent(checkpointer=cp, thread_id="t")diff --git a/tests/agent/test_agent_completion.py b/tests/agent/test_agent_completion.pyindex 8919555..09f1ba2 100644--- a/tests/agent/test_agent_completion.py+++ b/tests/agent/test_agent_completion.py@@ -14,18 +14,18 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.checkpointer.exceptions import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.checkpointer.exceptions import (CompletionMarkerFailedError,RunNotClaimedError,)-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import AskUser-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import (+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import AskUser+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_text,diff --git a/tests/agent/test_agent_fork.py b/tests/agent/test_agent_fork.pyindex 23ff2ca..fef9636 100644--- a/tests/agent/test_agent_fork.py+++ b/tests/agent/test_agent_fork.py@@ -1,9 +1,9 @@import pytest-from cubepi.agent.agent import Agent-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import FauxProviderdef _ok_faux() -> FauxProvider:@@ -54,7 +54,7 @@ async def test_agent_fork_v3_only_checkpointer_raises_CheckpointerError():'degraded mode': vanilla prompt() works but fork() must surfaceCheckpointerError so callers know the backend cannot support fork."""- from cubepi.checkpointer.exceptions import CheckpointerError+ from cubeloop.checkpointer.exceptions import CheckpointerErrorclass _V3Only:async def load(self, thread_id):diff --git a/tests/agent/test_agent_fork_once.py b/tests/agent/test_agent_fork_once.pyindex c496e71..68865c0 100644--- a/tests/agent/test_agent_fork_once.py+++ b/tests/agent/test_agent_fork_once.py@@ -3,14 +3,14 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, ForkOnceResult-from cubepi.checkpointer.exceptions import CheckpointerError-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl.binding import HitlBinding-from cubepi.middleware.base import Middleware-from cubepi.providers.base import AssistantMessage, ReasoningControl, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, ForkOnceResult+from cubeloop.checkpointer.exceptions import CheckpointerError+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.binding import HitlBinding+from cubeloop.middleware.base import Middleware+from cubeloop.providers.base import AssistantMessage, ReasoningControl, TextContent+from cubeloop.providers.faux import FauxProviderdef _ok_faux() -> FauxProvider:diff --git a/tests/agent/test_agent_messages_kw.py b/tests/agent/test_agent_messages_kw.pyindex cc3c56b..30d731e 100644--- a/tests/agent/test_agent_messages_kw.py+++ b/tests/agent/test_agent_messages_kw.py@@ -1,14 +1,14 @@import pytest-from cubepi.agent.agent import Agent-from cubepi.providers.base import (+from cubeloop.agent.agent import Agent+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,ToolResultMessage,UserMessage,)-from cubepi.providers.faux import FauxProvider+from cubeloop.providers.faux import FauxProviderdef _agent(**kw):@@ -27,7 +27,7 @@ def test_messages_kw_seeds_initial_history():def test_messages_kw_conflicts_with_thread_id_checkpointer():- from cubepi.checkpointer.memory import MemoryCheckpointer+ from cubeloop.checkpointer.memory import MemoryCheckpointermsgs = [UserMessage(content=[TextContent(text="hi")])]with pytest.raises(ValueError):diff --git a/tests/agent/test_agent_run_id.py b/tests/agent/test_agent_run_id.pyindex e70a2f9..8008576 100644--- a/tests/agent/test_agent_run_id.py+++ b/tests/agent/test_agent_run_id.py@@ -1,8 +1,8 @@import pytest-from cubepi.agent.agent import Agent-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.agent.agent import Agent+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import FauxProviderdef _ok_faux() -> FauxProvider:@@ -56,7 +56,7 @@ async def test_prompt_leaves_active_run_id_set_on_raise(monkeypatch):@pytest.mark.asyncioasync def test_appended_messages_carry_run_id():- from cubepi.checkpointer.memory import MemoryCheckpointer+ from cubeloop.checkpointer.memory import MemoryCheckpointercp = MemoryCheckpointer()a = Agent(@@ -74,10 +74,10 @@ async def test_appended_messages_carry_run_id():async def test_live_tool_results_carry_owning_run_id():from pydantic import BaseModel- from cubepi.agent.types import AgentTool, AgentToolResult- from cubepi.checkpointer.memory import MemoryCheckpointer- from cubepi.providers.base import ToolResultMessage- from cubepi.providers.faux import faux_assistant_message, faux_tool_call+ from cubeloop.agent.types import AgentTool, AgentToolResult+ from cubeloop.checkpointer.memory import MemoryCheckpointer+ from cubeloop.providers.base import ToolResultMessage+ from cubeloop.providers.faux import faux_assistant_message, faux_tool_callclass EchoParams(BaseModel):value: str@@ -179,8 +179,8 @@ async def test_prompt_rejects_mismatched_run_id_before_claim():"""Caller pre-stamps a Message with a different run_id than theone supplied to prompt(). Reject BEFORE claim_run so no row iswritten and the run_id is still reusable."""- from cubepi.checkpointer.memory import MemoryCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.memory import MemoryCheckpointer+ from cubeloop.providers.base import TextContent, UserMessagecp = MemoryCheckpointer()a = Agent(@@ -207,8 +207,8 @@ async def test_process_event_rejects_mismatched_message_run_id():message already carries a DIFFERENT run_id (defensive — a provideror middleware bug that produced the wrong stamp must not silentlywrite to the persisted history)."""- from cubepi.agent.types import MessageEndEvent- from cubepi.providers.base import (+ from cubeloop.agent.types import MessageEndEvent+ from cubeloop.providers.base import (AssistantMessage,TextContent,)diff --git a/tests/agent/test_agent_state.py b/tests/agent/test_agent_state.pyindex e9f9ee3..c80e66f 100644--- a/tests/agent/test_agent_state.py+++ b/tests/agent/test_agent_state.py@@ -1,4 +1,4 @@-from cubepi.agent.agent import AgentState+from cubeloop.agent.agent import AgentStatedef test_agent_state_default_active_run_id_none():diff --git a/tests/agent/test_checkpointer_integration.py b/tests/agent/test_checkpointer_integration.pyindex 55f120b..c4a81e4 100644--- a/tests/agent/test_checkpointer_integration.py+++ b/tests/agent/test_checkpointer_integration.py@@ -3,10 +3,10 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.providers.base import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.providers.base import (AssistantMessage,Model,TextContent,@@ -14,7 +14,7 @@ from cubepi.providers.base import (ToolResultMessage,UserMessage,)-from cubepi.providers.faux import (+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_tool_call,diff --git a/tests/agent/test_context_extra.py b/tests/agent/test_context_extra.pyindex bbd5c4c..7fd9c60 100644--- a/tests/agent/test_context_extra.py+++ b/tests/agent/test_context_extra.py@@ -5,7 +5,7 @@ from pathlib import Pathimport pytest-from cubepi.agent.types import AgentContext+from cubeloop.agent.types import AgentContextdef test_agent_context_default_extra_is_empty_dict() -> None:@@ -38,7 +38,7 @@ def test_extra_independent_between_instances() -> None:@pytest.mark.asyncioasync def test_save_extra_round_trip_via_checkpointer() -> None:"""save_extra + load round-trip works (sanity check for the checkpointer)."""- from cubepi.checkpointer import SQLiteCheckpointer+ from cubeloop.checkpointer import SQLiteCheckpointerwith tempfile.TemporaryDirectory() as d:path = Path(d) / "extra.db"@@ -53,9 +53,9 @@ async def test_save_extra_round_trip_via_checkpointer() -> None:async def test_agent_hydrates_ctx_extra_from_checkpointer() -> None:"""When agent loads a thread with pre-existing extra, the extra is preservedthrough the turn and written back via save_extra."""- from cubepi.agent.agent import Agent- from cubepi.checkpointer import SQLiteCheckpointer- from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.agent.agent import Agent+ from cubeloop.checkpointer import SQLiteCheckpointer+ from cubeloop.providers.faux import FauxProvider, faux_assistant_messagewith tempfile.TemporaryDirectory() as d:path = Path(d) / "hydrate.db"@@ -82,9 +82,9 @@ async def test_agent_hydrates_ctx_extra_from_checkpointer() -> None:async def test_agent_persists_ctx_extra_mutation_after_turn() -> None:"""Pre-seeded extra is round-tripped: hydrated on load, persisted viasave_extra after the turn completes."""- from cubepi.agent.agent import Agent- from cubepi.checkpointer import SQLiteCheckpointer- from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.agent.agent import Agent+ from cubeloop.checkpointer import SQLiteCheckpointer+ from cubeloop.providers.faux import FauxProvider, faux_assistant_messagewith tempfile.TemporaryDirectory() as d:path = Path(d) / "persist.db"diff --git a/tests/agent/test_e2e.py b/tests/agent/test_e2e.pyindex 1ccd70e..7d7a714 100644--- a/tests/agent/test_e2e.py+++ b/tests/agent/test_e2e.py@@ -2,9 +2,9 @@ import asynciofrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import (AssistantMessage,Model,ReasoningControl,@@ -13,7 +13,7 @@ from cubepi.providers.base import (ToolResultMessage,UserMessage,)-from cubepi.providers.faux import (+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_text,diff --git a/tests/agent/test_fork_once_result.py b/tests/agent/test_fork_once_result.pyindex d753abf..20f0022 100644--- a/tests/agent/test_fork_once_result.py+++ b/tests/agent/test_fork_once_result.py@@ -1,6 +1,6 @@import pytest-from cubepi.agent.types import ForkOnceResult+from cubeloop.agent.types import ForkOnceResultdef test_fork_once_result_constructs_and_is_frozen():diff --git a/tests/agent/test_hitl_binding.py b/tests/agent/test_hitl_binding.pyindex 33a9786..7fc5d65 100644--- a/tests/agent/test_hitl_binding.py+++ b/tests/agent/test_hitl_binding.py@@ -1,6 +1,6 @@-from cubepi.agent.types import AgentTool-from cubepi.hitl.binding import HitlBinding-from cubepi.middleware.base import Middleware+from cubeloop.agent.types import AgentTool+from cubeloop.hitl.binding import HitlBinding+from cubeloop.middleware.base import Middlewarefrom pydantic import BaseModeldiff --git a/tests/agent/test_hitl_binding_enforcement.py b/tests/agent/test_hitl_binding_enforcement.pyindex d58ca28..461ba0d 100644--- a/tests/agent/test_hitl_binding_enforcement.py+++ b/tests/agent/test_hitl_binding_enforcement.py@@ -1,10 +1,10 @@import pytest-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool-from cubepi.hitl.binding import HitlBinding-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool+from cubeloop.hitl.binding import HitlBinding+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import FauxProviderfrom pydantic import BaseModeldiff --git a/tests/agent/test_loop.py b/tests/agent/test_loop.pyindex f0ac49c..528a360 100644--- a/tests/agent/test_loop.py+++ b/tests/agent/test_loop.py@@ -4,14 +4,14 @@ from typing import Anyfrom pydantic import BaseModel-from cubepi.agent.loop import run_agent_loop, run_agent_loop_continue-from cubepi.agent.types import (+from cubeloop.agent.loop import run_agent_loop, run_agent_loop_continue+from cubeloop.agent.types import (AgentContext,AgentEvent,AgentTool,AgentToolResult,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BoundModel,Message,@@ -24,7 +24,7 @@ from cubepi.providers.base import (Usage,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call+from cubeloop.providers.faux import FauxProvider, faux_assistant_message, faux_tool_calldef make_user_message(text: str) -> UserMessage:@@ -204,8 +204,8 @@ class TestAgentLoop:between the assistant tool_use and its tool_result — strictAnthropic-style endpoints 400 on tool_use without an immediatelyfollowing tool_result."""- from cubepi.middleware.base import TurnAction- from cubepi.providers.base import ToolCall+ from cubeloop.middleware.base import TurnAction+ from cubeloop.providers.base import ToolCalltool = make_echo_tool()provider = FauxProvider(provider_id="faux")@@ -760,7 +760,7 @@ class TestLoopHitlPartialResults:siblings' tool_results from the messages the stateless loop returns —callers persisting the return value would otherwise resume withdangling tool_calls and re-run side-effecting work."""- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedasync def detaching_execute(tool_call_id, params, *, signal=None, on_update=Nonediff --git a/tests/agent/test_resolve_tool_call.py b/tests/agent/test_resolve_tool_call.pyindex 5b66c62..5683099 100644--- a/tests/agent/test_resolve_tool_call.py+++ b/tests/agent/test_resolve_tool_call.py@@ -2,19 +2,19 @@ from __future__ import annotationsfrom pydantic import BaseModel, Field-from cubepi.agent.tools import execute_tool_calls-from cubepi.agent.types import (+from cubeloop.agent.tools import execute_tool_calls+from cubeloop.agent.types import (AgentContext,AgentTool,AgentToolResult,ToolExecutionStartEvent,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,)-from cubepi.providers.faux import faux_assistant_message+from cubeloop.providers.faux import faux_assistant_messageclass _EchoArgs(BaseModel):diff --git a/tests/agent/test_respond_resume_run_id.py b/tests/agent/test_respond_resume_run_id.pyindex 0e4e175..7300fba 100644--- a/tests/agent/test_respond_resume_run_id.py+++ b/tests/agent/test_respond_resume_run_id.py@@ -16,16 +16,16 @@ import asyncioimport pytest-from cubepi.agent.agent import Agent-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl.ask_user import ask_user_tool-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.providers.base import (+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.ask_user import ask_user_tool+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,)-from cubepi.providers.faux import FauxProvider+from cubeloop.providers.faux import FauxProviderdef _pause_then_finish_provider() -> FauxProvider:diff --git a/tests/agent/test_tool_cycle_invariant.py b/tests/agent/test_tool_cycle_invariant.pyindex e4209dd..721f8bf 100644--- a/tests/agent/test_tool_cycle_invariant.py+++ b/tests/agent/test_tool_cycle_invariant.py@@ -2,23 +2,23 @@ import asyncioimport pytest-from cubepi.agent._tool_cycle import (+from cubeloop.agent._tool_cycle import (ToolCycleViolation,check_tool_cycle,)-from cubepi.agent.agent import Agent-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl.ask_user import ask_user_tool-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.middleware.base import TurnAction-from cubepi.providers.base import (+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.ask_user import ask_user_tool+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.middleware.base import TurnAction+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,ToolResultMessage,UserMessage,)-from cubepi.providers.faux import FauxProvider+from cubeloop.providers.faux import FauxProviderdef _asst(call_ids, run_id="R"):diff --git a/tests/agent/test_tool_decorator.py b/tests/agent/test_tool_decorator.pyindex 649498f..f062e0b 100644--- a/tests/agent/test_tool_decorator.py+++ b/tests/agent/test_tool_decorator.py@@ -3,10 +3,10 @@ import asyncioimport pytestfrom pydantic import Field-from cubepi import AgentTool, AgentToolResult, TextContent, tool-from cubepi.agent.tools import execute_tool_calls-from cubepi.agent.types import AgentContext-from cubepi.providers.base import AssistantMessage, ToolCall+from cubeloop import AgentTool, AgentToolResult, TextContent, tool+from cubeloop.agent.tools import execute_tool_calls+from cubeloop.agent.types import AgentContext+from cubeloop.providers.base import AssistantMessage, ToolCalldef _ctx(tools: list[AgentTool]) -> AgentContext:diff --git a/tests/agent/test_tool_event_extension.py b/tests/agent/test_tool_event_extension.pyindex f177902..43e69de 100644--- a/tests/agent/test_tool_event_extension.py+++ b/tests/agent/test_tool_event_extension.py@@ -10,14 +10,14 @@ from __future__ import annotationsfrom pydantic import BaseModel-from cubepi.agent.tools import execute_tool_calls-from cubepi.agent.types import (+from cubeloop.agent.tools import execute_tool_calls+from cubeloop.agent.types import (AgentContext,AgentTool,AgentToolResult,BeforeToolCallResult,)-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCallclass Params(BaseModel):diff --git a/tests/agent/test_tools.py b/tests/agent/test_tools.pyindex 052d6f5..587cd62 100644--- a/tests/agent/test_tools.py+++ b/tests/agent/test_tools.py@@ -3,15 +3,15 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.tools import execute_tool_calls-from cubepi.agent.types import (+from cubeloop.agent.tools import execute_tool_calls+from cubeloop.agent.types import (AfterToolCallResult,AgentContext,AgentTool,AgentToolResult,BeforeToolCallResult,)-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCallclass EchoParams(BaseModel):@@ -803,7 +803,7 @@ class TestParallelFaultIsolation:)async def test_hitl_raise_preserves_and_persists_sibling_results(self):- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedside_effects = []@@ -1012,7 +1012,7 @@ class TestFaultIsolationEdgeCases:async def test_after_tool_call_hitl_propagates_with_siblings_persisted(self):"""_finalize must re-raise HITL control exceptions from the hook —they are a suspend, not a tool failure — after siblings persist."""- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedasync def after(after_ctx, *, signal=None):if after_ctx.tool_call.id == "t2":@@ -1036,7 +1036,7 @@ class TestFaultIsolationEdgeCases:"""Suspending after a sibling result failed to persist would durablyrecord a batch missing completed work — the persistence failure mustwin over the suspend."""- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedasync def hitl_raiser(tool_call_id, params, *, signal=None, on_update=None):raise HitlDetached()@@ -1092,7 +1092,7 @@ class TestFaultIsolationEdgeCases:async def test_sequential_hitl_carries_partial_results(self):"""The sequential executor attaches already-emitted results to anescaping HITL control exception too."""- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedasync def hitl_raiser(tool_call_id, params, *, signal=None, on_update=None):raise HitlDetached()diff --git a/tests/agent/test_types.py b/tests/agent/test_types.pyindex af75715..f224934 100644--- a/tests/agent/test_types.py+++ b/tests/agent/test_types.py@@ -1,6 +1,6 @@from pydantic import BaseModel-from cubepi.agent.types import (+from cubeloop.agent.types import (AgentContext,AgentEndEvent,AgentStartEvent,@@ -17,7 +17,7 @@ from cubepi.agent.types import (TurnEndEvent,TurnStartEvent,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,StreamEvent,TextContent,diff --git a/tests/checkpointer/conftest.py b/tests/checkpointer/conftest.pyindex da5692b..eff11d0 100644--- a/tests/checkpointer/conftest.py+++ b/tests/checkpointer/conftest.py@@ -13,8 +13,11 @@ import pytest_asynciodef pg_dsn() -> str:"""Postgres DSN for tests. Override via CUBEPI_TEST_PG_DSN env."""return os.environ.get(- "CUBEPI_TEST_PG_DSN",- "postgresql://postgres:postgres@localhost:5432/postgres",+ "CUBELOOP_TEST_PG_DSN",+ os.environ.get(+ "CUBEPI_TEST_PG_DSN",+ "postgresql://postgres:postgres@localhost:5432/postgres",+ ),)@@ -79,13 +82,16 @@ async def pg_v4_dsn(clean_db: str):def mysql_dsn() -> str:"""MySQL DSN for tests. Override via CUBEPI_TEST_MYSQL_DSN env."""return os.environ.get(- "CUBEPI_TEST_MYSQL_DSN",- "mysql://root:root@localhost:3306/mysql",+ "CUBELOOP_TEST_MYSQL_DSN",+ os.environ.get(+ "CUBEPI_TEST_MYSQL_DSN",+ "mysql://root:root@localhost:3306/mysql",+ ),)def _mysql_cfg(dsn: str) -> dict:- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsnreturn _parse_dsn(dsn)diff --git a/tests/checkpointer/test_base.py b/tests/checkpointer/test_base.pyindex 36d6bfe..c37127e 100644--- a/tests/checkpointer/test_base.py+++ b/tests/checkpointer/test_base.py@@ -1,4 +1,4 @@-from cubepi.checkpointer.base import CheckpointData+from cubeloop.checkpointer.base import CheckpointDatadef test_checkpoint_data_default_parent_is_none():diff --git a/tests/checkpointer/test_exceptions.py b/tests/checkpointer/test_exceptions.pyindex 6d2543a..a2836fa 100644--- a/tests/checkpointer/test_exceptions.py+++ b/tests/checkpointer/test_exceptions.py@@ -1,10 +1,10 @@import pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (CheckpointerError,CheckpointerLockTimeoutError,CompletionMarkerFailedError,- CubepiSchemaError,+ CubeloopSchemaError,RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,@@ -32,8 +32,8 @@ def test_runtime_errors_inherit_checkpointer_error(exc_cls):def test_checkpointer_error_separate_from_schema_error():- assert not issubclass(CheckpointerError, CubepiSchemaError)- assert not issubclass(CubepiSchemaError, CheckpointerError)+ assert not issubclass(CheckpointerError, CubeloopSchemaError)+ assert not issubclass(CubeloopSchemaError, CheckpointerError)def test_completion_marker_failed_error_carries_run_id():diff --git a/tests/checkpointer/test_hitl_answer_ledger_unit.py b/tests/checkpointer/test_hitl_answer_ledger_unit.pyindex 2a8e298..1d18f4a 100644--- a/tests/checkpointer/test_hitl_answer_ledger_unit.py+++ b/tests/checkpointer/test_hitl_answer_ledger_unit.py@@ -4,8 +4,8 @@ import jsonimport pytest-from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer-from cubepi.checkpointer.postgres.checkpointer import PostgresCheckpointer+from cubeloop.checkpointer.mysql.checkpointer import MySQLCheckpointer+from cubeloop.checkpointer.postgres.checkpointer import PostgresCheckpointerclass _AsyncCtx:@@ -102,9 +102,9 @@ async def test_postgres_hitl_answer_ledger_crud() -> None:await cp.clear_hitl_answers("t-1", run_id="r-1")sqls = [sql for sql, _args in conn.exec_calls]- assert any("cubepi_hitl_answers" in sql for sql in sqls)+ assert any("cubeloop_hitl_answers" in sql for sql in sqls)assert any("ON CONFLICT (thread_id, run_id, question_id)" in sql for sql in sqls)- assert any("DELETE FROM cubepi_hitl_answers" in sql for sql in sqls)+ assert any("DELETE FROM cubeloop_hitl_answers" in sql for sql in sqls)@pytest.mark.asyncio@@ -142,9 +142,9 @@ async def test_mysql_hitl_answer_ledger_crud() -> None:await cp.clear_hitl_answers("t-1", run_id="r-1")sqls = [sql for sql, _params in conn.exec_calls]- assert any("cubepi_hitl_answers" in sql for sql in sqls)+ assert any("cubeloop_hitl_answers" in sql for sql in sqls)assert any("ON DUPLICATE KEY UPDATE" in sql for sql in sqls)- assert any("DELETE FROM cubepi_hitl_answers" in sql for sql in sqls)+ assert any("DELETE FROM cubeloop_hitl_answers" in sql for sql in sqls)@pytest.mark.asynciodiff --git a/tests/checkpointer/test_init.py b/tests/checkpointer/test_init.pyindex dbf0b26..91a98f1 100644--- a/tests/checkpointer/test_init.py+++ b/tests/checkpointer/test_init.py@@ -4,11 +4,11 @@ import pytestdef test_postgres_checkpointer_lazy_import_via_public_module() -> None:- """`from cubepi.checkpointer import PostgresCheckpointer` hits the lazy path."""- import cubepi.checkpointer as pkg+ """`from cubeloop.checkpointer import PostgresCheckpointer` hits the lazy path."""+ import cubeloop.checkpointer as pkgPG = pkg.PostgresCheckpointer # triggers __getattr__- from cubepi.checkpointer.postgres.checkpointer import (+ from cubeloop.checkpointer.postgres.checkpointer import (PostgresCheckpointer as Direct,)@@ -16,16 +16,16 @@ def test_postgres_checkpointer_lazy_import_via_public_module() -> None:def test_sqlite_checkpointer_lazy_import_via_public_module() -> None:- import cubepi.checkpointer as pkg+ import cubeloop.checkpointer as pkgSQ = pkg.SQLiteCheckpointer- from cubepi.checkpointer.sqlite import SQLiteCheckpointer as Direct+ from cubeloop.checkpointer.sqlite import SQLiteCheckpointer as Directassert SQ is Directdef test_unknown_attribute_raises_attribute_error() -> None:- import cubepi.checkpointer as pkg+ import cubeloop.checkpointer as pkgwith pytest.raises(AttributeError, match="has no attribute 'NotAThing'"):_ = pkg.NotAThingdiff --git a/tests/checkpointer/test_memory.py b/tests/checkpointer/test_memory.pyindex 363a004..8bacc66 100644--- a/tests/checkpointer/test_memory.py+++ b/tests/checkpointer/test_memory.py@@ -1,5 +1,5 @@-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.providers.base import TextContent, UserMessageclass TestMemoryCheckpointer:diff --git a/tests/checkpointer/test_memory_fork.py b/tests/checkpointer/test_memory_fork.pyindex b501914..b5ad335 100644--- a/tests/checkpointer/test_memory_fork.py+++ b/tests/checkpointer/test_memory_fork.py@@ -1,12 +1,12 @@import pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunNotCompletedError,ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.providers.base import TextContent, UserMessagedef _msg(run_id: str | None, text: str) -> UserMessage:diff --git a/tests/checkpointer/test_memory_runs.py b/tests/checkpointer/test_memory_runs.pyindex f8268f5..04820cd 100644--- a/tests/checkpointer/test_memory_runs.py+++ b/tests/checkpointer/test_memory_runs.py@@ -1,12 +1,12 @@import pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,)-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.providers.base import TextContent, UserMessage@pytest.mark.asyncio@@ -76,7 +76,7 @@ async def test_append_in_flight_run_id_ok():@pytest.mark.asyncioasync def test_load_pending_returns_tuple_with_run_id():- from cubepi.hitl.types import ConfirmRequest, HitlRequest+ from cubeloop.hitl.types import ConfirmRequest, HitlRequestcp = MemoryCheckpointer()req = HitlRequest(diff --git a/tests/checkpointer/test_mysql.py b/tests/checkpointer/test_mysql.pyindex 8354d81..e9a59c5 100644--- a/tests/checkpointer/test_mysql.py+++ b/tests/checkpointer/test_mysql.py@@ -3,7 +3,7 @@import aiomysqlimport pytest-from cubepi.checkpointer.mysql.alembic_helpers import (+from cubeloop.checkpointer.mysql.alembic_helpers import (messages_partition_clause,write_schema_version_op,)@@ -14,57 +14,57 @@ from cubepi.checkpointer.mysql.alembic_helpers import (def test_exceptions_are_postgres_aliases() -> None:- from cubepi.checkpointer.mysql.exceptions import (- CubepiSchemaError,- CubepiSchemaMismatch,- CubepiSchemaUninitialized,+ from cubeloop.checkpointer.mysql.exceptions import (+ CubeloopSchemaError,+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,)- from cubepi.checkpointer.postgres import exceptions as pg_exc+ from cubeloop.checkpointer.postgres import exceptions as pg_exc- assert CubepiSchemaError is pg_exc.CubepiSchemaError- assert CubepiSchemaMismatch is pg_exc.CubepiSchemaMismatch- assert CubepiSchemaUninitialized is pg_exc.CubepiSchemaUninitialized+ assert CubeloopSchemaError is pg_exc.CubeloopSchemaError+ assert CubeloopSchemaMismatch is pg_exc.CubeloopSchemaMismatch+ assert CubeloopSchemaUninitialized is pg_exc.CubeloopSchemaUninitializeddef test_models_import() -> None:- from cubepi.checkpointer.mysql.models import (+ from cubeloop.checkpointer.mysql.models import (EXPECTED_SCHEMA_VERSION,- CubepiHitlAnswer,+ CubeloopHitlAnswer,PARTITION_COUNT,- CubepiMessage,- CubepiSchemaVersion,- CubepiThread,- cubepi_metadata,+ CubeloopMessage,+ CubeloopSchemaVersion,+ CubeloopThread,+ cubeloop_metadata,)- assert EXPECTED_SCHEMA_VERSION == 5+ assert EXPECTED_SCHEMA_VERSION == 6assert PARTITION_COUNT == 64- assert CubepiThread.__tablename__ == "cubepi_threads"- assert CubepiMessage.__tablename__ == "cubepi_messages"- assert CubepiHitlAnswer.__tablename__ == "cubepi_hitl_answers"- assert CubepiSchemaVersion.__tablename__ == "cubepi_schema_version"- assert "cubepi_threads" in cubepi_metadata.tables- assert "cubepi_messages" in cubepi_metadata.tables- assert "cubepi_hitl_answers" in cubepi_metadata.tables- assert "cubepi_schema_version" in cubepi_metadata.tables+ assert CubeloopThread.__tablename__ == "cubeloop_threads"+ assert CubeloopMessage.__tablename__ == "cubeloop_messages"+ assert CubeloopHitlAnswer.__tablename__ == "cubeloop_hitl_answers"+ assert CubeloopSchemaVersion.__tablename__ == "cubeloop_schema_version"+ assert "cubeloop_threads" in cubeloop_metadata.tables+ assert "cubeloop_messages" in cubeloop_metadata.tables+ assert "cubeloop_hitl_answers" in cubeloop_metadata.tables+ assert "cubeloop_schema_version" in cubeloop_metadata.tablesdef test_threads_parent_self_fk_present() -> None:"""parent_thread_id keeps a self-FK (threads table is not partitioned)."""- from cubepi.checkpointer.mysql.models import cubepi_metadata+ from cubeloop.checkpointer.mysql.models import cubeloop_metadata- threads = cubepi_metadata.tables["cubepi_threads"]+ threads = cubeloop_metadata.tables["cubeloop_threads"]fk_targets = {fk.column.table.name for col in threads.columns for fk in col.foreign_keys}- assert "cubepi_threads" in fk_targets+ assert "cubeloop_threads" in fk_targetsdef test_messages_has_no_foreign_keys() -> None:"""messages table is partitioned, so no FK is allowed."""- from cubepi.checkpointer.mysql.models import cubepi_metadata+ from cubeloop.checkpointer.mysql.models import cubeloop_metadata- msgs = cubepi_metadata.tables["cubepi_messages"]+ msgs = cubeloop_metadata.tables["cubeloop_messages"]assert msgs.foreign_keys == set()@@ -74,11 +74,11 @@ def test_messages_has_no_metadata_index() -> None:The MySQL backend never indexes the JSON ``metadata`` column (Postgreshas a GIN index there; MySQL has no equivalent for the host-app cost)."""- from cubepi.checkpointer.mysql.models import cubepi_metadata+ from cubeloop.checkpointer.mysql.models import cubeloop_metadata- msgs = cubepi_metadata.tables["cubepi_messages"]+ msgs = cubeloop_metadata.tables["cubeloop_messages"]idx_names = {idx.name for idx in msgs.indexes}- assert idx_names == {"ix_cubepi_messages_thread_run"}+ assert idx_names == {"ix_cubeloop_messages_thread_run"}def test_messages_partition_clause() -> None:@@ -87,19 +87,32 @@ def test_messages_partition_clause() -> None:def test_write_schema_version_op_clears_stale_then_inserts() -> None:- from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+ from cubeloop.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSIONsql = write_schema_version_op()- assert "DELETE FROM cubepi_schema_version" in sql+ assert "cubeloop_schema_version" in sql+ assert "cubepi_schema_version" in sqlassert f"WHERE version <> {EXPECTED_SCHEMA_VERSION}" in sql- assert "INSERT IGNORE INTO cubepi_schema_version" in sql- assert f"VALUES ({EXPECTED_SCHEMA_VERSION})" in sql+ assert "INSERT IGNORE INTO cubeloop_schema_version" in sql+ assert "PREPARE cp_stmt FROM @cp_del" in sqlassert sql.index("DELETE") < sql.index("INSERT")+def test_upgrade_v5_to_v6_op_is_idempotent_guarded() -> None:+ from cubeloop.checkpointer.mysql.alembic_helpers import upgrade_v5_to_v6_op++ sql = upgrade_v5_to_v6_op()+ assert "information_schema.tables" in sql+ assert "cubeloop_threads" in sql+ assert "cubeloop_schema_version" in sql+ assert "PREPARE cp_v6 FROM @cp_sql" in sql+ assert "RENAME TABLE" in sql+ assert "DO 0" in sql++def test_role_of_known_message_types() -> None:- from cubepi.checkpointer.mysql.checkpointer import _role_of- from cubepi.providers.base import (+ from cubeloop.checkpointer.mysql.checkpointer import _role_of+ from cubeloop.providers.base import (AssistantMessage,TextContent,ToolResultMessage,@@ -119,7 +132,7 @@ def test_role_of_known_message_types() -> None:def test_role_of_rejects_unknown_message_type() -> None:- from cubepi.checkpointer.mysql.checkpointer import _role_of+ from cubeloop.checkpointer.mysql.checkpointer import _role_ofclass FakeMessage:pass@@ -129,7 +142,7 @@ def test_role_of_rejects_unknown_message_type() -> None:def test_parse_dsn_full() -> None:- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsncfg = _parse_dsn("mysql://user:[email protected]:3307/mydb")assert cfg == {@@ -142,7 +155,7 @@ def test_parse_dsn_full() -> None:def test_parse_dsn_defaults_port_3306() -> None:- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsncfg = _parse_dsn("mysql://root@localhost/x")assert cfg["port"] == 3306@@ -150,7 +163,7 @@ def test_parse_dsn_defaults_port_3306() -> None:def test_decode_json_handles_str_and_dict() -> None:- from cubepi.checkpointer.mysql.checkpointer import _decode_json+ from cubeloop.checkpointer.mysql.checkpointer import _decode_jsonassert _decode_json('{"a": 1}') == {"a": 1}assert _decode_json({"a": 1}) == {"a": 1}@@ -159,7 +172,7 @@ def test_decode_json_handles_str_and_dict() -> None:@pytest.mark.asyncioasync def test_append_empty_messages_is_noop() -> None:- from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer+ from cubeloop.checkpointer.mysql.checkpointer import MySQLCheckpointercp = MySQLCheckpointer("mysql://root@unreachable-host/none")assert cp._pool is None@@ -168,7 +181,7 @@ async def test_append_empty_messages_is_noop() -> None:def test_top_level_lazy_import() -> None:- import cubepi.checkpointer as cp_pkg+ import cubeloop.checkpointer as cp_pkgassert cp_pkg.MySQLCheckpointer is not Noneassert "MySQLCheckpointer" in cp_pkg.__all__@@ -193,7 +206,7 @@ def test_mysql_import_does_not_require_asyncpg() -> None:raise ModuleNotFoundError("No module named asyncpg")return real(name, *a, **k)builtins.__import__ = fake- from cubepi.checkpointer import MySQLCheckpointer+ from cubeloop.checkpointer import MySQLCheckpointerassert MySQLCheckpointer is not Noneprint("OK")"""@@ -211,35 +224,92 @@ def test_mysql_import_does_not_require_asyncpg() -> None:async def _setup_schema(dsn: str) -> None:- """Build the cubepi schema (matching what host alembic would generate)."""- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ """Fresh v6 schema — canonical current DDL, no historical helpers."""+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.alembic_helpers import create_runs_table_opconn = await aiomysql.connect(autocommit=True, **_parse_dsn(dsn))try:async with conn.cursor() as cur:await cur.execute("""- CREATE TABLE cubepi_threads (+ CREATE TABLE cubeloop_threads (thread_id VARCHAR(255) COLLATE utf8mb4_bin PRIMARY KEY,parent_thread_id VARCHAR(255) COLLATE utf8mb4_bin NULL,forked_at_seq BIGINT NULL,extra JSON NOT NULL DEFAULT (JSON_OBJECT()),+ pending_request JSON NULL,+ run_id VARCHAR(64) NULL,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMP,CONSTRAINT fk_parent FOREIGN KEY (parent_thread_id)- REFERENCES cubepi_threads (thread_id)+ REFERENCES cubeloop_threads (thread_id)) ENGINE=InnoDB""")- # Bring cubepi_threads up to the v3 shape via the public helpers.- from cubepi.checkpointer.mysql.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,- upgrade_v3_to_v4_op,- upgrade_v4_to_v5_op,+ await cur.execute(+ """+ CREATE TABLE cubeloop_messages (+ thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ seq BIGINT NOT NULL,+ role VARCHAR(32) NOT NULL,+ metadata JSON NOT NULL DEFAULT (JSON_OBJECT()),+ payload LONGBLOB NOT NULL,+ run_id VARCHAR(255) NULL,+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (thread_id, seq),+ KEY ix_cubeloop_messages_thread_run (thread_id, run_id)+ ) ENGINE=InnoDB """+ + messages_partition_clause())+ await cur.execute("""+ CREATE TABLE cubeloop_schema_version (+ version INT PRIMARY KEY+ ) ENGINE=InnoDB+ """)+ await cur.execute(create_runs_table_op())+ await cur.execute("""+ CREATE TABLE cubeloop_hitl_answers (+ thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,+ run_id VARCHAR(255) NOT NULL,+ question_id VARCHAR(255) NOT NULL,+ answer JSON NOT NULL,+ answered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (thread_id, run_id, question_id)+ ) ENGINE=InnoDB+ """)+ for stmt in write_schema_version_op().split(";"):+ if stmt.strip():+ await cur.execute(stmt)+ finally:+ await conn.ensure_closed()- await cur.execute(add_pending_request_column_op())- await cur.execute(add_run_id_column_op())++async def _setup_schema_v5(dsn: str) -> None:+ """Historical v5 (cubepi_* names) via frozen v1–v5 helpers."""+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.alembic_helpers import (+ add_pending_request_column_op,+ add_run_id_column_op,+ upgrade_v3_to_v4_op,+ upgrade_v4_to_v5_op,+ )++ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(dsn))+ try:+ async with conn.cursor() as cur:+ await cur.execute("""+ CREATE TABLE cubepi_threads (+ thread_id VARCHAR(255) COLLATE utf8mb4_bin PRIMARY KEY,+ parent_thread_id VARCHAR(255) COLLATE utf8mb4_bin NULL,+ forked_at_seq BIGINT NULL,+ extra JSON NOT NULL DEFAULT (JSON_OBJECT()),+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP+ ON UPDATE CURRENT_TIMESTAMP,+ CONSTRAINT fk_parent FOREIGN KEY (parent_thread_id)+ REFERENCES cubepi_threads (thread_id)+ ) ENGINE=InnoDB+ """)await cur.execute("""CREATE TABLE cubepi_messages (@@ -258,24 +328,23 @@ async def _setup_schema(dsn: str) -> None:version INT PRIMARY KEY) ENGINE=InnoDB""")- # v3 → v4: run_id on cubepi_messages + cubepi_runs partitioned table.+ await cur.execute(add_pending_request_column_op())+ await cur.execute(add_run_id_column_op())for stmt in upgrade_v3_to_v4_op().split(";"):if stmt.strip():await cur.execute(stmt)for stmt in upgrade_v4_to_v5_op().split(";"):if stmt.strip():await cur.execute(stmt)- for stmt in write_schema_version_op().split(";"):- if stmt.strip():- await cur.execute(stmt)+ await cur.execute("INSERT INTO cubepi_schema_version (version) VALUES (5)")finally:await conn.ensure_closed()@pytest.mark.asyncioasync def test_mysql_checkpointer_round_trip(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.providers.base import (+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.providers.base import (AssistantMessage,TextContent,Usage,@@ -308,8 +377,8 @@ async def test_mysql_checkpointer_round_trip(clean_mysql_db) -> None:@pytest.mark.asyncioasync def test_mysql_checkpointer_save_extra_merges(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -332,7 +401,7 @@ async def test_mysql_checkpointer_save_extra_shallow_merge_semantics((b) deep-merge nested objects. dict.update overwrites top-level keys,keeps null values, and replaces nested objects wholesale."""- from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql import MySQLCheckpointerawait _setup_schema(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -351,8 +420,8 @@ async def test_mysql_checkpointer_save_extra_shallow_merge_semantics(@pytest.mark.asyncioasync def test_mysql_checkpointer_seq_monotonic(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -370,33 +439,33 @@ async def test_mysql_checkpointer_seq_monotonic(clean_mysql_db) -> None:@pytest.mark.asyncioasync def test_uninitialized_schema_raises(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import (- CubepiSchemaUninitialized,+ from cubeloop.checkpointer.mysql import (+ CubeloopSchemaUninitialized,MySQLCheckpointer,)- with pytest.raises(CubepiSchemaUninitialized):+ with pytest.raises(CubeloopSchemaUninitialized):async with MySQLCheckpointer(clean_mysql_db):pass@pytest.mark.asyncioasync def test_version_mismatch_raises(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import CubepiSchemaMismatch, MySQLCheckpointer- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql import CubeloopSchemaMismatch, MySQLCheckpointer+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsnawait _setup_schema(clean_mysql_db)conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))try:async with conn.cursor() as cur:- await cur.execute("UPDATE cubepi_schema_version SET version = 999")+ await cur.execute("UPDATE cubeloop_schema_version SET version = 999")finally:await conn.ensure_closed()- with pytest.raises(CubepiSchemaMismatch) as exc_info:+ with pytest.raises(CubeloopSchemaMismatch) as exc_info:async with MySQLCheckpointer(clean_mysql_db):pass- from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+ from cubeloop.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSIONassert exc_info.value.expected == EXPECTED_SCHEMA_VERSIONassert exc_info.value.actual == 999@@ -404,7 +473,7 @@ async def test_version_mismatch_raises(clean_mysql_db) -> None:@pytest.mark.asyncioasync def test_empty_thread_load_returns_none(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql import MySQLCheckpointerawait _setup_schema(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -415,8 +484,8 @@ async def test_empty_thread_load_returns_none(clean_mysql_db) -> None:@pytest.mark.asyncioasync def test_mysql_checkpointer_rich_content_round_trip(clean_mysql_db) -> None:"""Round-trip thinking + tool-call + tool-result content types."""- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.providers.base import (+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.providers.base import (AssistantMessage,TextContent,ThinkingContent,@@ -468,8 +537,8 @@ async def test_mysql_checkpointer_concurrent_append_seq_unique("""import asyncio- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db, max_pool_size=4) as cp:@@ -490,21 +559,21 @@ async def test_mysql_checkpointer_concurrent_append_seq_unique(@pytest.mark.asyncioasync def test_empty_version_table_raises_uninitialized(clean_mysql_db) -> None:"""Schema present but cubepi_schema_version has no row → Uninitialized."""- from cubepi.checkpointer.mysql import (- CubepiSchemaUninitialized,+ from cubeloop.checkpointer.mysql import (+ CubeloopSchemaUninitialized,MySQLCheckpointer,)- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsnawait _setup_schema(clean_mysql_db)conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))try:async with conn.cursor() as cur:- await cur.execute("DELETE FROM cubepi_schema_version")+ await cur.execute("DELETE FROM cubeloop_schema_version")finally:await conn.ensure_closed()- with pytest.raises(CubepiSchemaUninitialized):+ with pytest.raises(CubeloopSchemaUninitialized):async with MySQLCheckpointer(clean_mysql_db):pass@@ -515,19 +584,21 @@ async def test_load_unknown_role_raises(clean_mysql_db) -> None:error on load, naming the row."""import msgpack- from cubepi.checkpointer.exceptions import CheckpointCorruptionError+ from cubeloop.checkpointer.exceptions import CheckpointCorruptionError- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsnawait _setup_schema(clean_mysql_db)payload = msgpack.packb({"content": []}, use_bin_type=True)conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))try:async with conn.cursor() as cur:- await cur.execute("INSERT INTO cubepi_threads (thread_id) VALUES ('t-bad')")await cur.execute(- "INSERT INTO cubepi_messages "+ "INSERT INTO cubeloop_threads (thread_id) VALUES ('t-bad')"+ )+ await cur.execute(+ "INSERT INTO cubeloop_messages ""(thread_id, seq, role, metadata, payload) ""VALUES ('t-bad', 1, 'bogus', '{}', %s)",(payload,),@@ -539,17 +610,17 @@ async def test_load_unknown_role_raises(clean_mysql_db) -> None:with pytest.raises(CheckpointCorruptionError, match="unknown role in DB") as ei:await cp.load("t-bad")assert isinstance(ei.value.__cause__, ValueError)- assert ei.value.row_ref == "cubepi_messages.seq=1"+ assert ei.value.row_ref == "cubeloop_messages.seq=1"@pytest.mark.asyncioasync def test_missing_version_column_raises_uninitialized(clean_mysql_db) -> None:"""A malformed cubepi_schema_version table (no `version` column) → 1054 path."""- from cubepi.checkpointer.mysql import (- CubepiSchemaUninitialized,+ from cubeloop.checkpointer.mysql import (+ CubeloopSchemaUninitialized,MySQLCheckpointer,)- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsnconn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))try:@@ -561,7 +632,7 @@ async def test_missing_version_column_raises_uninitialized(clean_mysql_db) -> Nofinally:await conn.ensure_closed()- with pytest.raises(CubepiSchemaUninitialized):+ with pytest.raises(CubeloopSchemaUninitialized):async with MySQLCheckpointer(clean_mysql_db):pass@@ -570,10 +641,10 @@ async def test_missing_version_column_raises_uninitialized(clean_mysql_db) -> Noasync def test_mysql_load_corrupt_row_raises_typed(clean_mysql_db) -> None:"""One bad payload row surfaces as CheckpointCorruptionError naming therow — not a raw msgpack error that hides which row is bad."""- from cubepi.checkpointer.exceptions import CheckpointCorruptionError- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.exceptions import CheckpointCorruptionError+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -588,10 +659,10 @@ async def test_mysql_load_corrupt_row_raises_typed(clean_mysql_db) -> None:try:async with conn.cursor() as cur:await cur.execute(- "UPDATE cubepi_messages SET payload = %s "+ "UPDATE cubeloop_messages SET payload = %s ""WHERE thread_id = 't-corrupt' AND seq = ("" SELECT max_seq FROM (SELECT max(seq) AS max_seq "- " FROM cubepi_messages WHERE thread_id = 't-corrupt') AS sub)",+ " FROM cubeloop_messages WHERE thread_id = 't-corrupt') AS sub)",(b"\xc1 not msgpack",),)finally:@@ -603,5 +674,48 @@ async def test_mysql_load_corrupt_row_raises_typed(clean_mysql_db) -> None:err = excinfo.valueassert err.thread_id == "t-corrupt"assert err.backend == "mysql"- assert err.row_ref.startswith("cubepi_messages.seq=")+ assert err.row_ref.startswith("cubeloop_messages.seq=")assert err.__cause__ is not None+++async def test_v5_to_v6_rename_is_idempotent_before_version_write(+ clean_mysql_db,+) -> None:+ """Rename can retry after a failure before write_schema_version_op."""+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql.alembic_helpers import upgrade_v5_to_v6_op+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.providers.base import TextContent, UserMessage++ await _setup_schema_v5(clean_mysql_db)+ conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))+ try:+ async with conn.cursor() as cur:+ for stmt in upgrade_v5_to_v6_op().split(";"):+ if stmt.strip():+ await cur.execute(stmt)+ # Simulate Alembic failing before the version writer, then retry.+ for stmt in upgrade_v5_to_v6_op().split(";"):+ if stmt.strip():+ await cur.execute(stmt)+ for stmt in write_schema_version_op().split(";"):+ if stmt.strip():+ await cur.execute(stmt)+ await cur.execute(+ "SELECT table_name FROM information_schema.tables "+ "WHERE table_schema = DATABASE()"+ )+ names = {row[0] for row in await cur.fetchall()}+ finally:+ await conn.ensure_closed()++ assert "cubeloop_threads" in names+ assert "cubeloop_schema_version" in names+ assert "cubepi_threads" not in names++ async with MySQLCheckpointer(clean_mysql_db) as cp:+ await cp.append("t-mig", [UserMessage(content=[TextContent(text="hi")])])+ data = await cp.load("t-mig")+ assert data is not None+ assert len(data.messages) == 1diff --git a/tests/checkpointer/test_mysql_fork.py b/tests/checkpointer/test_mysql_fork.pyindex 8c9c65b..a80bbb0 100644--- a/tests/checkpointer/test_mysql_fork.py+++ b/tests/checkpointer/test_mysql_fork.py@@ -6,13 +6,13 @@ import asyncioimport pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunNotCompletedError,ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.checkpointer.mysql import MySQLCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.mysql import MySQLCheckpointer+from cubeloop.providers.base import TextContent, UserMessagedef _msg(run_id: str | None, text: str) -> UserMessage:diff --git a/tests/checkpointer/test_mysql_pending_request.py b/tests/checkpointer/test_mysql_pending_request.pyindex 638fa3b..dd7f054 100644--- a/tests/checkpointer/test_mysql_pending_request.py+++ b/tests/checkpointer/test_mysql_pending_request.py@@ -1,61 +1,10 @@import aiomysqlimport pytest-from cubepi.checkpointer.mysql import MySQLCheckpointer-from cubepi.checkpointer.mysql.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,- messages_partition_clause,- write_schema_version_op,-)-from cubepi.checkpointer.mysql.checkpointer import _parse_dsn-from cubepi.hitl.types import ApproveRequest, HitlRequest---async def _setup_schema_v2(dsn: str) -> None:- """Bootstrap a v2 schema in a fresh DB (mirrors test_mysql.py::_setup_schema)."""- conn = await aiomysql.connect(autocommit=True, **_parse_dsn(dsn))- try:- async with conn.cursor() as cur:- await cur.execute("""- CREATE TABLE cubepi_threads (- thread_id VARCHAR(255) COLLATE utf8mb4_bin PRIMARY KEY,- parent_thread_id VARCHAR(255) COLLATE utf8mb4_bin NULL,- forked_at_seq BIGINT NULL,- extra JSON NOT NULL DEFAULT (JSON_OBJECT()),- created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP- ON UPDATE CURRENT_TIMESTAMP,- CONSTRAINT fk_parent FOREIGN KEY (parent_thread_id)- REFERENCES cubepi_threads (thread_id)- ) ENGINE=InnoDB- """)- # v2 + v3 column adds- await cur.execute(add_pending_request_column_op())- await cur.execute(add_run_id_column_op())- await cur.execute(- """- CREATE TABLE cubepi_messages (- thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,- seq BIGINT NOT NULL,- role VARCHAR(32) NOT NULL,- metadata JSON NOT NULL DEFAULT (JSON_OBJECT()),- payload LONGBLOB NOT NULL,- created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (thread_id, seq)- ) ENGINE=InnoDB """- + messages_partition_clause()- )- await cur.execute("""- CREATE TABLE cubepi_schema_version (- version INT PRIMARY KEY- ) ENGINE=InnoDB- """)- for stmt in write_schema_version_op().split(";"):- if stmt.strip():- await cur.execute(stmt)- finally:- await conn.ensure_closed()+from cubeloop.checkpointer.mysql import MySQLCheckpointer+from cubeloop.checkpointer.mysql.checkpointer import _parse_dsn+from cubeloop.hitl.types import ApproveRequest, HitlRequest+from tests.checkpointer.test_mysql import _setup_schema as _setup_schema_v2def _req(qid="tc-1") -> HitlRequest:@@ -103,7 +52,7 @@ async def test_mysql_pending_request_creates_thread_row_lazily(clean_mysql_db) -async def test_mysql_v2_schema_version_enforced(clean_mysql_db) -> None:"""If the host's alembic only ran v1 (schema_version=1), MySQLCheckpointer__aenter__ raises CubepiSchemaMismatch."""- from cubepi.checkpointer.mysql.exceptions import CubepiSchemaMismatch+ from cubeloop.checkpointer.mysql.exceptions import CubeloopSchemaMismatchconn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))try:@@ -115,6 +64,6 @@ async def test_mysql_v2_schema_version_enforced(clean_mysql_db) -> None:finally:await conn.ensure_closed()- with pytest.raises(CubepiSchemaMismatch):+ with pytest.raises(CubeloopSchemaMismatch):async with MySQLCheckpointer(clean_mysql_db):passdiff --git a/tests/checkpointer/test_mysql_runs.py b/tests/checkpointer/test_mysql_runs.pyindex a2ab25b..e9c0a3c 100644--- a/tests/checkpointer/test_mysql_runs.py+++ b/tests/checkpointer/test_mysql_runs.py@@ -3,17 +3,17 @@import aiomysqlimport pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,)-from cubepi.checkpointer.mysql import MySQLCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.mysql import MySQLCheckpointer+from cubeloop.providers.base import TextContent, UserMessageasync def _connect(dsn: str):- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsnreturn await aiomysql.connect(autocommit=True, **_parse_dsn(dsn))@@ -26,13 +26,13 @@ async def test_claim_run_creates_threads_row_lazily(mysql_v4_dsn) -> None:try:async with conn.cursor() as cur:await cur.execute(- "SELECT thread_id FROM cubepi_threads WHERE thread_id = %s",+ "SELECT thread_id FROM cubeloop_threads WHERE thread_id = %s",("t-lazy",),)row = await cur.fetchone()assert row is not Noneawait cur.execute(- "SELECT completed_at FROM cubepi_runs "+ "SELECT completed_at FROM cubeloop_runs ""WHERE thread_id = %s AND run_id = %s",("t-lazy", "r1"),)@@ -96,7 +96,7 @@ async def test_completion_seq_monotonic_per_thread(mysql_v4_dsn) -> None:try:async with conn.cursor() as cur:await cur.execute(- "SELECT run_id, completion_seq FROM cubepi_runs "+ "SELECT run_id, completion_seq FROM cubeloop_runs ""WHERE thread_id = %s ORDER BY completion_seq",("t",),)@@ -111,7 +111,7 @@ async def test_completion_seq_monotonic_per_thread(mysql_v4_dsn) -> None:@pytest.mark.asyncioasync def test_load_pending_returns_tuple_with_run_id(mysql_v4_dsn) -> None:- from cubepi.hitl.types import ConfirmRequest, HitlRequest+ from cubeloop.hitl.types import ConfirmRequest, HitlRequestasync with MySQLCheckpointer(mysql_v4_dsn) as cp:req = HitlRequest(@@ -144,7 +144,7 @@ async def test_append_persists_run_id_into_column(mysql_v4_dsn) -> None:try:async with conn.cursor() as cur:await cur.execute(- "SELECT run_id FROM cubepi_messages WHERE thread_id = %s",+ "SELECT run_id FROM cubeloop_messages WHERE thread_id = %s",("t",),)row = await cur.fetchone()diff --git a/tests/checkpointer/test_mysql_schema.py b/tests/checkpointer/test_mysql_schema.pyindex 7b1a6a1..0da1f96 100644--- a/tests/checkpointer/test_mysql_schema.py+++ b/tests/checkpointer/test_mysql_schema.py@@ -3,16 +3,16 @@import aiomysqlimport pytest-from cubepi.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.mysql.models import EXPECTED_SCHEMA_VERSION-def test_expected_schema_version_is_5() -> None:- assert EXPECTED_SCHEMA_VERSION == 5+def test_expected_schema_version_is_6() -> None:+ assert EXPECTED_SCHEMA_VERSION == 6@pytest.mark.asyncio-async def test_cubepi_runs_table_present(mysql_v4_dsn) -> None:- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+async def test_cubeloop_runs_table_present(mysql_v4_dsn) -> None:+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsncfg = _parse_dsn(mysql_v4_dsn)conn = await aiomysql.connect(autocommit=True, **cfg)@@ -20,7 +20,7 @@ async def test_cubepi_runs_table_present(mysql_v4_dsn) -> None:async with conn.cursor() as cur:await cur.execute("SELECT column_name FROM information_schema.columns "- "WHERE table_schema = %s AND table_name = 'cubepi_runs'",+ "WHERE table_schema = %s AND table_name = 'cubeloop_runs'",(cfg["db"],),)rows = await cur.fetchall()@@ -37,8 +37,8 @@ async def test_cubepi_runs_table_present(mysql_v4_dsn) -> None:@pytest.mark.asyncio-async def test_cubepi_messages_has_run_id_column(mysql_v4_dsn) -> None:- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+async def test_cubeloop_messages_has_run_id_column(mysql_v4_dsn) -> None:+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsncfg = _parse_dsn(mysql_v4_dsn)conn = await aiomysql.connect(autocommit=True, **cfg)@@ -46,7 +46,7 @@ async def test_cubepi_messages_has_run_id_column(mysql_v4_dsn) -> None:async with conn.cursor() as cur:await cur.execute("SELECT data_type FROM information_schema.columns "- "WHERE table_schema = %s AND table_name = 'cubepi_messages' "+ "WHERE table_schema = %s AND table_name = 'cubeloop_messages' ""AND column_name = 'run_id'",(cfg["db"],),)@@ -57,8 +57,8 @@ async def test_cubepi_messages_has_run_id_column(mysql_v4_dsn) -> None:@pytest.mark.asyncio-async def test_cubepi_hitl_answers_table_present(mysql_v4_dsn) -> None:- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+async def test_cubeloop_hitl_answers_table_present(mysql_v4_dsn) -> None:+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsncfg = _parse_dsn(mysql_v4_dsn)conn = await aiomysql.connect(autocommit=True, **cfg)@@ -67,7 +67,7 @@ async def test_cubepi_hitl_answers_table_present(mysql_v4_dsn) -> None:await cur.execute("SELECT column_name FROM information_schema.columns ""WHERE table_schema = %s "- "AND table_name = 'cubepi_hitl_answers'",+ "AND table_name = 'cubeloop_hitl_answers'",(cfg["db"],),)rows = await cur.fetchall()diff --git a/tests/checkpointer/test_postgres.py b/tests/checkpointer/test_postgres.pyindex b24b854..be02839 100644--- a/tests/checkpointer/test_postgres.py+++ b/tests/checkpointer/test_postgres.py@@ -8,33 +8,33 @@ import pytestdef test_models_import() -> None:- from cubepi.checkpointer.postgres.models import (+ from cubeloop.checkpointer.postgres.models import (EXPECTED_SCHEMA_VERSION,PARTITION_COUNT,- CubepiHitlAnswer,- CubepiMessage,- CubepiSchemaVersion,- CubepiThread,- cubepi_metadata,+ CubeloopHitlAnswer,+ CubeloopMessage,+ CubeloopSchemaVersion,+ CubeloopThread,+ cubeloop_metadata,)- assert EXPECTED_SCHEMA_VERSION == 5+ assert EXPECTED_SCHEMA_VERSION == 6assert PARTITION_COUNT == 64- assert CubepiThread.__tablename__ == "cubepi_threads"- assert CubepiMessage.__tablename__ == "cubepi_messages"- assert CubepiHitlAnswer.__tablename__ == "cubepi_hitl_answers"- assert CubepiSchemaVersion.__tablename__ == "cubepi_schema_version"- assert "cubepi_threads" in cubepi_metadata.tables- assert "cubepi_messages" in cubepi_metadata.tables- assert "cubepi_hitl_answers" in cubepi_metadata.tables- assert "cubepi_schema_version" in cubepi_metadata.tables+ assert CubeloopThread.__tablename__ == "cubeloop_threads"+ assert CubeloopMessage.__tablename__ == "cubeloop_messages"+ assert CubeloopHitlAnswer.__tablename__ == "cubeloop_hitl_answers"+ assert CubeloopSchemaVersion.__tablename__ == "cubeloop_schema_version"+ assert "cubeloop_threads" in cubeloop_metadata.tables+ assert "cubeloop_messages" in cubeloop_metadata.tables+ assert "cubeloop_hitl_answers" in cubeloop_metadata.tables+ assert "cubeloop_schema_version" in cubeloop_metadata.tablesdef test_cubepi_message_has_partition_by() -> None:"""The CubepiMessage table declares HASH partitioning."""- from cubepi.checkpointer.postgres.models import cubepi_metadata+ from cubeloop.checkpointer.postgres.models import cubeloop_metadata- msgs = cubepi_metadata.tables["cubepi_messages"]+ msgs = cubeloop_metadata.tables["cubeloop_messages"]# SQLAlchemy stores PG partition clause in info or dialect-specific args# Verify via dialect kwargsassert msgs.kwargs.get("postgresql_partition_by") == "HASH (thread_id)"@@ -42,72 +42,72 @@ def test_cubepi_message_has_partition_by() -> None:def test_cubepi_message_has_gin_index() -> None:"""The GIN index on metadata is registered."""- from cubepi.checkpointer.postgres.models import cubepi_metadata+ from cubeloop.checkpointer.postgres.models import cubeloop_metadata- msgs = cubepi_metadata.tables["cubepi_messages"]+ msgs = cubeloop_metadata.tables["cubeloop_messages"]idx_names = [i.name for i in msgs.indexes]- assert "ix_cubepi_messages_metadata_gin" in idx_names+ assert "ix_cubeloop_messages_metadata_gin" in idx_namesdef test_create_message_partitions_op_yields_64_statements() -> None:- from cubepi.checkpointer.postgres.alembic_helpers import (+ from cubeloop.checkpointer.postgres.alembic_helpers import (create_message_partitions_op,)sql = create_message_partitions_op()- assert sql.count("CREATE TABLE cubepi_messages_p") == 64+ assert sql.count("CREATE TABLE cubeloop_messages_p") == 64assert "modulus 64, remainder 0" in sqlassert "modulus 64, remainder 63" in sqldef test_create_message_partitions_op_partitions_are_zero_padded() -> None:- from cubepi.checkpointer.postgres.alembic_helpers import (+ from cubeloop.checkpointer.postgres.alembic_helpers import (create_message_partitions_op,)sql = create_message_partitions_op()# Partition names use 2-digit padding so they sort lexicographically- assert "cubepi_messages_p00 " in sql- assert "cubepi_messages_p63 " in sql+ assert "cubeloop_messages_p00 " in sql+ assert "cubeloop_messages_p63 " in sqldef test_write_schema_version_op_includes_expected_version() -> None:- from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op- from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION+ from cubeloop.checkpointer.postgres.alembic_helpers import write_schema_version_op+ from cubeloop.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSIONsql = write_schema_version_op()- assert "INSERT INTO cubepi_schema_version" in sql+ assert "cubeloop_schema_version" in sql+ assert "cubepi_schema_version" in sqlassert f"VALUES ({EXPECTED_SCHEMA_VERSION})" in sqlassert "ON CONFLICT" in sqldef test_write_schema_version_op_clears_stale_rows() -> None:"""A prior version's row must be removed so _verify_schema sees the new one."""- from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op- from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION+ from cubeloop.checkpointer.postgres.alembic_helpers import write_schema_version_op+ from cubeloop.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSIONsql = write_schema_version_op()- # Must DELETE rows whose version is not the expected one before INSERT.+ assert "DELETE FROM cubeloop_schema_version" in sqlassert "DELETE FROM cubepi_schema_version" in sqlassert f"WHERE version <> {EXPECTED_SCHEMA_VERSION}" in sql- # And the DELETE must come before the INSERT in the statement order.assert sql.index("DELETE") < sql.index("INSERT")def test_schema_uninitialized_is_schema_error() -> None:- from cubepi.checkpointer.postgres.exceptions import (- CubepiSchemaError,- CubepiSchemaUninitialized,+ from cubeloop.checkpointer.postgres.exceptions import (+ CubeloopSchemaError,+ CubeloopSchemaUninitialized,)- err = CubepiSchemaUninitialized("tables missing")- assert isinstance(err, CubepiSchemaError)+ err = CubeloopSchemaUninitialized("tables missing")+ assert isinstance(err, CubeloopSchemaError)def test_schema_mismatch_carries_expected_actual() -> None:- from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch+ from cubeloop.checkpointer.postgres.exceptions import CubeloopSchemaMismatch- err = CubepiSchemaMismatch(expected=2, actual=1, hint="run alembic")+ err = CubeloopSchemaMismatch(expected=2, actual=1, hint="run alembic")assert err.expected == 2assert err.actual == 1assert "expected=2" in str(err)@@ -116,9 +116,9 @@ def test_schema_mismatch_carries_expected_actual() -> None:def test_schema_mismatch_without_hint() -> None:- from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch+ from cubeloop.checkpointer.postgres.exceptions import CubeloopSchemaMismatch- err = CubepiSchemaMismatch(expected=2, actual=1)+ err = CubeloopSchemaMismatch(expected=2, actual=1)# No hint suffixassert "expected=2" in str(err)assert "actual=1" in str(err)@@ -126,8 +126,8 @@ def test_schema_mismatch_without_hint() -> None:def test_role_of_known_message_types() -> None:"""_role_of maps each concrete Message subclass to its role string."""- from cubepi.checkpointer.postgres.checkpointer import _role_of- from cubepi.providers.base import (+ from cubeloop.checkpointer.postgres.checkpointer import _role_of+ from cubeloop.providers.base import (AssistantMessage,TextContent,ToolResultMessage,@@ -150,7 +150,7 @@ def test_role_of_known_message_types() -> None:def test_role_of_rejects_unknown_message_type() -> None:"""_role_of raises for anything that isn't User/Assistant/ToolResult."""- from cubepi.checkpointer.postgres.checkpointer import _role_of+ from cubeloop.checkpointer.postgres.checkpointer import _role_ofclass FakeMessage:pass@@ -162,7 +162,7 @@ def test_role_of_rejects_unknown_message_type() -> None:@pytest.mark.asyncioasync def test_append_empty_messages_is_noop() -> None:"""append([]) returns early without touching the pool — no DB needed."""- from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.checkpointer.postgres import PostgresCheckpointercp = PostgresCheckpointer("postgresql://unreachable-host/none")# Pool intentionally never created — early return must precede the assert.@@ -176,7 +176,93 @@ async def test_append_empty_messages_is_noop() -> None:async def _setup_schema(dsn: str) -> None:- """Build the cubepi schema (matching what host alembic would generate)."""+ """Fresh v6 schema — canonical current DDL, no historical helpers."""+ from cubeloop.checkpointer.postgres.alembic_helpers import (+ create_message_partitions_op,+ create_runs_partitions_op,+ write_schema_version_op,+ )++ conn = await asyncpg.connect(dsn)+ try:+ await conn.execute("""+ CREATE TABLE cubeloop_threads (+ thread_id TEXT PRIMARY KEY,+ parent_thread_id TEXT REFERENCES cubeloop_threads(thread_id),+ forked_at_seq BIGINT,+ extra JSONB NOT NULL DEFAULT '{}'::jsonb,+ pending_request JSONB,+ run_id TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ """)+ await conn.execute("""+ CREATE TABLE cubeloop_messages (+ thread_id TEXT NOT NULL REFERENCES cubeloop_threads(thread_id) ON DELETE CASCADE,+ seq BIGINT NOT NULL,+ role TEXT NOT NULL,+ metadata JSONB NOT NULL DEFAULT '{}'::jsonb,+ payload BYTEA NOT NULL,+ run_id TEXT,+ 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_cubeloop_messages_metadata_gin+ ON cubeloop_messages USING GIN (metadata jsonb_path_ops);+ """)+ await conn.execute("""+ CREATE INDEX ix_cubeloop_messages_thread_run+ ON cubeloop_messages (thread_id, run_id);+ """)+ await conn.execute("""+ CREATE TABLE cubeloop_schema_version (+ version INTEGER PRIMARY KEY+ );+ """)+ await conn.execute("""+ CREATE TABLE cubeloop_runs (+ thread_id TEXT NOT NULL REFERENCES cubeloop_threads(thread_id) ON DELETE CASCADE,+ run_id TEXT NOT NULL,+ claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ completed_at TIMESTAMPTZ,+ completion_seq BIGINT,+ PRIMARY KEY (thread_id, run_id)+ ) PARTITION BY HASH (thread_id);+ """)+ await conn.execute(create_runs_partitions_op())+ await conn.execute("""+ CREATE INDEX ix_cubeloop_runs_thread_seq+ ON cubeloop_runs (thread_id, completion_seq);+ """)+ await conn.execute("""+ CREATE TABLE cubeloop_hitl_answers (+ thread_id TEXT NOT NULL REFERENCES cubeloop_threads(thread_id) ON DELETE CASCADE,+ run_id TEXT NOT NULL,+ question_id TEXT NOT NULL,+ answer JSONB NOT NULL,+ answered_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (thread_id, run_id, question_id)+ );+ """)+ await conn.execute(write_schema_version_op())+ finally:+ await conn.close()+++async def _setup_schema_v5(dsn: str) -> None:+ """Historical v5 (cubepi_* names) via frozen v1–v5 helpers."""+ from cubeloop.checkpointer.postgres.alembic_helpers import (+ add_pending_request_column_op,+ add_run_id_column_op,+ upgrade_v3_to_v4_op,+ upgrade_v4_to_v5_op,+ )+ from cubeloop.checkpointer.postgres.models import PARTITION_COUNT+conn = await asyncpg.connect(dsn)try:await conn.execute("""@@ -200,19 +286,14 @@ async def _setup_schema(dsn: str) -> None:PRIMARY KEY (thread_id, seq)) PARTITION BY HASH (thread_id);""")- from cubepi.checkpointer.postgres.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,- create_message_partitions_op,- upgrade_v3_to_v4_op,- upgrade_v4_to_v5_op,- write_schema_version_op,- )-- # Bring cubepi_threads up to the v3 shape (pending_request + run_id).await conn.execute(add_pending_request_column_op())await conn.execute(add_run_id_column_op())- await conn.execute(create_message_partitions_op())+ for i in range(PARTITION_COUNT):+ await conn.execute(+ f"CREATE TABLE cubepi_messages_p{i:02d} "+ f"PARTITION OF cubepi_messages "+ f"FOR VALUES WITH (modulus {PARTITION_COUNT}, remainder {i})"+ )await conn.execute("""CREATE INDEX ix_cubepi_messages_metadata_ginON cubepi_messages USING GIN (metadata jsonb_path_ops);@@ -222,10 +303,9 @@ async def _setup_schema(dsn: str) -> None:version INTEGER PRIMARY KEY);""")- # Apply v3→v4 (run_id on messages + cubepi_runs partitioned table).await conn.execute(upgrade_v3_to_v4_op())await conn.execute(upgrade_v4_to_v5_op())- await conn.execute(write_schema_version_op())+ await conn.execute("INSERT INTO cubepi_schema_version (version) VALUES (5)")finally:await conn.close()@@ -233,8 +313,8 @@ async def _setup_schema(dsn: str) -> None:@pytest.mark.asyncioasync def test_postgres_checkpointer_round_trip(clean_db) -> None:"""Append + load round-trips messages with metadata."""- from cubepi.checkpointer.postgres import PostgresCheckpointer- from cubepi.providers.base import (+ from cubeloop.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.providers.base import (AssistantMessage,TextContent,Usage,@@ -268,8 +348,8 @@ async def test_postgres_checkpointer_round_trip(clean_db) -> None:@pytest.mark.asyncioasync def test_postgres_checkpointer_save_extra_merges(clean_db) -> None:- from cubepi.checkpointer.postgres import PostgresCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -285,8 +365,8 @@ async def test_postgres_checkpointer_save_extra_merges(clean_db) -> None:@pytest.mark.asyncioasync def test_postgres_checkpointer_seq_monotonic(clean_db) -> None:"""Multiple append batches produce strictly monotonic seqs."""- from cubepi.checkpointer.postgres import PostgresCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -305,12 +385,12 @@ async def test_postgres_checkpointer_seq_monotonic(clean_db) -> None:@pytest.mark.asyncioasync def test_uninitialized_schema_raises(clean_db) -> None:"""Empty DB (no cubepi tables) → CubepiSchemaUninitialized."""- from cubepi.checkpointer.postgres import (- CubepiSchemaUninitialized,+ from cubeloop.checkpointer.postgres import (+ CubeloopSchemaUninitialized,PostgresCheckpointer,)- with pytest.raises(CubepiSchemaUninitialized):+ with pytest.raises(CubeloopSchemaUninitialized):async with PostgresCheckpointer(clean_db):pass@@ -318,22 +398,22 @@ async def test_uninitialized_schema_raises(clean_db) -> None:@pytest.mark.asyncioasync def test_version_mismatch_raises(clean_db) -> None:"""Schema present but version != EXPECTED → CubepiSchemaMismatch."""- from cubepi.checkpointer.postgres import (- CubepiSchemaMismatch,+ from cubeloop.checkpointer.postgres import (+ CubeloopSchemaMismatch,PostgresCheckpointer,)await _setup_schema(clean_db)conn = await asyncpg.connect(clean_db)try:- await conn.execute("UPDATE cubepi_schema_version SET version = 999")+ await conn.execute("UPDATE cubeloop_schema_version SET version = 999")finally:await conn.close()- with pytest.raises(CubepiSchemaMismatch) as exc_info:+ with pytest.raises(CubeloopSchemaMismatch) as exc_info:async with PostgresCheckpointer(clean_db):pass- from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION+ from cubeloop.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSIONassert exc_info.value.expected == EXPECTED_SCHEMA_VERSIONassert exc_info.value.actual == 999@@ -342,7 +422,7 @@ async def test_version_mismatch_raises(clean_db) -> None:@pytest.mark.asyncioasync def test_empty_thread_load_returns_none(clean_db) -> None:"""Loading an unknown thread returns None."""- from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.checkpointer.postgres import PostgresCheckpointerawait _setup_schema(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -354,9 +434,9 @@ async def test_empty_thread_load_returns_none(clean_db) -> None:async def test_postgres_load_corrupt_row_raises_typed(clean_db) -> None:"""One bad payload row surfaces as CheckpointCorruptionError naming therow — not a raw msgpack error that hides which row is bad."""- from cubepi.checkpointer.exceptions import CheckpointCorruptionError- from cubepi.checkpointer.postgres import PostgresCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.exceptions import CheckpointCorruptionError+ from cubeloop.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -370,9 +450,9 @@ async def test_postgres_load_corrupt_row_raises_typed(clean_db) -> None:conn = await asyncpg.connect(clean_db)try:await conn.execute(- "UPDATE cubepi_messages SET payload = $1 "+ "UPDATE cubeloop_messages SET payload = $1 ""WHERE thread_id = 't-corrupt' AND seq = ("- " SELECT max(seq) FROM cubepi_messages "+ " SELECT max(seq) FROM cubeloop_messages "" WHERE thread_id = 't-corrupt')",b"\xc1 not msgpack",)@@ -385,15 +465,15 @@ async def test_postgres_load_corrupt_row_raises_typed(clean_db) -> None:err = excinfo.valueassert err.thread_id == "t-corrupt"assert err.backend == "postgres"- assert err.row_ref.startswith("cubepi_messages.seq=")+ assert err.row_ref.startswith("cubeloop_messages.seq=")assert err.__cause__ is not None@pytest.mark.asyncioasync def test_postgres_load_unknown_role_raises_typed(clean_db) -> None:- from cubepi.checkpointer.exceptions import CheckpointCorruptionError- from cubepi.checkpointer.postgres import PostgresCheckpointer- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.checkpointer.exceptions import CheckpointCorruptionError+ from cubeloop.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.providers.base import TextContent, UserMessageawait _setup_schema(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -401,7 +481,7 @@ async def test_postgres_load_unknown_role_raises_typed(clean_db) -> None:conn = await asyncpg.connect(clean_db)try:await conn.execute(- "UPDATE cubepi_messages SET role = 'alien' WHERE thread_id = 't-role'"+ "UPDATE cubeloop_messages SET role = 'alien' WHERE thread_id = 't-role'")finally:await conn.close()@@ -411,3 +491,85 @@ async def test_postgres_load_unknown_role_raises_typed(clean_db) -> None:assert isinstance(excinfo.value.__cause__, ValueError)assert "alien" in str(excinfo.value)+++async def test_unmigrated_v5_raises_mismatch_not_uninitialized(clean_db) -> None:+ from cubeloop.checkpointer.postgres import (+ CubeloopSchemaMismatch,+ PostgresCheckpointer,+ )++ await _setup_schema_v5(clean_db)+ with pytest.raises(CubeloopSchemaMismatch) as ei:+ async with PostgresCheckpointer(clean_db):+ pass+ assert ei.value.expected == 6+ assert ei.value.actual == 5+ assert "upgrade_v5_to_v6_op" in str(ei.value)+++async def test_v5_to_v6_rename_then_round_trip(clean_db) -> None:+ from cubeloop.checkpointer.postgres.alembic_helpers import (+ upgrade_v5_to_v6_op,+ write_schema_version_op,+ )+ from cubeloop.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.providers.base import TextContent, UserMessage++ await _setup_schema_v5(clean_db)+ conn = await asyncpg.connect(clean_db)+ try:+ await conn.execute(upgrade_v5_to_v6_op())+ await conn.execute(write_schema_version_op())+ # Idempotent on complete v6.+ await conn.execute(upgrade_v5_to_v6_op())+ names = {+ r["table_name"]+ for r in await conn.fetch(+ "SELECT table_name FROM information_schema.tables "+ "WHERE table_schema = 'public'"+ )+ }+ assert "cubeloop_threads" in names+ assert "cubeloop_messages" in names+ assert "cubeloop_runs" in names+ assert "cubeloop_hitl_answers" in names+ assert "cubeloop_schema_version" in names+ assert "cubepi_threads" not in names+ finally:+ await conn.close()++ async with PostgresCheckpointer(clean_db) as cp:+ await cp.append("t-mig", [UserMessage(content=[TextContent(text="hi")])])+ data = await cp.load("t-mig")+ assert data is not None+ assert len(data.messages) == 1+++async def test_data_tables_without_version_table_are_not_uninitialized(+ clean_db,+) -> None:+ from cubeloop.checkpointer.postgres import (+ CubeloopSchemaMismatch,+ CubeloopSchemaUninitialized,+ PostgresCheckpointer,+ )++ conn = await asyncpg.connect(clean_db)+ try:+ await conn.execute("CREATE TABLE cubepi_threads (thread_id TEXT PRIMARY KEY)")+ finally:+ await conn.close()++ with pytest.raises(CubeloopSchemaMismatch) as ei:+ async with PostgresCheckpointer(clean_db):+ pass+ assert ei.value.actual == 0+ with pytest.raises(CubeloopSchemaMismatch):+ async with PostgresCheckpointer(clean_db):+ pass+ assert "Uninitialized" not in type(ei.value).__name__+ assert not isinstance(ei.value, CubeloopSchemaUninitialized)diff --git a/tests/checkpointer/test_postgres_fork.py b/tests/checkpointer/test_postgres_fork.pyindex e3003bf..c0882c6 100644--- a/tests/checkpointer/test_postgres_fork.py+++ b/tests/checkpointer/test_postgres_fork.py@@ -6,13 +6,13 @@ import asyncioimport pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunNotCompletedError,ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.providers.base import TextContent, UserMessagedef _msg(run_id: str | None, text: str) -> UserMessage:diff --git a/tests/checkpointer/test_postgres_pending_request.py b/tests/checkpointer/test_postgres_pending_request.pyindex 12b610b..66eb0c6 100644--- a/tests/checkpointer/test_postgres_pending_request.py+++ b/tests/checkpointer/test_postgres_pending_request.py@@ -1,58 +1,9 @@import asyncpgimport pytest-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.checkpointer.postgres.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,- create_message_partitions_op,- write_schema_version_op,-)-from cubepi.hitl.types import ApproveRequest, HitlRequest---async def _setup_schema_v2(dsn: str) -> None:- """Bootstrap the current cubepi schema in a fresh DB (now v3; legacy name kept).-- Adds both the v2 pending_request column and the v3 run_id column so the- HITL pending tests can exercise save_pending_request(... run_id=...)."""- conn = await asyncpg.connect(dsn)- try:- await conn.execute("""- CREATE TABLE cubepi_threads (- thread_id TEXT PRIMARY KEY,- parent_thread_id TEXT NULL REFERENCES cubepi_threads(thread_id),- forked_at_seq BIGINT NULL,- extra JSONB NOT NULL DEFAULT '{}'::jsonb,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()- );- """)- # v2 + v3 column adds- await conn.execute(add_pending_request_column_op())- await conn.execute(add_run_id_column_op())- 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()+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.hitl.types import ApproveRequest, HitlRequest+from tests.checkpointer.test_postgres import _setup_schema as _setup_schema_v2def _req(qid="tc-1") -> HitlRequest:@@ -100,7 +51,7 @@ async def test_postgres_pending_request_creates_thread_row_lazily(clean_db) -> Nasync def test_postgres_v2_schema_version_enforced(clean_db) -> None:"""If the host's alembic only ran v1 (no pending_request column, schema_version=1),PostgresCheckpointer().__aenter__ raises CubepiSchemaMismatch."""- from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch+ from cubeloop.checkpointer.postgres.exceptions import CubeloopSchemaMismatchconn = await asyncpg.connect(clean_db)try:@@ -110,6 +61,6 @@ async def test_postgres_v2_schema_version_enforced(clean_db) -> None:await conn.execute("INSERT INTO cubepi_schema_version (version) VALUES (1);")finally:await conn.close()- with pytest.raises(CubepiSchemaMismatch):+ with pytest.raises(CubeloopSchemaMismatch):async with PostgresCheckpointer(clean_db):passdiff --git a/tests/checkpointer/test_postgres_runs.py b/tests/checkpointer/test_postgres_runs.pyindex 9d9c31a..2071d01 100644--- a/tests/checkpointer/test_postgres_runs.py+++ b/tests/checkpointer/test_postgres_runs.py@@ -3,13 +3,13 @@import asyncpgimport pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,)-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.providers.base import TextContent, UserMessage@pytest.mark.asyncio@@ -19,12 +19,12 @@ async def test_claim_run_creates_threads_row_lazily(pg_v4_dsn):conn = await asyncpg.connect(pg_v4_dsn)try:row = await conn.fetchrow(- "SELECT thread_id FROM cubepi_threads WHERE thread_id = $1",+ "SELECT thread_id FROM cubeloop_threads WHERE thread_id = $1","t-lazy",)assert row is not Nonerun = await conn.fetchrow(- "SELECT completed_at FROM cubepi_runs WHERE thread_id = $1 AND run_id = $2",+ "SELECT completed_at FROM cubeloop_runs WHERE thread_id = $1 AND run_id = $2","t-lazy","r1",)@@ -86,7 +86,7 @@ async def test_completion_seq_monotonic_per_thread(pg_v4_dsn):conn = await asyncpg.connect(pg_v4_dsn)try:rows = await conn.fetch(- "SELECT run_id, completion_seq FROM cubepi_runs "+ "SELECT run_id, completion_seq FROM cubeloop_runs ""WHERE thread_id = $1 ORDER BY completion_seq","t",)@@ -100,7 +100,7 @@ async def test_completion_seq_monotonic_per_thread(pg_v4_dsn):@pytest.mark.asyncioasync def test_load_pending_returns_tuple_with_run_id(pg_v4_dsn):- from cubepi.hitl.types import ConfirmRequest, HitlRequest+ from cubeloop.hitl.types import ConfirmRequest, HitlRequestasync with PostgresCheckpointer(pg_v4_dsn) as cp:req = HitlRequest(@@ -132,7 +132,7 @@ async def test_append_persists_run_id_into_column(pg_v4_dsn):conn = await asyncpg.connect(pg_v4_dsn)try:row = await conn.fetchrow(- "SELECT run_id FROM cubepi_messages WHERE thread_id = $1",+ "SELECT run_id FROM cubeloop_messages WHERE thread_id = $1","t",)assert row is not Nonediff --git a/tests/checkpointer/test_postgres_schema.py b/tests/checkpointer/test_postgres_schema.pyindex a9376b4..9a5f454 100644--- a/tests/checkpointer/test_postgres_schema.py+++ b/tests/checkpointer/test_postgres_schema.py@@ -1,24 +1,25 @@import asyncpgimport pytest-from cubepi.checkpointer.postgres.checkpointer import _schema_mismatch_hint-from cubepi.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.postgres.checkpointer import _schema_mismatch_hint+from cubeloop.checkpointer.postgres.models import EXPECTED_SCHEMA_VERSION-def test_expected_schema_version_is_5():- assert EXPECTED_SCHEMA_VERSION == 5+def test_expected_schema_version_is_6():+ assert EXPECTED_SCHEMA_VERSION == 6-def test_schema_mismatch_hint_names_the_v4_to_v5_helper():- hint = _schema_mismatch_hint(actual=4, expected=5)- assert "upgrade_v4_to_v5_op()" in hint+def test_schema_mismatch_hint_names_the_v5_to_v6_helper():+ hint = _schema_mismatch_hint(actual=5, expected=6)+ assert "upgrade_v5_to_v6_op()" in hintassert "add_run_id_column_op" not in hintdef test_schema_mismatch_hint_names_every_step_across_multiple_versions():- hint = _schema_mismatch_hint(actual=3, expected=5)+ hint = _schema_mismatch_hint(actual=3, expected=6)assert "upgrade_v3_to_v4_op()" in hintassert "upgrade_v4_to_v5_op()" in hint+ assert "upgrade_v5_to_v6_op()" in hint@pytest.mark.asyncio@@ -27,7 +28,7 @@ async def test_cubepi_runs_table_present(pg_v4_dsn):try:rows = await conn.fetch("SELECT column_name FROM information_schema.columns "- "WHERE table_name = 'cubepi_runs'"+ "WHERE table_name = 'cubeloop_runs'")cols = {r["column_name"] for r in rows}assert {@@ -47,7 +48,7 @@ async def test_cubepi_messages_has_run_id_column(pg_v4_dsn):try:row = await conn.fetchrow("SELECT data_type FROM information_schema.columns "- "WHERE table_name = 'cubepi_messages' AND column_name = 'run_id'"+ "WHERE table_name = 'cubeloop_messages' AND column_name = 'run_id'")assert row is not Nonefinally:@@ -60,7 +61,7 @@ async def test_cubepi_hitl_answers_table_present(pg_v4_dsn):try:rows = await conn.fetch("SELECT column_name FROM information_schema.columns "- "WHERE table_name = 'cubepi_hitl_answers'"+ "WHERE table_name = 'cubeloop_hitl_answers'")cols = {r["column_name"] for r in rows}assert {diff --git a/tests/checkpointer/test_postgres_schema_version_v3.py b/tests/checkpointer/test_postgres_schema_version_v3.pyindex 30a9d1a..223e691 100644--- a/tests/checkpointer/test_postgres_schema_version_v3.py+++ b/tests/checkpointer/test_postgres_schema_version_v3.py@@ -7,8 +7,8 @@ from __future__ import annotationsimport asyncpgimport pytest-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.checkpointer.postgres.exceptions import CubeloopSchemaMismatch@pytest.mark.asyncio@@ -22,12 +22,12 @@ async def test_postgres_v2_database_refused_with_actionable_error(clean_db) -> Nfinally:await conn.close()- with pytest.raises(CubepiSchemaMismatch) as ei:+ with pytest.raises(CubeloopSchemaMismatch) as ei:async with PostgresCheckpointer(clean_db):passmsg = str(ei.value)- assert "expected 5" in msg or "expected=5" in msg+ assert "expected 6" in msg or "expected=6" in msgassert "actual 2" in msg or "actual=2" in msg# Hint mentions the host alembic migration path so operators know what to do.assert "alembic" in msg.lower()@@ -38,10 +38,10 @@ async def test_mysql_v2_database_refused_with_actionable_error(clean_mysql_db) -"""Same policy for MySQL (parallel to the Postgres test above)."""import aiomysql- from cubepi.checkpointer.mysql import MySQLCheckpointer- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn- from cubepi.checkpointer.mysql.exceptions import (- CubepiSchemaMismatch as MysqlMismatch,+ from cubeloop.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.exceptions import (+ CubeloopSchemaMismatch as MysqlMismatch,)conn = await aiomysql.connect(autocommit=True, **_parse_dsn(clean_mysql_db))@@ -59,6 +59,6 @@ async def test_mysql_v2_database_refused_with_actionable_error(clean_mysql_db) -passmsg = str(ei.value)- assert "expected 5" in msg or "expected=5" in msg+ assert "expected 6" in msg or "expected=6" in msgassert "actual 2" in msg or "actual=2" in msgassert "alembic" in msg.lower()diff --git a/tests/checkpointer/test_save_pending_request_run_id.py b/tests/checkpointer/test_save_pending_request_run_id.pyindex bc764ec..bf9af8a 100644--- a/tests/checkpointer/test_save_pending_request_run_id.py+++ b/tests/checkpointer/test_save_pending_request_run_id.py@@ -14,9 +14,9 @@ from typing import Anyimport pytest-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.checkpointer.sqlite import SQLiteCheckpointer-from cubepi.hitl.types import ApproveRequest, HitlRequest+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.hitl.types import ApproveRequest, HitlRequestdef _req(thread_id: str = "t-1", qid: str = "tc-1") -> HitlRequest:@@ -137,9 +137,7 @@ async def _setup_pg_schema_v3(dsn: str) -> None:"""Bootstrap a v3 schema in a fresh Postgres DB."""import asyncpg- from cubepi.checkpointer.postgres.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,+ from cubeloop.checkpointer.postgres.alembic_helpers import (create_message_partitions_op,write_schema_version_op,)@@ -147,20 +145,20 @@ async def _setup_pg_schema_v3(dsn: str) -> None:conn = await asyncpg.connect(dsn)try:await conn.execute("""- CREATE TABLE cubepi_threads (+ CREATE TABLE cubeloop_threads (thread_id TEXT PRIMARY KEY,- parent_thread_id TEXT NULL REFERENCES cubepi_threads(thread_id),+ parent_thread_id TEXT NULL REFERENCES cubeloop_threads(thread_id),forked_at_seq BIGINT NULL,extra JSONB NOT NULL DEFAULT '{}'::jsonb,+ pending_request JSONB,+ run_id TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),updated_at TIMESTAMPTZ NOT NULL DEFAULT now());""")- await conn.execute(add_pending_request_column_op())- await conn.execute(add_run_id_column_op())await conn.execute("""- CREATE TABLE cubepi_messages (- thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) ON DELETE CASCADE,+ CREATE TABLE cubeloop_messages (+ thread_id TEXT NOT NULL REFERENCES cubeloop_threads(thread_id) ON DELETE CASCADE,seq BIGINT NOT NULL,role TEXT NOT NULL,metadata JSONB NOT NULL DEFAULT '{}'::jsonb,@@ -171,11 +169,11 @@ async def _setup_pg_schema_v3(dsn: str) -> None:""")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);+ CREATE INDEX ix_cubeloop_messages_metadata_gin+ ON cubeloop_messages USING GIN (metadata jsonb_path_ops);""")await conn.execute("""- CREATE TABLE cubepi_schema_version (version INTEGER PRIMARY KEY);+ CREATE TABLE cubeloop_schema_version (version INTEGER PRIMARY KEY);""")await conn.execute(write_schema_version_op())finally:@@ -184,7 +182,7 @@ async def _setup_pg_schema_v3(dsn: str) -> None:@pytest.mark.asyncioasync def test_postgres_save_with_run_id_roundtrip(clean_db) -> None:- from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.checkpointer.postgres import PostgresCheckpointerawait _setup_pg_schema_v3(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -195,7 +193,7 @@ async def test_postgres_save_with_run_id_roundtrip(clean_db) -> None:@pytest.mark.asyncioasync def test_postgres_legacy_save_without_run_id(clean_db) -> None:- from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.checkpointer.postgres import PostgresCheckpointerawait _setup_pg_schema_v3(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -205,7 +203,7 @@ async def test_postgres_legacy_save_without_run_id(clean_db) -> None:@pytest.mark.asyncioasync def test_postgres_clear_clears_both_pending_and_run_id(clean_db) -> None:- from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.checkpointer.postgres import PostgresCheckpointerawait _setup_pg_schema_v3(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -217,7 +215,7 @@ async def test_postgres_clear_clears_both_pending_and_run_id(clean_db) -> None:@pytest.mark.asyncioasync def test_postgres_load_pending_run_id_missing_thread(clean_db) -> None:- from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.checkpointer.postgres import PostgresCheckpointerawait _setup_pg_schema_v3(clean_db)async with PostgresCheckpointer(clean_db) as cp:@@ -230,35 +228,33 @@ async def test_postgres_load_pending_run_id_missing_thread(clean_db) -> None:async def _setup_mysql_schema_v3(dsn: str) -> None:import aiomysql- from cubepi.checkpointer.mysql.alembic_helpers import (- add_pending_request_column_op,- add_run_id_column_op,+ from cubeloop.checkpointer.mysql.alembic_helpers import (messages_partition_clause,write_schema_version_op,)- from cubepi.checkpointer.mysql.checkpointer import _parse_dsn+ from cubeloop.checkpointer.mysql.checkpointer import _parse_dsnconn = await aiomysql.connect(autocommit=True, **_parse_dsn(dsn))try:async with conn.cursor() as cur:await cur.execute("""- CREATE TABLE cubepi_threads (+ CREATE TABLE cubeloop_threads (thread_id VARCHAR(255) COLLATE utf8mb4_bin PRIMARY KEY,parent_thread_id VARCHAR(255) COLLATE utf8mb4_bin NULL,forked_at_seq BIGINT NULL,extra JSON NOT NULL DEFAULT (JSON_OBJECT()),+ pending_request JSON NULL,+ run_id VARCHAR(64) NULL,created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMPON UPDATE CURRENT_TIMESTAMP,CONSTRAINT fk_parent FOREIGN KEY (parent_thread_id)- REFERENCES cubepi_threads (thread_id)+ REFERENCES cubeloop_threads (thread_id)) ENGINE=InnoDB""")- await cur.execute(add_pending_request_column_op())- await cur.execute(add_run_id_column_op())await cur.execute("""- CREATE TABLE cubepi_messages (+ CREATE TABLE cubeloop_messages (thread_id VARCHAR(255) COLLATE utf8mb4_bin NOT NULL,seq BIGINT NOT NULL,role VARCHAR(32) NOT NULL,@@ -270,7 +266,7 @@ async def _setup_mysql_schema_v3(dsn: str) -> None:+ messages_partition_clause())await cur.execute("""- CREATE TABLE cubepi_schema_version (+ CREATE TABLE cubeloop_schema_version (version INT PRIMARY KEY) ENGINE=InnoDB""")@@ -283,7 +279,7 @@ async def _setup_mysql_schema_v3(dsn: str) -> None:@pytest.mark.asyncioasync def test_mysql_save_with_run_id_roundtrip(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql import MySQLCheckpointerawait _setup_mysql_schema_v3(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -294,7 +290,7 @@ async def test_mysql_save_with_run_id_roundtrip(clean_mysql_db) -> None:@pytest.mark.asyncioasync def test_mysql_legacy_save_without_run_id(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql import MySQLCheckpointerawait _setup_mysql_schema_v3(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -304,7 +300,7 @@ async def test_mysql_legacy_save_without_run_id(clean_mysql_db) -> None:@pytest.mark.asyncioasync def test_mysql_clear_clears_both_pending_and_run_id(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql import MySQLCheckpointerawait _setup_mysql_schema_v3(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:@@ -316,7 +312,7 @@ async def test_mysql_clear_clears_both_pending_and_run_id(clean_mysql_db) -> Non@pytest.mark.asyncioasync def test_mysql_load_pending_run_id_missing_thread(clean_mysql_db) -> None:- from cubepi.checkpointer.mysql import MySQLCheckpointer+ from cubeloop.checkpointer.mysql import MySQLCheckpointerawait _setup_mysql_schema_v3(clean_mysql_db)async with MySQLCheckpointer(clean_mysql_db) as cp:diff --git a/tests/checkpointer/test_sqlite.py b/tests/checkpointer/test_sqlite.pyindex a271480..7af78ce 100644--- a/tests/checkpointer/test_sqlite.py+++ b/tests/checkpointer/test_sqlite.py@@ -3,8 +3,8 @@ import tempfileimport pytest-from cubepi.checkpointer.sqlite import SQLiteCheckpointer-from cubepi.providers.base import TextContent, ToolResultMessage, UserMessage+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.providers.base import TextContent, ToolResultMessage, UserMessage@pytest.fixture@@ -104,7 +104,7 @@ class TestSQLiteCheckpointer:"""Unknown roles are corruption, matching the postgres/mysqlbackends — the old silent raw-dict passthrough let bad data flowinto the message list and fail far from the cause."""- from cubepi.checkpointer.exceptions import CheckpointCorruptionError+ from cubeloop.checkpointer.exceptions import CheckpointCorruptionErrorasync with SQLiteCheckpointer(db_path) as cp:raw_msg = {"role": "custom", "data": "test"}@@ -116,7 +116,7 @@ class TestSQLiteCheckpointer:class TestCheckpointCorruption:async def test_corrupt_json_row_raises_typed(self, db_path):- from cubepi.checkpointer.exceptions import CheckpointCorruptionError+ from cubeloop.checkpointer.exceptions import CheckpointCorruptionErrorasync with SQLiteCheckpointer(db_path) as cp:await cp.append(@@ -143,7 +143,7 @@ class TestCheckpointCorruption:assert err.__cause__ is not Noneasync def test_unknown_role_raises_typed(self, db_path):- from cubepi.checkpointer.exceptions import CheckpointCorruptionError+ from cubeloop.checkpointer.exceptions import CheckpointCorruptionErrorasync with SQLiteCheckpointer(db_path) as cp:await cp.append("thread-1", [UserMessage(content=[TextContent(text="ok")])])diff --git a/tests/checkpointer/test_sqlite_concurrency.py b/tests/checkpointer/test_sqlite_concurrency.pyindex 6a8fbaa..b70f86f 100644--- a/tests/checkpointer/test_sqlite_concurrency.py+++ b/tests/checkpointer/test_sqlite_concurrency.py@@ -4,9 +4,9 @@ from pathlib import Pathimport aiosqliteimport pytest-from cubepi.checkpointer.exceptions import CheckpointerLockTimeoutError-from cubepi.checkpointer.sqlite import SQLiteCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.exceptions import CheckpointerLockTimeoutError+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.providers.base import TextContent, UserMessage@pytest.mark.asynciodiff --git a/tests/checkpointer/test_sqlite_fork.py b/tests/checkpointer/test_sqlite_fork.pyindex 6a38d01..96206ce 100644--- a/tests/checkpointer/test_sqlite_fork.py+++ b/tests/checkpointer/test_sqlite_fork.py@@ -3,13 +3,13 @@ from pathlib import Pathimport pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunNotCompletedError,ThreadAlreadyExistsError,ThreadNotFoundError,)-from cubepi.checkpointer.sqlite import SQLiteCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.providers.base import TextContent, UserMessagedef _msg(run_id: str | None, text: str) -> UserMessage:diff --git a/tests/checkpointer/test_sqlite_runs.py b/tests/checkpointer/test_sqlite_runs.pyindex 6e5e4fc..7425d9b 100644--- a/tests/checkpointer/test_sqlite_runs.py+++ b/tests/checkpointer/test_sqlite_runs.py@@ -3,13 +3,13 @@ from pathlib import Pathimport pytest-from cubepi.checkpointer.exceptions import (+from cubeloop.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,RunNotClaimedError,)-from cubepi.checkpointer.sqlite import SQLiteCheckpointer-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.providers.base import TextContent, UserMessage@pytest.mark.asyncio@@ -92,7 +92,7 @@ async def test_append_in_flight_run_id_ok():@pytest.mark.asyncioasync def test_load_pending_returns_tuple_with_run_id():- from cubepi.hitl.types import ConfirmRequest, HitlRequest+ from cubeloop.hitl.types import ConfirmRequest, HitlRequestwith tempfile.TemporaryDirectory() as d:async with SQLiteCheckpointer(str(Path(d) / "x.db")) as cp:diff --git a/tests/checkpointer/test_sqlite_schema.py b/tests/checkpointer/test_sqlite_schema.pyindex d4a4a7a..4a935d0 100644--- a/tests/checkpointer/test_sqlite_schema.py+++ b/tests/checkpointer/test_sqlite_schema.py@@ -3,7 +3,7 @@ from pathlib import Pathimport pytest-from cubepi.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer@pytest.mark.asynciodiff --git a/tests/cli/test_entrypoint.py b/tests/cli/test_entrypoint.pyindex bee39e6..884dff8 100644--- a/tests/cli/test_entrypoint.py+++ b/tests/cli/test_entrypoint.py@@ -6,7 +6,7 @@ import sysdef _run(*args: str) -> subprocess.CompletedProcess[str]:return subprocess.run(- [sys.executable, "-m", "cubepi.cli", *args],+ [sys.executable, "-m", "cubeloop.cli", *args],capture_output=True,text=True,)diff --git a/tests/cli/trace/test_commands.py b/tests/cli/trace/test_commands.pyindex b595e64..59b8398 100644--- a/tests/cli/trace/test_commands.py+++ b/tests/cli/trace/test_commands.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path-from cubepi.cli.__main__ import main+from cubeloop.cli.__main__ import maindef _write_run(directory: Path):diff --git a/tests/cli/trace/test_convert.py b/tests/cli/trace/test_convert.pyindex 503fc7f..81e9f15 100644--- a/tests/cli/trace/test_convert.py+++ b/tests/cli/trace/test_convert.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path-from cubepi.cli.__main__ import main+from cubeloop.cli.__main__ import main# ---------------------------------------------------------------------------@@ -415,14 +415,14 @@ class TestConvertErrors:class TestMessagesToOpenAI:def test_user_message(self):- from cubepi.cli.trace.convert import messages_to_openai+ from cubeloop.cli.trace.convert import messages_to_openaimsgs = [{"role": "user", "parts": [{"type": "text", "content": "hi"}]}]out = messages_to_openai(msgs)assert out == [{"role": "user", "content": "hi"}]def test_assistant_text(self):- from cubepi.cli.trace.convert import messages_to_openai+ from cubeloop.cli.trace.convert import messages_to_openaimsgs = [{"role": "assistant", "parts": [{"type": "text", "content": "hello"}]}]out = messages_to_openai(msgs)@@ -431,7 +431,7 @@ class TestMessagesToOpenAI:assert out[0]["content"] == "hello"def test_assistant_tool_call(self):- from cubepi.cli.trace.convert import messages_to_openai+ from cubeloop.cli.trace.convert import messages_to_openaimsgs = [{@@ -454,7 +454,7 @@ class TestMessagesToOpenAI:assert parsed == {"x": 1}def test_tool_result(self):- from cubepi.cli.trace.convert import messages_to_openai+ from cubeloop.cli.trace.convert import messages_to_openaimsgs = [{@@ -466,7 +466,7 @@ class TestMessagesToOpenAI:assert out == [{"role": "tool", "tool_call_id": "c1", "content": "ok"}]def test_unknown_role_skipped(self):- from cubepi.cli.trace.convert import messages_to_openai+ from cubeloop.cli.trace.convert import messages_to_openaimsgs = [{"role": "system", "parts": [{"type": "text", "content": "x"}]}]out = messages_to_openai(msgs)@@ -475,7 +475,7 @@ class TestMessagesToOpenAI:class TestMessagesToAnthropic:def test_user_message(self):- from cubepi.cli.trace.convert import messages_to_anthropic+ from cubeloop.cli.trace.convert import messages_to_anthropicmsgs = [{"role": "user", "parts": [{"type": "text", "content": "hi"}]}]out = messages_to_anthropic(msgs)@@ -483,7 +483,7 @@ class TestMessagesToAnthropic:assert out[0]["content"][0]["text"] == "hi"def test_tool_result_batched_into_user_message(self):- from cubepi.cli.trace.convert import messages_to_anthropic+ from cubeloop.cli.trace.convert import messages_to_anthropicmsgs = [{@@ -504,7 +504,7 @@ class TestMessagesToAnthropic:assert tool_resultsdef test_assistant_tool_use_block(self):- from cubepi.cli.trace.convert import messages_to_anthropic+ from cubeloop.cli.trace.convert import messages_to_anthropicmsgs = [{@@ -526,7 +526,7 @@ class TestMessagesToAnthropic:assert blocks[0]["input"] == {"a": 1}def test_trailing_tool_results_flushed(self):- from cubepi.cli.trace.convert import messages_to_anthropic+ from cubeloop.cli.trace.convert import messages_to_anthropicmsgs = [{diff --git a/tests/cli/trace/test_follow.py b/tests/cli/trace/test_follow.pyindex 5e04d32..6bec750 100644--- a/tests/cli/trace/test_follow.py+++ b/tests/cli/trace/test_follow.py@@ -2,8 +2,8 @@ from __future__ import annotationsimport json-from cubepi.cli.trace.follow import format_event, is_run_complete, iter_new_spans-from cubepi.cli.trace.model import Span+from cubeloop.cli.trace.follow import format_event, is_run_complete, iter_new_spans+from cubeloop.cli.trace.model import Spandef _line(span_id, parent_id, name):diff --git a/tests/cli/trace/test_loader.py b/tests/cli/trace/test_loader.pyindex 5aeb793..ed2c891 100644--- a/tests/cli/trace/test_loader.py+++ b/tests/cli/trace/test_loader.py@@ -5,7 +5,7 @@ from pathlib import Pathimport pytest-from cubepi.cli.trace.loader import (+from cubeloop.cli.trace.loader import (RunResolutionError,list_runs,load_run,@@ -267,8 +267,8 @@ def test_run_prompt_prefers_root_over_subagent_invoke_agent():# the ROOT (parent-less) invoke_agent, not a subagent's. The subagent span# is placed FIRST in the list so this distinguishes the parent-less filter# from plain iteration order (which would otherwise pick the subagent).- from cubepi.cli.trace.loader import _run_prompt- from cubepi.cli.trace.model import Span+ from cubeloop.cli.trace.loader import _run_prompt+ from cubeloop.cli.trace.model import Spansub = Span(_span(@@ -362,8 +362,8 @@ def test_list_runs_filters_by_meta(tmp_path):def test_filter_spans_by_meta():- from cubepi.cli.trace.loader import filter_spans_by_meta- from cubepi.cli.trace.model import Span+ from cubeloop.cli.trace.loader import filter_spans_by_meta+ from cubeloop.cli.trace.model import Spandef sp(trace_id, span_id, parent, name, **attrs):return Span(diff --git a/tests/cli/trace/test_model.py b/tests/cli/trace/test_model.pyindex 0f0a733..394478d 100644--- a/tests/cli/trace/test_model.py+++ b/tests/cli/trace/test_model.py@@ -1,6 +1,6 @@from __future__ import annotations-from cubepi.cli.trace.model import Span, build_forest+from cubeloop.cli.trace.model import Span, build_forestdef _raw(span_id, parent_id, name, start, end=None, status="UNSET", attrs=None):diff --git a/tests/cli/trace/test_render.py b/tests/cli/trace/test_render.pyindex 2fd37fd..233b91a 100644--- a/tests/cli/trace/test_render.py+++ b/tests/cli/trace/test_render.py@@ -2,9 +2,9 @@ from __future__ import annotationsfrom pathlib import Path-from cubepi.cli.trace.loader import RunSummary-from cubepi.cli.trace.model import Span, build_forest-from cubepi.cli.trace.render import render_runs, render_tree_to_text+from cubeloop.cli.trace.loader import RunSummary+from cubeloop.cli.trace.model import Span, build_forest+from cubeloop.cli.trace.render import render_runs, render_tree_to_textdef _raw(diff --git a/tests/cli/trace/test_schema_roundtrip.py b/tests/cli/trace/test_schema_roundtrip.pyindex c2cba4e..e6eecf0 100644--- a/tests/cli/trace/test_schema_roundtrip.py+++ b/tests/cli/trace/test_schema_roundtrip.py@@ -8,22 +8,22 @@ pytest.importorskip("opentelemetry.sdk.trace")from opentelemetry.sdk.trace import TracerProvider # noqa: E402-from cubepi.cli.trace.loader import load_run # noqa: E402-from cubepi.cli.trace.model import build_forest # noqa: E402-from cubepi.tracing.exporters import JsonlSpanExporter # noqa: E402-from cubepi.tracing.schema import CUBEPI_RUN_ID # noqa: E402+from cubeloop.cli.trace.loader import load_run # noqa: E402+from cubeloop.cli.trace.model import build_forest # noqa: E402+from cubeloop.tracing.exporters import JsonlSpanExporter # noqa: E402+from cubeloop.tracing.schema import CUBELOOP_RUN_ID # noqa: E402def test_real_exporter_output_parses(tmp_path):exporter = JsonlSpanExporter(directory=tmp_path)provider = TracerProvider()- tracer = provider.get_tracer("cubepi.tracing")+ tracer = provider.get_tracer("cubeloop.tracing")# After the `with` blocks exit the spans have ended; the span objects are# ReadableSpans, so we can hand them straight to the exporter.with tracer.start_as_current_span("invoke_agent") as root:- root.set_attribute(CUBEPI_RUN_ID, "roundtrip")+ root.set_attribute(CUBELOOP_RUN_ID, "roundtrip")with tracer.start_as_current_span("chat") as chat:- chat.set_attribute(CUBEPI_RUN_ID, "roundtrip")+ chat.set_attribute(CUBELOOP_RUN_ID, "roundtrip")exporter.export([root, chat])# One file per trace; stem is the 32-hex trace_id, not the run_id.diff --git a/tests/cli/trace/test_stats.py b/tests/cli/trace/test_stats.pyindex f7ffcf7..8587fcb 100644--- a/tests/cli/trace/test_stats.py+++ b/tests/cli/trace/test_stats.py@@ -1,7 +1,7 @@from __future__ import annotations-from cubepi.cli.trace.model import Span-from cubepi.cli.trace.stats import aggregate+from cubeloop.cli.trace.model import Span+from cubeloop.cli.trace.stats import aggregatedef _chat(model, in_tok, out_tok, dur_ms, error=False):diff --git a/tests/compat/test_cubepi_shim.py b/tests/compat/test_cubepi_shim.pynew file mode 100644index 0000000..be1ab3d--- /dev/null+++ b/tests/compat/test_cubepi_shim.py@@ -0,0 +1,85 @@+"""Transitional cubepi shim — import alias, warning, lazy tracing."""++from __future__ import annotations++import subprocess+import sys+import warnings++import pytest+++def test_import_cubepi_warns_and_reexports() -> None:+ import cubeloop++ with warnings.catch_warnings(record=True) as caught:+ warnings.simplefilter("always")+ import cubepi+ assert cubepi.Agent is cubeloop.Agent+ assert any(issubclass(w.category, DeprecationWarning) for w in caught)+++def test_deep_import_aliases_provider() -> None:+ from cubepi.providers.anthropic import AnthropicProvider+ from cubeloop.providers.anthropic import AnthropicProvider as Direct++ assert AnthropicProvider is Direct+++def test_deep_import_checkpointer() -> None:+ from cubepi.checkpointer.postgres import PostgresCheckpointer+ from cubeloop.checkpointer.postgres import PostgresCheckpointer as Direct++ assert PostgresCheckpointer is Direct+++def test_tracing_schema_lazy_without_otel() -> None:+ code = (+ "import builtins, sys\n"+ "real_import = builtins.__import__\n"+ "def fake(name, *a, **k):\n"+ " if name == 'opentelemetry' or name.startswith('opentelemetry.'):\n"+ " raise ImportError('hidden')\n"+ " return real_import(name, *a, **k)\n"+ "builtins.__import__ = fake\n"+ "from cubepi.tracing import schema\n"+ "assert schema.CUBELOOP_RUN_ID == 'cubeloop.run_id'\n"+ "print('ok')\n"+ )+ result = subprocess.run(+ [sys.executable, "-c", code], capture_output=True, text=True+ )+ assert result.returncode == 0, result.stderr+ assert "ok" in result.stdout+++def test_python_m_cubepi_trace_help() -> None:+ result = subprocess.run(+ [sys.executable, "-m", "cubepi", "trace", "--help"],+ capture_output=True,+ text=True,+ )+ assert result.returncode == 0, result.stderr+ assert "renamed to 'cubeloop'" in result.stderr+ assert "trace" in result.stdout+++def test_python_m_cubepi_cli_help() -> None:+ result = subprocess.run(+ [sys.executable, "-m", "cubepi.cli", "--help"],+ capture_output=True,+ text=True,+ )+ assert result.returncode == 0, result.stderr+ assert "trace" in result.stdout+++def test_second_import_does_not_reprint(capsys: pytest.CaptureFixture[str]) -> None:+ import cubepi # noqa: F401++ capsys.readouterr()+ import importlib++ importlib.reload(cubepi)+ captured = capsys.readouterr()+ assert "renamed to 'cubeloop'" not in captured.errdiff --git a/tests/deferred/_helpers.py b/tests/deferred/_helpers.pyindex 59673e4..7e3773e 100644--- a/tests/deferred/_helpers.py+++ b/tests/deferred/_helpers.py@@ -6,9 +6,9 @@ from collections.abc import Callablefrom pydantic import BaseModel-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.deferred import DeferredToolGroup, DeferredToolsMiddleware-from cubepi.providers.base import TextContent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.deferred import DeferredToolGroup, DeferredToolsMiddleware+from cubeloop.providers.base import TextContentclass _Empty(BaseModel):@@ -76,7 +76,7 @@ def _mw(groups, *, strategy="dispatch", extra=None) -> DeferredToolsMiddleware:def _make_faux_model():"""Create a minimal BoundModel for Agent construction."""- from cubepi.providers.faux import FauxProvider+ from cubeloop.providers.faux import FauxProviderprovider = FauxProvider()return provider.model("faux")diff --git a/tests/deferred/test_agent_wiring.py b/tests/deferred/test_agent_wiring.pyindex ca74267..db42578 100644--- a/tests/deferred/test_agent_wiring.py+++ b/tests/deferred/test_agent_wiring.py@@ -2,9 +2,9 @@ from __future__ import annotationsfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.deferred import DeferredToolsMiddleware-from cubepi.middleware.base import Middleware+from cubeloop.agent.agent import Agent+from cubeloop.deferred import DeferredToolsMiddleware+from cubeloop.middleware.base import Middlewarefrom tests.deferred._helpers import _dummy_tool, _make_faux_model, _make_group@@ -108,7 +108,7 @@ class TestAgentDeferredToolGroups:async def test_on_tools_expanded_deduplicates(self) -> None:"""Pre-loaded tools from resume are not duplicated by on_tools_expanded."""- from cubepi.agent.types import AgentContext+ from cubeloop.agent.types import AgentContextmodel = _make_faux_model()t1 = _dummy_tool("t1")@@ -136,7 +136,7 @@ class TestAgentDeferredToolGroups:class TestForkOnceDeniesMiddlewareTools:def test_fork_keeps_load_tools_in_schema(self) -> None:"""load_tools stays in the tool list for prompt-cache parity."""- from cubepi.agent.agent import _deny_in_fork+ from cubeloop.agent.agent import _deny_in_forkmodel = _make_faux_model()group = _make_group("mcp:github", ["t1", "t2"])@@ -157,7 +157,7 @@ class TestForkOnceDeniesMiddlewareTools:async def test_fork_load_tools_returns_error(self) -> None:"""load_tools in fork returns is_error=True instead of executing."""- from cubepi.agent.agent import _deny_in_fork+ from cubeloop.agent.agent import _deny_in_forkmodel = _make_faux_model()group = _make_group("mcp:github", ["t1"])@@ -208,8 +208,8 @@ class TestExplicitResolverComposition:"""An explicit resolve_tool_call runs first but does NOT disable theauto-created deferred middleware's resolver (unlike other hooks,resolve_tool_call composes first-non-None)."""- from cubepi.agent.types import AgentContext- from cubepi.providers.base import ToolCall+ from cubeloop.agent.types import AgentContext+ from cubeloop.providers.base import ToolCallmodel = _make_faux_model()seen: list[str] = []@@ -239,8 +239,8 @@ class TestExplicitResolverComposition:assert seen == ["deferred_tool_call"] # explicit resolver ran firstasync def test_explicit_resolver_wins_when_it_rewrites(self) -> None:- from cubepi.agent.types import AgentContext- from cubepi.providers.base import ToolCall+ from cubeloop.agent.types import AgentContext+ from cubeloop.providers.base import ToolCallmodel = _make_faux_model()diff --git a/tests/deferred/test_catalog.py b/tests/deferred/test_catalog.pyindex f2a1d40..8662f6c 100644--- a/tests/deferred/test_catalog.py+++ b/tests/deferred/test_catalog.py@@ -1,7 +1,7 @@from __future__ import annotations-from cubepi.deferred._catalog import render_catalog, render_static_catalog-from cubepi.deferred.types import DeferredToolGroup+from cubeloop.deferred._catalog import render_catalog, render_static_catalog+from cubeloop.deferred.types import DeferredToolGroupclass TestDeferredToolGroup:diff --git a/tests/deferred/test_dispatch.py b/tests/deferred/test_dispatch.pyindex 44f78f1..8c90c6d 100644--- a/tests/deferred/test_dispatch.py+++ b/tests/deferred/test_dispatch.py@@ -5,9 +5,9 @@ import jsonfrom pydantic import BaseModel-from cubepi.agent.types import AgentContext, AgentTool, AgentToolResult-from cubepi.providers.base import TextContent, ToolCall-from cubepi.deferred import DeferredToolGroup, DeferredToolsMiddleware+from cubeloop.agent.types import AgentContext, AgentTool, AgentToolResult+from cubeloop.providers.base import TextContent, ToolCall+from cubeloop.deferred import DeferredToolGroup, DeferredToolsMiddlewarefrom tests.deferred._helpers import _dummy_tool, _echo_tool, _mwfrom tests.deferred._helpers import _make_group as _make_group_base@@ -120,8 +120,8 @@ class TestDispatchStrategy:async def test_direct_native_call_to_hidden_tool_executes(self) -> None:"""If the model hallucinates a direct tool_use with the real name,the engine resolves it from context.tools despite expose_to_model=False."""- from cubepi.agent.tools import execute_tool_calls- from cubepi.providers.faux import faux_assistant_message+ from cubeloop.agent.tools import execute_tool_calls+ from cubeloop.providers.faux import faux_assistant_messagemw = _mw([_make_group("g", ["t1"])])ctx = AgentContext(system_prompt="", messages=[], tools=list(mw.tools))@@ -191,7 +191,7 @@ class _CapturingFaux:"""FauxProvider subclass recording every request's (system_prompt, tools)."""def __new__(cls, **kwargs):- from cubepi.providers.faux import FauxProvider+ from cubeloop.providers.faux import FauxProviderclass _Capturing(FauxProvider):def __init__(self, **kw):@@ -228,8 +228,8 @@ class _CapturingFaux:class TestByteStability:async def test_prefix_static_across_load_and_dispatch(self) -> None:- from cubepi.agent.agent import Agent- from cubepi.providers.faux import faux_assistant_message, faux_tool_call+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.faux import faux_assistant_message, faux_tool_callprovider = _CapturingFaux()provider.set_responses(@@ -278,9 +278,9 @@ class TestDispatchFork:"""Forks forward the resolver, so deferred_tool_call works on toolsthe parent already loaded (regression guard: v1 forks could callexpanded tools natively)."""- from cubepi.agent.agent import Agent- from cubepi.checkpointer.memory import MemoryCheckpointer- from cubepi.providers.faux import (+ from cubeloop.agent.agent import Agent+ from cubeloop.checkpointer.memory import MemoryCheckpointer+ from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_tool_call,@@ -334,8 +334,8 @@ class TestCodexReviewFindings:parallel executor."""import asyncio as aio- from cubepi.agent.tools import execute_tool_calls- from cubepi.providers.faux import faux_assistant_message+ from cubeloop.agent.tools import execute_tool_calls+ from cubeloop.providers.faux import faux_assistant_messageorder: list[str] = []@@ -411,8 +411,8 @@ class TestCodexReviewFindings:assert seen == []async def test_implicit_load_failure_surfaces_loader_error(self) -> None:- from cubepi.agent.tools import execute_tool_calls- from cubepi.providers.faux import faux_assistant_message+ from cubeloop.agent.tools import execute_tool_calls+ from cubeloop.providers.faux import faux_assistant_messageasync def _failing_loader():raise RuntimeError("connection refused")@@ -448,8 +448,8 @@ class TestCodexReviewFindings:async def test_dispatcher_rejects_non_dict_arguments(self) -> None:"""Garbage inner arguments must hit the dispatcher's own schemavalidation, not be coerced to {} and silently run the tool."""- from cubepi.agent.tools import execute_tool_calls- from cubepi.providers.faux import faux_assistant_message+ from cubeloop.agent.tools import execute_tool_calls+ from cubeloop.providers.faux import faux_assistant_messagemw = _mw([_make_group("g", ["t1"])])ctx = AgentContext(system_prompt="", messages=[], tools=list(mw.tools))@@ -476,8 +476,8 @@ class TestSequentialOrderingPreserved:"""In a batch that is sequential by raw names, a later dispatchercall's loader must NOT run before an earlier sequential tool hasexecuted (the loader may depend on state that tool sets up)."""- from cubepi.agent.tools import execute_tool_calls- from cubepi.providers.faux import faux_assistant_message+ from cubeloop.agent.tools import execute_tool_calls+ from cubeloop.providers.faux import faux_assistant_messageclass _NoArgs(BaseModel):passdiff --git a/tests/deferred/test_expand_tool.py b/tests/deferred/test_expand_tool.pyindex 28a540b..376ec03 100644--- a/tests/deferred/test_expand_tool.py+++ b/tests/deferred/test_expand_tool.py@@ -1,12 +1,12 @@from __future__ import annotations-from cubepi.deferred._expand_tool import (+from cubeloop.deferred._expand_tool import (TOOL_NAME,LoadToolsInput,LoadToolsOutput,_make_load_tools,)-from cubepi.agent.types import AgentTool+from cubeloop.agent.types import AgentToolclass TestLoadToolsInput:diff --git a/tests/deferred/test_middleware.py b/tests/deferred/test_middleware.pyindex c56be86..13b60a4 100644--- a/tests/deferred/test_middleware.py+++ b/tests/deferred/test_middleware.py@@ -1,9 +1,9 @@from __future__ import annotations-from cubepi.agent.types import AgentContext, AgentTool, AgentToolResult-from cubepi.deferred.middleware import DeferredToolsMiddleware-from cubepi.deferred.types import DeferredToolGroup-from cubepi.providers.base import TextContent+from cubeloop.agent.types import AgentContext, AgentTool, AgentToolResult+from cubeloop.deferred.middleware import DeferredToolsMiddleware+from cubeloop.deferred.types import DeferredToolGroup+from cubeloop.providers.base import TextContentfrom tests.deferred._helpers import _dummy_tool, _make_group@@ -392,9 +392,9 @@ class TestAfterToolCallHook:"""Tests that exercise the after_tool_call hook directly (not via _expand)."""async def test_drains_pending_on_load_tools_call(self) -> None:- from cubepi.agent.types import AfterToolCallContext- from cubepi.deferred._expand_tool import TOOL_NAME- from cubepi.providers.base import AssistantMessage, ToolCall+ from cubeloop.agent.types import AfterToolCallContext+ from cubeloop.deferred._expand_tool import TOOL_NAME+ from cubeloop.providers.base import AssistantMessage, ToolCallextra: dict = {}group = _make_group("mcp:github", ["t1", "t2"])@@ -424,8 +424,8 @@ class TestAfterToolCallHook:assert len(mw._pending_injection) == 0async def test_skips_non_load_tools_call(self) -> None:- from cubepi.agent.types import AfterToolCallContext- from cubepi.providers.base import AssistantMessage, ToolCall+ from cubeloop.agent.types import AfterToolCallContext+ from cubeloop.providers.base import AssistantMessage, ToolCallextra: dict = {}group = _make_group("mcp:github", ["t1"])@@ -450,9 +450,9 @@ class TestAfterToolCallHook:assert len(mw._pending_injection) == 1 # not drainedasync def test_skips_error_result(self) -> None:- from cubepi.agent.types import AfterToolCallContext- from cubepi.deferred._expand_tool import TOOL_NAME- from cubepi.providers.base import AssistantMessage, ToolCall+ from cubeloop.agent.types import AfterToolCallContext+ from cubeloop.deferred._expand_tool import TOOL_NAME+ from cubeloop.providers.base import AssistantMessage, ToolCallextra: dict = {}group = _make_group("mcp:github", ["t1"])diff --git a/tests/e2e/test_fork_concurrency_pg.py b/tests/e2e/test_fork_concurrency_pg.pyindex 9085e85..c430070 100644--- a/tests/e2e/test_fork_concurrency_pg.py+++ b/tests/e2e/test_fork_concurrency_pg.py@@ -19,14 +19,14 @@ import asyncioimport pytest-from cubepi.agent.agent import Agent-from cubepi.checkpointer.exceptions import (+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.exceptions import (RunAlreadyClaimedError,RunAlreadyCompletedError,)-from cubepi.checkpointer.postgres.checkpointer import PostgresCheckpointer-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.checkpointer.postgres.checkpointer import PostgresCheckpointer+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import FauxProviderdef _ok_faux() -> FauxProvider:diff --git a/tests/e2e/test_fork_e2e.py b/tests/e2e/test_fork_e2e.pyindex 95a6ea2..154003c 100644--- a/tests/e2e/test_fork_e2e.py+++ b/tests/e2e/test_fork_e2e.py@@ -15,9 +15,9 @@ from __future__ import annotationsimport pytest-from cubepi.agent.agent import Agent-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.agent.agent import Agent+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import FauxProviderdef _ok_faux() -> FauxProvider:@@ -58,14 +58,14 @@ async def _run_happy_path(cp) -> None:@pytest.mark.asyncioasync def test_fork_e2e_memory():- from cubepi.checkpointer.memory import MemoryCheckpointer+ from cubeloop.checkpointer.memory import MemoryCheckpointerawait _run_happy_path(MemoryCheckpointer())@pytest.mark.asyncioasync def test_fork_e2e_sqlite(tmp_path):- from cubepi.checkpointer.sqlite import SQLiteCheckpointer+ from cubeloop.checkpointer.sqlite import SQLiteCheckpointerasync with SQLiteCheckpointer(str(tmp_path / "x.db")) as cp:await _run_happy_path(cp)@@ -73,7 +73,7 @@ async def test_fork_e2e_sqlite(tmp_path):@pytest.mark.asyncioasync def test_fork_e2e_postgres(pg_v4_dsn):- from cubepi.checkpointer.postgres.checkpointer import PostgresCheckpointer+ from cubeloop.checkpointer.postgres.checkpointer import PostgresCheckpointerasync with PostgresCheckpointer(pg_v4_dsn) as cp:await _run_happy_path(cp)@@ -81,7 +81,7 @@ async def test_fork_e2e_postgres(pg_v4_dsn):@pytest.mark.asyncioasync def test_fork_e2e_mysql(mysql_v4_dsn):- from cubepi.checkpointer.mysql.checkpointer import MySQLCheckpointer+ from cubeloop.checkpointer.mysql.checkpointer import MySQLCheckpointerasync with MySQLCheckpointer(mysql_v4_dsn) as cp:await _run_happy_path(cp)diff --git a/tests/e2e/test_fork_hitl_e2e.py b/tests/e2e/test_fork_hitl_e2e.pyindex a9f77fc..b047e77 100644--- a/tests/e2e/test_fork_hitl_e2e.py+++ b/tests/e2e/test_fork_hitl_e2e.py@@ -18,12 +18,12 @@ import asyncioimport pytest-from cubepi.agent.agent import Agent-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl.ask_user import ask_user_tool-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall-from cubepi.providers.faux import FauxProvider+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.ask_user import ask_user_tool+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.providers.faux import FauxProviderdef _ask_then_finish_provider() -> FauxProvider:diff --git a/tests/errors/test_classify_images.py b/tests/errors/test_classify_images.pyindex 21279a3..b599100 100644--- a/tests/errors/test_classify_images.py+++ b/tests/errors/test_classify_images.py@@ -1,6 +1,6 @@import pytest-from cubepi.errors import (+from cubeloop.errors import (ContextLengthExceeded,ProviderAuthFailed,ProviderBadRequest,@@ -8,7 +8,7 @@ from cubepi.errors import (RateLimited,classify_and_raise,)-from cubepi.providers.images.types import ImagesModel+from cubeloop.providers.images.types import ImagesModeldef _img_model() -> ImagesModel:@@ -73,7 +73,7 @@ def test_unknown_exception_falls_through_reraise():def test_chat_model_still_works():"""Widening must not break the existing chat-side call path."""- from cubepi.providers.base import Model+ from cubeloop.providers.base import Modelchat_model = Model(id="claude-sonnet-4-6", provider_id="anthropic", context_window=200_000diff --git a/tests/hitl/test_agent_abort_pending.py b/tests/hitl/test_agent_abort_pending.pyindex b0613ac..2d1e10d 100644--- a/tests/hitl/test_agent_abort_pending.py+++ b/tests/hitl/test_agent_abort_pending.py@@ -5,14 +5,14 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import AskUser-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware-from cubepi.providers.base import TextContent-from cubepi.providers.faux import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import AskUser+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware+from cubeloop.providers.base import TextContent+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_text,diff --git a/tests/hitl/test_agent_channel_wiring.py b/tests/hitl/test_agent_channel_wiring.pyindex 1e50683..0e40182 100644--- a/tests/hitl/test_agent_channel_wiring.py+++ b/tests/hitl/test_agent_channel_wiring.py@@ -1,8 +1,8 @@import pytest-from cubepi.agent.agent import Agent-from cubepi.hitl import HitlError-from cubepi.hitl.channel import InMemoryChannel-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.agent.agent import Agent+from cubeloop.hitl import HitlError+from cubeloop.hitl.channel import InMemoryChannel+from cubeloop.providers.faux import FauxProvider, faux_assistant_messagedef _agent(channel=None):diff --git a/tests/hitl/test_agent_respond.py b/tests/hitl/test_agent_respond.pyindex ff2d2b3..d82c208 100644--- a/tests/hitl/test_agent_respond.py+++ b/tests/hitl/test_agent_respond.py@@ -5,19 +5,19 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import (ApproveAnswer,AskUser,HitlNoPendingRequest,HitlStaleAnswer,)-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware-from cubepi.providers.base import TextContent-from cubepi.providers.faux import (+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware+from cubeloop.providers.base import TextContent+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_text,@@ -111,7 +111,7 @@ async def test_respond_stale_answer():thread_id="t-1",)# Manually persist a pending then try the wrong qid.- from cubepi.hitl.types import ApproveRequest, HitlRequest+ from cubeloop.hitl.types import ApproveRequest, HitlRequestawait cp.save_pending_request("t-1",diff --git a/tests/hitl/test_approval_policy_binding.py b/tests/hitl/test_approval_policy_binding.pyindex c7917f1..22b98cf 100644--- a/tests/hitl/test_approval_policy_binding.py+++ b/tests/hitl/test_approval_policy_binding.py@@ -1,7 +1,7 @@-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl.channel import CheckpointedChannel, InMemoryChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware, ConfirmToolCallMiddleware-from cubepi.hitl.policy import Approve+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.channel import CheckpointedChannel, InMemoryChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware, ConfirmToolCallMiddleware+from cubeloop.hitl.policy import Approvedef _approve_policy(ctx):diff --git a/tests/hitl/test_approval_policy_middleware.py b/tests/hitl/test_approval_policy_middleware.pyindex 2ee1fec..f73bf05 100644--- a/tests/hitl/test_approval_policy_middleware.py+++ b/tests/hitl/test_approval_policy_middleware.py@@ -1,10 +1,10 @@import asyncio-from cubepi.agent.types import AgentContext, BeforeToolCallContext-from cubepi.hitl import Approve, ApproveAnswer, AskUser, Deny-from cubepi.hitl.channel import InMemoryChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.agent.types import AgentContext, BeforeToolCallContext+from cubeloop.hitl import Approve, ApproveAnswer, AskUser, Deny+from cubeloop.hitl.channel import InMemoryChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCalldef _ctx(tool_call_id="tc-1") -> BeforeToolCallContext:diff --git a/tests/hitl/test_ask_user_binding.py b/tests/hitl/test_ask_user_binding.pyindex 6297a67..e1eba70 100644--- a/tests/hitl/test_ask_user_binding.py+++ b/tests/hitl/test_ask_user_binding.py@@ -1,6 +1,6 @@-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl.ask_user import ask_user_tool-from cubepi.hitl.channel import CheckpointedChannel, InMemoryChannel+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.ask_user import ask_user_tool+from cubeloop.hitl.channel import CheckpointedChannel, InMemoryChanneldef test_ask_user_tool_with_checkpointed_channel_sets_binding():diff --git a/tests/hitl/test_ask_user_tool.py b/tests/hitl/test_ask_user_tool.pyindex 1bb1d3e..1585429 100644--- a/tests/hitl/test_ask_user_tool.py+++ b/tests/hitl/test_ask_user_tool.py@@ -1,7 +1,7 @@import asyncio-from cubepi.hitl.ask_user import ask_user_tool-from cubepi.hitl.channel import InMemoryChannel+from cubeloop.hitl.ask_user import ask_user_tool+from cubeloop.hitl.channel import InMemoryChannelasync def test_ask_user_tool_is_sequential():diff --git a/tests/hitl/test_checkpointed_channel.py b/tests/hitl/test_checkpointed_channel.pyindex d48181b..076546c 100644--- a/tests/hitl/test_checkpointed_channel.py+++ b/tests/hitl/test_checkpointed_channel.py@@ -4,9 +4,9 @@ import asyncioimport pytest-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import ApproveAnswer, HitlDurabilityNotGuaranteed, HitlError-from cubepi.hitl.channel import CheckpointedChannel+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import ApproveAnswer, HitlDurabilityNotGuaranteed, HitlError+from cubeloop.hitl.channel import CheckpointedChannelasync def test_checkpointed_persists_pending_on_ask():@@ -28,7 +28,7 @@ async def test_checkpointed_persists_pending_on_ask():async def test_checkpointed_durability_guard_rejects_inside_custom_tool():- from cubepi.hitl.channel import _in_custom_tool_var+ from cubeloop.hitl.channel import _in_custom_tool_varcp = MemoryCheckpointer()ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")@@ -41,7 +41,7 @@ async def test_checkpointed_durability_guard_rejects_inside_custom_tool():async def test_checkpointed_durability_optin_allows():- from cubepi.hitl.channel import _in_custom_tool_var+ from cubeloop.hitl.channel import _in_custom_tool_varcp = MemoryCheckpointer()ch = CheckpointedChannel(@@ -73,12 +73,12 @@ async def test_detach_leaves_pending_persisted():while ch.pending is None:await asyncio.sleep(0)if ch._future is not None and not ch._future.done():- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedch._future.set_exception(HitlDetached())asyncio.create_task(detacher())- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedwith pytest.raises(HitlDetached):await ch.confirm("ok?")@@ -87,7 +87,7 @@ async def test_detach_leaves_pending_persisted():def test_checkpointed_channel_public_export():- from cubepi.hitl import CheckpointedChannel as Exported+ from cubeloop.hitl import CheckpointedChannel as Exportedassert Exported is CheckpointedChanneldiff --git a/tests/hitl/test_checkpointed_channel_run_id.py b/tests/hitl/test_checkpointed_channel_run_id.pyindex 28f5a92..88ec6c0 100644--- a/tests/hitl/test_checkpointed_channel_run_id.py+++ b/tests/hitl/test_checkpointed_channel_run_id.py@@ -14,10 +14,10 @@ import asyncioimport pytest-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import ApproveAnswer-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.hitl.types import Question+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import ApproveAnswer+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.hitl.types import Questionasync def test_run_id_persisted_on_approve():@@ -90,7 +90,7 @@ async def test_legacy_checkpointer_works_without_run_id_kwarg():keep working when the host constructs CheckpointedChannel WITHOUTa run_id — the channel must not unconditionally pass the new kwarg."""- from cubepi.hitl.types import HitlRequest+ from cubeloop.hitl.types import HitlRequestclass LegacyCheckpointer:"""Mimics a v2-era third-party checkpointer. save_pending_request@@ -150,13 +150,13 @@ async def test_run_id_cleared_on_detach_stays_persisted():async def detacher():while ch.pending is None:await asyncio.sleep(0)- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedif ch._future is not None and not ch._future.done():ch._future.set_exception(HitlDetached())asyncio.create_task(detacher())- from cubepi.hitl.exceptions import HitlDetached+ from cubeloop.hitl.exceptions import HitlDetachedwith pytest.raises(HitlDetached):await ch.confirm("ok?")diff --git a/tests/hitl/test_checkpointer_pending_request.py b/tests/hitl/test_checkpointer_pending_request.pyindex 38574b0..38216cd 100644--- a/tests/hitl/test_checkpointer_pending_request.py+++ b/tests/hitl/test_checkpointer_pending_request.py@@ -1,9 +1,9 @@import tempfileimport pytest-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.checkpointer.sqlite import SQLiteCheckpointer-from cubepi.hitl.types import ApproveRequest, HitlRequest+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.hitl.types import ApproveRequest, HitlRequestdef _req(thread_id="t-1", qid="q-1") -> HitlRequest:diff --git a/tests/hitl/test_compose_middleware.py b/tests/hitl/test_compose_middleware.pyindex f769352..ab0db70 100644--- a/tests/hitl/test_compose_middleware.py+++ b/tests/hitl/test_compose_middleware.py@@ -1,10 +1,10 @@-from cubepi.agent.types import (+from cubeloop.agent.types import (AgentContext,BeforeToolCallContext,BeforeToolCallResult,)-from cubepi.middleware.base import Middleware, compose_middleware-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.middleware.base import Middleware, compose_middleware+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCalldef _ctx(args: dict | None = None) -> BeforeToolCallContext:diff --git a/tests/hitl/test_confirm_tool_call_middleware.py b/tests/hitl/test_confirm_tool_call_middleware.pyindex 85e206f..dd89271 100644--- a/tests/hitl/test_confirm_tool_call_middleware.py+++ b/tests/hitl/test_confirm_tool_call_middleware.py@@ -1,10 +1,10 @@import asyncio-from cubepi.agent.types import AgentContext, BeforeToolCallContext-from cubepi.hitl import ApproveAnswer-from cubepi.hitl.channel import InMemoryChannel-from cubepi.hitl.middleware import ConfirmToolCallMiddleware-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.agent.types import AgentContext, BeforeToolCallContext+from cubeloop.hitl import ApproveAnswer+from cubeloop.hitl.channel import InMemoryChannel+from cubeloop.hitl.middleware import ConfirmToolCallMiddleware+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCalldef _ctx(name="bash"):diff --git a/tests/hitl/test_edge_cases.py b/tests/hitl/test_edge_cases.pyindex 71e8561..eaa9a4b 100644--- a/tests/hitl/test_edge_cases.py+++ b/tests/hitl/test_edge_cases.py@@ -4,30 +4,30 @@ import asyncioimport pytest-from cubepi.agent.agent import Agent-from cubepi.agent.types import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import (AgentContext,BeforeToolCallContext,)-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import (+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import (ApproveAnswer,HitlError,HitlNoPendingRequest,HitlStaleAnswer,Question,)-from cubepi.hitl.channel import InMemoryChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware-from cubepi.hitl.testing import NoopChannel, ScriptedChannel-from cubepi.hitl.types import ApproveRequest, HitlRequest-from cubepi.providers.base import (+from cubeloop.hitl.channel import InMemoryChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware+from cubeloop.hitl.testing import NoopChannel, ScriptedChannel+from cubeloop.hitl.types import ApproveRequest, HitlRequest+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,Usage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.faux import FauxProvider, faux_assistant_message# ── Agent error guards ──────────────────────────────────────────────────────@@ -232,7 +232,7 @@ def test_noop_channel_error_on_unknown_kind():"""NoopChannel handles approve (ApproveAnswer), confirm (True), ask (dict).An unknown kind (e.g. a synthetic payload with a made-up kind) triggersthe HitlError guard."""- from cubepi.hitl.types import ConfirmRequest+ from cubeloop.hitl.types import ConfirmRequestch = NoopChannel()# ConfirmRequest has kind="confirm", which NoopChannel handles fine.@@ -246,7 +246,7 @@ def test_noop_channel_error_on_unknown_kind():def test_args_to_dict_fallback():- from cubepi.hitl.middleware import _args_to_dict+ from cubeloop.hitl.middleware import _args_to_dictclass _Custom:def __init__(self):@@ -280,7 +280,7 @@ async def test_policy_type_error():async def test_merge_hitl_details_non_dict_base():- from cubepi.agent.tools import _merge_hitl_details+ from cubeloop.agent.tools import _merge_hitl_detailsresult = _merge_hitl_details("plain_string", {"a": 1})assert result["_non_dict_details"] == "plain_string"@@ -288,14 +288,14 @@ async def test_merge_hitl_details_non_dict_base():async def test_merge_hitl_details_base_is_none():- from cubepi.agent.tools import _merge_hitl_details+ from cubeloop.agent.tools import _merge_hitl_detailsresult = _merge_hitl_details(None, {"x": 1})assert result == {"hitl": {"x": 1}}async def test_merge_hitl_details_hitl_is_none():- from cubepi.agent.tools import _merge_hitl_details+ from cubeloop.agent.tools import _merge_hitl_detailsassert _merge_hitl_details(None, None) is Noneassert _merge_hitl_details({"a": 1}, None) == {"a": 1}@@ -318,7 +318,7 @@ async def test_answer_with_answered_qid_is_noop():# answering again after resolution won't match — pending is None now# and a stale answer would raise. We want to verify the current behavior# is safe (no error for already-resolved).- from cubepi.hitl import HitlStaleAnswer+ from cubeloop.hitl import HitlStaleAnswerwith pytest.raises(HitlStaleAnswer):await ch.answer("any-qid", True) # stale after resolution@@ -335,7 +335,7 @@ async def test_cancel_with_stale_qid_raises():asyncio.create_task(host())await ch.confirm("ok?")# cancel with a qid that isn't pending → HitlStaleAnswer- from cubepi.hitl import HitlStaleAnswer+ from cubeloop.hitl import HitlStaleAnswerwith pytest.raises(HitlStaleAnswer):await ch.cancel("not-the-qid")diff --git a/tests/hitl/test_events.py b/tests/hitl/test_events.pyindex da059a2..3beacce 100644--- a/tests/hitl/test_events.py+++ b/tests/hitl/test_events.py@@ -1,10 +1,10 @@-from cubepi.agent.types import (+from cubeloop.agent.types import (AgentAbortedEvent,AgentSuspendedEvent,HitlAnswerEvent,HitlRequestEvent,)-from cubepi.hitl.types import ConfirmRequest, HitlRequest+from cubeloop.hitl.types import ConfirmRequest, HitlRequestdef _req() -> HitlRequest:diff --git a/tests/hitl/test_exceptions.py b/tests/hitl/test_exceptions.pyindex 745e3c7..2135325 100644--- a/tests/hitl/test_exceptions.py+++ b/tests/hitl/test_exceptions.py@@ -1,5 +1,5 @@import pytest-from cubepi.hitl.exceptions import (+from cubeloop.hitl.exceptions import (HitlControlException,HitlCancelled,HitlTimedOut,diff --git a/tests/hitl/test_hitl_span_attributes.py b/tests/hitl/test_hitl_span_attributes.pyindex 3899141..4f04a9d 100644--- a/tests/hitl/test_hitl_span_attributes.py+++ b/tests/hitl/test_hitl_span_attributes.py@@ -19,10 +19,10 @@ from opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import ApproveAnswer-from cubepi.hitl.channel import CheckpointedChannel, InMemoryChannel-from cubepi.hitl.exceptions import HitlDetached+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import ApproveAnswer+from cubeloop.hitl.channel import CheckpointedChannel, InMemoryChannel+from cubeloop.hitl.exceptions import HitlDetached@pytest.fixturediff --git a/tests/hitl/test_in_memory_channel.py b/tests/hitl/test_in_memory_channel.pyindex 04cd840..2484790 100644--- a/tests/hitl/test_in_memory_channel.py+++ b/tests/hitl/test_in_memory_channel.py@@ -1,7 +1,7 @@import asyncioimport pytest-from cubepi.hitl import (+from cubeloop.hitl import (ApproveAnswer,HitlCancelled,HitlConcurrencyError,@@ -10,7 +10,7 @@ from cubepi.hitl import (HitlTimedOut,Question,)-from cubepi.hitl.channel import InMemoryChannel, _BaseChannel+from cubeloop.hitl.channel import InMemoryChannel, _BaseChannelclass _BareChannel(_BaseChannel):@@ -163,7 +163,7 @@ async def test_concurrent_request_raises_hitl_concurrency_error():async def test_signal_abort_raises_hitl_aborted():- from cubepi.hitl.exceptions import HitlAborted+ from cubeloop.hitl.exceptions import HitlAbortedch = InMemoryChannel()signal = asyncio.Event()@@ -252,7 +252,7 @@ async def test_answer_ledger_replays_raw_dict_as_approve_answer():async def test_answer_ledger_replay_emits_hitl_answer_event():- from cubepi.agent.types import HitlAnswerEvent+ from cubeloop.agent.types import HitlAnswerEventemitted: list[object] = []ch = InMemoryChannel()@@ -291,7 +291,7 @@ async def test_cancel_with_stale_qid_raises():async def test_resume_short_circuit_emits_hitl_answer_event():"""Resume short-circuit must emit HitlAnswerEvent so subscribers(e.g. IM outbound tailers) learn the question was answered."""- from cubepi.agent.types import HitlAnswerEvent+ from cubeloop.agent.types import HitlAnswerEventemitted: list[object] = []ch = InMemoryChannel()diff --git a/tests/hitl/test_loop_hitl_passthrough.py b/tests/hitl/test_loop_hitl_passthrough.pyindex 0b4acb0..cc12526 100644--- a/tests/hitl/test_loop_hitl_passthrough.py+++ b/tests/hitl/test_loop_hitl_passthrough.py@@ -1,8 +1,8 @@import pytest-from cubepi.hitl.exceptions import HitlAborted, HitlCancelled, HitlDetached-from cubepi.agent.tools import execute_tool_calls-from cubepi.agent.types import AgentContext, AgentTool, AgentToolResult-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.hitl.exceptions import HitlAborted, HitlCancelled, HitlDetached+from cubeloop.agent.tools import execute_tool_calls+from cubeloop.agent.types import AgentContext, AgentTool, AgentToolResult+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCallfrom pydantic import BaseModel@@ -133,7 +133,7 @@ async def test_parallel_detach_does_not_leak_start_events():Codex PR #127 review feedback (P2 agent/tools.py)."""- from cubepi.agent.types import ToolExecutionStartEvent+ from cubeloop.agent.types import ToolExecutionStartEventasync def t1_execute(call_id, args, *, signal=None, on_update=None):return AgentToolResult(content=[TextContent(text="ok")])diff --git a/tests/hitl/test_parallel_approval_ledger.py b/tests/hitl/test_parallel_approval_ledger.pyindex c496c5b..1f78f00 100644--- a/tests/hitl/test_parallel_approval_ledger.py+++ b/tests/hitl/test_parallel_approval_ledger.py@@ -5,14 +5,14 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl import ApproveAnswer, AskUser-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware-from cubepi.providers.base import TextContent, ToolResultMessage-from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl import ApproveAnswer, AskUser+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware+from cubeloop.providers.base import TextContent, ToolResultMessage+from cubeloop.providers.faux import FauxProvider, faux_assistant_message, faux_tool_callclass _NoParams(BaseModel):diff --git a/tests/hitl/test_resume_cache_prefix.py b/tests/hitl/test_resume_cache_prefix.pyindex cde8e1a..cb81fa4 100644--- a/tests/hitl/test_resume_cache_prefix.py+++ b/tests/hitl/test_resume_cache_prefix.py@@ -5,15 +5,15 @@ import asyncioimport pytestfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.checkpointer.sqlite import SQLiteCheckpointer-from cubepi.hitl import ApproveAnswer, AskUser-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.hitl.middleware import ApprovalPolicyMiddleware-from cubepi.providers.base import TextContent-from cubepi.providers.faux import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer+from cubeloop.hitl import ApproveAnswer, AskUser+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.hitl.middleware import ApprovalPolicyMiddleware+from cubeloop.providers.base import TextContent+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_text,diff --git a/tests/hitl/test_subagent_channel_inheritance.py b/tests/hitl/test_subagent_channel_inheritance.pyindex e42840e..81f88a4 100644--- a/tests/hitl/test_subagent_channel_inheritance.py+++ b/tests/hitl/test_subagent_channel_inheritance.py@@ -1,13 +1,13 @@from pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.hitl import ApproveAnswer-from cubepi.hitl.channel import InMemoryChannel-from cubepi.hitl.testing import NoopChannel, ScriptedChannel-from cubepi.hitl.types import Question-from cubepi.providers.base import TextContent-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.hitl import ApproveAnswer+from cubeloop.hitl.channel import InMemoryChannel+from cubeloop.hitl.testing import NoopChannel, ScriptedChannel+from cubeloop.hitl.types import Question+from cubeloop.providers.base import TextContent+from cubeloop.providers.faux import FauxProvider, faux_assistant_messagedef _faux_with(responses):diff --git a/tests/hitl/test_trace_spans.py b/tests/hitl/test_trace_spans.pyindex 42f5328..3232a2c 100644--- a/tests/hitl/test_trace_spans.py+++ b/tests/hitl/test_trace_spans.py@@ -7,8 +7,8 @@ from opentelemetry import tracefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter-from cubepi.hitl import ApproveAnswer-from cubepi.hitl.channel import InMemoryChannel+from cubeloop.hitl import ApproveAnswer+from cubeloop.hitl.channel import InMemoryChannel@pytest.fixturediff --git a/tests/hitl/test_types.py b/tests/hitl/test_types.pyindex 312f8d5..ab8ecf4 100644--- a/tests/hitl/test_types.py+++ b/tests/hitl/test_types.py@@ -1,7 +1,7 @@import dataclassesimport pytest-from cubepi.hitl.types import (+from cubeloop.hitl.types import (Option,Question,ConfirmRequest,@@ -73,7 +73,7 @@ def test_approve_answer_decisions():def test_before_tool_call_result_new_fields():- from cubepi.agent.types import BeforeToolCallResult+ from cubeloop.agent.types import BeforeToolCallResultr = BeforeToolCallResult(edited_args={"x": 1},@@ -91,7 +91,7 @@ def test_before_tool_call_result_new_fields():def test_approval_decision_dataclasses_frozen():- from cubepi.hitl.policy import Approve, Deny, AskUser+ from cubeloop.hitl.policy import Approve, Deny, AskUsera = Approve()d = Deny(reason="forbidden")diff --git a/tests/mcp/test_adapter.py b/tests/mcp/test_adapter.pyindex b928298..481c8d1 100644--- a/tests/mcp/test_adapter.py+++ b/tests/mcp/test_adapter.py@@ -4,7 +4,7 @@ from contextlib import asynccontextmanagerimport pytest-from cubepi.mcp._adapter import (+from cubeloop.mcp._adapter import (make_mcp_agent_tool,mcp_schema_to_pydantic_model,)@@ -196,7 +196,7 @@ async def test_make_mcp_agent_tool_routes_to_call_remote() -> None:result = await tool.execute("test-call-id-1", args, signal=None, on_update=None)assert called == {"name": "search", "args": {"query": "cats"}}assert len(result.content) == 1- from cubepi.providers.base import TextContent+ from cubeloop.providers.base import TextContentassert isinstance(result.content[0], TextContent)assert result.content[0].text == "result"@@ -262,7 +262,7 @@ async def test_signal_abort_cancels_in_flight_mcp_call() -> None:isn't bounded by MCP timeout (codex overall-review MAJOR)."""import asyncio as _asyncio- from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubeloop.mcp._adapter import make_mcp_agent_toolstarted = _asyncio.Event()finished = _asyncio.Event()@@ -320,10 +320,10 @@ async def test_agent_abort_during_mcp_call_does_not_raise() -> None:follow-up on PR #88."""import asyncio as _asyncio- from cubepi.agent.agent import Agent- from cubepi.mcp._adapter import make_mcp_agent_tool- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.agent.agent import Agent+ from cubeloop.mcp._adapter import make_mcp_agent_tool+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_messagein_flight = _asyncio.Event()@@ -382,8 +382,8 @@ async def test_signal_abort_swallows_span_set_attribute_errors(monkeypatch) -> Npath (defensive-branch coverage)."""import asyncio as _asyncio- from cubepi.mcp._adapter import make_mcp_agent_tool- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp._adapter import make_mcp_agent_tool+ from cubeloop.mcp import _tracing as mcp_tracing# Force mcp_client_span to yield a span whose set_attribute raises.class _BoomSpan:@@ -403,7 +403,7 @@ async def test_signal_abort_swallows_span_set_attribute_errors(monkeypatch) -> Nasync def _fake_span(**_kw):yield _BoomSpan()- monkeypatch.setattr("cubepi.mcp._adapter.mcp_client_span", _fake_span)+ monkeypatch.setattr("cubeloop.mcp._adapter.mcp_client_span", _fake_span)async def _call(_name, _args):return {"content": [], "isError": False}@@ -439,7 +439,7 @@ async def test_signal_abort_does_not_block_on_slow_call_cleanup() -> None:import asyncio as _asyncioimport time as _time- from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubeloop.mcp._adapter import make_mcp_agent_toolin_flight = _asyncio.Event()cleanup_started = _asyncio.Event()@@ -497,7 +497,7 @@ async def test_signal_already_set_before_call_aborts_immediately() -> None:on PR #88)."""import asyncio as _asyncio- from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubeloop.mcp._adapter import make_mcp_agent_toolcalled = Falsediff --git a/tests/mcp/test_http_loader.py b/tests/mcp/test_http_loader.pyindex 96834e8..d379f6c 100644--- a/tests/mcp/test_http_loader.py+++ b/tests/mcp/test_http_loader.py@@ -16,7 +16,7 @@ import pytestdef test_import_http_loader() -> None:"""Loader function is importable from the public module path."""- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httpassert callable(load_mcp_tools_http)@@ -116,8 +116,8 @@ def _install_fake_transport(monkeypatch, *, tools, call_response, init_result=No@pytest.mark.asyncioasync def test_load_mcp_tools_http_lists_and_calls_tool(monkeypatch) -> None:"""Mocked transport: lists tools, then invokes one and serializes response."""- from cubepi.mcp import load_mcp_tools_http- from cubepi.providers.base import TextContent+ from cubeloop.mcp import load_mcp_tools_http+ from cubeloop.providers.base import TextContenttools_resp = [SimpleNamespace(@@ -172,7 +172,7 @@ async def test_load_mcp_tools_http_lists_and_calls_tool(monkeypatch) -> None:assert sessions[1].calls == [("search", {"query": "cats"})]# text + image preserved; unsupported "resource" dropped- from cubepi.providers.base import ImageContent+ from cubeloop.providers.base import ImageContentassert len(result.content) == 2assert isinstance(result.content[0], TextContent)@@ -185,7 +185,7 @@ async def test_load_mcp_tools_http_lists_and_calls_tool(monkeypatch) -> None:@pytest.mark.asyncioasync def test_load_mcp_tools_http_propagates_is_error(monkeypatch) -> None:- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httptools_resp = [SimpleNamespace(@@ -216,7 +216,7 @@ async def test_load_mcp_tools_http_propagates_is_error(monkeypatch) -> None:@pytest.mark.asyncioasync def test_load_mcp_tools_http_preserves_structured_content(monkeypatch) -> None:"""structuredContent flows through to AgentToolResult.details."""- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httptools_resp = [SimpleNamespace(@@ -244,7 +244,7 @@ async def test_load_mcp_tools_http_preserves_structured_content(monkeypatch) ->@pytest.mark.asyncioasync def test_load_mcp_tools_http_handles_empty_content(monkeypatch) -> None:"""resp.content == None should not break the serializer."""- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httptools_resp = [SimpleNamespace(@@ -274,7 +274,7 @@ async def test_load_mcp_tools_http_streamable_transport(monkeypatch) -> None:discovery and per-tool ``call_tool`` must go through the matchingstreamable_http client."""- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httptools_resp = [SimpleNamespace(@@ -326,7 +326,7 @@ async def test_load_mcp_tools_http_streamable_transport(monkeypatch) -> None:@pytest.mark.asyncioasync def test_load_mcp_tools_http_rejects_unknown_transport() -> None:"""Unknown transport raises ValueError; we do not silently fall back."""- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httpwith pytest.raises(ValueError, match="unsupported MCP transport"):await load_mcp_tools_http(@@ -338,7 +338,7 @@ async def test_load_mcp_tools_http_rejects_unknown_transport() -> None:@pytest.mark.asyncioasync def test_load_mcp_tools_http_initialize_timeout(monkeypatch) -> None:"""A session that hangs on initialize must raise TimeoutError, not block."""- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httpclass _HangingSession:def __init__(self, *streams):@@ -378,11 +378,13 @@ async def test_load_mcp_tools_http_initialize_timeout(monkeypatch) -> None:@pytest.mark.asyncioasync 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")+ server_url = os.environ.get("CUBELOOP_TEST_MCP_HTTP_URL") or os.environ.get(+ "CUBEPI_TEST_MCP_HTTP_URL"+ )if not server_url:- pytest.skip("Set CUBEPI_TEST_MCP_HTTP_URL to run this test")+ pytest.skip("Set CUBELOOP_TEST_MCP_HTTP_URL to run this test")- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httpdiscovery = await load_mcp_tools_http(server_url)assert len(discovery.tools) > 0@@ -401,7 +403,7 @@ async def test_load_mcp_tools_http_captures_server_info_from_initialize(monkeypatch,) -> None:"""Implementation.icons + websiteUrl + name flow into MCPServerInfo."""- from cubepi.mcp import MCPDiscoveryResult, MCPIcon, load_mcp_tools_http+ from cubeloop.mcp import MCPDiscoveryResult, MCPIcon, load_mcp_tools_httpinit_result = SimpleNamespace(serverInfo=SimpleNamespace(@@ -450,7 +452,7 @@ async def test_load_mcp_tools_http_captures_server_info_from_initialize(@pytest.mark.asyncioasync def test_load_mcp_tools_http_captures_per_tool_icons(monkeypatch) -> None:"""Per-tool ``Tool.icons`` flow into ``tool_infos`` keyed by tool name."""- from cubepi.mcp import MCPIcon, load_mcp_tools_http+ from cubeloop.mcp import MCPIcon, load_mcp_tools_httptools_resp = [SimpleNamespace(@@ -482,7 +484,7 @@ async def test_load_mcp_tools_http_captures_per_tool_icons(monkeypatch) -> None:@pytest.mark.asyncioasync def test_load_mcp_tools_http_handles_missing_server_icons(monkeypatch) -> None:"""Server without icons / websiteUrl yields MCPServerInfo with empty defaults."""- from cubepi.mcp import load_mcp_tools_http+ from cubeloop.mcp import load_mcp_tools_httpinit_result = SimpleNamespace(serverInfo=SimpleNamespace(@@ -514,7 +516,7 @@ def test_stamp_session_id_handles_otel_missing(monkeypatch) -> None:tracing extra is installed (defensive-branch coverage)."""import builtins- from cubepi.mcp import http_loader+ from cubeloop.mcp import http_loaderreal_import = builtins.__import__@@ -532,7 +534,7 @@ def test_stamp_session_id_noop_without_active_span() -> None:"""When no recording span is active (``ctx.is_valid == False``)``_stamp_session_id`` must return without touching the span(defensive-branch coverage)."""- from cubepi.mcp import http_loader+ from cubeloop.mcp import http_loader# No tracer provider set up — get_current_span returns the OTel# NonRecordingSpan whose ctx.is_valid is False.@@ -555,7 +557,7 @@ def test_stamp_session_id_swallows_set_attribute_errors(monkeypatch) -> None:def set_attribute(self, *_a, **_kw):raise RuntimeError("boom")- from cubepi.mcp import http_loader+ from cubeloop.mcp import http_loadermonkeypatch.setattr(_otel_trace, "get_current_span", lambda: _BoomSpan())# Must not raise.@@ -599,7 +601,7 @@ async def test_stamp_session_id_attaches_attr_to_current_span() -> None:provider.add_span_processor(SimpleSpanProcessor(exporter))tracer = provider.get_tracer("test")- from cubepi.mcp.http_loader import _stamp_session_id+ from cubeloop.mcp.http_loader import _stamp_session_idwith tracer.start_as_current_span("test-span"):_stamp_session_id("session-abc-123")diff --git a/tests/mcp/test_stdio_loader.py b/tests/mcp/test_stdio_loader.pyindex 03a423e..b169dd5 100644--- a/tests/mcp/test_stdio_loader.py+++ b/tests/mcp/test_stdio_loader.py@@ -6,7 +6,7 @@ import pytestdef test_import_stdio_loader() -> None:- from cubepi.mcp import load_mcp_tools_stdio+ from cubeloop.mcp import load_mcp_tools_stdioassert callable(load_mcp_tools_stdio)@@ -14,7 +14,7 @@ def test_import_stdio_loader() -> None:@pytest.mark.asyncioasync def test_stdio_loader_against_fake_server() -> None:"""Spawn the fake stdio server, list tools, invoke 'echo'."""- from cubepi.mcp import MCPDiscoveryResult, load_mcp_tools_stdio+ from cubeloop.mcp import MCPDiscoveryResult, load_mcp_tools_stdiodiscovery = await load_mcp_tools_stdio(command=sys.executable,@@ -33,7 +33,7 @@ async def test_stdio_loader_against_fake_server() -> None:args = echo.parameters(text="hello")result = await echo.execute("tc-stdio-1", args, signal=None, on_update=None)assert len(result.content) == 1- from cubepi.providers.base import TextContent+ from cubeloop.providers.base import TextContentassert isinstance(result.content[0], TextContent)assert result.content[0].text == "hello"diff --git a/tests/mcp/test_types.py b/tests/mcp/test_types.pyindex 66039c2..86c4a56 100644--- a/tests/mcp/test_types.py+++ b/tests/mcp/test_types.py@@ -9,7 +9,7 @@ from __future__ import annotationsfrom types import SimpleNamespace-from cubepi.mcp.types import (+from cubeloop.mcp.types import (MCPIcon,MCPServerInfo,MCPToolInfo,diff --git a/tests/middleware/compaction/test_boundary.py b/tests/middleware/compaction/test_boundary.pyindex 6fdaec6..6665ca4 100644--- a/tests/middleware/compaction/test_boundary.py+++ b/tests/middleware/compaction/test_boundary.py@@ -1,10 +1,10 @@from __future__ import annotations-from cubepi.middleware.compaction.boundary import (+from cubeloop.middleware.compaction.boundary import (safe_boundary,tail_start_by_tokens,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,Message,TextContent,diff --git a/tests/middleware/compaction/test_pruner.py b/tests/middleware/compaction/test_pruner.pyindex 2a77e2c..ec83127 100644--- a/tests/middleware/compaction/test_pruner.py+++ b/tests/middleware/compaction/test_pruner.py@@ -1,7 +1,7 @@from __future__ import annotations-from cubepi.middleware.compaction.pruner import prune_tool_results-from cubepi.providers.base import (+from cubeloop.middleware.compaction.pruner import prune_tool_results+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,diff --git a/tests/middleware/compaction/test_summarizer.py b/tests/middleware/compaction/test_summarizer.pyindex 9b9013a..75d0249 100644--- a/tests/middleware/compaction/test_summarizer.py+++ b/tests/middleware/compaction/test_summarizer.py@@ -3,12 +3,12 @@ from __future__ import annotationsimport asynciofrom typing import Any-from cubepi.middleware.compaction import CompactionState-from cubepi.middleware.compaction.summarizer import (+from cubeloop.middleware.compaction import CompactionState+from cubeloop.middleware.compaction.summarizer import (_format_message_for_summary,summarize,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BoundModel,Message,@@ -228,14 +228,14 @@ def test_tool_call_empty_arguments() -> None:def test_dynamic_budget_floor_for_small_content() -> None:- from cubepi.middleware.compaction.summarizer import _dynamic_summary_budget+ from cubeloop.middleware.compaction.summarizer import _dynamic_summary_budgetsmall = [UserMessage(content=[TextContent(text="hi")])]assert _dynamic_summary_budget(small) == 1024def test_dynamic_budget_scales_with_content() -> None:- from cubepi.middleware.compaction.summarizer import _dynamic_summary_budget+ from cubeloop.middleware.compaction.summarizer import _dynamic_summary_budget# 40 000 chars ≈ 20 000 tokens → budget = 20 000 * 0.15 = 3 000large = [UserMessage(content=[TextContent(text="x" * 40_000)])]@@ -245,13 +245,13 @@ def test_dynamic_budget_scales_with_content() -> None:def test_dynamic_budget_empty_input_floor() -> None:- from cubepi.middleware.compaction.summarizer import _dynamic_summary_budget+ from cubeloop.middleware.compaction.summarizer import _dynamic_summary_budgetassert _dynamic_summary_budget([]) == 1024def test_dynamic_budget_ceiling() -> None:- from cubepi.middleware.compaction.summarizer import _dynamic_summary_budget+ from cubeloop.middleware.compaction.summarizer import _dynamic_summary_budgethuge = [UserMessage(content=[TextContent(text="x" * 200_000)])]assert _dynamic_summary_budget(huge) == 4096@@ -311,7 +311,7 @@ async def test_summarize_ref_messages_used_for_refs() -> None:transcript_text = provider.calls[0]["messages"][0].content[0].textassert "pruned content" in transcript_text# But refs are computed from the ORIGINAL messages- from cubepi.middleware.compaction.state import message_refs+ from cubeloop.middleware.compaction.state import message_refsassert state.summarized_message_refs == message_refs(original)@@ -320,7 +320,7 @@ async def test_summarize_ref_messages_used_for_refs() -> None:def test_fallback_summary_includes_user_requests() -> None:- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.summarizer import build_fallback_summarymsgs: list[Message] = [UserMessage(content=[TextContent(text="Please write a hello world script")]),@@ -332,8 +332,8 @@ def test_fallback_summary_includes_user_requests() -> None:def test_fallback_summary_includes_tool_names() -> None:- from cubepi.middleware.compaction.summarizer import build_fallback_summary- from cubepi.providers.base import ToolResultMessage+ from cubeloop.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.providers.base import ToolResultMessagemsgs: list[Message] = [UserMessage(content=[TextContent(text="run the tests")]),@@ -352,8 +352,8 @@ def test_fallback_summary_includes_tool_names() -> None:def test_fallback_summary_merges_existing() -> None:- from cubepi.middleware.compaction.state import CompactionState- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.state import CompactionState+ from cubeloop.middleware.compaction.summarizer import build_fallback_summaryexisting = CompactionState(summary="prior context", is_fallback=False)msgs: list[Message] = [UserMessage(content=[TextContent(text="new task")])]@@ -363,7 +363,7 @@ def test_fallback_summary_merges_existing() -> None:def test_fallback_summary_caps_user_requests_at_five() -> None:- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.summarizer import build_fallback_summarymsgs: list[Message] = [UserMessage(content=[TextContent(text=f"request {i}")]) for i in range(10)@@ -375,8 +375,8 @@ def test_fallback_summary_caps_user_requests_at_five() -> None:def test_fallback_summary_uses_ref_messages_for_refs() -> None:- from cubepi.middleware.compaction.state import message_refs- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.state import message_refs+ from cubeloop.middleware.compaction.summarizer import build_fallback_summarytranscript = [UserMessage(content=[TextContent(text="pruned content")])]original = [UserMessage(content=[TextContent(text="full original")])]@@ -388,7 +388,7 @@ def test_fallback_summary_uses_ref_messages_for_refs() -> None:def test_summary_has_eight_sections() -> None:- from cubepi.middleware.compaction.summarizer import SUMMARIZER_SYSTEM_PROMPT+ from cubeloop.middleware.compaction.summarizer import SUMMARIZER_SYSTEM_PROMPTfor section in ("Goal",@@ -404,7 +404,7 @@ def test_summary_has_eight_sections() -> None:def test_system_prompt_marks_output_as_non_instruction() -> None:- from cubepi.middleware.compaction.summarizer import SUMMARIZER_SYSTEM_PROMPT+ from cubeloop.middleware.compaction.summarizer import SUMMARIZER_SYSTEM_PROMPT# Collapse whitespace so line breaks don't fail the substring assertions.text = " ".join(SUMMARIZER_SYSTEM_PROMPT.lower().split())@@ -450,7 +450,7 @@ async def test_summarize_uses_existing_summary_suffix_override() -> None:def test_shrink_strings_recurses_into_lists() -> None:"""The list branch of _shrink_strings shrinks string leaves inside lists,leaves non-string leaves intact."""- from cubepi.middleware.compaction.summarizer import _shrink_strings+ from cubeloop.middleware.compaction.summarizer import _shrink_stringslong_text = "x" * 500obj = ["short", long_text, 42, True, None, [long_text]]@@ -468,7 +468,7 @@ def test_shrink_strings_recurses_into_lists() -> None:def test_format_arguments_non_json_serialisable_falls_back_to_str() -> None:"""A value json.dumps can't handle (e.g. a custom object) falls back tostr() instead of raising — defensive against odd backend payloads."""- from cubepi.middleware.compaction.summarizer import _format_arguments+ from cubeloop.middleware.compaction.summarizer import _format_argumentsclass _NotJson:def __repr__(self) -> str:@@ -488,7 +488,7 @@ def test_fallback_summary_does_not_embed_prior_fallback() -> None:"""A fallback that follows another fallback must NOT embed the priorfallback text under 'Prior context:'. Otherwise each LLM-outage turndoubles the summary size — the chain compounds verbatim across runs."""- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.summarizer import build_fallback_summary# Run 1: clean fallback.msgs_1: list[Message] = [@@ -525,7 +525,7 @@ def test_fallback_summary_does_not_embed_prior_fallback() -> None:def test_fallback_summary_user_lines_capped_after_merging() -> None:"""Cap of 5 user lines holds across the merge with a prior fallback."""- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.summarizer import build_fallback_summarymsgs_1 = [UserMessage(content=[TextContent(text=f"older {i}")]) for i in range(4)]state_1 = build_fallback_summary(msgs_1, existing=None)@@ -547,8 +547,8 @@ def test_fallback_summary_after_real_summary_still_embeds_prior() -> None:"""When the prior was a REAL summary (is_fallback=False), the newfallback still embeds it under 'Prior context:' — only fallback-after-fallback is the unbounded-growth path."""- from cubepi.middleware.compaction.state import CompactionState- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.state import CompactionState+ from cubeloop.middleware.compaction.summarizer import build_fallback_summaryreal_prior = CompactionState(summary="## Goal\nbuild the thing", is_fallback=False)msgs = [UserMessage(content=[TextContent(text="next task")])]@@ -561,8 +561,8 @@ def test_fallback_preserves_real_prior_across_multiple_outage_turns() -> None:"""Codex P2: real summary → fallback → fallback. The 2nd fallback muststill carry the real summary's prior context, otherwise an outage ofmore than one compaction cycle drops everything summarised before it."""- from cubepi.middleware.compaction.state import CompactionState- from cubepi.middleware.compaction.summarizer import build_fallback_summary+ from cubeloop.middleware.compaction.state import CompactionState+ from cubeloop.middleware.compaction.summarizer import build_fallback_summary# Step 1: a real LLM summary covering "early work".real_summary = CompactionState(diff --git a/tests/middleware/compaction/test_tokens.py b/tests/middleware/compaction/test_tokens.pyindex a6200d3..4069b40 100644--- a/tests/middleware/compaction/test_tokens.py+++ b/tests/middleware/compaction/test_tokens.py@@ -1,10 +1,10 @@from __future__ import annotations-from cubepi.middleware.compaction.tokens import (+from cubeloop.middleware.compaction.tokens import (approx_tokens,real_context_estimate,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,TextContent,ThinkingContent,diff --git a/tests/middleware/test_after_model_response.py b/tests/middleware/test_after_model_response.pyindex 3ac586d..3c0d02e 100644--- a/tests/middleware/test_after_model_response.py+++ b/tests/middleware/test_after_model_response.py@@ -2,16 +2,16 @@import pytest-from cubepi import Agent-from cubepi.agent.types import AgentContext-from cubepi.middleware.base import Middleware, TurnAction, compose_middleware-from cubepi.providers.base import (+from cubeloop import Agent+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.base import Middleware, TurnAction, compose_middleware+from cubeloop.providers.base import (AssistantMessage,TextContent,Usage,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.faux import FauxProvider, faux_assistant_messagedef _mk_response(text: str = "hi") -> AssistantMessage:@@ -238,7 +238,7 @@ async def test_agent_no_middleware_natural_flow() -> None:async def test_ctx_extra_flows_into_loop_context(tmp_path) -> None:"""Middleware reading ctx.extra inside the loop sees the hydrated valueAND mutations persist to checkpointer after the turn (Bug A)."""- from cubepi.checkpointer import MemoryCheckpointer+ from cubeloop.checkpointer import MemoryCheckpointerseen_extra: list[dict] = []@@ -277,7 +277,7 @@ async def test_ctx_extra_flows_into_loop_context(tmp_path) -> None:async def test_turn_action_response_persists_in_agent_state(tmp_path) -> None:"""When after_model_response mutates the response, agent state andcheckpointer reflect the mutation (Bug B)."""- from cubepi.checkpointer import MemoryCheckpointer+ from cubeloop.checkpointer import MemoryCheckpointerdef _mk(text: str) -> AssistantMessage:return AssistantMessage(content=[TextContent(text=text)], usage=Usage())@@ -317,8 +317,8 @@ async def test_turn_action_response_persists_in_agent_state(tmp_path) -> None:async def test_turn_action_inject_messages_persist(tmp_path) -> None:"""Messages injected via TurnAction.inject_messages persist to agentstate and checkpointer (Bug C)."""- from cubepi.checkpointer import MemoryCheckpointer- from cubepi.providers.base import UserMessage+ from cubeloop.checkpointer import MemoryCheckpointer+ from cubeloop.providers.base import UserMessageinjected_once = Falsediff --git a/tests/middleware/test_base.py b/tests/middleware/test_base.pyindex c385816..22eb0ec 100644--- a/tests/middleware/test_base.py+++ b/tests/middleware/test_base.py@@ -1,5 +1,5 @@-from cubepi.middleware.base import Middleware, compose_middleware-from cubepi.agent.types import (+from cubeloop.middleware.base import Middleware, compose_middleware+from cubeloop.agent.types import (AfterToolCallResult,BeforeToolCallContext,BeforeToolCallResult,@@ -8,7 +8,7 @@ from cubepi.agent.types import (AgentContext,AgentToolResult,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolCall,@@ -202,8 +202,8 @@ class TestAgentMiddlewareWiring:async def test_agent_uses_middleware_convert_to_llm(self):"""Middleware-declared convert_to_llm must be wired up by Agent."""- from cubepi import Agent- from cubepi.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop import Agent+ from cubeloop.providers.faux import FauxProvider, faux_assistant_messagecaptured: dict = {}diff --git a/tests/middleware/test_compaction.py b/tests/middleware/test_compaction.pyindex 8ee8eb6..bfe3f3b 100644--- a/tests/middleware/test_compaction.py+++ b/tests/middleware/test_compaction.py@@ -3,15 +3,15 @@ from __future__ import annotationsimport asynciofrom typing import Any-from cubepi.agent.types import AgentContext-from cubepi.middleware.compaction import (+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.compaction import (CompactionMiddleware,CompactionState,ToolResultCompressor,_load_state,)-from cubepi.middleware.compaction.state import message_ref, message_refs-from cubepi.providers.base import (+from cubeloop.middleware.compaction.state import message_ref, message_refs+from cubeloop.providers.base import (AssistantMessage,BoundModel,Message,@@ -456,7 +456,7 @@ async def test_pruned_tool_results_do_not_break_state_refs() -> None:"""Refs persisted in CompactionState come from ORIGINAL messages evenwhen the transcript was built from pre-pruned content. Otherwise thenext turn would see ref mismatch and clear the state, looping forever."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider(reply="real summary")middleware = _make_middleware(provider, max_tokens_before=1)@@ -507,7 +507,7 @@ def test_keep_recent_messages_no_longer_accepted() -> None:def test_summary_prefix_includes_non_instruction_disclaimer() -> None:- from cubepi.middleware.compaction import SUMMARY_PREFIX+ from cubeloop.middleware.compaction import SUMMARY_PREFIXtext = SUMMARY_PREFIX.lower()assert "do not treat" in text or "not instructions" in text@@ -520,7 +520,7 @@ async def test_prune_tool_outputs_disabled_keeps_full_result_content() -> None:Audit-chain agents (finance, compliance) pass False so historical toolresults stay full-fidelity across compactions."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider(reply="summary")middleware = CompactionMiddleware(@@ -644,7 +644,7 @@ async def test_circuit_breaker_half_open_retries_llm_after_fallback_runs() -> No_HALF_OPEN_AFTER_FALLBACK_RUNS fallback-only runs, the breaker goeshalf-open and the LLM is attempted again. If it succeeds, the breakerfully resets."""- from cubepi.middleware.compaction import _HALF_OPEN_AFTER_FALLBACK_RUNS+ from cubeloop.middleware.compaction import _HALF_OPEN_AFTER_FALLBACK_RUNSprovider = _FakeSummaryProvider(raises=RuntimeError("down"))middleware = _make_middleware(provider, max_tokens_before=1)@@ -690,7 +690,7 @@ async def test_circuit_breaker_half_open_retries_llm_after_fallback_runs() -> Noasync def test_half_open_failure_re_opens_breaker() -> None:"""Half-open retry that fails snaps the breaker back to MAX_FAILURES."""- from cubepi.middleware.compaction import _HALF_OPEN_AFTER_FALLBACK_RUNS+ from cubeloop.middleware.compaction import _HALF_OPEN_AFTER_FALLBACK_RUNSprovider = _FakeSummaryProvider(raises=RuntimeError("down"))middleware = _make_middleware(provider, max_tokens_before=1)@@ -871,7 +871,7 @@ async def test_under_threshold_does_not_silently_prune_tool_outputs() -> None:not the pruned view. Otherwise old tool outputs are silently replacedwith one-liner placeholders on every turn, with no state recording theloss."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider()# Big threshold so the un-pruned history stays under it.@@ -907,7 +907,7 @@ async def test_no_safe_boundary_does_not_silently_prune_tool_outputs() -> None:"""Codex round 6 P2: when over threshold but safe_boundary returns None(no valid split point), the middleware must return original messagesrather than the pruned view."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider()# Threshold low enough that the conversation exceeds it.@@ -940,7 +940,7 @@ async def test_anti_thrash_guard_skip_does_not_silently_prune() -> None:"""Codex round 6 P2: when the anti-thrash guard fires, the returned viewmust come from the un-pruned messages so the main model still sees thefull tool outputs."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider()big_text = "x" * 5000 # 2500 tokens via approx_tokens@@ -1003,7 +1003,7 @@ def _make_middleware_with_compressor(async def test_compressor_preserved_text_appended_to_summary() -> None:"""Preserved tool results appear in the summary message text."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider(reply="conversation summary")@@ -1041,7 +1041,7 @@ async def test_compressor_preserved_text_appended_to_summary() -> None:async def test_compressor_preserved_excluded_from_summarizer_input() -> None:"""Preserved messages are not fed to the summarizer LLM."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider(reply="summary")@@ -1079,7 +1079,7 @@ async def test_compressor_preserved_excluded_from_summarizer_input() -> None:async def test_compressor_none_return_uses_default_pruning() -> None:"""When compressor returns None for all messages, behavior is identicalto not having a compressor."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider(reply="summary")@@ -1112,7 +1112,7 @@ async def test_compressor_none_return_uses_default_pruning() -> None:async def test_compressor_preserved_persists_across_compaction_rounds() -> None:"""Preserved results from earlier rounds survive in subsequent compressed views."""- from cubepi.providers.base import ToolCall, ToolResultMessage+ from cubeloop.providers.base import ToolCall, ToolResultMessageprovider = _FakeSummaryProvider(reply="round 1 summary")@@ -1167,7 +1167,7 @@ async def test_trailing_synthetic_control_does_not_age_current_tool_results() ->user control. The ordinary four-message history has no legal boundary at``min_compact_messages=4``; the control must not manufacture one."""- from cubepi.providers.base import (+ from cubeloop.providers.base import (ToolCall,ToolResultMessage,synthetic_user_message,@@ -1224,8 +1224,8 @@ async def test_trailing_synthetic_control_does_not_age_current_tool_results() ->async def test_trailing_controls_count_toward_compaction_threshold() -> None:"""Controls stay in the size calculation even though they do not set the tail."""- from cubepi.middleware.compaction.tokens import real_context_estimate- from cubepi.providers.base import synthetic_user_message+ from cubeloop.middleware.compaction.tokens import real_context_estimate+ from cubeloop.providers.base import synthetic_user_messageprovider = _FakeSummaryProvider(reply="combined view crossed threshold")middleware = CompactionMiddleware(@@ -1263,7 +1263,7 @@ async def test_old_prefix_compacts_without_pruning_current_multi_tool_evidence()None):"""Older turns may compact while a current multi-tool turn stays raw."""- from cubepi.providers.base import (+ from cubeloop.providers.base import (ToolCall,ToolResultMessage,synthetic_user_message,@@ -1333,10 +1333,10 @@ async def test_old_prefix_compacts_without_pruning_current_multi_tool_evidence()def test_split_only_detaches_trailing_synthetic_user_messages() -> None:"""Plain user tails and synthetic tool results remain ordinary history."""- from cubepi.middleware.compaction import (+ from cubeloop.middleware.compaction import (_split_trailing_synthetic_user_controls,)- from cubepi.providers.base import (+ from cubeloop.providers.base import (ToolCall,ToolResultMessage,synthetic_user_message,@@ -1376,7 +1376,7 @@ async def test_compaction_state_refs_survive_trailing_control_becoming_internal(None):"""Suffix splitting does not change persisted prefix indices or refs."""- from cubepi.providers.base import synthetic_user_message+ from cubeloop.providers.base import synthetic_user_messageprovider = _FakeSummaryProvider(reply="stable summary")compacting = CompactionMiddleware(diff --git a/tests/middleware/test_init_exports.py b/tests/middleware/test_init_exports.pyindex 0bc4083..fd719ca 100644--- a/tests/middleware/test_init_exports.py+++ b/tests/middleware/test_init_exports.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport pytest-import cubepi.middleware as middleware+import cubeloop.middleware as middlewaredef test_lazy_exports_resolve_builtin_middleware() -> None:diff --git a/tests/middleware/test_on_run_end.py b/tests/middleware/test_on_run_end.pyindex 7175997..e68220a 100644--- a/tests/middleware/test_on_run_end.py+++ b/tests/middleware/test_on_run_end.py@@ -4,11 +4,11 @@ from __future__ import annotationsimport pytest-from cubepi import Agent-from cubepi.agent.types import AgentContext-from cubepi.middleware.base import Middleware, compose_middleware-from cubepi.providers.base import TextContent, UserMessage-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop import Agent+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.base import Middleware, compose_middleware+from cubeloop.providers.base import TextContent, UserMessage+from cubeloop.providers.faux import FauxProvider, faux_assistant_messagedef _mk_ctx() -> AgentContext:@@ -168,7 +168,7 @@ async def test_on_run_end_none_does_not_add_turn() -> None:@pytest.mark.asyncioasync def test_on_run_end_injected_messages_in_history() -> None:"""Messages injected by on_run_end appear in agent.state.messages."""- from cubepi.providers.base import AssistantMessage+ from cubeloop.providers.base import AssistantMessageprovider = FauxProvider(provider_id="faux")provider.set_responses(@@ -202,7 +202,7 @@ async def test_on_run_end_injected_messages_in_history() -> None:@pytest.mark.asyncioasync def test_on_run_end_fires_via_should_stop_after_turn() -> None:"""on_run_end fires when should_stop_after_turn exits the inner loop."""- from cubepi.agent.types import ShouldStopAfterTurnContext+ from cubeloop.agent.types import ShouldStopAfterTurnContextprovider = FauxProvider(provider_id="faux")provider.set_responses(diff --git a/tests/middleware/test_subagents.py b/tests/middleware/test_subagents.pyindex 6500448..8b8738e 100644--- a/tests/middleware/test_subagents.py+++ b/tests/middleware/test_subagents.py@@ -5,10 +5,10 @@ from typing import Anyfrom pydantic import BaseModel-from cubepi import Agent, AgentTool, AgentToolResult, TextContent, UserMessage-from cubepi.middleware.subagents import SubagentMiddleware, SubagentSpec-from cubepi.providers.base import AssistantMessage, MessageStream, StreamEvent-from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call+from cubeloop import Agent, AgentTool, AgentToolResult, TextContent, UserMessage+from cubeloop.middleware.subagents import SubagentMiddleware, SubagentSpec+from cubeloop.providers.base import AssistantMessage, MessageStream, StreamEvent+from cubeloop.providers.faux import FauxProvider, faux_assistant_message, faux_tool_calldef _make_middleware(@@ -505,7 +505,7 @@ async def test_subagent_strips_checkpointed_hitl_bound_tools() -> None:entry would reject the run with ``"Agent has checkpointed HITL elementsbound to run_ids ..."`` because the child runs under its own run_id."""- from cubepi.hitl.binding import HitlBinding+ from cubeloop.hitl.binding import HitlBindingclass _NoOpParams(BaseModel):pass@@ -576,8 +576,8 @@ async def test_subagent_strips_middleware_exposing_checkpointed_hitl_tools() ->``checkpointed HITL elements bound to run_ids`` error this fix is meantto avoid (codex P2 on PR #159)."""- from cubepi.hitl.binding import HitlBinding- from cubepi.middleware.base import Middleware+ from cubeloop.hitl.binding import HitlBinding+ from cubeloop.middleware.base import Middlewareclass _NoOpParams(BaseModel):passdiff --git a/tests/middleware/test_transform_system_prompt.py b/tests/middleware/test_transform_system_prompt.pyindex cf7eedb..1f5f145 100644--- a/tests/middleware/test_transform_system_prompt.py+++ b/tests/middleware/test_transform_system_prompt.py@@ -2,10 +2,10 @@import pytest-from cubepi import Agent-from cubepi.agent.types import AgentContext-from cubepi.middleware.base import Middleware, compose_middleware-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop import Agent+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.base import Middleware, compose_middleware+from cubeloop.providers.faux import FauxProvider, faux_assistant_messageclass _AppendA(Middleware):diff --git a/tests/providers/images/test_base.py b/tests/providers/images/test_base.pyindex e66c417..846cc24 100644--- a/tests/providers/images/test_base.py+++ b/tests/providers/images/test_base.py@@ -1,11 +1,11 @@import pytest-from cubepi.providers.images.base import BaseImagesProvider, ImagesProvider-from cubepi.providers.images.capability import (+from cubeloop.providers.images.base import BaseImagesProvider, ImagesProvider+from cubeloop.providers.images.capability import (ImagesCapabilityDescriptor,SizeSpec,)-from cubepi.providers.images.types import (+from cubeloop.providers.images.types import (AssistantImages,ImagesContext,ImagesCost,diff --git a/tests/providers/images/test_capability.py b/tests/providers/images/test_capability.pyindex 73dae7f..cf4900c 100644--- a/tests/providers/images/test_capability.py+++ b/tests/providers/images/test_capability.py@@ -1,4 +1,4 @@-from cubepi.providers.images.capability import (+from cubeloop.providers.images.capability import (ImagesCapabilityDescriptor,SizeSpec,)diff --git a/tests/providers/images/test_capability_payload_mapping.py b/tests/providers/images/test_capability_payload_mapping.pyindex 3433939..3556697 100644--- a/tests/providers/images/test_capability_payload_mapping.py+++ b/tests/providers/images/test_capability_payload_mapping.py@@ -1,11 +1,11 @@import pytest-from cubepi.providers.images.base import BaseImagesProvider-from cubepi.providers.images.capability import (+from cubeloop.providers.images.base import BaseImagesProvider+from cubeloop.providers.images.capability import (ImagesCapabilityDescriptor,SizeSpec,)-from cubepi.providers.images.types import (+from cubeloop.providers.images.types import (AssistantImages,ImagesContext,ImagesModel,diff --git a/tests/providers/images/test_faux_provider.py b/tests/providers/images/test_faux_provider.pyindex 5a9faa4..5fe6781 100644--- a/tests/providers/images/test_faux_provider.py+++ b/tests/providers/images/test_faux_provider.py@@ -2,9 +2,9 @@ import base64import pytest-from cubepi.errors import ProviderError, RateLimited-from cubepi.providers.images.faux import FauxImagesProvider-from cubepi.providers.images.types import ImagesContext+from cubeloop.errors import ProviderError, RateLimited+from cubeloop.providers.images.faux import FauxImagesProvider+from cubeloop.providers.images.types import ImagesContextdef _png_b64() -> str:@@ -50,7 +50,7 @@ async def test_raise_on_call_can_be_base_provider_error():def test_inherits_from_base_images_provider():- from cubepi.providers.images.base import BaseImagesProvider+ from cubeloop.providers.images.base import BaseImagesProviderp = FauxImagesProvider(png_b64=_png_b64())assert isinstance(p, BaseImagesProvider)@@ -68,7 +68,7 @@ async def test_pre_set_signal_returns_aborted_matching_real_provider():path actually aborts."""import asyncio- from cubepi.providers.images.types import ImagesOptions+ from cubeloop.providers.images.types import ImagesOptionsp = FauxImagesProvider(png_b64=_png_b64())model = p.model("faux-1")@@ -90,7 +90,7 @@ async def test_unset_signal_still_returns_happy_path_image():Faux returns the deterministic image as usual."""import asyncio- from cubepi.providers.images.types import ImagesOptions+ from cubeloop.providers.images.types import ImagesOptionsp = FauxImagesProvider(png_b64=_png_b64())model = p.model("faux-1")@@ -158,8 +158,8 @@ async def test_subscribe_response_fires_on_pre_set_abort_with_images_aborted():the same way OpenAIImagesProvider does."""import asyncio- from cubepi.providers.images import ImagesAborted- from cubepi.providers.images.types import ImagesOptions+ from cubeloop.providers.images import ImagesAborted+ from cubeloop.providers.images.types import ImagesOptionsp = FauxImagesProvider(png_b64=_png_b64())model = p.model("faux-1")@@ -186,7 +186,7 @@ async def test_pre_set_abort_skips_request_listener_in_faux():contract as OpenAIImagesProvider."""import asyncio- from cubepi.providers.images.types import ImagesOptions+ from cubeloop.providers.images.types import ImagesOptionsp = FauxImagesProvider(png_b64=_png_b64())model = p.model("faux-1")diff --git a/tests/providers/images/test_openai_images.py b/tests/providers/images/test_openai_images.pyindex e187833..9caef87 100644--- a/tests/providers/images/test_openai_images.py+++ b/tests/providers/images/test_openai_images.py@@ -4,18 +4,18 @@ from types import SimpleNamespaceimport pytest-from cubepi.errors import (+from cubeloop.errors import (ProviderAuthFailed,ProviderUnavailable,RateLimited,)-from cubepi.providers.base import ImageContent-from cubepi.providers.images.capability import (+from cubeloop.providers.base import ImageContent+from cubeloop.providers.images.capability import (ImagesCapabilityDescriptor,SizeSpec,)-from cubepi.providers.images.openai_images import OpenAIImagesProvider-from cubepi.providers.images.types import (+from cubeloop.providers.images.openai_images import OpenAIImagesProvider+from cubeloop.providers.images.types import (ImagesContext,ImagesOptions,)@@ -288,7 +288,7 @@ async def test_subscribe_response_fires_on_abort_with_images_aborted():takes the normal awaited path. If it were CancelledError, thesync fast-path would schedule async listeners as detached tasksthat asyncio.run() teardown could cancel before they run."""- from cubepi.providers.images import ImagesAborted+ from cubeloop.providers.images import ImagesAbortedp = _provider(sleep=0.5)model = p.model("gpt-image-1")@@ -326,7 +326,7 @@ async def test_async_response_observer_awaited_on_abort():fast-path triggered by exc being a CancelledError); underasyncio.run() teardown those detached tasks were getting cancelledbefore they could record the abort."""- from cubepi.providers.images import ImagesAborted+ from cubeloop.providers.images import ImagesAbortedp = _provider(sleep=0.5)model = p.model("gpt-image-1")@@ -633,7 +633,7 @@ async def test_pre_set_signal_does_not_fire_request_listener():async def test_pre_set_signal_still_fires_response_listener():"""Pre-set signal aborts cleanly but the response observer still fires(with body=None, exc=ImagesAborted) so tracing records the abort."""- from cubepi.providers.images import ImagesAborted+ from cubeloop.providers.images import ImagesAbortedp = _provider()model = p.model("gpt-image-1")diff --git a/tests/providers/images/test_types.py b/tests/providers/images/test_types.pyindex 4510f26..0852aa6 100644--- a/tests/providers/images/test_types.py+++ b/tests/providers/images/test_types.py@@ -4,8 +4,8 @@ from typing import get_argsimport pytestfrom pydantic import ValidationError-from cubepi.providers.base import ImageContent-from cubepi.providers.images.types import (+from cubeloop.providers.base import ImageContent+from cubeloop.providers.images.types import (AssistantImages,ImagesContext,ImagesCost,@@ -133,12 +133,12 @@ def test_assistant_images_provider_id_renamed():def test_top_level_re_exports():- """The image types are reachable via `from cubepi import ...`."""- import cubepi+ """The image types are reachable via `from cubeloop import ...`."""+ import cubeloopassert (- cubepi.ImagesModel- is __import__("cubepi.providers.images", fromlist=["ImagesModel"]).ImagesModel+ cubeloop.ImagesModel+ is __import__("cubeloop.providers.images", fromlist=["ImagesModel"]).ImagesModel)for name in ("AssistantImages",@@ -152,4 +152,4 @@ def test_top_level_re_exports():"ImagesProvider","SizeSpec",):- assert hasattr(cubepi, name), f"cubepi.{name} not exported"+ assert hasattr(cubeloop, name), f"cubepi.{name} not exported"diff --git a/tests/providers/test_anthropic.py b/tests/providers/test_anthropic.pyindex 694a8ec..cecafa4 100644--- a/tests/providers/test_anthropic.py+++ b/tests/providers/test_anthropic.py@@ -6,8 +6,8 @@ from unittest.mock import MagicMockimport pytest-from cubepi.providers.anthropic import AnthropicProvider, CacheRetention-from cubepi.providers.base import (+from cubeloop.providers.anthropic import AnthropicProvider, CacheRetention+from cubeloop.providers.base import (ImageContent,Model,ReasoningControl,@@ -1472,7 +1472,7 @@ class TestAnthropicTypedErrorWrapping:@pytest.mark.asyncioasync def test_rate_limit_429_delivers_rate_limited_to_listener(self) -> None:- from cubepi.errors import RateLimited+ from cubeloop.errors import RateLimitedexc = _FakeAnthropicExc("Rate limit exceeded", status_code=429)provider = _make_provider("none")@@ -1503,7 +1503,7 @@ class TestAnthropicTypedErrorWrapping:async def test_context_length_message_delivers_context_length_exceeded(self,) -> None:- from cubepi.errors import ContextLengthExceeded+ from cubeloop.errors import ContextLengthExceededexc = _FakeAnthropicExc("This model's maximum context length is 200000 tokens.", status_code=400diff --git a/tests/providers/test_anthropic_cache_policy.py b/tests/providers/test_anthropic_cache_policy.pyindex 4bb3d76..2eca817 100644--- a/tests/providers/test_anthropic_cache_policy.py+++ b/tests/providers/test_anthropic_cache_policy.py@@ -2,11 +2,11 @@import pytest-from cubepi.providers.anthropic import (+from cubeloop.providers.anthropic import (AnthropicProvider,DefaultCacheMarkerPolicy,)-from cubepi.providers.base import Message, TextContent, UserMessage+from cubeloop.providers.base import Message, TextContent, UserMessagedef test_default_policy_marks_system() -> None:diff --git a/tests/providers/test_anthropic_capability.py b/tests/providers/test_anthropic_capability.pyindex 32e14b0..277dcd6 100644--- a/tests/providers/test_anthropic_capability.py+++ b/tests/providers/test_anthropic_capability.py@@ -12,15 +12,15 @@ from typing import Anyimport pytest-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.base import (+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.base import (Model,ReasoningControl,StreamOptions,TextContent,UserMessage,)-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,ReasoningCapability,TemperatureSpec,diff --git a/tests/providers/test_base.py b/tests/providers/test_base.pyindex 844d4d9..6235619 100644--- a/tests/providers/test_base.py+++ b/tests/providers/test_base.py@@ -3,7 +3,7 @@ from typing import Anyimport pytest-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,ImageContent,diff --git a/tests/providers/test_bound_model.py b/tests/providers/test_bound_model.pyindex cbb0991..a94a9ed 100644--- a/tests/providers/test_bound_model.py+++ b/tests/providers/test_bound_model.py@@ -1,6 +1,6 @@-from cubepi.providers.base import AssistantMessage, BaseProvider, BoundModel, Model-from cubepi.providers.base import TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.providers.base import AssistantMessage, BaseProvider, BoundModel, Model+from cubeloop.providers.base import TextContent+from cubeloop.providers.faux import FauxProviderdef test_base_provider_model_binds_runtime_provider_and_model_spec() -> None:diff --git a/tests/providers/test_bound_model_calls.py b/tests/providers/test_bound_model_calls.pyindex e43d989..a5f0d2a 100644--- a/tests/providers/test_bound_model_calls.py+++ b/tests/providers/test_bound_model_calls.py@@ -4,7 +4,7 @@ from typing import Anyimport pytest-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,Message,@@ -15,7 +15,7 @@ from cubepi.providers.base import (ToolDefinition,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.faux import FauxProvider, faux_assistant_messageclass _RecordingProvider(BaseProvider):diff --git a/tests/providers/test_content_index.py b/tests/providers/test_content_index.pyindex abc68c4..082e29e 100644--- a/tests/providers/test_content_index.py+++ b/tests/providers/test_content_index.py@@ -1,5 +1,5 @@-from cubepi.providers.base import Model-from cubepi.providers.faux import (+from cubeloop.providers.base import Model+from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,faux_text,diff --git a/tests/providers/test_fallback.py b/tests/providers/test_fallback.pyindex d66a17c..55f0c60 100644--- a/tests/providers/test_fallback.py+++ b/tests/providers/test_fallback.py@@ -4,7 +4,7 @@ from typing import Anyimport pytest-from cubepi.errors import (+from cubeloop.errors import (ContextLengthExceeded,ProviderAuthFailed,ProviderBadRequest,@@ -12,7 +12,7 @@ from cubepi.errors import (ProviderUnavailable,RateLimited,)-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,BoundModel,@@ -26,8 +26,8 @@ from cubepi.providers.base import (ToolDefinition,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.providers.fallback import DEFAULT_TRIGGER_ERRORS, FallbackBoundModel+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.fallback import DEFAULT_TRIGGER_ERRORS, FallbackBoundModelclass _RaisingProvider(BaseProvider):@@ -93,7 +93,7 @@ def test_default_trigger_errors_composition() -> None:assert ContextLengthExceeded in DEFAULT_TRIGGER_ERRORSassert ProviderBadRequest in DEFAULT_TRIGGER_ERRORSassert ProviderAuthFailed not in DEFAULT_TRIGGER_ERRORS- from cubepi.errors import ContentFiltered+ from cubeloop.errors import ContentFilteredassert ContentFiltered not in DEFAULT_TRIGGER_ERRORS@@ -393,7 +393,7 @@ async def test_generate_error_assistant_message_triggers_failover() -> None:def test_chain_providers_for_fallback_returns_unique_providers_in_order() -> None:"""FallbackBoundModel chain → list of unique providers, primary first."""- from cubepi.providers.fallback import chain_providers+ from cubeloop.providers.fallback import chain_providersp1 = FauxProvider(provider_id="p1")p2 = FauxProvider(provider_id="p2")@@ -406,7 +406,7 @@ def test_chain_providers_for_fallback_returns_unique_providers_in_order() -> Nondef test_chain_providers_dedupes_shared_provider_across_legs() -> None:"""Two chain entries on the same provider instance → single entry in output."""- from cubepi.providers.fallback import chain_providers+ from cubeloop.providers.fallback import chain_providersshared = FauxProvider(provider_id="shared")other = FauxProvider(provider_id="other")@@ -421,7 +421,7 @@ def test_chain_providers_dedupes_shared_provider_across_legs() -> None:def test_chain_providers_for_plain_bound_model_returns_single_entry() -> None:"""A plain BoundModel → single-entry list with its provider."""- from cubepi.providers.fallback import chain_providers+ from cubeloop.providers.fallback import chain_providersp = FauxProvider(provider_id="plain")out = chain_providers(p.model("x"))@@ -430,7 +430,7 @@ def test_chain_providers_for_plain_bound_model_returns_single_entry() -> None:def test_chain_providers_for_none_returns_empty() -> None:"""None model → empty list (used by attach()'s legacy fallback path)."""- from cubepi.providers.fallback import chain_providers+ from cubeloop.providers.fallback import chain_providersassert chain_providers(None) == []@@ -442,7 +442,7 @@ def test_chain_providers_warns_when_chain_leg_is_not_base_provider(caplog) -> No"""import logging- from cubepi.providers.fallback import chain_providers+ from cubeloop.providers.fallback import chain_providersreal = FauxProvider(provider_id="real")@@ -473,7 +473,7 @@ def test_chain_providers_warns_when_chain_leg_is_not_base_provider(caplog) -> Nodef test_chain_providers_returns_empty_for_object_without_provider_or_chain() -> None:"""Walk: model is not None, has no .chain, .provider isn't aBaseProvider → final `return []` path."""- from cubepi.providers.base import chain_providers+ from cubeloop.providers.base import chain_providersclass _Bare:"""Object that satisfies `model is not None` but exposes neither@@ -487,7 +487,7 @@ def test_collect_agent_providers_falls_back_to_legacy_provider_attribute() -> No"""When ``agent._model`` is absent / yields no providers and theagent itself exposes a ``provider`` attribute that IS a BaseProvider,use it. Covers the legacy fallback path."""- from cubepi.providers.base import collect_agent_providers+ from cubeloop.providers.base import collect_agent_providersreal = FauxProvider(provider_id="legacy")@@ -502,7 +502,7 @@ def test_collect_agent_providers_empty_when_no_model_or_legacy_provider() -> Non"""No `_model`, no `provider` → empty list. Defensive for fullydetached agents (unlikely in practice but the contract guarantees []rather than a crash)."""- from cubepi.providers.base import collect_agent_providers+ from cubeloop.providers.base import collect_agent_providersclass _BlankAgent:pass@@ -778,7 +778,7 @@ async def test_first_event_typed_rate_limited_retries_then_failovers() -> None:@pytest.mark.asyncioasync def test_sticky_after_successful_failover() -> None:- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run+ from cubeloop.providers.fallback import begin_fallback_run, end_fallback_runerr = ProviderUnavailable("down", provider="primary", model="m")primary = _raising(err)@@ -802,7 +802,7 @@ async def test_sticky_after_successful_failover() -> None:@pytest.mark.asyncioasync def test_sticky_second_call_skips_primary() -> None:- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run+ from cubeloop.providers.fallback import begin_fallback_run, end_fallback_runerr = ProviderUnavailable("down", provider="primary", model="m")primary_p = _CountingRaiseProvider(err, fail_times=99, provider_id="primary")@@ -825,7 +825,7 @@ async def test_sticky_second_call_skips_primary() -> None:@pytest.mark.asyncioasync def test_new_run_resets_sticky_to_primary() -> None:- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run+ from cubeloop.providers.fallback import begin_fallback_run, end_fallback_runprim = FauxProvider(provider_id="primary")prim.set_responses(@@ -851,7 +851,7 @@ async def test_new_run_resets_sticky_to_primary() -> None:@pytest.mark.asyncioasync def test_new_run_after_failover_probes_primary_again() -> None:- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run+ from cubeloop.providers.fallback import begin_fallback_run, end_fallback_runerr = ProviderUnavailable("down", provider="primary", model="m")primary_p = _CountingRaiseProvider(err, fail_times=99, provider_id="primary")@@ -937,7 +937,7 @@ async def test_generate_skips_too_small_middle_leg() -> None:@pytest.mark.asyncioasync def test_content_filtered_does_not_hop_unless_listed() -> None:- from cubepi.errors import ContentFiltered+ from cubeloop.errors import ContentFilterederr = ContentFiltered("blocked", provider="primary", model="m")primary = _raising(err)@@ -950,7 +950,7 @@ async def test_content_filtered_does_not_hop_unless_listed() -> None:@pytest.mark.asyncioasync def test_content_filtered_hops_when_opted_in() -> None:- from cubepi.errors import ContentFiltered+ from cubeloop.errors import ContentFilterederr = ContentFiltered("blocked", provider="primary", model="m")primary = _raising(err)@@ -966,7 +966,7 @@ async def test_content_filtered_hops_when_opted_in() -> None:@pytest.mark.asyncioasync def test_reset_active_and_index_helpers() -> None:- from cubepi.providers.fallback import (+ from cubeloop.providers.fallback import (begin_fallback_run,end_fallback_run,get_active_index,@@ -1055,7 +1055,7 @@ async def test_async_on_retry_is_awaited() -> None:def test_context_too_small_without_need_or_window() -> None:- from cubepi.providers.fallback import _context_too_small+ from cubeloop.providers.fallback import _context_too_smallbound = BoundModel(provider=_RaisingProvider(ProviderUnavailable("x")),@@ -1075,7 +1075,7 @@ def test_context_too_small_without_need_or_window() -> None:def test_start_index_clamps_out_of_range() -> None:- from cubepi.providers.fallback import (+ from cubeloop.providers.fallback import (begin_fallback_run,end_fallback_run,set_active_index,@@ -1091,7 +1091,7 @@ def test_start_index_clamps_out_of_range() -> None:def test_stick_noop_when_disabled() -> None:- from cubepi.providers.fallback import begin_fallback_run, end_fallback_run+ from cubeloop.providers.fallback import begin_fallback_run, end_fallback_runfbm = FallbackBoundModel(chain=(_faux("p", "hi"),), sticky_within_run=False)token = begin_fallback_run()diff --git a/tests/providers/test_faux.py b/tests/providers/test_faux.pyindex 97ccd90..e4c1dcf 100644--- a/tests/providers/test_faux.py+++ b/tests/providers/test_faux.py@@ -1,7 +1,7 @@import asynciofrom unittest.mock import patch-from cubepi.providers.base import (+from cubeloop.providers.base import (Model,StreamEvent,StreamOptions,@@ -9,7 +9,7 @@ from cubepi.providers.base import (ToolDefinition,UserMessage,)-from cubepi.providers.faux import (+from cubeloop.providers.faux import (FauxProvider,_can_accept_extended_args,faux_assistant_message,@@ -66,7 +66,7 @@ class TestFauxHelpers:class TestFauxProvider:def _make_model(self):- from cubepi.providers.base import Model+ from cubeloop.providers.base import Modelreturn Model(id="faux-1", provider_id="faux")@@ -321,7 +321,7 @@ class TestFauxProviderExtendedFactory:"""Tests for extended factory signature (messages, model, system_prompt, tools)."""def _make_model(self):- from cubepi.providers.base import Model+ from cubeloop.providers.base import Modelreturn Model(id="faux-1", provider_id="faux")@@ -468,7 +468,7 @@ class TestFauxProviderPromptCache:"""Tests for prompt cache simulation."""def _make_model(self):- from cubepi.providers.base import Model+ from cubeloop.providers.base import Modelreturn Model(id="faux-1", provider_id="faux")@@ -731,7 +731,7 @@ class TestFauxProviderAbortDuringBlocks:push via a patched MessageStream.push, so it's set before thefor-block check runs for the next block."""- from cubepi.providers.base import MessageStream+ from cubeloop.providers.base import MessageStreamprovider = FauxProvider(token_size_min=100, token_size_max=100)signal = asyncio.Event()@@ -760,7 +760,7 @@ class TestFauxProviderAbortDuringBlocks:Uses push-patching to set the signal synchronously in the producer,avoiding consumer-side races."""- from cubepi.providers.base import MessageStream+ from cubeloop.providers.base import MessageStreamlong_thinking = "a" * 200provider = FauxProvider(token_size_min=1, token_size_max=1)@@ -798,7 +798,7 @@ class TestFauxProviderAbortDuringBlocks:Uses push-patching to set the signal synchronously in the producer,avoiding consumer-side races."""- from cubepi.providers.base import MessageStream+ from cubeloop.providers.base import MessageStreamlarge_args = {f"key_{i}": f"value_{i}" for i in range(20)}provider = FauxProvider(token_size_min=1, token_size_max=1)@@ -837,7 +837,7 @@ class TestFauxProviderAbortDuringBlocks:Uses push-patching to set the signal synchronously in the producer,avoiding consumer-side races."""- from cubepi.providers.base import MessageStream+ from cubeloop.providers.base import MessageStreamlong_text = "word " * 100provider = FauxProvider(token_size_min=1, token_size_max=1)diff --git a/tests/providers/test_hooks.py b/tests/providers/test_hooks.pyindex 93a040e..1506c06 100644--- a/tests/providers/test_hooks.py+++ b/tests/providers/test_hooks.py@@ -6,7 +6,7 @@ import inspectfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch-from cubepi.providers.base import (+from cubeloop.providers.base import (Model,ProviderResponse,StreamOptions,@@ -141,8 +141,8 @@ class TestInvokeOnResponse:class TestAnthropicProviderHooks:async def test_on_payload_called_with_kwargs(self):"""on_payload receives the payload dict and model before the API call."""- from cubepi.providers.anthropic import AnthropicProvider- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.anthropic import AnthropicProvider+ from cubeloop.providers.base import TextContent, UserMessagecaptured_payloads: list[tuple[dict, Model]] = []@@ -194,8 +194,8 @@ class TestAnthropicProviderHooks:async def test_on_payload_replaces_kwargs(self):"""When on_payload returns a dict, that dict replaces the payload."""- from cubepi.providers.anthropic import AnthropicProvider- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.anthropic import AnthropicProvider+ from cubeloop.providers.base import TextContent, UserMessagedef on_payload(payload: dict, model: Model) -> dict:payload["model"] = "replaced-model"@@ -248,8 +248,8 @@ class TestAnthropicProviderHooks:class TestOpenAIProviderHooks:async def test_on_payload_called_with_kwargs(self):"""on_payload receives the payload dict and model before the API call."""- from cubepi.providers.openai import OpenAIProvider- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.openai import OpenAIProvider+ from cubeloop.providers.base import TextContent, UserMessagecaptured_payloads: list[tuple[dict, Model]] = []@@ -298,8 +298,8 @@ class TestOpenAIProviderHooks:async def test_on_payload_replaces_kwargs(self):"""When on_payload returns a dict, that dict replaces the payload."""- from cubepi.providers.openai import OpenAIProvider- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.openai import OpenAIProvider+ from cubeloop.providers.base import TextContent, UserMessagedef on_payload(payload: dict, model: Model) -> dict:payload["temperature"] = 0.5@@ -344,8 +344,8 @@ class TestOpenAIProviderHooks:class TestOpenAIResponsesProviderHooks:async def test_on_payload_called_with_kwargs(self):"""on_payload receives the payload dict and model before the API call."""- from cubepi.providers.openai_responses import OpenAIResponsesProvider- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.openai_responses import OpenAIResponsesProvider+ from cubeloop.providers.base import TextContent, UserMessagecaptured_payloads: list[tuple[dict, Model]] = []@@ -395,8 +395,8 @@ class TestOpenAIResponsesProviderHooks:async def test_on_payload_replaces_kwargs(self):"""When on_payload returns a dict, that dict replaces the payload."""- from cubepi.providers.openai_responses import OpenAIResponsesProvider- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.openai_responses import OpenAIResponsesProvider+ from cubeloop.providers.base import TextContent, UserMessagedef on_payload(payload: dict, model: Model) -> dict:payload["temperature"] = 0.7@@ -440,8 +440,8 @@ class TestOpenAIResponsesProviderHooks:async def test_on_response_called_when_http_response_available(self):"""on_response is invoked with HTTP metadata after the API call."""- from cubepi.providers.openai_responses import OpenAIResponsesProvider- from cubepi.providers.base import TextContent, UserMessage+ from cubeloop.providers.openai_responses import OpenAIResponsesProvider+ from cubeloop.providers.base import TextContent, UserMessagecaptured_responses: list[tuple[ProviderResponse, Model]] = []@@ -505,7 +505,7 @@ class TestOpenAIResponsesProviderHooks:class TestProtocolConformance:def test_provider_protocol_accepts_options(self):"""The Provider protocol's stream method includes options."""- from cubepi.providers.base import Provider+ from cubeloop.providers.base import Providersig = inspect.signature(Provider.stream)params = sig.parametersdiff --git a/tests/providers/test_init.py b/tests/providers/test_init.pyindex 35a5d5f..5a938ee 100644--- a/tests/providers/test_init.py+++ b/tests/providers/test_init.py@@ -1,4 +1,4 @@-from cubepi.providers import (+from cubeloop.providers import (get_anthropic_provider,get_openai_provider,get_openai_responses_provider,diff --git a/tests/providers/test_listener_registry.py b/tests/providers/test_listener_registry.pyindex 4e0e16f..be4bbcf 100644--- a/tests/providers/test_listener_registry.py+++ b/tests/providers/test_listener_registry.py@@ -12,8 +12,8 @@ import timeimport pytest-from cubepi.providers.base import Model, StreamEvent, StreamOptions, UserMessage-from cubepi.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.base import Model, StreamEvent, StreamOptions, UserMessage+from cubeloop.providers.faux import FauxProvider, faux_assistant_messageMODEL = Model(id="faux-1", provider_id="faux")@@ -598,7 +598,7 @@ class TestBaseProvider:"""Cover BaseProvider sentinels not exercised by Faux."""async def test_stream_raises_not_implemented(self):- from cubepi.providers.base import BaseProvider+ from cubeloop.providers.base import BaseProviderclass Empty(BaseProvider):pass@@ -621,13 +621,13 @@ class TestFireListenersHelpers:end-to-end."""async def test_fire_listeners_empty_returns(self):- from cubepi.providers.base import _fire_listeners+ from cubeloop.providers.base import _fire_listeners# Empty list — must return without touching anything.await _fire_listeners([])async def test_fire_listeners_swallows_sync_exception(self):- from cubepi.providers.base import _fire_listeners+ from cubeloop.providers.base import _fire_listenersseen: list = []@@ -642,12 +642,12 @@ class TestFireListenersHelpers:assert seen == ["payload"]def test_fire_listeners_sync_empty_returns(self):- from cubepi.providers.base import _fire_listeners_sync+ from cubeloop.providers.base import _fire_listeners_sync_fire_listeners_sync([]) # No listeners — short-circuit.def test_fire_listeners_sync_swallows_sync_exception(self):- from cubepi.providers.base import _fire_listeners_sync+ from cubeloop.providers.base import _fire_listeners_syncseen: list = []@@ -664,7 +664,7 @@ class TestFireListenersHelpers:"""Outside a running event loop, asyncio.create_task raisesRuntimeError. The sync helper must swallow it (covers theno-running-loop branch in the detached-task scheduling)."""- from cubepi.providers.base import _fire_listeners_sync+ from cubeloop.providers.base import _fire_listeners_syncasync def async_cb(x):pass # pragma: no cover — never awaited in this test@@ -679,8 +679,8 @@ class TestProviderEmit:but the Faux end-to-end tests exercise Faux's _emit only."""async def test_anthropic_emit_fires_chunk_listeners(self):- from cubepi.providers.anthropic import AnthropicProvider- from cubepi.providers.base import MessageStream+ from cubeloop.providers.anthropic import AnthropicProvider+ from cubeloop.providers.base import MessageStreamprovider = AnthropicProvider(api_key="test-key")seen: list = []@@ -696,8 +696,8 @@ class TestProviderEmit:assert first.type == "text_delta"async def test_openai_emit_fires_chunk_listeners(self):- from cubepi.providers.openai import OpenAIProvider- from cubepi.providers.base import MessageStream+ from cubeloop.providers.openai import OpenAIProvider+ from cubeloop.providers.base import MessageStreamprovider = OpenAIProvider(api_key="test-key")seen: list = []@@ -708,8 +708,8 @@ class TestProviderEmit:assert seen == ["text_delta"]async def test_openai_responses_emit_fires_chunk_listeners(self):- from cubepi.providers.openai_responses import OpenAIResponsesProvider- from cubepi.providers.base import MessageStream+ from cubeloop.providers.openai_responses import OpenAIResponsesProvider+ from cubeloop.providers.base import MessageStreamprovider = OpenAIResponsesProvider(api_key="test-key")seen: list = []@@ -725,7 +725,7 @@ class TestAssembleResponse:optional-field branches without needing a real LLM stream."""def test_openai_assemble_with_system_fingerprint_and_service_tier(self):- from cubepi.providers.openai import OpenAIProvider+ from cubeloop.providers.openai import OpenAIProviderclass FakeUsageDetails:cached_tokens = 7@@ -763,7 +763,7 @@ class TestAssembleResponse:assert body["usage"]["prompt_tokens_details"] == {"cached_tokens": 7}def test_openai_assemble_without_optional_fields(self):- from cubepi.providers.openai import OpenAIProvider+ from cubeloop.providers.openai import OpenAIProviderbody = OpenAIProvider._assemble_response(response_id=None,diff --git a/tests/providers/test_message_metadata.py b/tests/providers/test_message_metadata.pyindex 7780b5d..356a504 100644--- a/tests/providers/test_message_metadata.py+++ b/tests/providers/test_message_metadata.py@@ -4,14 +4,14 @@ import tempfilefrom pathlib import Pathimport pytest-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolResultMessage,Usage,UserMessage,)-from cubepi.checkpointer import MemoryCheckpointer, SQLiteCheckpointer+from cubeloop.checkpointer import MemoryCheckpointer, SQLiteCheckpointerdef test_user_message_default_metadata_is_empty_dict() -> None:diff --git a/tests/providers/test_message_run_id.py b/tests/providers/test_message_run_id.pyindex fb2b588..38f3175 100644--- a/tests/providers/test_message_run_id.py+++ b/tests/providers/test_message_run_id.py@@ -1,4 +1,4 @@-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,TextContent,ToolResultMessage,diff --git a/tests/providers/test_models.py b/tests/providers/test_models.pyindex 079b543..efae533 100644--- a/tests/providers/test_models.py+++ b/tests/providers/test_models.py@@ -1,5 +1,5 @@-from cubepi.providers.base import Model-from cubepi.providers.models import models_are_equal+from cubeloop.providers.base import Model+from cubeloop.providers.models import models_are_equaldef test_models_are_equal_by_provider_and_model_id():diff --git a/tests/providers/test_openai.py b/tests/providers/test_openai.pyindex 05b1595..c6f1049 100644--- a/tests/providers/test_openai.py+++ b/tests/providers/test_openai.py@@ -6,8 +6,8 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from cubepi.providers.openai import OpenAIProvider-from cubepi.providers.base import (+from cubeloop.providers.openai import OpenAIProvider+from cubeloop.providers.base import (AssistantMessage,ImageContent,Model,@@ -963,7 +963,7 @@ class TestOpenAITypedErrorWrapping:@pytest.mark.asyncioasync def test_rate_limit_429_delivers_rate_limited_to_listener(self) -> None:- from cubepi.errors import RateLimited+ from cubeloop.errors import RateLimitedexc = _FakeSdkExc("Rate limit exceeded", status_code=429)mock_client = MagicMock()@@ -996,7 +996,7 @@ class TestOpenAITypedErrorWrapping:async def test_context_length_message_delivers_context_length_exceeded(self,) -> None:- from cubepi.errors import ContextLengthExceeded+ from cubeloop.errors import ContextLengthExceededexc = _FakeSdkExc("This model's maximum context length is 128000 tokens.", status_code=400diff --git a/tests/providers/test_openai_capability.py b/tests/providers/test_openai_capability.pyindex d2919d8..ebf6086 100644--- a/tests/providers/test_openai_capability.py+++ b/tests/providers/test_openai_capability.py@@ -6,19 +6,19 @@ the provider's internal state. Stream-time assertions come in Task 6.import pytest-from cubepi.providers.base import (+from cubeloop.providers.base import (Model,ReasoningControl,StreamOptions,TextContent,UserMessage,)-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,ReasoningCapability,TemperatureSpec,)-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.openai import OpenAIProviderdef test_provider_accepts_capability_kwarg():diff --git a/tests/providers/test_openai_extras_and_schema.py b/tests/providers/test_openai_extras_and_schema.pyindex c7de4d7..e24c381 100644--- a/tests/providers/test_openai_extras_and_schema.py+++ b/tests/providers/test_openai_extras_and_schema.py@@ -12,13 +12,13 @@ from unittest.mock import MagicMock, patchimport pytestfrom pydantic import BaseModel-from cubepi.providers.base import (+from cubeloop.providers.base import (Model,StreamOptions,TextContent,UserMessage,)-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.openai import OpenAIProviderdef _model() -> Model:diff --git a/tests/providers/test_openai_reasoning.py b/tests/providers/test_openai_reasoning.pyindex ee3559b..d1cdc30 100644--- a/tests/providers/test_openai_reasoning.py+++ b/tests/providers/test_openai_reasoning.py@@ -7,8 +7,8 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from cubepi.providers.openai import OpenAIProvider-from cubepi.providers.base import (+from cubeloop.providers.openai import OpenAIProvider+from cubeloop.providers.base import (Model,TextContent,ThinkingContent,diff --git a/tests/providers/test_openai_responses.py b/tests/providers/test_openai_responses.pyindex e70bde0..289d598 100644--- a/tests/providers/test_openai_responses.py+++ b/tests/providers/test_openai_responses.py@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,ImageContent,Model,@@ -21,7 +21,7 @@ from cubepi.providers.base import (ToolResultMessage,UserMessage,)-from cubepi.providers.openai_responses import OpenAIResponsesProvider+from cubeloop.providers.openai_responses import OpenAIResponsesProvider# ---------------------------------------------------------------------------diff --git a/tests/providers/test_openai_responses_capability.py b/tests/providers/test_openai_responses_capability.pyindex 8788b5d..1eae863 100644--- a/tests/providers/test_openai_responses_capability.py+++ b/tests/providers/test_openai_responses_capability.py@@ -10,19 +10,19 @@ from unittest.mock import AsyncMock, MagicMockimport pytest-from cubepi.providers.base import (+from cubeloop.providers.base import (Model,ReasoningControl,StreamOptions,TextContent,UserMessage,)-from cubepi.providers.capability import (+from cubeloop.providers.capability import (CapabilityDescriptor,ReasoningCapability,TemperatureSpec,)-from cubepi.providers.openai_responses import OpenAIResponsesProvider+from cubeloop.providers.openai_responses import OpenAIResponsesProviderdef _model(id: str = "gpt-5-test", *, reasoning: bool = False, **kw) -> Model:diff --git a/tests/providers/test_reasoning_capability.py b/tests/providers/test_reasoning_capability.pyindex 373a940..e844e2f 100644--- a/tests/providers/test_reasoning_capability.py+++ b/tests/providers/test_reasoning_capability.py@@ -1,5 +1,5 @@-from cubepi.providers.base import Model, ReasoningControl, StreamOptions-from cubepi.providers.capability import (+from cubeloop.providers.base import Model, ReasoningControl, StreamOptions+from cubeloop.providers.capability import (CapabilityDescriptor,CapabilityWarning,PayloadPreview,@@ -8,7 +8,7 @@ from cubepi.providers.capability import (lint_capability,preview_payload,)-from cubepi.providers.reasoning_profiles import get_capability_profile+from cubeloop.providers.reasoning_profiles import get_capability_profiledef test_stream_options_default_reasoning_is_off_medium_none():diff --git a/tests/providers/test_sender_attribution.py b/tests/providers/test_sender_attribution.pyindex 1903b49..1d04e9c 100644--- a/tests/providers/test_sender_attribution.py+++ b/tests/providers/test_sender_attribution.py@@ -1,6 +1,6 @@"""Tests for sender_attribution helpers used by group chat."""-from cubepi.providers.base import (+from cubeloop.providers.base import (ImageContent,TextContent,UserMessage,diff --git a/tests/providers/test_tool_choice.py b/tests/providers/test_tool_choice.pyindex d5fb73f..a39aa24 100644--- a/tests/providers/test_tool_choice.py+++ b/tests/providers/test_tool_choice.py@@ -10,11 +10,11 @@ from __future__ import annotationsfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.base import Model, ToolDefinition, UserMessage, TextContent-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.providers.openai import OpenAIProvider-from cubepi.providers.openai_responses import OpenAIResponsesProvider+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.base import Model, ToolDefinition, UserMessage, TextContent+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.providers.openai import OpenAIProvider+from cubeloop.providers.openai_responses import OpenAIResponsesProvider# ---------------------------------------------------------------------------diff --git a/tests/test_capability.py b/tests/test_capability.pyindex bdf435f..cc0b716 100644--- a/tests/test_capability.py+++ b/tests/test_capability.py@@ -1,8 +1,8 @@import pytestfrom pydantic import ValidationError-from cubepi.providers.base import Model, ReasoningControl-from cubepi.providers.capability import (+from cubeloop.providers.base import Model, ReasoningControl+from cubeloop.providers.capability import (CapabilityDescriptor,ReasoningCapability,TemperatureSpec,diff --git a/tests/test_errors.py b/tests/test_errors.pyindex 26ea414..af32eb6 100644--- a/tests/test_errors.py+++ b/tests/test_errors.py@@ -6,7 +6,7 @@ from types import SimpleNamespaceimport pytest-from cubepi.errors import (+from cubeloop.errors import (ContentFiltered,ContextLengthExceeded,ModelNotFound,@@ -20,7 +20,7 @@ from cubepi.errors import (_status_of,classify_and_raise,)-from cubepi.providers.base import Model, TextContent, UserMessage+from cubeloop.providers.base import Model, TextContent, UserMessage# ---------------------------------------------------------------------------@@ -370,7 +370,7 @@ class TestSDKConnectionErrors:class TestErrorCodeExtraction:def test_openai_error_code(self) -> None:- from cubepi.errors import extract_error_code+ from cubeloop.errors import extract_error_codeexc = _FakeExc("nope", status_code=400)exc.body = {@@ -396,7 +396,7 @@ class TestErrorCodeExtraction:assert not isinstance(ei.value, ModelNotFound)def test_nested_error_object_and_attr_error(self) -> None:- from cubepi.errors import extract_error_code+ from cubeloop.errors import extract_error_codenested = _FakeExc("x", status_code=400)nested.error = {"error": {"code": "model_not_available"}}@@ -412,7 +412,7 @@ class TestErrorCodeExtraction:assert extract_error_code(attr) == "content_filter"def test_type_fallback_and_param_model(self) -> None:- from cubepi.errors import extract_error_code+ from cubeloop.errors import extract_error_codetyp = _FakeExc("x", status_code=400)typ.error = {"type": "invalid_model"}@@ -427,7 +427,7 @@ class TestErrorCodeExtraction:assert extract_error_code(other) == "overloaded_error"def test_looks_like_model_not_found_gates(self) -> None:- from cubepi.errors import _looks_like_model_not_found+ from cubeloop.errors import _looks_like_model_not_foundassert _looks_like_model_not_found(status=500, code="model_not_found", msg="x")assert _looks_like_model_not_found(@@ -441,12 +441,12 @@ class TestErrorCodeExtraction:)def test_content_filtered_by_code(self) -> None:- from cubepi.errors import _looks_like_content_filtered+ from cubeloop.errors import _looks_like_content_filteredassert _looks_like_content_filtered(code="content_filter", msg="nope")def test_classify_string_error_branches(self) -> None:- from cubepi.errors import classify_string_error+ from cubeloop.errors import classify_string_errorassert isinstance(classify_string_error("maximum context length exceeded"),@@ -469,7 +469,7 @@ class TestErrorCodeExtraction:)def test_error_from_stream_fields_context_length(self) -> None:- from cubepi.errors import error_from_stream_fields+ from cubeloop.errors import error_from_stream_fieldserr = error_from_stream_fields(error_message="too long",@@ -481,7 +481,7 @@ class TestErrorCodeExtraction:assert err.tokens_in == 99def test_annotate_error_event_typed_and_raw(self) -> None:- from cubepi.errors import annotate_error_event+ from cubeloop.errors import annotate_error_eventrl = RateLimited("wait", retry_after=1.5, provider="p", model="m")fields = annotate_error_event(rl)diff --git a/tests/test_goal.py b/tests/test_goal.pyindex 76d06fd..848434e 100644--- a/tests/test_goal.py+++ b/tests/test_goal.py@@ -3,10 +3,10 @@from __future__ import annotations-from cubepi import Agent-from cubepi.agent.types import AgentContext-from cubepi.middleware.goal import GoalMiddleware, _format_messages_for_eval-from cubepi.providers.base import (+from cubeloop import Agent+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.goal import GoalMiddleware, _format_messages_for_eval+from cubeloop.providers.base import (AssistantMessage,ImageContent,Message,@@ -15,7 +15,7 @@ from cubepi.providers.base import (ToolResultMessage,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call+from cubeloop.providers.faux import FauxProvider, faux_assistant_message, faux_tool_calldef _ctx(messages: list[Message] | None = None) -> AgentContext:diff --git a/tests/test_init.py b/tests/test_init.pyindex bce2e1e..933b66b 100644--- a/tests/test_init.py+++ b/tests/test_init.py@@ -4,9 +4,9 @@ from __future__ import annotationsdef test_capability_types_re_exported():- import cubepi+ import cubeloop- assert hasattr(cubepi, "CapabilityDescriptor")- assert hasattr(cubepi, "ReasoningCapability")- assert hasattr(cubepi, "TemperatureSpec")- assert not hasattr(cubepi, "ReasoningLevelSpec")+ assert hasattr(cubeloop, "CapabilityDescriptor")+ assert hasattr(cubeloop, "ReasoningCapability")+ assert hasattr(cubeloop, "TemperatureSpec")+ assert not hasattr(cubeloop, "ReasoningLevelSpec")diff --git a/tests/test_package.py b/tests/test_package.pyindex 2328d5f..a085857 100644--- a/tests/test_package.py+++ b/tests/test_package.py@@ -21,12 +21,12 @@ def test_version_attribute_present_and_matches_metadata() -> None:``cubepi.__version__`` and the installed distribution wouldmake trace metadata lie about what produced the spans."""- import cubepi+ import cubeloop- assert hasattr(cubepi, "__version__"), "cubepi must expose __version__"- assert cubepi.__version__ == _pkg_version("cubepi"), (- f"cubepi.__version__ ({cubepi.__version__!r}) drifted from the "- f"installed distribution version ({_pkg_version('cubepi')!r}) — "+ assert hasattr(cubeloop, "__version__"), "cubepi must expose __version__"+ assert cubeloop.__version__ == _pkg_version("cubeloop"), (+ f"cubeloop.__version__ ({cubeloop.__version__!r}) drifted from the "+ f"installed distribution version ({_pkg_version('cubeloop')!r}) — ""check pyproject.toml's [project].version field.")@@ -35,17 +35,17 @@ def test_version_string_shape() -> None:"""Version should look like a PEP 440 release (e.g. ``0.4.0``,``0.4.1.dev0``). Catches accidental ``unknown`` fallbacks landingin a published package."""- import cubepi+ import cubeloop- assert re.match(r"^\d+\.\d+", cubepi.__version__), (- f"cubepi.__version__ {cubepi.__version__!r} doesn't look like a "+ assert re.match(r"^\d+\.\d+", cubeloop.__version__), (+ f"cubepi.__version__ {cubeloop.__version__!r} doesn't look like a "f"PEP 440 version — fallback path may have been hit.")def test_version_listed_in_dunder_all() -> None:- """``__version__`` must be in ``__all__`` so ``from cubepi import *``+ """``__version__`` must be in ``__all__`` so ``from cubeloop import *``surfaces it and editors auto-complete it."""- import cubepi+ import cubeloop- assert "__version__" in cubepi.__all__+ assert "__version__" in cubeloop.__all__diff --git a/tests/test_structured_output.py b/tests/test_structured_output.pyindex 6a3a21b..1ba4849 100644--- a/tests/test_structured_output.py+++ b/tests/test_structured_output.py@@ -5,12 +5,12 @@ from __future__ import annotationsimport pytestfrom pydantic import BaseModel-from cubepi.providers.base import (+from cubeloop.providers.base import (StructuredOutputError,TextContent,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call+from cubeloop.providers.faux import FauxProvider, faux_assistant_message, faux_tool_callclass MovieReview(BaseModel):@@ -172,7 +172,7 @@ async def test_generate_structured_retry_includes_tool_result_message() -> None:assert result.rating == 8# The retry call should have: original UserMessage, failed AssistantMessage,# ToolResultMessage (error), UserMessage (retry prompt)- from cubepi.providers.base import ToolResultMessage+ from cubeloop.providers.base import ToolResultMessagetool_results = [m for m in captured_messages if isinstance(m, ToolResultMessage)]assert len(tool_results) == 1diff --git a/tests/test_synthetic_messages.py b/tests/test_synthetic_messages.pyindex 53d4844..9be21f4 100644--- a/tests/test_synthetic_messages.py+++ b/tests/test_synthetic_messages.py@@ -9,11 +9,11 @@ from __future__ import annotationsfrom typing import Any-from cubepi import Agent-from cubepi.agent.types import AgentContext-from cubepi.middleware.goal import GoalMiddleware-from cubepi.middleware.todo import TodoListMiddleware-from cubepi.providers.base import (+from cubeloop import Agent+from cubeloop.agent.types import AgentContext+from cubeloop.middleware.goal import GoalMiddleware+from cubeloop.middleware.todo import TodoListMiddleware+from cubeloop.providers.base import (SYNTHETIC_METADATA_KEY,SYNTHETIC_SOURCE_METADATA_KEY,AssistantMessage,@@ -23,7 +23,7 @@ from cubepi.providers.base import (is_synthetic_message,synthetic_user_message,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call+from cubeloop.providers.faux import FauxProvider, faux_assistant_message, faux_tool_call# ---------------------------------------------------------------------------# Factory + predicate unit testsdiff --git a/tests/tracing/test_attach_atomicity.py b/tests/tracing/test_attach_atomicity.pyindex 5100225..46aa948 100644--- a/tests/tracing/test_attach_atomicity.py+++ b/tests/tracing/test_attach_atomicity.py@@ -12,10 +12,10 @@ from __future__ import annotationsimport pytest-from cubepi.agent.agent import Agent-from cubepi.providers.base import Model-from cubepi.providers.faux import FauxProvider-from cubepi.tracing import Tracer+from cubeloop.agent.agent import Agent+from cubeloop.providers.base import Model+from cubeloop.providers.faux import FauxProvider+from cubeloop.tracing import TracerMODEL = Model(id="faux-1", provider_id="faux")@@ -71,7 +71,7 @@ async def test_recorder_attach_unwinds_on_partial_provider_subscription_failure(async def test_tracer_attach_unwinds_recorder_on_mcp_register_failure(monkeypatch):agent, provider, tracer = _build_unattached()try:- import cubepi.mcp._tracing as mcp_tracing+ import cubeloop.mcp._tracing as mcp_tracingdef _boom(_provider, **_kwargs): # noqa: ANN001, ANN202raise RuntimeError("register_provider failed")@@ -127,7 +127,7 @@ async def test_tracer_attach_cleanup_swallows_recorder_detach_error(monkeypatch)# raises inside the recorder's synchronous cleanup).monkeypatch.setattr(agent, "subscribe", lambda listener: _raising_unsub)- import cubepi.mcp._tracing as mcp_tracing+ import cubeloop.mcp._tracing as mcp_tracingdef _boom(_provider, **_kwargs): # noqa: ANN001, ANN202raise RuntimeError("register_provider failed")diff --git a/tests/tracing/test_content_recording.py b/tests/tracing/test_content_recording.pyindex afb13a9..2bcc1f0 100644--- a/tests/tracing/test_content_recording.py+++ b/tests/tracing/test_content_recording.py@@ -5,9 +5,9 @@ attrs on each span layer per the OTel GenAI semconv:- ``invoke_agent`` (root): gen_ai.input.messages / gen_ai.output.messages/ gen_ai.system_instructions-- ``cubepi.turn``: gen_ai.input.messages / gen_ai.output.messages+- ``cubeloop.turn``: gen_ai.input.messages / gen_ai.output.messages- ``chat``: gen_ai.system_instructions / gen_ai.input.messages /- gen_ai.tool.definitions / cubepi.llm.raw_request / cubepi.llm.raw_response+ gen_ai.tool.definitions / cubeloop.llm.raw_request / cubeloop.llm.raw_response- ``execute_tool``: gen_ai.tool.call.arguments / gen_ai.tool.call.resultPlus a ``redact`` hook on the Tracer for per-attribute filtering.@@ -22,11 +22,11 @@ from opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResultfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import Model, TextContent, ToolCall-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.tracing import Tracer+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import Model, TextContent, ToolCall+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.tracing import TracerMODEL = Model(id="faux-1", provider_id="faux")@@ -95,8 +95,8 @@ class TestContentDisabled:"gen_ai.tool.definitions","gen_ai.tool.call.arguments","gen_ai.tool.call.result",- "cubepi.llm.raw_request",- "cubepi.llm.raw_response",+ "cubeloop.llm.raw_request",+ "cubeloop.llm.raw_response",):assert forbidden not in attrs, (f"{span.name} should not carry {forbidden} with record_content=False"@@ -139,7 +139,7 @@ class TestContentDisabled:await agent.wait_for_idle()await tracer.shutdown()- turn = next(span for span in exporter.spans if span.name == "cubepi.turn")+ turn = next(span for span in exporter.spans if span.name == "cubeloop.turn")assert turn.status.status_code.name == "ERROR"assert turn.status.description == "model error"assert secret not in repr(dict(turn.attributes or {}))@@ -190,10 +190,10 @@ class TestChatContent:attrs = _attrs(chat)assert "gen_ai.system_instructions" in attrsassert "gen_ai.input.messages" in attrs- raw = json.loads(attrs["cubepi.llm.raw_request"])+ raw = json.loads(attrs["cubeloop.llm.raw_request"])assert raw["model"] == MODEL.idassert "messages" in raw- resp = json.loads(attrs["cubepi.llm.raw_response"])+ resp = json.loads(attrs["cubeloop.llm.raw_response"])assert resp["id"] == "faux-1"assert resp["role"] == "assistant"@@ -275,7 +275,7 @@ class TestTurnContent:await agent.wait_for_idle()await tracer.shutdown()- turn = next(s for s in exporter.spans if s.name == "cubepi.turn")+ turn = next(s for s in exporter.spans if s.name == "cubeloop.turn")inp = _json_attr(turn, "gen_ai.input.messages")assert inp[0]["parts"][0]["content"] == "hi"out = _json_attr(turn, "gen_ai.output.messages")@@ -376,9 +376,9 @@ class TestChatInputForContinuedHistory:"""async def test_resume_chat_input_includes_prior_history(self):- from cubepi.providers.base import UserMessage as _U- from cubepi.providers.base import AssistantMessage as _A- from cubepi.providers.base import ToolResultMessage as _TR+ from cubeloop.providers.base import UserMessage as _U+ from cubeloop.providers.base import AssistantMessage as _A+ from cubeloop.providers.base import ToolResultMessage as _TRagent, provider, exporter, tracer = await _build(record_content=True)# Pre-load the agent with conversation history via the@@ -459,7 +459,7 @@ class TestRedaction:async def test_redact_can_drop_attribute(self):def redact(key: str, value: Any) -> Any:- if key == "cubepi.llm.raw_request":+ if key == "cubeloop.llm.raw_request":return Nonereturn value@@ -472,7 +472,7 @@ class TestRedaction:await tracer.shutdown()chat = next(s for s in exporter.spans if s.name.startswith("chat "))- assert "cubepi.llm.raw_request" not in _attrs(chat)+ assert "cubeloop.llm.raw_request" not in _attrs(chat)assert "gen_ai.input.messages" in _attrs(chat)async def test_redact_exception_is_swallowed(self):@@ -494,16 +494,16 @@ class TestRedaction:class TestContentHelpers:def test_messages_to_semconv_handles_all_block_types(self):- from cubepi.providers.base import (+ from cubeloop.providers.base import (AssistantMessage,ThinkingContent,)- from cubepi.providers.base import ToolCall as _ToolCall- from cubepi.providers.base import (+ from cubeloop.providers.base import ToolCall as _ToolCall+ from cubeloop.providers.base import (ToolResultMessage,UserMessage,)- from cubepi.tracing.content import messages_to_semconv+ from cubeloop.tracing.content import messages_to_semconvmsgs = [UserMessage(content=[TextContent(text="hi")]),@@ -543,7 +543,7 @@ class TestContentHelpers:}def test_tool_definitions_anthropic_shape(self):- from cubepi.tracing.content import tool_definitions_to_semconv+ from cubeloop.tracing.content import tool_definitions_to_semconvpayload = {"tools": [@@ -564,7 +564,7 @@ class TestContentHelpers:]def test_tool_definitions_openai_chat_shape(self):- from cubepi.tracing.content import tool_definitions_to_semconv+ from cubeloop.tracing.content import tool_definitions_to_semconvpayload = {"tools": [@@ -588,7 +588,7 @@ class TestContentHelpers:]def test_serialize_for_attribute_fallback(self):- from cubepi.tracing.content import serialize_for_attribute+ from cubeloop.tracing.content import serialize_for_attributeclass NotJsonable:passdiff --git a/tests/tracing/test_fork_once_span.py b/tests/tracing/test_fork_once_span.pyindex 4cb0d33..5ede0b1 100644--- a/tests/tracing/test_fork_once_span.py+++ b/tests/tracing/test_fork_once_span.py@@ -1,9 +1,9 @@import pytest-from cubepi.agent.agent import Agent-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.providers.base import AssistantMessage, TextContent-from cubepi.providers.faux import FauxProvider+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.providers.base import AssistantMessage, TextContent+from cubeloop.providers.faux import FauxProviderdef _ok_faux() -> FauxProvider:@@ -32,11 +32,11 @@ async def test_fork_once_emits_named_span(in_memory_exporter):await a2.fork_once("src", "follow up?", after_run_id="R1")spans = in_memory_exporter.get_finished_spans()names = [s.name for s in spans]- assert "cubepi.agent.fork_once" in names- span = next(s for s in spans if s.name == "cubepi.agent.fork_once")+ assert "cubeloop.agent.fork_once" in names+ span = next(s for s in spans if s.name == "cubeloop.agent.fork_once")attrs = dict(span.attributes)- assert attrs["cubepi.fork.src_thread_id"] == "src"- assert attrs["cubepi.fork.after_run_id"] == "R1"+ assert attrs["cubeloop.fork.src_thread_id"] == "src"+ assert attrs["cubeloop.fork.after_run_id"] == "R1"@pytest.mark.asynciodiff --git a/tests/tracing/test_hitl_suspension.py b/tests/tracing/test_hitl_suspension.pyindex 096114d..da96539 100644--- a/tests/tracing/test_hitl_suspension.py+++ b/tests/tracing/test_hitl_suspension.py@@ -10,15 +10,15 @@ from typing import Anyfrom opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult-from cubepi.agent.agent import Agent-from cubepi.checkpointer.memory import MemoryCheckpointer-from cubepi.hitl.ask_user import ask_user_tool-from cubepi.hitl.channel import CheckpointedChannel-from cubepi.mcp import _tracing as mcp_tracing-from cubepi.providers.base import AssistantMessage, TextContent, ToolCall-from cubepi.providers.faux import FauxProvider-from cubepi.tracing import Tracer-from cubepi.tracing import recorder as recorder_module+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.memory import MemoryCheckpointer+from cubeloop.hitl.ask_user import ask_user_tool+from cubeloop.hitl.channel import CheckpointedChannel+from cubeloop.mcp import _tracing as mcp_tracing+from cubeloop.providers.base import AssistantMessage, TextContent, ToolCall+from cubeloop.providers.faux import FauxProvider+from cubeloop.tracing import Tracer+from cubeloop.tracing import recorder as recorder_moduleclass InMemoryExporter(SpanExporter):@@ -108,7 +108,7 @@ async def test_suspended_outcome_without_snapshot_emits_no_event() -> None:async def test_recorder_suspension_without_active_run_is_noop() -> None:- from cubepi.tracing.recorder import Recorder+ from cubeloop.tracing.recorder import Recordertracer = Tracer(service_name="test", exporters=[])recorder = Recorder(tracer)@@ -133,33 +133,33 @@ async def test_suspended_run_exports_suspended_trace_without_abort_or_leaks() ->roots = [span for span in exporter.spans if span.name == "invoke_agent"]assert len(roots) == 1- assert roots[0].attributes.get("cubepi.output.messages.count") == 1+ assert roots[0].attributes.get("cubeloop.output.messages.count") == 1suspended_spans = [spanfor span in exporter.spans- if span.name in {"invoke_agent", "cubepi.turn"}+ if span.name in {"invoke_agent", "cubeloop.turn"}or span.name.startswith("execute_tool ")]assert {span.name for span in suspended_spans} == {"invoke_agent",- "cubepi.turn",+ "cubeloop.turn","execute_tool ask_user",}assert all(- span.attributes.get("cubepi.run.outcome") == "suspended"+ span.attributes.get("cubeloop.run.outcome") == "suspended"for span in suspended_spans)assert not [span.namefor span in exporter.spans- if span.attributes.get("cubepi.aborted") is True+ if span.attributes.get("cubeloop.aborted") is True]assert len(mcp_tracing._provider_stack) == provider_stack_baselineassert len(mcp_tracing._active_entries) == active_entries_baselineasync def test_recorder_suspension_finalizes_all_open_resources() -> None:- from cubepi.tracing.recorder import Recorder, _RunState+ from cubeloop.tracing.recorder import Recorder, _RunStateclass _Span:def __init__(self) -> None:@@ -200,7 +200,7 @@ async def test_recorder_suspension_finalizes_all_open_resources() -> None:await tracer.shutdown()for span in (agent_span, turn_span, chat_span, tool_span):- assert span.attributes["cubepi.run.outcome"] == "suspended"+ assert span.attributes["cubeloop.run.outcome"] == "suspended"assert span.ended is Trueassert stream.closed is Trueassert run.tool_spans == {}@@ -211,7 +211,7 @@ async def test_recorder_suspension_finalizes_all_open_resources() -> None:async def test_recorder_suspension_cleanup_continues_after_resource_errors() -> None:- from cubepi.tracing.recorder import Recorder, _RunState+ from cubeloop.tracing.recorder import Recorder, _RunStateclass _Span:def __init__(self) -> None:@@ -248,7 +248,7 @@ async def test_recorder_suspension_cleanup_continues_after_resource_errors() ->recorder._on_agent_suspended()await tracer.shutdown()- assert agent_span.attributes["cubepi.run.outcome"] == "suspended"+ assert agent_span.attributes["cubeloop.run.outcome"] == "suspended"assert agent_span.ended is Trueassert run.tool_spans == {}assert run.chat_span is None@@ -312,8 +312,8 @@ async def test_earlier_listener_failure_cannot_hide_suspension_from_tracer() ->roots = [span for span in exporter.spans if span.name == "invoke_agent"]assert len(roots) == 1- assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"- assert roots[0].attributes.get("cubepi.aborted") is not True+ assert roots[0].attributes.get("cubeloop.run.outcome") == "suspended"+ assert roots[0].attributes.get("cubeloop.aborted") is not Trueasync def test_cancelled_listener_cannot_hide_suspension_from_tracer() -> None:@@ -340,8 +340,8 @@ async def test_cancelled_listener_cannot_hide_suspension_from_tracer() -> None:assert agent.state.active_run_id is Noneroots = [span for span in exporter.spans if span.name == "invoke_agent"]assert len(roots) == 1- assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"- assert roots[0].attributes.get("cubepi.aborted") is not True+ assert roots[0].attributes.get("cubeloop.run.outcome") == "suspended"+ assert roots[0].attributes.get("cubeloop.aborted") is not Trueasync def test_listener_cancellation_takes_priority_after_terminal_fanout() -> None:@@ -377,7 +377,7 @@ async def test_listener_cancellation_takes_priority_after_terminal_fanout() -> Nassert isinstance(raised, asyncio.CancelledError)roots = [span for span in exporter.spans if span.name == "invoke_agent"]assert len(roots) == 1- assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"+ assert roots[0].attributes.get("cubeloop.run.outcome") == "suspended"async def test_detach_then_owner_cancel_clears_suspension_snapshot() -> None:@@ -405,8 +405,8 @@ async def test_detach_then_owner_cancel_clears_suspension_snapshot() -> None:assert unhandled == []roots = [span for span in exporter.spans if span.name == "invoke_agent"]assert len(roots) == 1- assert roots[0].attributes.get("cubepi.run.outcome") is None- assert roots[0].attributes.get("cubepi.aborted") is True+ assert roots[0].attributes.get("cubeloop.run.outcome") is None+ assert roots[0].attributes.get("cubeloop.aborted") is Trueasync def test_reset_before_owner_resumes_does_not_drop_suspension_snapshot() -> None:@@ -425,8 +425,8 @@ async def test_reset_before_owner_resumes_does_not_drop_suspension_snapshot() ->assert persisted_pending is not Noneroots = [span for span in exporter.spans if span.name == "invoke_agent"]assert len(roots) == 1- assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"- assert roots[0].attributes.get("cubepi.aborted") is not True+ assert roots[0].attributes.get("cubeloop.run.outcome") == "suspended"+ assert roots[0].attributes.get("cubeloop.aborted") is not Trueasync def test_respond_after_suspension_opens_a_new_activation_trace() -> None:@@ -444,9 +444,9 @@ async def test_respond_after_suspension_opens_a_new_activation_trace() -> None:roots = [span for span in exporter.spans if span.name == "invoke_agent"]assert len(roots) == 2- assert roots[0].attributes.get("cubepi.run.outcome") == "suspended"- assert roots[1].attributes.get("cubepi.run.outcome") is None- assert roots[1].attributes.get("cubepi.aborted") is not True+ assert roots[0].attributes.get("cubeloop.run.outcome") == "suspended"+ assert roots[1].attributes.get("cubeloop.run.outcome") is None+ assert roots[1].attributes.get("cubeloop.aborted") is not Trueassert roots[0].context.trace_id != roots[1].context.trace_iddiff --git a/tests/tracing/test_jsonl_exporter.py b/tests/tracing/test_jsonl_exporter.pyindex 6532891..a928b20 100644--- a/tests/tracing/test_jsonl_exporter.py+++ b/tests/tracing/test_jsonl_exporter.py@@ -8,24 +8,24 @@ pytest.importorskip("opentelemetry.sdk.trace")from opentelemetry.sdk.trace import TracerProvider # noqa: E402-from cubepi.tracing.exporters import JsonlSpanExporter # noqa: E402-from cubepi.tracing.schema import CUBEPI_RUN_ID # noqa: E402+from cubeloop.tracing.exporters import JsonlSpanExporter # noqa: E402+from cubeloop.tracing.schema import CUBELOOP_RUN_ID # noqa: E402def test_jsonl_shards_by_trace_id_not_run_id(tmp_path):# A parent span and a nested (subagent) span share one trace_id but carry- # DIFFERENT cubepi.run_id values — the subagent run gets its own run_id.+ # DIFFERENT cubeloop.run_id values — the subagent run gets its own run_id.exporter = JsonlSpanExporter(directory=tmp_path)provider = TracerProvider()- tracer = provider.get_tracer("cubepi.tracing")+ tracer = provider.get_tracer("cubeloop.tracing")with tracer.start_as_current_span("invoke_agent") as parent:- parent.set_attribute(CUBEPI_RUN_ID, "parent-run")+ parent.set_attribute(CUBELOOP_RUN_ID, "parent-run")with tracer.start_as_current_span("invoke_agent") as child:# Same trace, different run id (nested subagent run).- child.set_attribute(CUBEPI_RUN_ID, "subagent-run")+ child.set_attribute(CUBELOOP_RUN_ID, "subagent-run")assert parent.context.trace_id == child.context.trace_id- assert parent.attributes[CUBEPI_RUN_ID] != child.attributes[CUBEPI_RUN_ID]+ assert parent.attributes[CUBELOOP_RUN_ID] != child.attributes[CUBELOOP_RUN_ID]exporter.export([parent, child])diff --git a/tests/tracing/test_lazy_import.py b/tests/tracing/test_lazy_import.pyindex 99f7614..b835d6e 100644--- a/tests/tracing/test_lazy_import.py+++ b/tests/tracing/test_lazy_import.py@@ -7,7 +7,7 @@ import sysimport pytest-import cubepi.tracing+import cubeloop.tracingdef test_schema_importable_without_opentelemetry():@@ -21,8 +21,8 @@ def test_schema_importable_without_opentelemetry():" raise ImportError('hidden')\n"" return real_import(name, *a, **k)\n""builtins.__import__ = fake\n"- "from cubepi.tracing import schema\n"- "assert schema.CUBEPI_RUN_ID == 'cubepi.run_id'\n"+ "from cubeloop.tracing import schema\n"+ "assert schema.CUBELOOP_RUN_ID == 'cubeloop.run_id'\n""print('ok')\n")result = subprocess.run(@@ -34,10 +34,10 @@ def test_schema_importable_without_opentelemetry():def test_unknown_attribute_raises_attribute_error():with pytest.raises(AttributeError):- cubepi.tracing.does_not_exist+ cubeloop.tracing.does_not_existdef test_dir_lists_public_names():- names = dir(cubepi.tracing)+ names = dir(cubeloop.tracing)assert "Tracer" in namesassert "JsonlSpanExporter" in namesdiff --git a/tests/tracing/test_mcp_spans.py b/tests/tracing/test_mcp_spans.pyindex 3eefe30..d52f6f0 100644--- a/tests/tracing/test_mcp_spans.py+++ b/tests/tracing/test_mcp_spans.py@@ -1,7 +1,7 @@"""Phase 5: pin MCP CLIENT span emissions + W3C traceparent propagation.The MCP adapter wraps every ``call_remote`` invocation in-:func:`cubepi.mcp._tracing.mcp_client_span`, which opens a CLIENT span+:func:`cubeloop.mcp._tracing.mcp_client_span`, which opens a CLIENT spanwith the GenAI MCP semconv attributes. When the OTel API is absent thecontext manager is a no-op (verified separately)."""@@ -22,7 +22,7 @@ from opentelemetry.sdk.trace.export import ()from opentelemetry.trace import SpanKind, StatusCode-from cubepi.mcp._adapter import make_mcp_agent_tool+from cubeloop.mcp._adapter import make_mcp_agent_toolclass _CaptureExporter(SpanExporter):@@ -45,7 +45,7 @@ def _make_provider() -> tuple[TracerProvider, _CaptureExporter]:Each test gets its own provider; we don't use trace.set_tracer_providerglobally, instead we monkeypatch the module-level ``_otel_trace`` in- ``cubepi.mcp._tracing`` so MCP fetches the test's tracer.+ ``cubeloop.mcp._tracing`` so MCP fetches the test's tracer."""resource = Resource.create({"service.name": "mcp-span-tests"})provider = TracerProvider(resource=resource)@@ -55,8 +55,8 @@ def _make_provider() -> tuple[TracerProvider, _CaptureExporter]:def _patch_mcp_trace(monkeypatch, provider: TracerProvider) -> None:- """Swap the cubepi.mcp._tracing module's ``get_tracer`` to use ours."""- import cubepi.mcp._tracing as mcp_tracing+ """Swap the cubeloop.mcp._tracing module's ``get_tracer`` to use ours."""+ import cubeloop.mcp._tracing as mcp_tracingclass _ShimTraceMod:@staticmethod@@ -194,7 +194,7 @@ class TestMCPClientSpan:async def test_span_records_cancellation(self, monkeypatch):"""Cancellation is a control signal, not a failure — match thechat / turn / invoke_agent convention: leave Status UNSET,- record cubepi.aborted=true + error.type, do NOT add an+ record cubeloop.aborted=true + error.type, do NOT add an``exception`` event."""provider, exporter = _make_provider()_patch_mcp_trace(monkeypatch, provider)@@ -212,11 +212,11 @@ class TestMCPClientSpan:assert len(mcp_spans) == 1span = mcp_spans[0]attrs = _attrs(span)- assert attrs["error.type"] == "cubepi.aborted"- assert attrs["cubepi.aborted"] is True+ assert attrs["error.type"] == "cubeloop.aborted"+ assert attrs["cubeloop.aborted"] is True# Status stays UNSET; cancel is not a failure.assert span.status.status_code == StatusCode.UNSET- # No exception event — cancel is signaled via cubepi.aborted only.+ # No exception event — cancel is signaled via cubeloop.aborted only.assert not any(e.name == "exception" for e in span.events)@@ -247,7 +247,7 @@ class TestMCPIsErrorResponse:assert attrs["error.type"] == "mcp.is_error"async def test_protocol_error_message_is_private_by_default(self, monkeypatch):- from cubepi.mcp._tracing import mark_span_mcp_error, mcp_client_span+ from cubeloop.mcp._tracing import mark_span_mcp_error, mcp_client_spanprovider, exporter = _make_provider()_patch_mcp_trace(monkeypatch, provider)@@ -288,7 +288,7 @@ class TestMCPIsErrorResponse:class TestNoOpWhenOTelMissing:async def test_context_manager_yields_none_when_no_otel(self, monkeypatch):- import cubepi.mcp._tracing as mcp_tracing+ import cubeloop.mcp._tracing as mcp_tracingmonkeypatch.setattr(mcp_tracing, "_OTEL_AVAILABLE", False)@@ -306,7 +306,7 @@ class TestTraceparentHelper:):provider, _ = _make_provider()_patch_mcp_trace(monkeypatch, provider)- from cubepi.mcp._tracing import current_traceparent+ from cubeloop.mcp._tracing import current_traceparenttracer = provider.get_tracer("test")with tracer.start_as_current_span("test-span"):@@ -321,7 +321,7 @@ class TestTraceparentHelper:assert len(parts[3]) == 2async def test_current_traceparent_none_without_span(self, monkeypatch):- from cubepi.mcp._tracing import current_traceparent+ from cubeloop.mcp._tracing import current_traceparent# No active span (and no recording context set up).assert current_traceparent() is None@@ -333,8 +333,8 @@ class TestTraceparentInjection:instrumented MCP servers can continue the trace (codex round 2)."""async def test_traceparent_header_set_inside_mcp_span(self, monkeypatch):- from cubepi.mcp import _tracing as mcp_tracing- from cubepi.mcp._tracing import mcp_client_span+ from cubeloop.mcp import _tracing as mcp_tracing+ from cubeloop.mcp._tracing import mcp_client_span# Force OTel on with a deterministic tracer.provider, _exporter = _make_provider()@@ -364,7 +364,7 @@ class TestTraceparentInjection:assert tp.startswith("00-") and len(tp.split("-")) == 4async def test_no_header_added_when_no_active_span(self, monkeypatch):- from cubepi.mcp._tracing import current_traceparent+ from cubeloop.mcp._tracing import current_traceparent# Outside any span: helper returns None and loader must not add# a traceparent header.@@ -372,20 +372,20 @@ class TestTraceparentInjection:class TestTracerProviderRouting:- """When a user constructs a cubepi.tracing.Tracer with its own+ """When a user constructs a cubeloop.tracing.Tracer with its ownprivate provider and calls attach(agent), MCP CLIENT spans mustflow through that same provider's exporters — without this, MCPspans would silently land in the OTel global no-op provider(codex round 5)."""async def test_mcp_span_lands_in_tracer_exporter(self):- from cubepi.agent.agent import Agent- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import (+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import (FauxProvider,faux_assistant_message,)- from cubepi.tracing import Tracer+ from cubeloop.tracing import Tracerfrom pydantic import BaseModel@@ -399,7 +399,7 @@ class TestTracerProviderRouting:async def call_remote(name, args):return {"content": [{"type": "text", "text": "ok"}], "isError": False}- from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubeloop.mcp._adapter import make_mcp_agent_toolmcp_tool = make_mcp_agent_tool(name="search",@@ -459,10 +459,10 @@ class TestTracerProviderRouting:assert client_span.parent.span_id == tool_ctx.span_idasync def test_mcp_exception_is_private_without_content_opt_in(self):- from cubepi.agent.agent import Agent- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.tracing import Tracersecret = "Authorization: Bearer MCPSECRET"exporter = _CaptureExporter()@@ -520,10 +520,10 @@ class TestTracerProviderRouting:assert secret not in repr(dict(event.attributes or {}))async def test_mcp_exception_details_remain_available_with_content_opt_in(self):- from cubepi.agent.agent import Agent- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.tracing import Tracersecret = "diagnostic mcp failure"exporter = _CaptureExporter()@@ -578,10 +578,10 @@ class TestTracerProviderRouting:async def test_unparented_mcp_exception_fails_closed_with_opted_in_tracer(self):"""Without a tool-span owner, the global provider stack cannot provewhich concurrent Tracer owns the call, so content must stay disabled."""- from cubepi.agent.agent import Agent- from cubepi.mcp._tracing import mcp_client_span- from cubepi.providers.faux import FauxProvider- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.mcp._tracing import mcp_client_span+ from cubeloop.providers.faux import FauxProvider+ from cubeloop.tracing import Tracersecret = "Authorization: Bearer UNPARENTEDMCPSECRET"exporter = _CaptureExporter()@@ -617,17 +617,17 @@ class TestTracerProviderRouting:the remaining agent's MCP spans must still land in the Tracer'sexporter. Refcounted register/unregister is the contract(codex round-6 review on PR #86)."""- from cubepi.agent.agent import Agent- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.tracing import Tracerexporter = _CaptureExporter()async def call_remote(name, args):return {"content": [{"type": "text", "text": "ok"}], "isError": False}- from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubeloop.mcp._adapter import make_mcp_agent_tooldef _make_agent():mcp_tool = make_mcp_agent_tool(@@ -680,7 +680,7 @@ class TestTracerProviderRouting:)def test_register_and_unregister_provider(self, monkeypatch):- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp import _tracing as mcp_tracing# Start from a clean stack so the assertion below is well-defined# regardless of other tests' attach()/detach() side-effects.@@ -700,7 +700,7 @@ class TestTracerProviderRouting:continue flowing through it. Without this, a Tracer attached toagent A and B then detached from A would drop MCP routing for B(codex round-6 review on PR #86)."""- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp import _tracing as mcp_tracingmonkeypatch.setattr(mcp_tracing, "_provider_stack", [])@@ -733,7 +733,7 @@ class TestMCPSpanParentage:# Open a synthetic "execute_tool" span and register it as the# parent for tool_call_id "tc1" — the same hook the cubepi# recorder uses.- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp import _tracing as mcp_tracingtracer = provider.get_tracer("test")tool_span = tracer.start_span("execute_tool search")@@ -760,7 +760,7 @@ class TestMCPSpanParentage:assert client_span.parent.span_id == tool_ctx.span_idasync def test_two_tracers_route_mcp_by_parent_owner(self):- """Two different cubepi.Tracer instances attached to two agents+ """Two different cubeloop.Tracer instances attached to two agentsin the same process. An MCP CLIENT span emitted under agent A'sexecute_tool span must export through Tracer A's exporter — notTracer B's, even if B was attached more recently (LIFO order on@@ -769,12 +769,12 @@ class TestMCPSpanParentage:Without this routing, agent A's trace would be missing its MCPleg and Tracer B's exporter would receive a stray span withagent A's trace_id (codex round-7 review on PR #86)."""- from cubepi.agent.agent import Agent- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.tracing import Tracer- from cubepi.mcp._adapter import make_mcp_agent_tool+ from cubeloop.mcp._adapter import make_mcp_agent_toolasync def call_remote(name, args):return {"content": [{"type": "text", "text": "ok"}], "isError": False}@@ -863,11 +863,11 @@ class TestMCPSpanParentage:only its own parent (codex round-8 review on PR #86)."""import asyncio as _asyncio- from cubepi.agent.agent import Agent- from cubepi.mcp._adapter import make_mcp_agent_tool- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.mcp._adapter import make_mcp_agent_tool+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.tracing import Tracer# Gate that holds both agents' MCP calls inside the# ``execute_tool`` span at the same time, so any global-dict@@ -962,12 +962,12 @@ class TestMCPSpanParentage:registry valid until the child task's cleanup runs — pin thatan MCP CLIENT span is still correctly parented under``execute_tool`` in this mode (codex round-9 review)."""- from cubepi.agent.agent import Agent- from cubepi.agent.types import AgentTool- from cubepi.mcp._adapter import make_mcp_agent_tool- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.agent.types import AgentTool+ from cubeloop.mcp._adapter import make_mcp_agent_tool+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.tracing import Tracerasync def call_remote(name, args):return {"content": [{"type": "text", "text": "ok"}], "isError": False}@@ -1032,19 +1032,19 @@ class TestMCPSpanParentage:bypasses the cubepi agent loop's ``except Exception`` handler,so a cancelled run never emits ``ToolExecutionEndEvent`` andnever reaches the per-event unregister. Without an explicit- cleanup path, ``_active_entries`` in ``cubepi.mcp._tracing``+ cleanup path, ``_active_entries`` in ``cubeloop.mcp._tracing``would grow unbounded across aborted runs (codex round-10).Pin: after a cancelled run + detach, ``_active_entries`` isback to its pre-run size."""import asyncio as _asyncio- from cubepi.agent.agent import Agent- from cubepi.mcp import _tracing as mcp_tracing- from cubepi.mcp._adapter import make_mcp_agent_tool- from cubepi.providers.base import ToolCall- from cubepi.providers.faux import FauxProvider, faux_assistant_message- from cubepi.tracing import Tracer+ from cubeloop.agent.agent import Agent+ from cubeloop.mcp import _tracing as mcp_tracing+ from cubeloop.mcp._adapter import make_mcp_agent_tool+ from cubeloop.providers.base import ToolCall+ from cubeloop.providers.faux import FauxProvider, faux_assistant_message+ from cubeloop.tracing import Tracerbaseline = len(mcp_tracing._active_entries)@@ -1131,7 +1131,7 @@ class TestMCPSpanParentage:(codex round-9 review)."""import asyncio as _asyncio- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp import _tracing as mcp_tracing# Build a parent task that registers, then a child task that# unregisters. We assert the dict is empty after cleanup.@@ -1169,7 +1169,7 @@ class TestMCPSpanParentage:execute_tool span (codex P2, PR #122)."""import asyncio as _asyncio- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp import _tracing as mcp_tracingtok_outer = mcp_tracing.register_tool_span("outer", "span-outer", provider="prov-outer"@@ -1223,7 +1223,7 @@ class TestMCPSpanParentage:class TestLoaderHelpers:def test_split_address_parses_url(self):- from cubepi.mcp.http_loader import _split_address+ from cubeloop.mcp.http_loader import _split_addressassert _split_address("https://api.example.com:8443/mcp") == ("api.example.com",@@ -1234,7 +1234,7 @@ class TestLoaderHelpers:assert port is Nonedef test_split_address_on_empty(self):- from cubepi.mcp.http_loader import _split_address+ from cubeloop.mcp.http_loader import _split_address# urlparse("") returns hostname=None, port=None — both nones is# the documented signal that the helper couldn't extract values.@@ -1243,7 +1243,7 @@ class TestLoaderHelpers:assert port is Nonedef test_extract_protocol_version(self):- from cubepi.mcp.http_loader import _extract_protocol_version+ from cubeloop.mcp.http_loader import _extract_protocol_versionclass FakeInit:protocolVersion = "2025-11-25"diff --git a/tests/tracing/test_meter.py b/tests/tracing/test_meter.pyindex 3f54088..2ec1d25 100644--- a/tests/tracing/test_meter.py+++ b/tests/tracing/test_meter.py@@ -15,11 +15,11 @@ from opentelemetry.sdk.metrics.export import (from opentelemetry.sdk.metrics import MeterProviderfrom opentelemetry.sdk.resources import Resource-from cubepi.agent.agent import Agent-from cubepi.providers.base import Model-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.tracing import Meter-from cubepi.tracing.schema import SCHEMA_URL, SCOPE_NAME+from cubeloop.agent.agent import Agent+from cubeloop.providers.base import Model+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.tracing import Meter+from cubeloop.tracing.schema import SCHEMA_URL, SCOPE_NAMEMODEL = Model(id="faux-1", provider_id="faux")@@ -163,8 +163,8 @@ class TestProviderOnToolMetrics:then has no tool entries to update). Codex P2 finding on PR #85."""from pydantic import BaseModel- from cubepi.agent.types import AgentTool, AgentToolResult- from cubepi.providers.base import TextContent, ToolCall+ from cubeloop.agent.types import AgentTool, AgentToolResult+ from cubeloop.providers.base import TextContent, ToolCallclass P(BaseModel):pass@@ -354,7 +354,7 @@ class TestFallbackChainCoverage:"""Issue #167 — Meter.attach() should subscribe to every chain provider."""async def test_attach_subscribes_to_every_chain_provider(self):- from cubepi.providers.fallback import FallbackBoundModel+ from cubeloop.providers.fallback import FallbackBoundModelprimary = FauxProvider(provider_id="primary")secondary = FauxProvider(provider_id="secondary")@@ -376,7 +376,7 @@ class TestFallbackChainCoverage:assert len(getattr(secondary, "_request_listeners", [])) == 0async def test_attach_dedupes_shared_provider_across_chain(self):- from cubepi.providers.fallback import FallbackBoundModel+ from cubeloop.providers.fallback import FallbackBoundModelshared = FauxProvider(provider_id="shared")chain_model = FallbackBoundModel(diff --git a/tests/tracing/test_nonblocking_flush.py b/tests/tracing/test_nonblocking_flush.pyindex 96d8b09..27bb899 100644--- a/tests/tracing/test_nonblocking_flush.py+++ b/tests/tracing/test_nonblocking_flush.py@@ -22,10 +22,10 @@ import timefrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult-from cubepi.agent.agent import Agent-from cubepi.providers.base import Model-from cubepi.providers.faux import FauxProvider-from cubepi.tracing import Tracer, trace+from cubeloop.agent.agent import Agent+from cubeloop.providers.base import Model+from cubeloop.providers.faux import FauxProvider+from cubeloop.tracing import Tracer, traceMODEL = Model(id="faux-1", provider_id="faux")@@ -127,8 +127,8 @@ async def test_meter_force_flush_calls_provider_off_the_loop_thread():from opentelemetry.sdk.metrics.export import InMemoryMetricReaderfrom opentelemetry.sdk.resources import Resource- from cubepi.tracing import Meter- from cubepi.tracing.schema import SCHEMA_URL+ from cubeloop.tracing import Meter+ from cubeloop.tracing.schema import SCHEMA_URLreader = InMemoryMetricReader()resource = Resource.create({"service.name": "test"}, schema_url=SCHEMA_URL)diff --git a/tests/tracing/test_oneshot.py b/tests/tracing/test_oneshot.pyindex 179bacd..b482d41 100644--- a/tests/tracing/test_oneshot.py+++ b/tests/tracing/test_oneshot.py@@ -8,7 +8,7 @@ import pytestfrom opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,Message,MessageStream,@@ -20,9 +20,9 @@ from cubepi.providers.base import (ToolDefinition,UserMessage,)-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.tracing import Tracer-from cubepi.tracing.tracer import _OneShotSession+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.tracing import Tracer+from cubeloop.tracing.tracer import _OneShotSessionMODEL = Model(id="faux-1", provider_id="faux")@@ -118,14 +118,14 @@ async def test_oneshot_produces_root_and_chat_spans() -> None:root = by_name["invoke_agent"]attrs = dict(root.attributes or {})assert attrs.get("gen_ai.operation.name") == "invoke_agent"- assert attrs.get("cubepi.oneshot.operation") == "test_op"- # operation also exposed under cubepi.metadata.* for --meta CLI filter- assert attrs.get("cubepi.metadata.oneshot_operation") == "test_op"- assert attrs.get("cubepi.metadata.conversation_id") == "conv-123"- assert attrs.get("cubepi.metadata.user_id") == "usr-456"- assert "cubepi.run_id" in attrs+ assert attrs.get("cubeloop.oneshot.operation") == "test_op"+ # operation also exposed under cubeloop.metadata.* for --meta CLI filter+ assert attrs.get("cubeloop.metadata.oneshot_operation") == "test_op"+ assert attrs.get("cubeloop.metadata.conversation_id") == "conv-123"+ assert attrs.get("cubeloop.metadata.user_id") == "usr-456"+ assert "cubeloop.run_id" in attrs# Successful one-shot must NOT be marked aborted by the cleanup sweeper.- assert attrs.get("cubepi.aborted") is None+ assert attrs.get("cubeloop.aborted") is Noneassert attrs.get("error.type") is Nonechat = by_name[f"chat {MODEL.id}"]@@ -162,8 +162,8 @@ async def test_oneshot_metadata_on_root_span() -> None:roots = [s for s in exporter.spans if s.name == "invoke_agent"]assert len(roots) == 1attrs = dict(roots[0].attributes or {})- assert attrs["cubepi.oneshot.operation"] == "consolidate_memory"- assert attrs["cubepi.metadata.conversation_id"] == "conv-abc"+ assert attrs["cubeloop.oneshot.operation"] == "consolidate_memory"+ assert attrs["cubeloop.metadata.conversation_id"] == "conv-abc"@pytest.mark.asyncio@@ -192,8 +192,8 @@ async def test_oneshot_user_metadata_cannot_shadow_reserved_oneshot_operation()roots = [s for s in exporter.spans if s.name == "invoke_agent"]assert len(roots) == 1attrs = dict(roots[0].attributes or {})- assert attrs["cubepi.metadata.oneshot_operation"] == "real_op"- assert attrs["cubepi.oneshot.operation"] == "real_op"+ assert attrs["cubeloop.metadata.oneshot_operation"] == "real_op"+ assert attrs["cubeloop.oneshot.operation"] == "real_op"@pytest.mark.asyncio@@ -633,14 +633,14 @@ async def test_oneshot_cancelled_generate_closes_chat_span() -> None:await tracer.shutdown()# Root span must be exported; chat span if opened must also be ended.- # Cancellation is tracked as cubepi.aborted (not StatusCode.ERROR),+ # Cancellation is tracked as cubeloop.aborted (not StatusCode.ERROR),# matching the agent path's contract.roots = [s for s in exporter.spans if s.name == "invoke_agent"]assert len(roots) == 1root = roots[0]attrs = dict(root.attributes or {})- assert attrs.get("cubepi.aborted") is True- assert attrs.get("error.type") == "cubepi.aborted"+ assert attrs.get("cubeloop.aborted") is True+ assert attrs.get("error.type") == "cubeloop.aborted"assert not any(event.name == "exception" for event in root.events)@@ -648,7 +648,7 @@ async def test_oneshot_cancelled_generate_closes_chat_span() -> None:async def test_oneshot_cancel_mid_stream_marks_open_chat_span_aborted() -> None:"""When cancellation happens after the chat span has been opened by theprovider request listener but before the response listener has closed- it, the oneshot cleanup must close it and stamp cubepi.aborted."""+ it, the oneshot cleanup must close it and stamp cubeloop.aborted."""import asyncio# Slow provider: streams the response one token at a time so we can@@ -674,12 +674,12 @@ async def test_oneshot_cancel_mid_stream_marks_open_chat_span_aborted() -> None:await tracer.force_flush()await tracer.shutdown()- # Chat span must have been ended with cubepi.aborted=true+ # Chat span must have been ended with cubeloop.aborted=truechat_spans = [s for s in exporter.spans if s.name.startswith("chat ")]assert chat_spans, "expected at least one chat span (opened by request listener)"chat_attrs = dict(chat_spans[0].attributes or {})- assert chat_attrs.get("cubepi.aborted") is True- assert chat_attrs.get("error.type") == "cubepi.aborted"+ assert chat_attrs.get("cubeloop.aborted") is True+ assert chat_attrs.get("error.type") == "cubeloop.aborted"@pytest.mark.asyncio@@ -687,7 +687,7 @@ async def test_oneshot_does_not_interfere_with_concurrent_agent() -> None:"""Oneshot's active-run gate must not bleed into a concurrent Agent run."""import asyncio- from cubepi.agent.agent import Agent+ from cubeloop.agent.agent import Agentprovider = FauxProvider(provider_id="faux")# Push responses for both agent and oneshotdiff --git a/tests/tracing/test_otlp_exporter.py b/tests/tracing/test_otlp_exporter.pyindex 5e755a2..92b18bb 100644--- a/tests/tracing/test_otlp_exporter.py+++ b/tests/tracing/test_otlp_exporter.py@@ -9,8 +9,8 @@ from typing import Anyimport pytestfrom opentelemetry.sdk.trace.export import SpanExporter-from cubepi.tracing.recorder import Recorder-from cubepi.tracing.tracer import Tracer+from cubeloop.tracing.recorder import Recorder+from cubeloop.tracing.tracer import Tracerclass _Span:@@ -23,7 +23,7 @@ class _Span:class TestOTLPSpanExporterReExport:def test_otlp_exporter_is_importable(self):- from cubepi.tracing.exporters import OTLPSpanExporter+ from cubeloop.tracing.exporters import OTLPSpanExporter# Returned class must be the actual OTLP exporter.assert OTLPSpanExporter.__module__.startswith(@@ -31,7 +31,7 @@ class TestOTLPSpanExporterReExport:)def test_otlp_exporter_can_be_constructed(self):- from cubepi.tracing.exporters import OTLPSpanExporter+ from cubeloop.tracing.exporters import OTLPSpanExporter# Construct with default kwargs — should not require a live# collector at construction time.@@ -41,7 +41,7 @@ class TestOTLPSpanExporterReExport:exporter.shutdown()def test_unknown_attr_still_raises(self):- from cubepi.tracing import exporters+ from cubeloop.tracing import exporterswith pytest.raises(AttributeError):_ = exporters.NotAnExporter # type: ignore[attr-defined]@@ -51,8 +51,8 @@ class TestOpenAIRequestAttrs:def test_service_tier_recorded_on_request(self):# Direct unit-level: build a fake payload with service_tier# and feed _on_provider_request via the Recorder.- from cubepi.providers.base import Model- from cubepi.tracing import Tracer+ from cubeloop.providers.base import Model+ from cubeloop.tracing import Tracertracer = Tracer(service_name="t", exporters=[])recorder = Recorder(tracer)diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.pyindex 9b21ad3..eb3feb1 100644--- a/tests/tracing/test_recorder.py+++ b/tests/tracing/test_recorder.py@@ -14,15 +14,15 @@ from opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResultfrom opentelemetry.trace import SpanKind, StatusCode-from cubepi.agent.agent import Agent-from cubepi.agent.types import (+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import (AgentTool,AgentToolResult,BeforeToolCallResult,)-from cubepi.providers.base import BoundModel, Model, TextContent, ToolCall-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.tracing import Tracer+from cubeloop.providers.base import BoundModel, Model, TextContent, ToolCall+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.tracing import TracerMODEL = Model(id="faux-1", provider_id="faux")@@ -77,7 +77,7 @@ def _find_attached_recorder(provider):"""Walk a provider's request_listeners to return the cubepiRecorder instance — used by tests that need to drive recordercallbacks directly with synthetic provider events."""- from cubepi.tracing.recorder import Recorder+ from cubeloop.tracing.recorder import Recorderfor cb in getattr(provider, "_request_listeners", []):if hasattr(cb, "__self__") and isinstance(cb.__self__, Recorder):@@ -100,7 +100,7 @@ class TestSpanTreeBasic:names = sorted(s.name for s in exporter.spans)assert "invoke_agent" in names- assert "cubepi.turn" in names+ assert "cubeloop.turn" in namesassert any(n.startswith("chat ") for n in names)assert len(exporter.spans) == 3@@ -117,8 +117,8 @@ class TestSpanTreeBasic:attrs = _attrs(roots[0])assert attrs["gen_ai.operation.name"] == "invoke_agent"assert attrs["gen_ai.provider.name"] == "faux"- assert "cubepi.run_id" in attrs- assert "cubepi.agent.system_prompt.sha256" in attrs+ assert "cubeloop.run_id" in attrs+ assert "cubeloop.agent.system_prompt.sha256" in attrsassert roots[0].kind == SpanKind.INTERNAL@@ -154,12 +154,12 @@ class TestTurnSpan:await agent.wait_for_idle()await tracer.shutdown()- turn = [s for s in exporter.spans if s.name == "cubepi.turn"][0]+ turn = [s for s in exporter.spans if s.name == "cubeloop.turn"][0]attrs = _attrs(turn)assert "gen_ai.operation.name" not in attrsassert "gen_ai.workflow.name" not in attrs- assert attrs["cubepi.turn.index"] == 0- assert attrs["cubepi.turn.stop_reason"] == "stop"+ assert attrs["cubeloop.turn.index"] == 0+ assert attrs["cubeloop.turn.stop_reason"] == "stop"async def test_multi_turn_indexes_increment(self):from pydantic import BaseModel@@ -188,12 +188,12 @@ class TestTurnSpan:await tracer.shutdown()turns = sorted(- [s for s in exporter.spans if s.name == "cubepi.turn"],+ [s for s in exporter.spans if s.name == "cubeloop.turn"],key=lambda s: s.start_time or 0,)assert len(turns) == 2- assert _attrs(turns[0])["cubepi.turn.index"] == 0- assert _attrs(turns[1])["cubepi.turn.index"] == 1+ assert _attrs(turns[0])["cubeloop.turn.index"] == 0+ assert _attrs(turns[1])["cubeloop.turn.index"] == 1class TestExecuteToolSpan:@@ -241,9 +241,9 @@ class TestExecuteToolSpan:# Recorder reads them off the agent's tool registry at exec# start.assert attrs["gen_ai.tool.description"] == "echo a thing"- assert attrs["cubepi.tool.execution_mode"] in {"parallel", "sequential"}- assert attrs["cubepi.tool.is_error"] is False- assert "cubepi.tool.terminate" not in attrs+ assert attrs["cubeloop.tool.execution_mode"] in {"parallel", "sequential"}+ assert attrs["cubeloop.tool.is_error"] is False+ assert "cubeloop.tool.terminate" not in attrsasync def test_tool_terminate_flag_propagates(self):from pydantic import BaseModel@@ -271,9 +271,9 @@ class TestExecuteToolSpan:await tracer.shutdown()t_span = [s for s in exporter.spans if s.name.startswith("execute_tool ")][0]- assert _attrs(t_span)["cubepi.tool.terminate"] is True- turn = [s for s in exporter.spans if s.name == "cubepi.turn"][0]- assert _attrs(turn)["cubepi.turn.terminated_by_tool"] is True+ assert _attrs(t_span)["cubeloop.tool.terminate"] is True+ turn = [s for s in exporter.spans if s.name == "cubeloop.turn"][0]+ assert _attrs(turn)["cubeloop.turn.terminated_by_tool"] is Trueasync def test_tool_blocked_by_hook(self):from pydantic import BaseModel@@ -308,11 +308,11 @@ class TestExecuteToolSpan:t_span = [s for s in exporter.spans if s.name.startswith("execute_tool ")][0]attrs = _attrs(t_span)- assert attrs["cubepi.tool.is_error"] is True- assert attrs["cubepi.tool.blocked_by_hook"] is True- assert attrs["cubepi.tool.block_reason"] == "no thanks"+ assert attrs["cubeloop.tool.is_error"] is True+ assert attrs["cubeloop.tool.blocked_by_hook"] is True+ assert attrs["cubeloop.tool.block_reason"] == "no thanks"assert t_span.status.status_code == StatusCode.ERROR- assert attrs["error.type"] == "cubepi.tool.blocked_by_hook"+ assert attrs["error.type"] == "cubeloop.tool.blocked_by_hook"class TestParentChild:@@ -348,13 +348,13 @@ class TestParentChild:by_name = _spans_by_name(exporter)root = by_name["invoke_agent"][0]assert root.parent is None- for turn in by_name["cubepi.turn"]:+ for turn in by_name["cubeloop.turn"]:assert turn.parent is not Noneassert turn.parent.span_id == root.context.span_idfor chat in [s for s in exporter.spans if s.name.startswith("chat ")]:assert chat.parent is not Noneassert chat.parent.span_id in {- t.context.span_id for t in by_name["cubepi.turn"]+ t.context.span_id for t in by_name["cubeloop.turn"]}@@ -400,7 +400,7 @@ class TestErrorAndAbort:root = [s for s in exporter.spans if s.name == "invoke_agent"][0]attrs = _attrs(root)- assert attrs.get("cubepi.aborted") is True+ assert attrs.get("cubeloop.aborted") is Trueasync def test_chat_span_marks_aborted_when_provider_returns_no_body(self):"""Real Anthropic/OpenAI/OpenAI-Responses abort branches return@@ -433,7 +433,7 @@ class TestErrorAndAbort:recorder = _find_attached_recorder(provider)assert recorder is not None- from cubepi.agent.types import AgentStartEvent, TurnStartEvent+ from cubeloop.agent.types import AgentStartEvent, TurnStartEventawait recorder._on_agent_event(AgentStartEvent())await recorder._on_agent_event(TurnStartEvent())@@ -450,8 +450,8 @@ class TestErrorAndAbort:assert len(chats) >= 2aborted_chat = chats[-1]attrs = _attrs(aborted_chat)- assert attrs.get("cubepi.aborted") is True- assert attrs.get("error.type") == "cubepi.aborted"+ assert attrs.get("cubeloop.aborted") is True+ assert attrs.get("error.type") == "cubeloop.aborted"assert aborted_chat.status.status_code == StatusCode.UNSETasync def test_no_body_without_signal_keeps_chat_unset(self):@@ -473,7 +473,7 @@ class TestErrorAndAbort:recorder = _find_attached_recorder(provider)assert recorder is not None- from cubepi.agent.types import AgentStartEvent, TurnStartEvent+ from cubeloop.agent.types import AgentStartEvent, TurnStartEventawait recorder._on_agent_event(AgentStartEvent())await recorder._on_agent_event(TurnStartEvent())@@ -487,10 +487,10 @@ class TestErrorAndAbort:assert len(chats) >= 2fallback_chat = chats[-1]attrs = _attrs(fallback_chat)- assert "cubepi.aborted" not in attrs, (+ assert "cubeloop.aborted" not in attrs, ("non-abort (None, None) fallback must not be marked aborted")- assert attrs.get("error.type") != "cubepi.aborted"+ assert attrs.get("error.type") != "cubeloop.aborted"assert fallback_chat.status.status_code == StatusCode.UNSET@@ -501,9 +501,9 @@ class TestMiddlewareProviders:turn is recorded."""async def test_compaction_summary_provider_emits_chat_span(self):- from cubepi.checkpointer.memory import MemoryCheckpointer- from cubepi.middleware.compaction import CompactionMiddleware- from cubepi.providers.base import UserMessage+ from cubeloop.checkpointer.memory import MemoryCheckpointer+ from cubeloop.middleware.compaction import CompactionMiddleware+ from cubeloop.providers.base import UserMessagemain = FauxProvider()summarizer = FauxProvider()@@ -564,7 +564,7 @@ class TestMiddlewareProviders:# Both chat spans share the agent run's trace_id — the summarizer# call must be part of the same trace, not a sibling root.- turn = [s for s in exporter.spans if s.name == "cubepi.turn"][0]+ turn = [s for s in exporter.spans if s.name == "cubeloop.turn"][0]for chat in chats:assert chat.context.trace_id == turn.context.trace_id@@ -581,9 +581,9 @@ class TestMiddlewareProviders:# dedupe would route the summarizer through the main listener and# let it clobber the root attribution. The fix gates on the model,# not the listener — this regression test pins that contract.- from cubepi.checkpointer.memory import MemoryCheckpointer- from cubepi.middleware.compaction import CompactionMiddleware- from cubepi.providers.base import UserMessage+ from cubeloop.checkpointer.memory import MemoryCheckpointer+ from cubeloop.middleware.compaction import CompactionMiddleware+ from cubeloop.providers.base import UserMessageshared = FauxProvider()agent_model = Model(id="agent-1", provider_id="faux-main")@@ -645,7 +645,7 @@ class TestMiddlewareProviders:# ``Middleware.extra_llm_calls()`` default must return an empty# iterable so middlewares that don't drive any LLM are zero-cost on# Recorder.attach.- from cubepi.middleware.base import Middleware+ from cubeloop.middleware.base import Middlewareassert list(Middleware().extra_llm_calls()) == []@@ -657,7 +657,7 @@ class TestMiddlewareProviders:# degenerate keys from the extra set so the run still gets a# concrete root attribution (even if it ends up reflecting whichever# call fired first).- from cubepi.middleware.base import Middleware+ from cubeloop.middleware.base import Middlewareclass _SameModelMiddleware(Middleware):def __init__(self, provider, model):@@ -695,7 +695,7 @@ class TestMiddlewareProviders:# ``_subscribe`` — its calls simply won't be observable, but attach# must not error. Covers the early-return branch in ``_subscribe``# that codecov flagged.- from cubepi.middleware.base import Middleware+ from cubeloop.middleware.base import Middlewareclass _DuckProvider:pass@@ -730,7 +730,7 @@ class TestMiddlewareProviders:# If a middleware's ``extra_llm_calls()`` raises during attach the# recorder must keep going — the agent's own provider is the# load-bearing subscription, a buggy middleware mustn't break tracing.- from cubepi.middleware.base import Middleware+ from cubeloop.middleware.base import Middlewareclass _BoomMiddleware(Middleware):def extra_llm_calls(self):@@ -767,12 +767,12 @@ class TestSafeToolName:overall-review MINOR)."""def test_top_level_name(self):- from cubepi.tracing.recorder import _safe_tool_name+ from cubeloop.tracing.recorder import _safe_tool_nameassert _safe_tool_name({"name": "search"}) == "search"def test_openai_chat_nested_function_shape(self):- from cubepi.tracing.recorder import _safe_tool_name+ from cubeloop.tracing.recorder import _safe_tool_nameassert (_safe_tool_name({"type": "function", "function": {"name": "fetch"}})@@ -780,7 +780,7 @@ class TestSafeToolName:)def test_object_attribute(self):- from cubepi.tracing.recorder import _safe_tool_name+ from cubeloop.tracing.recorder import _safe_tool_nameclass _T:name = "calc"@@ -788,7 +788,7 @@ class TestSafeToolName:assert _safe_tool_name(_T()) == "calc"def test_missing_name_returns_empty(self):- from cubepi.tracing.recorder import _safe_tool_name+ from cubeloop.tracing.recorder import _safe_tool_nameassert _safe_tool_name({}) == ""assert _safe_tool_name({"type": "function"}) == ""@@ -810,7 +810,7 @@ class TestRequestMaxTokensCrossProvider:recorder = _find_attached_recorder(provider)assert recorder is not None- from cubepi.agent.types import AgentStartEvent, TurnStartEvent+ from cubeloop.agent.types import AgentStartEvent, TurnStartEventawait recorder._on_agent_event(AgentStartEvent())await recorder._on_agent_event(TurnStartEvent())@@ -835,7 +835,7 @@ class TestChatSpanOutputMessages:provider actually returned - independent of the turn/agent-level rollup,which is built later from the agent's own message accumulation and isn'tavailable yet inside the `subscribe_response` callback. Previously only- `cubepi.llm.raw_response` was recorded here despite the code comment+ `cubeloop.llm.raw_response` was recorded here despite the code commentalready saying otherwise."""@@ -850,7 +850,7 @@ class TestChatSpanOutputMessages:recorder = _find_attached_recorder(provider)assert recorder is not None- from cubepi.agent.types import AgentStartEvent, TurnStartEvent+ from cubeloop.agent.types import AgentStartEvent, TurnStartEventawait recorder._on_agent_event(AgentStartEvent())await recorder._on_agent_event(TurnStartEvent())@@ -1018,24 +1018,24 @@ class TestCancellationExportsSpans:detach()await tracer.shutdown()- # invoke_agent + cubepi.turn + chat must all have been ended+ # invoke_agent + cubeloop.turn + chat must all have been ended# and exported, even though no AgentEnd/TurnEnd fired.names = {s.name for s in exporter.spans}assert "invoke_agent" in names, (f"cancelled run's invoke_agent span not exported; got {names}")- assert "cubepi.turn" in names+ assert "cubeloop.turn" in namesassert any(n.startswith("chat ") for n in names)- # Each must carry cubepi.aborted so the backend sees the+ # Each must carry cubeloop.aborted so the backend sees the# interruption rather than thinking the run completed.for span in exporter.spans:- if span.name in ("invoke_agent", "cubepi.turn") or span.name.startswith(+ if span.name in ("invoke_agent", "cubeloop.turn") or span.name.startswith("chat "):attrs = _attrs(span)- assert attrs.get("cubepi.aborted") is True, (- f"{span.name} missing cubepi.aborted after cancellation"+ assert attrs.get("cubeloop.aborted") is True, (+ f"{span.name} missing cubeloop.aborted after cancellation")@@ -1046,7 +1046,7 @@ class TestCloseOpenSpansDefensive:(codex overall-review BLOCKING follow-up: pure coverage)."""def test_close_open_spans_swallows_set_attribute_errors(self):- from cubepi.tracing.recorder import Recorder, _RunState+ from cubeloop.tracing.recorder import Recorder, _RunStatetracer = Tracer(service_name="t", exporters=[])recorder = Recorder(tracer)@@ -1080,7 +1080,7 @@ class TestAgentSignalHelper:no-agent and signal-raises edges so codecov accepts the patch."""def test_returns_false_when_no_agent_attached(self):- from cubepi.tracing.recorder import Recorder+ from cubeloop.tracing.recorder import Recordertracer = Tracer(service_name="t", exporters=[])recorder = Recorder(tracer)@@ -1088,7 +1088,7 @@ class TestAgentSignalHelper:assert recorder._agent_signal_is_set() is Falsedef test_returns_false_when_agent_has_no_signal(self):- from cubepi.tracing.recorder import Recorder+ from cubeloop.tracing.recorder import Recordertracer = Tracer(service_name="t", exporters=[])recorder = Recorder(tracer)@@ -1100,7 +1100,7 @@ class TestAgentSignalHelper:assert recorder._agent_signal_is_set() is Falsedef test_returns_false_when_signal_is_set_raises(self):- from cubepi.tracing.recorder import Recorder+ from cubeloop.tracing.recorder import Recordertracer = Tracer(service_name="t", exporters=[])recorder = Recorder(tracer)@@ -1124,8 +1124,8 @@ class TestTranscriptSeedingDefensiveBranches:raising-state branches so the patch is fully covered."""async def test_no_seed_when_agent_has_no_state(self):- from cubepi.tracing.recorder import Recorder- from cubepi.agent.types import AgentStartEvent+ from cubeloop.tracing.recorder import Recorder+ from cubeloop.agent.types import AgentStartEventtracer = Tracer(service_name="t", exporters=[])recorder = Recorder(tracer)@@ -1141,8 +1141,8 @@ class TestTranscriptSeedingDefensiveBranches:assert recorder._run.transcript == []async def test_seed_handles_exception_in_state_messages(self):- from cubepi.tracing.recorder import Recorder- from cubepi.agent.types import AgentStartEvent+ from cubeloop.tracing.recorder import Recorder+ from cubeloop.agent.types import AgentStartEventtracer = Tracer(service_name="t", exporters=[])recorder = Recorder(tracer)@@ -1183,7 +1183,7 @@ class TestAttachedContextManager:# After the block, spans have been flushed.names = {s.name for s in exporter.spans}assert "invoke_agent" in names- assert "cubepi.turn" in names+ assert "cubeloop.turn" in namesassert any(n.startswith("chat ") for n in names)async def test_cancellation_inside_block_still_closes_spans(self):@@ -1206,11 +1206,11 @@ class TestAttachedContextManager:assert "invoke_agent" in names, (f"cancelled run's invoke_agent span did not export; got {names}")- # Each open-at-cancel span carries cubepi.aborted.+ # Each open-at-cancel span carries cubeloop.aborted.for span in exporter.spans:- if span.name == "invoke_agent" or span.name == "cubepi.turn":+ if span.name == "invoke_agent" or span.name == "cubeloop.turn":attrs = _attrs(span)- assert attrs.get("cubepi.aborted") is True+ assert attrs.get("cubeloop.aborted") is Trueasync def test_exception_inside_block_still_detaches(self):provider = FauxProvider(provider_id="faux")@@ -1245,7 +1245,7 @@ class TestAttachedContextManager:raise sentinel# Patch the underlying force_flush to fail.- import cubepi.tracing.tracer as _t_mod+ import cubeloop.tracing.tracer as _t_modoriginal = tracer.force_flushtracer.force_flush = _bad_flush # type: ignore[method-assign]@@ -1298,11 +1298,11 @@ class TestAttachedContextManager:class TestTracingContext:- """``cubepi.tracing.tracing_context`` sets per-task tags ++ """``cubeloop.tracing.tracing_context`` sets per-task tags +metadata that the recorder stamps onto the invoke_agent span."""async def test_tags_land_on_invoke_agent_span(self):- from cubepi.tracing import tracing_context+ from cubeloop.tracing import tracing_contextagent, provider, exporter, tracer = await _build()provider.append_responses([faux_assistant_message("ok")])@@ -1314,10 +1314,10 @@ class TestTracingContext:root = next(s for s in exporter.spans if s.name == "invoke_agent")attrs = _attrs(root)- assert attrs.get("cubepi.tags") == ("beta-arm", "test-suite")+ assert attrs.get("cubeloop.tags") == ("beta-arm", "test-suite")async def test_metadata_keys_land_with_prefix(self):- from cubepi.tracing import tracing_context+ from cubeloop.tracing import tracing_contextagent, provider, exporter, tracer = await _build()provider.append_responses([faux_assistant_message("ok")])@@ -1329,8 +1329,8 @@ class TestTracingContext:root = next(s for s in exporter.spans if s.name == "invoke_agent")attrs = _attrs(root)- assert attrs.get("cubepi.metadata.user_id") == "u-42"- assert attrs.get("cubepi.metadata.ab_arm") == "control"+ assert attrs.get("cubeloop.metadata.user_id") == "u-42"+ assert attrs.get("cubeloop.metadata.ab_arm") == "control"async def test_no_context_means_no_tag_attr(self):agent, provider, exporter, tracer = await _build()@@ -1341,12 +1341,12 @@ class TestTracingContext:root = next(s for s in exporter.spans if s.name == "invoke_agent")attrs = _attrs(root)- assert "cubepi.tags" not in attrs+ assert "cubeloop.tags" not in attrsasync def test_context_does_not_leak_across_runs(self):"""The contextvar resets on block exit — the next run startedoutside the block must NOT carry the previous tags."""- from cubepi.tracing import tracing_context+ from cubeloop.tracing import tracing_contextagent, provider, exporter, tracer = await _build()provider.append_responses(@@ -1368,11 +1368,11 @@ class TestTracingContext:key=lambda s: s.start_time or 0,)assert len(roots) == 2- assert _attrs(roots[0]).get("cubepi.tags") == ("scoped",)- assert "cubepi.tags" not in _attrs(roots[1])+ assert _attrs(roots[0]).get("cubeloop.tags") == ("scoped",)+ assert "cubeloop.tags" not in _attrs(roots[1])async def test_nested_contexts_merge_additively(self):- from cubepi.tracing import tracing_context+ from cubeloop.tracing import tracing_contextagent, provider, exporter, tracer = await _build()provider.append_responses([faux_assistant_message("ok")])@@ -1387,13 +1387,13 @@ class TestTracingContext:root = next(s for s in exporter.spans if s.name == "invoke_agent")attrs = _attrs(root)- assert attrs.get("cubepi.tags") == ("outer", "inner")- assert attrs.get("cubepi.metadata.k") == "inner-val"- assert attrs.get("cubepi.metadata.x") == "new"+ assert attrs.get("cubeloop.tags") == ("outer", "inner")+ assert attrs.get("cubeloop.metadata.k") == "inner-val"+ assert attrs.get("cubeloop.metadata.x") == "new"async def test_unsupported_metadata_value_is_dropped(self):"""OTel attributes can't hold dicts or arbitrary objects."""- from cubepi.tracing import tracing_context+ from cubeloop.tracing import tracing_contextagent, provider, exporter, tracer = await _build()provider.append_responses([faux_assistant_message("ok")])@@ -1411,9 +1411,9 @@ class TestTracingContext:root = next(s for s in exporter.spans if s.name == "invoke_agent")attrs = _attrs(root)- assert attrs.get("cubepi.metadata.good_str") == "yes"- assert attrs.get("cubepi.metadata.good_int") == 42- assert "cubepi.metadata.bad_dict" not in attrs+ assert attrs.get("cubeloop.metadata.good_str") == "yes"+ assert attrs.get("cubeloop.metadata.good_int") == 42+ assert "cubeloop.metadata.bad_dict" not in attrsasync def test_metadata_set_attribute_typeerror_is_swallowed(self, monkeypatch):"""OTel SDK silently drops most invalid attribute values, but@@ -1422,20 +1422,20 @@ class TestTracingContext:per-key so one bad metadata entry can't crash the whole span(covers the defensive ``except (TypeError, ValueError)``branch)."""- from cubepi.tracing import tracing_context+ from cubeloop.tracing import tracing_contextfrom opentelemetry.sdk.trace import Span as _SdkSpanagent, provider, exporter, tracer = await _build()provider.append_responses([faux_assistant_message("ok")])- # Patch set_attribute to raise on a specific cubepi.metadata.*+ # Patch set_attribute to raise on a specific cubeloop.metadata.*# key while letting every other attribute go through. The- # recorder writes many cubepi.* / gen_ai.* attrs at agent+ # recorder writes many cubeloop.* / gen_ai.* attrs at agent# start, so we need to be surgical.original = _SdkSpan.set_attributedef _selective_set_attribute(self, key, value):- if key == "cubepi.metadata.boom":+ if key == "cubeloop.metadata.boom":raise TypeError("simulated OTel reject")return original(self, key, value)@@ -1449,17 +1449,17 @@ class TestTracingContext:root = next(s for s in exporter.spans if s.name == "invoke_agent")attrs = _attrs(root)# bad key swallowed; good key landed.- assert "cubepi.metadata.boom" not in attrs- assert attrs.get("cubepi.metadata.good") == "yes"+ assert "cubeloop.metadata.boom" not in attrs+ assert attrs.get("cubeloop.metadata.good") == "yes"async def test_metadata_cannot_clobber_reserved_cubepi_attrs(self):"""User-supplied metadata keys must not be able to overwrite- recorder-owned schema attributes like ``cubepi.run_id`` —+ recorder-owned schema attributes like ``cubeloop.run_id`` —the JSONL exporter shards spans by that key, so aninvoke_agent span with a clobbered ``run_id`` ends up in adifferent file than its turn/chat/tool spans (codex P2 on- PR #92). The fix is the ``cubepi.metadata.*`` sub-namespace."""- from cubepi.tracing import tracing_context+ PR #92). The fix is the ``cubeloop.metadata.*`` sub-namespace."""+ from cubeloop.tracing import tracing_contextagent, provider, exporter, tracer = await _build()provider.append_responses([faux_assistant_message("ok")])@@ -1472,14 +1472,14 @@ class TestTracingContext:root = next(s for s in exporter.spans if s.name == "invoke_agent")attrs = _attrs(root)# The genuine recorder-owned value is unchanged…- assert attrs.get("cubepi.run_id") and attrs["cubepi.run_id"] != "hijacked"+ assert attrs.get("cubeloop.run_id") and attrs["cubeloop.run_id"] != "hijacked"# …and the user-supplied values land under the safe namespace.- assert attrs.get("cubepi.metadata.run_id") == "hijacked"- assert attrs.get("cubepi.metadata.turn.index") == "x"+ assert attrs.get("cubeloop.metadata.run_id") == "hijacked"+ assert attrs.get("cubeloop.metadata.turn.index") == "x"class TestBusinessRunIdAlignment:- """cubepi.run_id must equal the agent/host business run id.+ """cubeloop.run_id must equal the agent/host business run id.See dev/specs/2026-08-10-unify-trace-run-id.md — no second tracer-private uuid when active_run_id is set.@@ -1495,7 +1495,7 @@ class TestBusinessRunIdAlignment:assert returned == "host-run-42"assert exporter.spans- run_ids = {_attrs(s).get("cubepi.run_id") for s in exporter.spans}+ run_ids = {_attrs(s).get("cubeloop.run_id") for s in exporter.spans}assert run_ids == {"host-run-42"}async def test_agent_minted_run_id_matches_prompt_return(self):@@ -1507,7 +1507,7 @@ class TestBusinessRunIdAlignment:await tracer.shutdown()assert returned- run_ids = {_attrs(s).get("cubepi.run_id") for s in exporter.spans}+ run_ids = {_attrs(s).get("cubeloop.run_id") for s in exporter.spans}assert run_ids == {returned}async def test_sequential_runs_do_not_leak_run_id(self):@@ -1528,7 +1528,7 @@ class TestBusinessRunIdAlignment:assert r1 == "run-a" and r2 == "run-b"by_run: dict[str, int] = {}for s in exporter.spans:- rid = _attrs(s).get("cubepi.run_id")+ rid = _attrs(s).get("cubeloop.run_id")assert rid in ("run-a", "run-b")by_run[rid] = by_run.get(rid, 0) + 1assert by_run.get("run-a", 0) >= 1@@ -1674,7 +1674,7 @@ class TestAtexitFlush:class TestJsonlExporter:async def test_writes_jsonl_files(self, tmp_path):- from cubepi.tracing.exporters import JsonlSpanExporter+ from cubeloop.tracing.exporters import JsonlSpanExporterprovider = FauxProvider(provider_id="faux")provider.append_responses([faux_assistant_message("ok")])@@ -1706,7 +1706,7 @@ class TestFallbackChainCoverage:async def test_attach_subscribes_to_every_chain_provider(self):"""When agent.model is a FallbackBoundModel, attach() should listenon each unique provider in chain — not just chain[0]."""- from cubepi.providers.fallback import FallbackBoundModel+ from cubeloop.providers.fallback import FallbackBoundModelprimary = FauxProvider(provider_id="primary")secondary = FauxProvider(provider_id="secondary")@@ -1730,7 +1730,7 @@ class TestFallbackChainCoverage:async def test_attach_dedupes_shared_provider_across_chain(self):"""If chain[0] and chain[1] share the same provider instance,attach() must register listeners on it only once."""- from cubepi.providers.fallback import FallbackBoundModel+ from cubeloop.providers.fallback import FallbackBoundModelshared = FauxProvider(provider_id="shared")chain_model = FallbackBoundModel(@@ -1767,7 +1767,7 @@ class TestFallbackChainCoverage:attach, then verify secondary's spec key is absent from the recorder's``_extra_call_models`` set."""- from cubepi.providers.fallback import FallbackBoundModel+ from cubeloop.providers.fallback import FallbackBoundModelprimary = FauxProvider(provider_id="primary")secondary = FauxProvider(provider_id="secondary")diff --git a/tests/tracing/test_recorder_coverage.py b/tests/tracing/test_recorder_coverage.pyindex 49169d1..03199b2 100644--- a/tests/tracing/test_recorder_coverage.py+++ b/tests/tracing/test_recorder_coverage.py@@ -1,4 +1,4 @@-"""Extra coverage for cubepi.tracing.recorder — pins the contracts+"""Extra coverage for cubeloop.tracing.recorder — pins the contractscodex flagged in the round-1 review and exercises the response-bodyshape parsers and error-type derivation paths that aren't covered bythe FauxProvider end-to-end tests.@@ -14,11 +14,11 @@ from opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResultfrom opentelemetry.trace import StatusCode-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import Model, TextContent, ToolCall-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.tracing import Tracer+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import Model, TextContent, ToolCall+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.tracing import TracerMODEL = Model(id="faux-1", provider_id="faux")@@ -44,7 +44,7 @@ def _attrs(span: ReadableSpan) -> dict[str, Any]:# ----------------------------------------------------------------------------# P2-1: every span must carry cubepi.run_id (codex round 1)+# P2-1: every span must carry cubeloop.run_id (codex round 1)# ---------------------------------------------------------------------------@@ -62,19 +62,19 @@ class TestRunIdOnEverySpan:await tracer.shutdown()assert exporter.spans, "expected spans"- run_ids = {_attrs(s).get("cubepi.run_id") for s in exporter.spans}+ run_ids = {_attrs(s).get("cubeloop.run_id") for s in exporter.spans}assert len(run_ids) == 1assert None not in run_ids- # Same run id appears on invoke_agent / cubepi.turn / chat ...+ # Same run id appears on invoke_agent / cubeloop.turn / chat ...assert run_ids.pop() is not Noneclass TestJsonlSharding:async def test_jsonl_shards_all_spans_under_run_file(self, tmp_path):"""All spans from one run must end up in the same per-run file —- codex flagged that without cubepi.run_id on child spans the+ codex flagged that without cubeloop.run_id on child spans theJsonlSpanExporter routed them to unknown-run.jsonl."""- from cubepi.tracing.exporters import JsonlSpanExporter+ from cubeloop.tracing.exporters import JsonlSpanExporterprovider = FauxProvider(provider_id="faux")provider.append_responses([faux_assistant_message("ok")])@@ -116,8 +116,8 @@ class TestChatSpanAbort:assert len(chats) == 1attrs = _attrs(chats[0])# Cooperative abort: no exception, but body has stop_reason="aborted".- assert attrs.get("cubepi.aborted") is True- assert attrs.get("error.type") == "cubepi.aborted"+ assert attrs.get("cubeloop.aborted") is True+ assert attrs.get("error.type") == "cubeloop.aborted"# Status remains UNSET — abort is a control signal, not a failure.assert chats[0].status.status_code == StatusCode.UNSET@@ -138,7 +138,7 @@ class _Span:def _recorder():- from cubepi.tracing.recorder import Recorder+ from cubeloop.tracing.recorder import Recordertracer = Tracer(service_name="t", exporters=[])return Recorder(tracer)@@ -226,12 +226,12 @@ class TestOpenAIResponsesShape:class TestSystemPromptExtraction:def test_anthropic_string_system(self):- from cubepi.tracing.recorder import _extract_system_prompt+ from cubeloop.tracing.recorder import _extract_system_promptassert _extract_system_prompt({"system": "hi"}) == "hi"def test_anthropic_cached_system_blocks(self):- from cubepi.tracing.recorder import _extract_system_prompt+ from cubeloop.tracing.recorder import _extract_system_promptpayload = {"system": [@@ -242,12 +242,12 @@ class TestSystemPromptExtraction:assert _extract_system_prompt(payload) == "helloworld"def test_faux_system_prompt_key(self):- from cubepi.tracing.recorder import _extract_system_prompt+ from cubeloop.tracing.recorder import _extract_system_promptassert _extract_system_prompt({"system_prompt": "faux"}) == "faux"def test_openai_chat_first_system_message(self):- from cubepi.tracing.recorder import _extract_system_prompt+ from cubeloop.tracing.recorder import _extract_system_promptpayload = {"messages": [@@ -258,7 +258,7 @@ class TestSystemPromptExtraction:assert _extract_system_prompt(payload) == "be helpful"def test_openai_responses_developer_role(self):- from cubepi.tracing.recorder import _extract_system_prompt+ from cubeloop.tracing.recorder import _extract_system_promptpayload = {"input": [@@ -269,7 +269,7 @@ class TestSystemPromptExtraction:assert _extract_system_prompt(payload) == "be precise"def test_no_system_returns_none(self):- from cubepi.tracing.recorder import _extract_system_prompt+ from cubeloop.tracing.recorder import _extract_system_promptassert _extract_system_prompt({}) is Noneassert _extract_system_prompt({"messages": []}) is None@@ -283,34 +283,34 @@ class TestSystemPromptExtraction:class TestErrorType:def test_cancelled_error(self):- from cubepi.tracing.errors import cubepi_error_type_for+ from cubeloop.tracing.errors import cubeloop_error_type_for- assert cubepi_error_type_for(asyncio.CancelledError()) == "cubepi.aborted"+ assert cubeloop_error_type_for(asyncio.CancelledError()) == "cubeloop.aborted"def test_timeout(self):- from cubepi.tracing.errors import cubepi_error_type_for+ from cubeloop.tracing.errors import cubeloop_error_type_for- assert cubepi_error_type_for(asyncio.TimeoutError()) == "timeout"- assert cubepi_error_type_for(TimeoutError()) == "timeout"+ assert cubeloop_error_type_for(asyncio.TimeoutError()) == "timeout"+ assert cubeloop_error_type_for(TimeoutError()) == "timeout"def test_connection_error(self):- from cubepi.tracing.errors import cubepi_error_type_for+ from cubeloop.tracing.errors import cubeloop_error_type_for- assert cubepi_error_type_for(ConnectionError()) == "connection_error"+ assert cubeloop_error_type_for(ConnectionError()) == "connection_error"def test_builtin_exception_uses_qualname(self):- from cubepi.tracing.errors import cubepi_error_type_for+ from cubeloop.tracing.errors import cubeloop_error_type_for- assert cubepi_error_type_for(ValueError("x")) == "ValueError"+ assert cubeloop_error_type_for(ValueError("x")) == "ValueError"def test_module_qualified_class(self):- from cubepi.tracing.errors import cubepi_error_type_for+ from cubeloop.tracing.errors import cubeloop_error_type_forclass CustomErr(Exception):passerr = CustomErr()- out = cubepi_error_type_for(err)+ out = cubeloop_error_type_for(err)assert out.endswith("CustomErr")@@ -321,12 +321,12 @@ class TestErrorType:class TestSchemaConstants:def test_schema_url_pinned(self):- from cubepi.tracing.schema import SCHEMA_URL+ from cubeloop.tracing.schema import SCHEMA_URLassert SCHEMA_URL == "https://opentelemetry.io/schemas/1.41.0"def test_provider_name_known(self):- from cubepi.tracing.schema import map_provider_name+ from cubeloop.tracing.schema import map_provider_nameassert map_provider_name("anthropic") == "anthropic"assert map_provider_name("azure_openai") == "azure.ai.openai"@@ -334,7 +334,7 @@ class TestSchemaConstants:assert map_provider_name("vertex_ai") == "gcp.vertex_ai"def test_provider_name_unknown_prefixed(self):- from cubepi.tracing.schema import map_provider_name+ from cubeloop.tracing.schema import map_provider_nameassert map_provider_name("nobody") == "unknown:nobody"@@ -730,7 +730,7 @@ class TestStreamRecording:# Now simulate a second run where the file write raises.# We directly patch the stream_file.write on the recorder's _run state# after the second AgentStart so the open succeeds but every write fails.- import cubepi.tracing.recorder as _rec_mod+ import cubeloop.tracing.recorder as _rec_mod_orig_on_agent_start = _rec_mod.Recorder._on_agent_start@@ -777,7 +777,7 @@ class TestStreamRecording:async def test_stream_close_exception_swallowed_on_agent_end(self, tmp_path):"""If stream_file.close() raises during _on_agent_end, it is swallowed."""- import cubepi.tracing.recorder as _rec_mod+ import cubeloop.tracing.recorder as _rec_modfrom unittest.mock import MagicMock, patchprovider = FauxProvider(provider_id="faux")@@ -814,7 +814,7 @@ class TestStreamRecording:async def test_stream_close_exception_swallowed_on_cancel(self, tmp_path):"""If stream_file.close() raises during _close_open_spans, it is swallowed."""- import cubepi.tracing.recorder as _rec_mod+ import cubeloop.tracing.recorder as _rec_modfrom unittest.mock import MagicMock, patchprovider = FauxProvider(tokens_per_second=5.0)diff --git a/tests/tracing/test_subagent_nesting.py b/tests/tracing/test_subagent_nesting.pyindex 9bc9ecc..7715bd6 100644--- a/tests/tracing/test_subagent_nesting.py+++ b/tests/tracing/test_subagent_nesting.py@@ -23,11 +23,11 @@ from opentelemetry.sdk.trace import ReadableSpanfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResultfrom pydantic import BaseModel-from cubepi.agent.agent import Agent-from cubepi.agent.types import AgentTool, AgentToolResult-from cubepi.providers.base import Model, TextContent, ToolCall-from cubepi.providers.faux import FauxProvider, faux_assistant_message-from cubepi.tracing import Tracer+from cubeloop.agent.agent import Agent+from cubeloop.agent.types import AgentTool, AgentToolResult+from cubeloop.providers.base import Model, TextContent, ToolCall+from cubeloop.providers.faux import FauxProvider, faux_assistant_message+from cubeloop.tracing import TracerMODEL = Model(id="faux-1", provider_id="faux")@@ -174,12 +174,12 @@ async def test_cancelled_inner_gate_released_for_parents_next_turn():# Identify the parent run unambiguously via the execute_tool span's run_id.tool_span = next(s for s in exporter.spans if s.name == "execute_tool spawn")- parent_run_id = (tool_span.attributes or {}).get("cubepi.run_id")+ parent_run_id = (tool_span.attributes or {}).get("cubeloop.run_id")parent_chats = [sfor s in exporter.spansif (s.attributes or {}).get("gen_ai.operation.name") == "chat"- and (s.attributes or {}).get("cubepi.run_id") == parent_run_id+ and (s.attributes or {}).get("cubeloop.run_id") == parent_run_id]assert len(parent_chats) == 2, (f"expected 2 parent-run chat spans, got {len(parent_chats)}"@@ -192,7 +192,7 @@ async def test_inner_run_nests_under_active_tool_span():invoke_agent span must nest under that tool span — inheriting trace_idand setting parent_span_id — instead of starting a new root."""- from cubepi.mcp import _tracing as mcp_tracing+ from cubeloop.mcp import _tracing as mcp_tracingprovider = FauxProvider(provider_id="faux")exporter = InMemoryExporter()@@ -233,7 +233,7 @@ async def test_inner_run_nests_under_active_tool_span():async def test_full_nested_subtree_via_real_tool():"""End-to-end composition of Tasks 1+2: a tool whose body attaches and runsan inner agent (which itself calls a tool) yields the full nested subtree- ``execute_tool spawn -> invoke_agent -> cubepi.turn -> {chat,+ ``execute_tool spawn -> invoke_agent -> cubeloop.turn -> {chat,execute_tool inner_tool}`` — the inner chat and inner tool span both descendfrom the inner run's root, and the inner root nests under the tool span."""@@ -337,7 +337,7 @@ async def test_provider_chunk_and_response_gated_when_run_not_active():even if this recorder's run still has an open chat_span. Defensive backstopbeyond the ``chat_span is None`` guard (a non-owning recorder normally neveropens a chat_span at all)."""- from cubepi.tracing import recorder as rec+ from cubeloop.tracing import recorder as recexporter = InMemoryExporter()tracer = Tracer(service_name="t", agent_name="a", exporters=[exporter])diff --git a/tests/tracing/test_trace_scope.py b/tests/tracing/test_trace_scope.pyindex bea86ec..18fcd13 100644--- a/tests/tracing/test_trace_scope.py+++ b/tests/tracing/test_trace_scope.py@@ -14,10 +14,10 @@ import asyncioimport pytestfrom opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult-from cubepi.agent.agent import Agent-from cubepi.providers.base import Model-from cubepi.providers.faux import FauxProvider-from cubepi.tracing import Tracer, trace+from cubeloop.agent.agent import Agent+from cubeloop.providers.base import Model+from cubeloop.providers.faux import FauxProvider+from cubeloop.tracing import Tracer, traceMODEL = Model(id="faux-1", provider_id="faux")@@ -176,7 +176,7 @@ async def test_trace_swallows_mcp_unregister_failure(monkeypatch):# Real attach registers the MCP provider; make unregister blow up on detach.# The body must still run and the failure must not propagate.agent, _provider, tracer = _build()- import cubepi.mcp._tracing as mcp_tracing+ import cubeloop.mcp._tracing as mcp_tracingbaseline = len(mcp_tracing._provider_stack)try:diff --git a/tests/utils/test_json_parse.py b/tests/utils/test_json_parse.pyindex 9c72eac..af3993b 100644--- a/tests/utils/test_json_parse.py+++ b/tests/utils/test_json_parse.py@@ -6,7 +6,7 @@ import jsonimport pytest-from cubepi.utils.json_parse import (+from cubeloop.utils.json_parse import (_close_partial_json,parse_streaming_json,repair_json,diff --git a/uv.lock b/uv.lockindex 698a61c..b3a51a8 100644--- a/uv.lock+++ b/uv.lock@@ -9,6 +9,12 @@ resolution-markers = ["python_full_version < '3.14' and sys_platform != 'win32'",]+[manifest]+members = [+ "cubeloop",+ "cubepi",+]+[[package]]name = "aiomysql"version = "0.3.2"@@ -521,8 +527,8 @@ wheels = [][[package]]-name = "cubepi"-version = "0.13.6"+name = "cubeloop"+version = "0.14.0"source = { editable = "." }dependencies = [{ name = "anthropic" },@@ -566,6 +572,7 @@ dev = [{ name = "aiomysql" },{ name = "aiosqlite" },{ name = "asyncpg" },+ { name = "cubepi" },{ name = "mcp" },{ name = "msgpack" },{ name = "mypy" },@@ -603,6 +610,7 @@ dev = [{ name = "aiomysql", specifier = ">=0.2" },{ name = "aiosqlite", specifier = ">=0.22.1" },{ name = "asyncpg", specifier = ">=0.29" },+ { name = "cubepi", editable = "compat/cubepi" },{ name = "mcp", specifier = ">=1.0" },{ name = "msgpack", specifier = ">=1.0" },{ name = "mypy", specifier = ">=2.1.0" },@@ -614,6 +622,50 @@ dev = [{ name = "sqlalchemy", specifier = ">=2.0" },]+[[package]]+name = "cubepi"+version = "0.14.0"+source = { editable = "compat/cubepi" }+dependencies = [+ { name = "cubeloop" },+]++[package.optional-dependencies]+mcp = [+ { name = "cubeloop", extra = ["mcp"] },+]+mysql = [+ { name = "cubeloop", extra = ["mysql"] },+]+postgres = [+ { name = "cubeloop", extra = ["postgres"] },+]+sqlite = [+ { name = "cubeloop", extra = ["sqlite"] },+]+trace-cli = [+ { name = "cubeloop", extra = ["trace-cli"] },+]+tracing = [+ { name = "cubeloop", extra = ["tracing"] },+]+tracing-otlp = [+ { name = "cubeloop", extra = ["tracing-otlp"] },+]++[package.metadata]+requires-dist = [+ { name = "cubeloop", editable = "." },+ { name = "cubeloop", extras = ["mcp"], marker = "extra == 'mcp'", editable = "." },+ { name = "cubeloop", extras = ["mysql"], marker = "extra == 'mysql'", editable = "." },+ { name = "cubeloop", extras = ["postgres"], marker = "extra == 'postgres'", editable = "." },+ { name = "cubeloop", extras = ["sqlite"], marker = "extra == 'sqlite'", editable = "." },+ { name = "cubeloop", extras = ["trace-cli"], marker = "extra == 'trace-cli'", editable = "." },+ { name = "cubeloop", extras = ["tracing"], marker = "extra == 'tracing'", editable = "." },+ { name = "cubeloop", extras = ["tracing-otlp"], marker = "extra == 'tracing-otlp'", editable = "." },+]+provides-extras = ["sqlite", "postgres", "mysql", "mcp", "tracing", "tracing-otlp", "trace-cli"]+[[package]]name = "distro"version = "1.9.0"diff --git a/website/docs/api/index.mdx b/website/docs/api/index.mdxindex 0765f52..7c47003 100644--- a/website/docs/api/index.mdx+++ b/website/docs/api/index.mdx@@ -1,18 +1,18 @@---title: API Reference-description: "Reference documentation for the CubePi Python API."+description: "Reference documentation for the CubeLoop Python API."---# API Reference-Auto-generated from CubePi's public modules.+Auto-generated from CubeLoop's public modules.-- `cubepi.agent`-- `cubepi.providers`-- `cubepi.checkpointer`-- `cubepi.middleware`-- `cubepi.mcp`-- `cubepi.tracing`-- `cubepi.utils`+- `cubeloop.agent`+- `cubeloop.providers`+- `cubeloop.checkpointer`+- `cubeloop.middleware`+- `cubeloop.mcp`+- `cubeloop.tracing`+- `cubeloop.utils`The module pages above are generated at build time from docstrings and are not editable by hand.diff --git a/website/docs/getting-started/core-concepts.md b/website/docs/getting-started/core-concepts.mdindex a98ffca..0c21f26 100644--- a/website/docs/getting-started/core-concepts.md+++ b/website/docs/getting-started/core-concepts.md@@ -1,11 +1,11 @@---title: Core Concepts-description: "Learn the six core concepts of CubePi: Agent, Tool, Provider, Stream & Events, Middleware, and Checkpointer."+description: "Learn the six core concepts of CubeLoop: Agent, Tool, Provider, Stream & Events, Middleware, and Checkpointer."---# Core Concepts-Six concepts cover everything CubePi does. Read this page once, then+Six concepts cover everything CubeLoop does. Read this page once, thenthe rest of the docs become a lookup table.## Agent@@ -35,10 +35,10 @@ sync or async.## ToolA tool is an async function the model can call. Decorate it with-`@tool` and CubePi generates the input schema from the parameters:+`@tool` and CubeLoop generates the input schema from the parameters:```python-from cubepi import tool+from cubeloop import tool@toolasync def search(query: str, limit: int = 10) -> str:@@ -159,7 +159,7 @@ backends implement them. See [HITL guide](../guides/hitl/overview).## HITL (Human-in-the-Loop)-CubePi ships a built-in `cubepi.hitl` module for scenarios where the+CubeLoop ships a built-in `cubeloop.hitl` module for scenarios where theagent needs to **pause and wait for a human**:- **Sandbox confirmation** — a dangerous tool (bash, file write) needs@@ -168,7 +168,7 @@ agent needs to **pause and wait for a human**:and waits for the answer.```python-from cubepi.hitl import InMemoryChannel, ConfirmToolCallMiddleware, ask_user_tool+from cubeloop.hitl import InMemoryChannel, ConfirmToolCallMiddleware, ask_user_toolchannel = InMemoryChannel()@@ -206,21 +206,21 @@ can ingest agent runs without custom instrumentation. Install theextra:```bash-pip install "cubepi[tracing]" # OTel SDK-pip install "cubepi[tracing-otlp]" # + OTLP/HTTP exporter+pip install "cubeloop[tracing]" # OTel SDK+pip install "cubeloop[tracing-otlp]" # + OTLP/HTTP exporter```then wrap your agent in an `async with`:```python-from cubepi.tracing import Tracer-from cubepi.tracing.exporters import JsonlSpanExporter+from cubeloop.tracing import Tracer+from cubeloop.tracing.exporters import JsonlSpanExporterasync with (Tracer(service_name="my-bot",agent_name="assistant",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],) as tracer,tracer.attached(agent),):@@ -228,7 +228,7 @@ async with (```Each run emits an `invoke_agent` root span containing one-`cubepi.turn` per LLM round-trip, plus `chat` (CLIENT) and+`cubeloop.turn` per LLM round-trip, plus `chat` (CLIENT) and`execute_tool` children. By default **no prompt content or modeloutput is recorded** — opt in with `Tracer(record_content=True)` anda `redact` callback for PII. Pair with `Meter(...)` for token /diff --git a/website/docs/getting-started/installation.md b/website/docs/getting-started/installation.mdindex d7ee8dc..72095d3 100644--- a/website/docs/getting-started/installation.md+++ b/website/docs/getting-started/installation.md@@ -1,11 +1,11 @@---title: Installation-description: "Install CubePi via pip. Python 3.11+ required. Supports Linux, macOS, and Windows."+description: "Install CubeLoop via pip. Python 3.11+ required. Supports Linux, macOS, and Windows."---# Installation-CubePi runs on **Python 3.11+**. The core has three runtime+CubeLoop runs on **Python 3.11+**. The core has three runtimedependencies: `pydantic`, `anthropic`, `openai`. Optional features(SQLite, Postgres, MCP, OpenTelemetry tracing) are gated behind extrasso you only install what you use.@@ -13,18 +13,18 @@ so you only install what you use.## With pip```bash-pip install cubepi+pip install cubeloop```Optional extras:```bash-pip install "cubepi[sqlite]" # adds aiosqlite for SQLiteCheckpointer-pip install "cubepi[postgres]" # adds asyncpg + sqlalchemy + msgpack-pip install "cubepi[mcp]" # adds the MCP SDK for tool loaders-pip install "cubepi[tracing]" # adds opentelemetry-sdk for Tracer / Meter-pip install "cubepi[tracing-otlp]" # adds the OTLP/HTTP span exporter-pip install "cubepi[sqlite,mcp,tracing]" # combine+pip install "cubeloop[sqlite]" # adds aiosqlite for SQLiteCheckpointer+pip install "cubeloop[postgres]" # adds asyncpg + sqlalchemy + msgpack+pip install "cubeloop[mcp]" # adds the MCP SDK for tool loaders+pip install "cubeloop[tracing]" # adds opentelemetry-sdk for Tracer / Meter+pip install "cubeloop[tracing-otlp]" # adds the OTLP/HTTP span exporter+pip install "cubeloop[sqlite,mcp,tracing]" # combine```## With uv@@ -33,8 +33,8 @@ pip install "cubepi[sqlite,mcp,tracing]" # combinepip and is the recommended workflow:```bash-uv add cubepi-uv add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+uv add cubeloop+uv add "cubeloop[sqlite,postgres,mcp,tracing,tracing-otlp]"```In an existing uv project, `uv sync` re-locks the environment after@@ -43,15 +43,15 @@ edits to `pyproject.toml`.## With Poetry```bash-poetry add cubepi-poetry add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+poetry add cubeloop+poetry add "cubeloop[sqlite,postgres,mcp,tracing,tracing-otlp]"```## Verifying the install```bash-python -c "import cubepi; print(cubepi.__doc__)"-# cubepi — Pythonic async-native agent framework.+python -c "import cubeloop; print(cubeloop.__doc__)"+# cubeloop — Pythonic async-native agent framework.```If you see an `ImportError`, your interpreter is likely \< 3.11 — check@@ -59,13 +59,13 @@ If you see an `ImportError`, your interpreter is likely \< 3.11 — check## Configuring provider credentials-CubePi providers read credentials from constructor arguments. Most+CubeLoop providers read credentials from constructor arguments. Mostdeployments pull them from environment variables:```pythonimport os-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.openai import OpenAIProvideranthropic = AnthropicProvider(provider_id="anthropic", api_key=os.environ["ANTHROPIC_API_KEY"])openai = OpenAIProvider(provider_id="openai", api_key=os.environ["OPENAI_API_KEY"])diff --git a/website/docs/getting-started/quick-start.md b/website/docs/getting-started/quick-start.mdindex b3a86f9..18cec6f 100644--- a/website/docs/getting-started/quick-start.md+++ b/website/docs/getting-started/quick-start.md@@ -1,6 +1,6 @@---title: Quick Start-description: "Build your first CubePi agent in minutes with this step-by-step quick-start guide."+description: "Build your first CubeLoop agent in minutes with this step-by-step quick-start guide."---# Quick Start@@ -12,7 +12,7 @@ response token-by-token, and exits cleanly.## Prerequisites- Python 3.11+-- `cubepi` installed (`pip install cubepi`)+- `cubeloop` installed (`pip install cubeloop`)- An `ANTHROPIC_API_KEY` in your environment## The full script@@ -23,8 +23,8 @@ Save this as `weather_agent.py`:import asyncioimport os-from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -69,11 +69,11 @@ tool result threaded through.## What just happened-CubePi ran a loop that looks (conceptually) like this:+CubeLoop ran a loop that looks (conceptually) like this:1. `agent.prompt("What's the weather in Tokyo?")` enqueued a`UserMessage` and called the model.-2. The model decided to invoke `get_weather(city="Tokyo")` — CubePi+2. The model decided to invoke `get_weather(city="Tokyo")` — CubeLoopparsed the JSON args against the schema `@tool` generated from yourfunction signature, called your `async def`, and fed the result backas a `ToolResultMessage`.diff --git a/website/docs/guides/agents/first-agent.md b/website/docs/guides/agents/first-agent.mdindex 30c0ced..6e4553c 100644--- a/website/docs/guides/agents/first-agent.md+++ b/website/docs/guides/agents/first-agent.md@@ -1,6 +1,6 @@---title: Building Your First Agent-description: "Create and run your first CubePi agent — choose a provider, define a system prompt, and send a message."+description: "Create and run your first CubeLoop agent — choose a provider, define a system prompt, and send a message."---# Building Your First Agent@@ -17,7 +17,7 @@ expects.```pythonimport os-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(provider_id="anthropic", api_key=os.environ["ANTHROPIC_API_KEY"])model = provider.model(@@ -39,7 +39,7 @@ in 0.7.A tool is an async function decorated with `@tool`:```python-from cubepi import tool+from cubeloop import tool@tool@@ -58,7 +58,7 @@ A few details:or a full `AgentToolResult` when you need `details`/`is_error`.- Need cancellation or progress streaming? Declare `signal` (an`asyncio.Event` set when the user cancels) and/or `on_update(partial)`- in the signature and CubePi injects them — see+ in the signature and CubeLoop injects them — see[Tool Use](./tool-use#streaming-tool-progress).- For a shared params model or dynamic construction, the longhand`AgentTool(...)` is equivalent — see [Tool Use](./tool-use).@@ -66,7 +66,7 @@ A few details:## Step 3 — assemble the agent```python-from cubepi import Agent+from cubeloop import Agentagent = Agent(model=model,@@ -160,11 +160,11 @@ async def main():- **No `text_delta` events** — Did you subscribe *before* calling`prompt()`? Listeners only see events emitted after registration.- **Tool not found** — The model invoked a tool whose `name` doesn't- match any tool in `tools=[...]`. CubePi reports this as a tool result+ match any tool in `tools=[...]`. CubeLoop reports this as a tool resultwith `is_error=True` rather than crashing — check the`tool_execution_end` event's `result`.- **Pydantic ValidationError swallowed** — If the model produces- malformed JSON, CubePi captures the validation error and feeds it+ malformed JSON, CubeLoop captures the validation error and feeds itback as a tool error result. The model usually corrects itself onthe next turn.diff --git a/website/docs/guides/agents/forking.md b/website/docs/guides/agents/forking.mdindex 6498d85..612468b 100644--- a/website/docs/guides/agents/forking.md+++ b/website/docs/guides/agents/forking.md@@ -5,7 +5,7 @@ description: "Branch a conversation at a completed-run boundary — persistent f# Conversation Forking-A **fork** branches a conversation at a completed-run boundary. CubePi+A **fork** branches a conversation at a completed-run boundary. CubeLoopgives you two variants:- **`Agent.fork(...)`** — a *persistent* fork. Copies messages from the@@ -159,8 +159,8 @@ When you use `ask_user_tool` or `ApprovalPolicyMiddleware` with a```pythonimport uuid-from cubepi import Agent-from cubepi.hitl import CheckpointedChannel, ask_user_tool+from cubeloop import Agent+from cubeloop.hitl import CheckpointedChannel, ask_user_toolrun_id = uuid.uuid4().hexchannel = CheckpointedChannel(checkpointer=cp, thread_id="conv_123", run_id=run_id)@@ -204,7 +204,7 @@ upgrade path:## Legacy data behaviour-CubePi treats messages from before this feature (no `run_id`+CubeLoop treats messages from before this feature (no `run_id`column populated, i.e. `run_id IS NULL`) gracefully:- **Mixed threads** — a thread that already has legacy messages anddiff --git a/website/docs/guides/agents/multi-turn.md b/website/docs/guides/agents/multi-turn.mdindex fc21806..2a419d4 100644--- a/website/docs/guides/agents/multi-turn.md+++ b/website/docs/guides/agents/multi-turn.md@@ -1,11 +1,11 @@---title: Multi-turn Conversations-description: "Build multi-turn conversational agents with CubePi's stateful agent loop and message history."+description: "Build multi-turn conversational agents with CubeLoop's stateful agent loop and message history."---# Multi-turn Conversations-A "turn" in CubePi is one round of: user input → model response (and+A "turn" in CubeLoop is one round of: user input → model response (andmaybe tools) → optional more model responses to tool results. Theagent's `_messages` list grows across turns; this guide covers how todrive multi-turn flows correctly and how to inject input while the@@ -21,7 +21,7 @@ await agent.prompt("What's my name?")# → "Your name is Sam."```-History lives on `agent.state.messages`. CubePi appends each user+History lives on `agent.state.messages`. CubeLoop appends each usermessage, each assistant message, and each tool result. The providergets the full list every time, so context windows matter (see[Context Management](#context-management) below).@@ -92,7 +92,7 @@ Subsequent calls just append.## Context management-CubePi does **not** truncate or summarise context on your behalf. The+CubeLoop does **not** truncate or summarise context on your behalf. Thefull message list is sent to the model on every turn. Strategies:- **Manual truncation** — Implement a@@ -121,7 +121,7 @@ to call anywhere.## Restoring state from disk```python-from cubepi.checkpointer import SQLiteCheckpointer+from cubeloop.checkpointer import SQLiteCheckpointerasync with SQLiteCheckpointer("conv.db") as cp:agent = Agent(diff --git a/website/docs/guides/agents/prompt-caching.md b/website/docs/guides/agents/prompt-caching.mdindex 5c4e983..1d79433 100644--- a/website/docs/guides/agents/prompt-caching.md+++ b/website/docs/guides/agents/prompt-caching.md@@ -1,6 +1,6 @@---title: Prompt Caching-description: "How CubePi maximises prompt cache hit rates — append-only message storage, automatic cache breakpoints, and how to avoid breaking the cache."+description: "How CubeLoop maximises prompt cache hit rates — append-only message storage, automatic cache breakpoints, and how to avoid breaking the cache."---# Prompt Caching@@ -11,8 +11,8 @@ The savings are significant: Anthropic charges cached tokens at**10% of the normal input price**, and cache hits also reducetime-to-first-token.-CubePi is designed from the ground up to maximise cache hit rates.-This guide explains how caching works, why CubePi's architecture+CubeLoop is designed from the ground up to maximise cache hit rates.+This guide explains how caching works, why CubeLoop's architecturekeeps the cache warm, and what you can do (or avoid doing) topreserve those hits.@@ -52,7 +52,7 @@ ordering, whitespace, a timestamp field — the resulting byte sequencediffers from the previous request and **every cache breakpoint fromthat point on misses**.-CubePi's checkpointer is append-only: it only ever adds new messages+CubeLoop's checkpointer is append-only: it only ever adds new messagesto the end of the thread. The in-memory `agent.state.messages` listgrows by appending; it is never rebuilt or reshuffled. This means theprefix of every request is guaranteed to be byte-identical to the@@ -82,7 +82,7 @@ entry will be a hit on turn N+2.### Configuration```python-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop.providers.anthropic import AnthropicProvider# Default: short TTL (5 min), automatic breakpointsprovider = AnthropicProvider(api_key="…")@@ -113,13 +113,13 @@ Cache hit rate for a turn:`cache_read_tokens / (input_tokens + cache_read_tokens + cache_write_tokens)`.:::tip-`input_tokens` in CubePi's `Usage` is the **uncached** portion — tokens that+`input_tokens` in CubeLoop's `Usage` is the **uncached** portion — tokens thatwere actually processed by the model this turn. The full prompt token count is`input_tokens + cache_read_tokens + cache_write_tokens`. On a 100 % cache hit,`input_tokens` is 0.:::-You can also see these fields in the `cubepi trace` CLI output and in+You can also see these fields in the `cubeloop trace` CLI output and inthe OTel spans emitted by `Tracer`. Note that the OTel span attribute`gen_ai.usage.input_tokens` follows the GenAI Semantic Convention and reportsthe **inclusive** total (uncached + cached):@@ -134,14 +134,14 @@ gen_ai.usage.cache_read.input_tokens = 7 980 (cached subset)## OpenAI: automatic cachingOpenAI caches automatically for prompts longer than 1 024 tokens —-no explicit `cache_control` markers are needed. CubePi surfaces the+no explicit `cache_control` markers are needed. CubeLoop surfaces thehit data through the same `Usage` interface:```pythonusage.cache_read_tokens # maps to prompt_tokens_details.cached_tokens```-There is nothing to configure on the CubePi side. Keep the system+There is nothing to configure on the CubeLoop side. Keep the systemprompt and tool definitions stable across turns and OpenAI's cachewill warm up naturally.@@ -186,8 +186,8 @@ If the default three-breakpoint strategy does not fit your use case,implement `CacheMarkerPolicy` and pass it to the provider:```python-from cubepi.providers.anthropic import CacheMarkerPolicy, AnthropicProvider-from cubepi.providers.base import Message+from cubeloop.providers.anthropic import CacheMarkerPolicy, AnthropicProvider+from cubeloop.providers.base import Messageclass SystemOnlyPolicy:"""Cache only the system prompt — useful when tool lists change often."""diff --git a/website/docs/guides/agents/streaming.md b/website/docs/guides/agents/streaming.mdindex 288931d..d13433d 100644--- a/website/docs/guides/agents/streaming.md+++ b/website/docs/guides/agents/streaming.md@@ -1,11 +1,11 @@---title: Streaming Events-description: "Stream events and tokens from CubePi agents in real time using subscribers and MessageStream."+description: "Stream events and tokens from CubeLoop agents in real time using subscribers and MessageStream."---# Streaming Events-CubePi exposes two streams, layered:+CubeLoop exposes two streams, layered:1. **Provider stream** — `MessageStream` you get from`provider.stream(...)`. Yields `StreamEvent`s describing the raw@@ -102,7 +102,7 @@ def on_event(event, signal=None):print(event.stream_event.delta, end="", flush=True)```-The shape that CubePi guarantees is the one in the table above+The shape that CubeLoop guarantees is the one in the table above(`MessageUpdateEvent.stream_event.delta`). Always match the outerevent's `type == "message_update"` (or check `stream_event` exists)before reaching into `stream_event.type`.@@ -167,5 +167,5 @@ canonical way to get the final message.- [Tool Use](./tool-use) — the `tool_execution_*` triplet in detail.- [Multi-turn](./multi-turn) — event order around steering and resume.-- [API Reference → StreamEvent](../../api/cubepi-providers#streamevent)+- [API Reference → StreamEvent](../../api/cubeloop-providers#streamevent)for the field-level schema.diff --git a/website/docs/guides/agents/tool-use.md b/website/docs/guides/agents/tool-use.mdindex 201c1c7..6bc0cb9 100644--- a/website/docs/guides/agents/tool-use.md+++ b/website/docs/guides/agents/tool-use.md@@ -1,11 +1,11 @@---title: Tool Use & Parallel Execution-description: "Register tools, execute them in parallel or sequentially, and handle results with Pydantic validation in CubePi."+description: "Register tools, execute them in parallel or sequentially, and handle results with Pydantic validation in CubeLoop."---# Tool Use & Parallel Execution-Tools are how an agent acts on the world. CubePi turns each `AgentTool`+Tools are how an agent acts on the world. CubeLoop turns each `AgentTool`into a JSON Schema for the model, validates arguments with Pydantic,runs the work, and feeds the result back as a `ToolResultMessage`. Bydefault tools run in parallel when the model calls more than one in a@@ -13,14 +13,14 @@ single turn.## The `@tool` decorator-The quickest way to define a tool is to decorate an async function. CubePi+The quickest way to define a tool is to decorate an async function. CubeLoopgenerates the input schema from the parameters, so there's no separate modelor boilerplate `execute` signature to write:```pythonfrom typing import Annotatedfrom pydantic import Field-from cubepi import tool+from cubeloop import tool@tool@@ -45,7 +45,7 @@ The return value can be a plain `str` (wrapped as text, as above), a`details`, `is_error`, or `terminate`:```python-from cubepi import tool, AgentToolResult, TextContent+from cubeloop import tool, AgentToolResult, TextContent@tool@@ -78,7 +78,7 @@ tools dynamically or share one params model across several tools:```pythonfrom pydantic import BaseModel, Field-from cubepi import AgentTool, AgentToolResult, TextContent+from cubeloop import AgentTool, AgentToolResult, TextContentclass SearchParams(BaseModel):@@ -109,7 +109,7 @@ into the JSON Schema and helps the model understand each parameter.## Parallel by defaultWhen the model emits multiple tool calls in one assistant message,-CubePi schedules them on `asyncio.create_task()` and gathers them.+CubeLoop schedules them on `asyncio.create_task()` and gathers them.That's almost always what you want.```python@@ -213,7 +213,7 @@ underlying library.Two ways:-1. **Raise an exception.** CubePi catches it, turns it into an+1. **Raise an exception.** CubeLoop catches it, turns it into an`AgentToolResult` with `is_error=True` and the exception string as`TextContent`.2. **Return `is_error=True` explicitly.** Useful when you want a@@ -244,7 +244,7 @@ async def submit_final_answer(tool_call_id, params, *, signal=None, on_update=No)```-CubePi only terminates if *every* tool result in the current batch is+CubeLoop only terminates if *every* tool result in the current batch is`terminate=True`. The agent loop emits `turn_end`, then `agent_end`,and exits.@@ -268,9 +268,9 @@ tools into the model-visible tools array as native tools — remainsavailable via `deferred_tool_strategy="inject"`.)```python-from cubepi import Agent-from cubepi.deferred import DeferredToolGroup-from cubepi.mcp import load_mcp_tools_stdio+from cubeloop import Agent+from cubeloop.deferred import DeferredToolGroup+from cubeloop.mcp import load_mcp_tools_stdioasync def load_github_tools():result = await load_mcp_tools_stdio(@@ -318,7 +318,7 @@ and the advanced middleware constructor.there unless you have a downstream consumer.- **Pydantic strictness surprises** — `Field(..., min_length=1)` letsthe model see the constraint via JSON Schema; constraints help, but- remember the model still sometimes sends bad JSON. CubePi turns the+ remember the model still sometimes sends bad JSON. CubeLoop turns the`ValidationError` into a tool error result; you don't need to wrapvalidation yourself.- **`tools=[]` and the model still asks for a tool** — Usually meansdiff --git a/website/docs/guides/checkpointing/custom.md b/website/docs/guides/checkpointing/custom.mdindex b06cf86..c994e29 100644--- a/website/docs/guides/checkpointing/custom.md+++ b/website/docs/guides/checkpointing/custom.md@@ -1,6 +1,6 @@---title: Custom Backends-description: "Implement a custom checkpointer backend for CubePi using the Checkpointer protocol."+description: "Implement a custom checkpointer backend for CubeLoop using the Checkpointer protocol."---# Custom Checkpointing Backends@@ -35,8 +35,8 @@ on first call.import jsonfrom typing import Anyimport redis.asyncio as aredis-from cubepi.checkpointer.base import CheckpointData-from cubepi.providers.base import AssistantMessage, Message, ToolResultMessage, UserMessage+from cubeloop.checkpointer.base import CheckpointData+from cubeloop.providers.base import AssistantMessage, Message, ToolResultMessage, UserMessage_ROLE_TO_CLS: dict[str, type[Message]] = {@@ -47,7 +47,7 @@ _ROLE_TO_CLS: dict[str, type[Message]] = {class RedisCheckpointer:- def __init__(self, redis_url: str, prefix: str = "cubepi:") -> None:+ def __init__(self, redis_url: str, prefix: str = "cubeloop:") -> None:self._url = redis_urlself._prefix = prefixself._r: aredis.Redis | None = None@@ -115,7 +115,7 @@ async with RedisCheckpointer("redis://localhost:6379") as cp:2. **Order preserved.** `load` returns messages in the order they wereappended. Use a list, a sorted key, or a sequence column.3. **Idempotent re-`load`.** Calling `load` twice on the same thread- should yield identical results. (CubePi calls it once, but tools+ should yield identical results. (CubeLoop calls it once, but toolsoften need to too.)4. **`extra` is a merge.** `save_extra({"a": 1})` followed by`save_extra({"b": 2})` should leave `{"a": 1, "b": 2}` — not just@@ -154,8 +154,8 @@ agent = Agent(model=…, checkpointer=FileCheckpointer("/tmp/cp"), thread_id="x"Drop-in test pattern using `FauxProvider`:```python-from cubepi import Agent-from cubepi.providers import FauxProvider, faux_assistant_message+from cubeloop import Agent+from cubeloop.providers import FauxProvider, faux_assistant_messageasync def test_roundtrip():cp = MyCheckpointer(…)@@ -181,7 +181,7 @@ async def test_roundtrip():## Common pitfalls- **Mutating returned `CheckpointData`** — Either deep-copy on the way- in, or document that the agent owns the list. CubePi's built-ins+ in, or document that the agent owns the list. CubeLoop's built-inscopy.- **Losing `metadata`** — `model_dump(mode="json")` preserves`metadata`. If you serialise via `__dict__` you'll drop it.@@ -194,9 +194,9 @@ async def test_roundtrip():## See also-- [`Checkpointer` Protocol API](../../api/cubepi-checkpointer) — full+- [`Checkpointer` Protocol API](../../api/cubeloop-checkpointer) — fullsignature.-- [SQLiteCheckpointer source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/sqlite.py)+- [SQLiteCheckpointer source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/checkpointer/sqlite.py)— a complete reference implementation.-- [PostgresCheckpointer source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/postgres/checkpointer.py)+- [PostgresCheckpointer source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/checkpointer/postgres/checkpointer.py)— production-grade reference.diff --git a/website/docs/guides/checkpointing/mysql.md b/website/docs/guides/checkpointing/mysql.mdindex 4163731..e636840 100644--- a/website/docs/guides/checkpointing/mysql.md+++ b/website/docs/guides/checkpointing/mysql.md@@ -1,6 +1,6 @@---title: MySQL Checkpointing-description: "Use MySQLCheckpointer for persistent agent state in CubePi with the MySQL backend."+description: "Use MySQLCheckpointer for persistent agent state in CubeLoop with the MySQL backend."---# MySQL Checkpointing@@ -19,7 +19,7 @@ engine.Install the extra:```bash-pip install "cubepi[mysql]"+pip install "cubeloop[mysql]"```This pulls in `aiomysql`, `sqlalchemy`, and `msgpack`.@@ -28,9 +28,9 @@ This pulls in `aiomysql`, `sqlalchemy`, and `msgpack`.```pythonimport asyncio-from cubepi import Agent-from cubepi.checkpointer import MySQLCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import MySQLCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -61,57 +61,57 @@ async with MySQLCheckpointer(## Schema-The checkpointer expects `cubepi_threads`, `cubepi_messages`,-`cubepi_runs`, `cubepi_hitl_answers`, and `cubepi_schema_version`. Like-Postgres (and unlike SQLite), CubePi **does not create these for you** —+The checkpointer expects `cubeloop_threads`, `cubeloop_messages`,+`cubeloop_runs`, `cubeloop_hitl_answers`, and `cubeloop_schema_version`. Like+Postgres (and unlike SQLite), CubeLoop **does not create these for you** —it verifies on `__aenter__` that they exist with the expected`schema_version`.-If they're missing, you get `CubepiSchemaUninitialized`. If the version-doesn't match this CubePi release, you get `CubepiSchemaMismatch`. A+If they're missing, you get `CubeloopSchemaUninitialized`. If the version+doesn't match this CubeLoop release, you get `CubeloopSchemaMismatch`. Aproduction database belongs to the host application's migration system(Alembic, …), not to a third-party library.### Bootstrapping via Alembic-CubePi exposes the SQLAlchemy `MetaData` so your migrations can adopt+CubeLoop exposes the SQLAlchemy `MetaData` so your migrations can adoptthe schema:```python# alembic/env.py-from cubepi.checkpointer.mysql import cubepi_metadata, EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.mysql import cubeloop_metadata, EXPECTED_SCHEMA_VERSION-target_metadata = [my_app_metadata, cubepi_metadata]+target_metadata = [my_app_metadata, cubeloop_metadata]```Then autogenerate a revision:```bash-alembic revision --autogenerate -m "add cubepi checkpointer"+alembic revision --autogenerate -m "add cubeloop checkpointer"```-The `cubepi_messages` table is `KEY`-partitioned, which SQLAlchemy's+The `cubeloop_messages` table is `KEY`-partitioned, which SQLAlchemy'sautogenerate cannot express, so append the partition clause and theschema-version write with the provided helpers:```python# In a migration's upgrade():-from cubepi.checkpointer.mysql.alembic_helpers import (+from cubeloop.checkpointer.mysql.alembic_helpers import (messages_partition_clause,write_schema_version_op,)def upgrade():- op.create_table("cubepi_threads", ...)+ op.create_table("cubeloop_threads", ...)op.create_table(- "cubepi_messages", ...,+ "cubeloop_messages", ...,mysql_engine="InnoDB",)# KEY(thread_id) partitioning is not autogenerated — apply it explicitly:op.execute(- "ALTER TABLE cubepi_messages " + messages_partition_clause()+ "ALTER TABLE cubeloop_messages " + messages_partition_clause())- op.create_table("cubepi_schema_version", ...)+ op.create_table("cubeloop_schema_version", ...)# write_schema_version_op() returns two ';'-separated statements# (DELETE then INSERT). MySQL/pymysql runs one statement per execute,# so split and execute each:@@ -121,38 +121,38 @@ def upgrade():````write_schema_version_op()` is idempotent: it deletes any rows from a-prior CubePi version and inserts the current one. When CubePi later+prior CubeLoop version and inserts the current one. When CubeLoop laterbumps `EXPECTED_SCHEMA_VERSION`, generate a new revision and run itagain.## Data model```-cubepi_threads+cubeloop_threadsthread_id (PK) -- VARCHAR(255) utf8mb4_bin (case-sensitive)parent_thread_id -- self-FK, for forksforked_at_seq -- seq number at fork pointextra -- JSONcreated_at / updated_at-cubepi_messages+cubeloop_messagesthread_id, seq -- composite PK; partitioned by KEY(thread_id) into 64role -- "user" | "assistant" | "tool"metadata -- JSON (not indexed; see below)payload -- LONGBLOB (msgpack)created_at-cubepi_runs+cubeloop_runsthread_id, run_id -- composite PKclaimed_at / completed_atcompletion_seq-cubepi_hitl_answers+cubeloop_hitl_answersthread_id, run_id, question_id -- composite PKanswer -- JSONanswered_at-cubepi_schema_version+cubeloop_schema_versionversion (PK)```@@ -163,7 +163,7 @@ Important properties:thread row. Two concurrent writers on the same thread serializecleanly.- **`payload` is msgpack-encoded `model.model_dump(mode="json")`.**- CubePi reconstructs the Pydantic model on read.+ CubeLoop reconstructs the Pydantic model on read.- **`metadata` is JSON, queryable** via MySQL JSON functions. It is**not** indexed — MySQL can't index a JSON column directly. If youneed to query messages by metadata, add a generated-column index@@ -199,8 +199,8 @@ from `dict.update`.)`MySQLCheckpointer` implements the v4 `snapshot` / `fork` /`claim_run` / `mark_run_complete` / `load_pending` Protocol methods,so it supports both `Agent.fork(...)` and `Agent.fork_once(...)`. The-`parent_thread_id` / `forked_at_seq` columns on `cubepi_threads`-record fork lineage; `cubepi_runs` (added in v4) tracks per-run+`parent_thread_id` / `forked_at_seq` columns on `cubeloop_threads`+record fork lineage; `cubeloop_runs` (added in v4) tracks per-runclaim/completion state.See the [Conversation Forking](../agents/forking) guide for the user-facing@@ -216,7 +216,7 @@ call, so split before executing:```python# In a migration's upgrade():-from cubepi.checkpointer.mysql.alembic_helpers import (+from cubeloop.checkpointer.mysql.alembic_helpers import (upgrade_v3_to_v4_op,write_schema_version_op,)@@ -244,7 +244,7 @@ cycle completes.```python# In a migration's upgrade():-from cubepi.checkpointer.mysql.alembic_helpers import (+from cubeloop.checkpointer.mysql.alembic_helpers import (upgrade_v4_to_v5_op,write_schema_version_op,)@@ -258,13 +258,37 @@ def upgrade():op.execute(stmt)```+## Schema v5 → v6 migration++0.14 renames the MySQL tables from `cubepi_*` to `cubeloop_*`.+`EXPECTED_SCHEMA_VERSION` is 6. Apply this **before** opening a 0.14+checkpointer on an existing database:++```python+from cubeloop.checkpointer.mysql.alembic_helpers import (+ upgrade_v5_to_v6_op,+ write_schema_version_op,+)++def upgrade():+ for stmt in upgrade_v5_to_v6_op().split(";"):+ if stmt.strip():+ op.execute(stmt)+ for stmt in write_schema_version_op().split(";"):+ if stmt.strip():+ op.execute(stmt)+```++Do not run the v6 `CREATE TABLE` helpers against a v5 database. See the+[migration guide](../../migration/from-cubepi).+## Common pitfalls-- **`CubepiSchemaUninitialized`** — Your DB is empty, your migrations- didn't run, or the `cubepi_schema_version` table is malformed. Apply+- **`CubeloopSchemaUninitialized`** — Your DB is empty, your migrations+ didn't run, or the `cubeloop_schema_version` table is malformed. Applythe host alembic upgrade first.-- **`CubepiSchemaMismatch`** — You upgraded CubePi but didn't generate a- new migration. Generate one, apply it, and CubePi will start.+- **`CubeloopSchemaMismatch`** — You upgraded CubeLoop but didn't generate a+ new migration. Generate one, apply it, and CubeLoop will start.- **JSON default errors on older MySQL** — JSON columns use`DEFAULT (JSON_OBJECT())`, which requires MySQL 8.0.13+.- **Case-insensitive thread-ID collisions** — Thread IDs use the@@ -272,14 +296,14 @@ def upgrade():hand-roll the DDL, keep that collation.- **`CheckpointCorruptionError` on `load()`** — A persisted message rowfailed to deserialize (bad msgpack payload, schema-invalid data, or an- unknown role). The error's `row_ref` (e.g. `cubepi_messages.seq=42`)+ unknown role). The error's `row_ref` (e.g. `cubeloop_messages.seq=42`)locates the bad row for inspection or surgical repair; `thread_id` and- `__cause__` carry the rest. CubePi never skips corrupt rows silently.+ `__cause__` carry the rest. CubeLoop never skips corrupt rows silently.## See also- [Postgres Checkpointing](./postgres) — the Postgres-backed sibling.- [SQLite Checkpointing](./sqlite) — single-process alternative.- [Custom Backends](./custom) — Protocol details.-- [Package README](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/mysql/README.md)+- [Package README](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/checkpointer/mysql/README.md)— the full host-integration runbook next to the code.diff --git a/website/docs/guides/checkpointing/postgres.md b/website/docs/guides/checkpointing/postgres.mdindex e091003..9cfc204 100644--- a/website/docs/guides/checkpointing/postgres.md+++ b/website/docs/guides/checkpointing/postgres.md@@ -13,7 +13,7 @@ the same `thread_id` without trampling each other.Install the extra:```bash-pip install "cubepi[postgres]"+pip install "cubeloop[postgres]"```This pulls in `asyncpg`, `sqlalchemy`, and `msgpack`.@@ -22,9 +22,9 @@ This pulls in `asyncpg`, `sqlalchemy`, and `msgpack`.```pythonimport asyncio-from cubepi import Agent-from cubepi.checkpointer import PostgresCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import PostgresCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -54,15 +54,15 @@ async with PostgresCheckpointer(## Schema-The checkpointer expects `cubepi_threads`, `cubepi_messages`,-`cubepi_runs`, `cubepi_hitl_answers`, and `cubepi_schema_version`.-Unlike SQLite, CubePi+The checkpointer expects `cubeloop_threads`, `cubeloop_messages`,+`cubeloop_runs`, `cubeloop_hitl_answers`, and `cubeloop_schema_version`.+Unlike SQLite, CubeLoop**does not create these for you** — it verifies on `__aenter__` thatthey exist with the expected `schema_version`.-If they're missing, you get `CubepiSchemaUninitialized`. If the-version doesn't match this CubePi release, you get-`CubepiSchemaMismatch`.+If they're missing, you get `CubeloopSchemaUninitialized`. If the+version doesn't match this CubeLoop release, you get+`CubeloopSchemaMismatch`.The reason: a production database belongs to the host application'smigration system (Alembic, Atlas, …), not to a third-party library@@ -70,78 +70,81 @@ that might fight your existing migrations.### Bootstrapping via Alembic-CubePi exposes the SQLAlchemy `MetaData` so your migrations can adopt+CubeLoop exposes the SQLAlchemy `MetaData` so your migrations can adoptthe schema:```python# alembic/env.py-from cubepi.checkpointer.postgres import cubepi_metadata, EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.postgres import cubeloop_metadata, EXPECTED_SCHEMA_VERSION-target_metadata = [my_app_metadata, cubepi_metadata]+target_metadata = [my_app_metadata, cubeloop_metadata]```Then autogenerate a revision:```bash-alembic revision --autogenerate -m "add cubepi checkpointer"+alembic revision --autogenerate -m "add cubeloop checkpointer"```-Autogenerate emits the `CREATE TABLE`s from `cubepi_metadata`, but-SQLAlchemy `MetaData` **cannot model two things CubePi needs**, so add+Autogenerate emits the `CREATE TABLE`s from `cubeloop_metadata`, but+SQLAlchemy `MetaData` **cannot model two things CubeLoop needs**, so addthem to the generated migration by hand: the 64 hash partitions of-`cubepi_messages` (via `create_message_partitions_op()`) and the-`cubepi_schema_version` row (via `write_schema_version_op()`). Use the-helpers:+`cubeloop_messages` (via `create_message_partitions_op()`), the 64+partitions of `cubeloop_runs` (via `create_runs_partitions_op()`), and+the `cubeloop_schema_version` row (via `write_schema_version_op()`). Use+the helpers:```python# In a migration's upgrade():-from cubepi.checkpointer.postgres.alembic_helpers import (+from cubeloop.checkpointer.postgres.alembic_helpers import (create_message_partitions_op,+ create_runs_partitions_op,write_schema_version_op,)def upgrade():- op.create_table(...) # auto-generated from cubepi_metadata- op.execute(create_message_partitions_op()) # creates the 64 hash partitions+ op.create_table(...) # auto-generated from cubeloop_metadata+ op.execute(create_message_partitions_op()) # 64 hash partitions of cubeloop_messages+ op.execute(create_runs_partitions_op()) # 64 hash partitions of cubeloop_runsop.execute(write_schema_version_op()) # records EXPECTED_SCHEMA_VERSION```Both helpers return a SQL string — you pass them to `op.execute(...)`.`write_schema_version_op()` is idempotent: it deletes any rows from a-prior CubePi version and inserts the current one.+prior CubeLoop version and inserts the current one.-When CubePi later upgrades and bumps `EXPECTED_SCHEMA_VERSION`, you+When CubeLoop later upgrades and bumps `EXPECTED_SCHEMA_VERSION`, yougenerate a new revision and call `op.execute(write_schema_version_op())`again.## Data model```-cubepi_threads+cubeloop_threadsthread_id (PK)parent_thread_id -- for forksforked_at_seq -- seq number at fork pointextra -- JSONBcreated_at / updated_at-cubepi_messages+cubeloop_messagesthread_id, seq -- composite PK; partitioned by HASH(thread_id) into 64role -- "user" | "assistant" | "tool"metadata -- JSONB (indexed via GIN)payload -- bytea (msgpack)created_at-cubepi_runs+cubeloop_runsthread_id, run_id -- composite PKclaimed_at / completed_atcompletion_seq-cubepi_hitl_answers+cubeloop_hitl_answersthread_id, run_id, question_id -- composite PKanswer -- JSONBanswered_at-cubepi_schema_version+cubeloop_schema_versionversion (PK)```@@ -151,7 +154,7 @@ Important properties:per thread, allocated under a `pg_advisory_xact_lock(hashtext(thread_id))`.Two concurrent writers on the same thread serialize cleanly.- **`payload` is msgpack-encoded `model.model_dump(mode="json")`.**- CubePi reconstructs the Pydantic model on read.+ CubeLoop reconstructs the Pydantic model on read.- **`metadata` is JSONB, queryable.** The full message also has`metadata` inside the payload, but the column is the canonical viewfor SQL queries.@@ -179,7 +182,7 @@ The pool default of `min=1, max=10` is fine for most apps; bump`save_extra` does a JSONB merge, not a replace:```sql-extra = cubepi_threads.extra || EXCLUDED.extra+extra = cubeloop_threads.extra || EXCLUDED.extra```So writing `{"foo": 1}` then `{"bar": 2}` leaves `{"foo": 1, "bar":@@ -191,8 +194,8 @@ keys.`PostgresCheckpointer` implements the v4 `snapshot` / `fork` /`claim_run` / `mark_run_complete` / `load_pending` Protocol methods,so it supports both `Agent.fork(...)` and `Agent.fork_once(...)`. The-`parent_thread_id` and `forked_at_seq` columns on `cubepi_threads`-record fork lineage; `cubepi_runs` (the v4 partitioned table) tracks+`parent_thread_id` and `forked_at_seq` columns on `cubeloop_threads`+record fork lineage; `cubeloop_runs` (the v4 partitioned table) tracksper-run claim/completion state.See the [Conversation Forking](../agents/forking) guide for the user-facing@@ -207,7 +210,7 @@ partitions. Use the provided alembic helper:```python# In a migration's upgrade():-from cubepi.checkpointer.postgres.alembic_helpers import (+from cubeloop.checkpointer.postgres.alembic_helpers import (upgrade_v3_to_v4_op,write_schema_version_op,)@@ -233,7 +236,7 @@ cycle completes.```python# In a migration's upgrade():-from cubepi.checkpointer.postgres.alembic_helpers import (+from cubeloop.checkpointer.postgres.alembic_helpers import (upgrade_v4_to_v5_op,write_schema_version_op,)@@ -243,20 +246,41 @@ def upgrade():op.execute(write_schema_version_op()) # bumps cubepi_schema_version to 5```+## Schema v5 → v6 migration++0.14 renames the Postgres tables from `cubepi_*` to `cubeloop_*`.+`EXPECTED_SCHEMA_VERSION` is 6. Apply this **before** opening a 0.14+checkpointer on an existing database:++```python+from cubeloop.checkpointer.postgres.alembic_helpers import (+ upgrade_v5_to_v6_op,+ write_schema_version_op,+)++def upgrade():+ op.execute(upgrade_v5_to_v6_op())+ op.execute(write_schema_version_op()) # writes 6 into cubeloop_schema_version+```++Do not run the v6 `CREATE TABLE` helpers against a v5 database — they+would try to create tables that already exist under the old names.+See the [migration guide](../../migration/from-cubepi).+## Common pitfalls-- **`CubepiSchemaUninitialized`** — Your DB is empty or your+- **`CubeloopSchemaUninitialized`** — Your DB is empty or yourmigrations didn't run. Apply the host alembic upgrade first.-- **`CubepiSchemaMismatch`** — You upgraded CubePi but didn't generate- a new migration. Generate one, apply it, and CubePi will start.+- **`CubeloopSchemaMismatch`** — You upgraded CubeLoop but didn't generate+ a new migration. Generate one, apply it, and CubeLoop will start.:::info Schema v2 (HITL)- CubePi ≥ the HITL feature bumps `EXPECTED_SCHEMA_VERSION` from 1 to 2+ CubeLoop ≥ the HITL feature bumps `EXPECTED_SCHEMA_VERSION` from 1 to 2and adds a `pending_request JSONB NULL` column to `cubepi_threads`.Your host alembic upgrade must call`add_pending_request_column_op()` (from- `cubepi.checkpointer.postgres.alembic_helpers`) before bumping the+ `cubeloop.checkpointer.postgres.alembic_helpers`) before bumping theschema_version row. See the [HITL guide](../hitl/overview) for the fullcross-process flow.:::@@ -265,15 +289,15 @@ def upgrade():- **`asyncpg.exceptions.UndefinedTableError` outside `__aenter__`** —Means you're using the checkpointer outside of `async with`. Thepool isn't connected yet. Wrap in the context manager.-- **Mixing host SQLAlchemy `MetaData`** — CubePi ships its own+- **Mixing host SQLAlchemy `MetaData`** — CubeLoop ships its own`MetaData` instance precisely so it can coexist with your app'smodels without colliding. Don't merge them into your global metadata— pass both to Alembic separately.- **`CheckpointCorruptionError` on `load()`** — A persisted message rowfailed to deserialize (bad msgpack payload, schema-invalid data, or an- unknown role). The error's `row_ref` (e.g. `cubepi_messages.seq=42`)+ unknown role). The error's `row_ref` (e.g. `cubeloop_messages.seq=42`)locates the bad row for inspection or surgical repair; `thread_id` and- `__cause__` carry the rest. CubePi never skips corrupt rows silently —+ `__cause__` carry the rest. CubeLoop never skips corrupt rows silently —dropping a message that carries `tool_calls` would leave thetranscript in a state every provider rejects.@@ -283,5 +307,5 @@ def upgrade():- [Custom Backends](./custom) — Protocol details.- [Recipes → Postgres + FastAPI Service](../../recipes/postgres-fastapi)— a deployable HTTP-fronted agent.-- [Package README](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/postgres/README.md)+- [Package README](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/checkpointer/postgres/README.md)— the full host-integration runbook next to the code.diff --git a/website/docs/guides/checkpointing/sqlite.md b/website/docs/guides/checkpointing/sqlite.mdindex 99fa18c..2903734 100644--- a/website/docs/guides/checkpointing/sqlite.md+++ b/website/docs/guides/checkpointing/sqlite.md@@ -1,6 +1,6 @@---title: SQLite Checkpointing-description: "Use SQLiteCheckpointer for lightweight single-process agent state persistence in CubePi."+description: "Use SQLiteCheckpointer for lightweight single-process agent state persistence in CubeLoop."---# SQLite Checkpointing@@ -13,7 +13,7 @@ environment where one Python process owns the conversation.Install the extra:```bash-pip install "cubepi[sqlite]"+pip install "cubeloop[sqlite]"```This pulls in `aiosqlite`.@@ -22,9 +22,9 @@ This pulls in `aiosqlite`.```pythonimport asyncio-from cubepi import Agent-from cubepi.checkpointer import SQLiteCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import SQLiteCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -80,7 +80,7 @@ CREATE TABLE thread_extra (`thread_extra`. Middleware that wants thread-scoped state shouldwrite into `context.extra`.-This schema is append-only. CubePi never updates or deletes rows.+This schema is append-only. CubeLoop never updates or deletes rows.## HITL tables@@ -113,9 +113,9 @@ execute the batch only after every gate is satisfied.No manual migration is needed — `CREATE TABLE IF NOT EXISTS` isidempotent.-## When CubePi reads+## When CubeLoop reads-On the **first** `prompt()` after instantiation, CubePi calls+On the **first** `prompt()` after instantiation, CubeLoop calls`load(thread_id)`. If the thread exists, history is restored into`agent.state.messages` and `extra` is restored into the agent'sprivate `_extra` dict.@@ -141,7 +141,7 @@ isolates them.## Concurrency modelThe checkpointer uses an `asyncio.Lock` around every read and write.-SQLite itself can be written from multiple processes, but CubePi's+SQLite itself can be written from multiple processes, but CubeLoop'sexpectation is that a single agent instance owns a thread. If youhave multiple processes writing the same `agent.db`:@@ -163,10 +163,10 @@ the [Conversation Forking](../agents/forking) guide for the user-facing API.## Schema v3 → v4 migration-Unlike Postgres and MySQL, SQLite's schema is managed by CubePi+Unlike Postgres and MySQL, SQLite's schema is managed by CubeLoopitself: the v3→v4 upgrade (adding `run_id` to `messages` and-creating a `cubepi_runs` table) runs automatically on `__aenter__`-the first time a v4 CubePi connects to a v3 file. No host action is+creating a `runs` table) runs automatically on `__aenter__`+the first time a v4 CubeLoop connects to a v3 file. No host action isrequired.Pre-feature messages keep `run_id = NULL` and remain readable; see@@ -205,7 +205,7 @@ sqlite3 agent.db "VACUUM"None`. Always wrap in `async with`.- **Two processes writing the same thread** — Interleaved history.Use Postgres or coordinate at the application layer.-- **WAL mode not enabled** — CubePi uses the default journal mode for+- **WAL mode not enabled** — CubeLoop uses the default journal mode forportability. For a single-writer, many-reader app, enable WAL oncevia `sqlite3 agent.db "PRAGMA journal_mode=WAL"` for better readconcurrency.@@ -216,7 +216,7 @@ sqlite3 agent.db "VACUUM"failed to deserialize (bad JSON, schema-invalid data, or an unknownrole). The error's `row_ref` (e.g. `messages.id=42`) locates the badrow so you can inspect or repair it with plain SQL; `thread_id` and- `__cause__` carry the rest of the context. CubePi never skips corrupt+ `__cause__` carry the rest of the context. CubeLoop never skips corruptrows silently — dropping a message that carries `tool_calls` wouldleave the transcript in a state every provider rejects.diff --git a/website/docs/guides/hitl/durable.md b/website/docs/guides/hitl/durable.mdindex eba9d37..b639726 100644--- a/website/docs/guides/hitl/durable.md+++ b/website/docs/guides/hitl/durable.md@@ -1,7 +1,7 @@---title: Cross-process & durabilitysidebar_position: 3-description: "Suspend a CubePi agent on a HITL request and resume it in another process with a CheckpointedChannel; durable-scope rules."+description: "Suspend a CubeLoop agent on a HITL request and resume it in another process with a CheckpointedChannel; durable-scope rules."---# Cross-process flow & durability@@ -12,9 +12,9 @@ Full lifecycle of a suspend/resume cycle:```pythonimport asyncio-from cubepi.agent.agent import Agent-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.hitl import (+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.hitl import (ApproveAnswer, CheckpointedChannel, ConfirmToolCallMiddleware,)@@ -113,7 +113,7 @@ well-defined safe suspension points:**Custom tools that mix HITL with other work inside `execute()` are NOTdurable cross-process by default.** If such a tool's process dies mid-execute,-anything that ran before the channel call would be lost. CubePi will raise+anything that ran before the channel call would be lost. CubeLoop will raise`HitlDurabilityNotGuaranteed` unless the `CheckpointedChannel` is constructedwith `allow_inside_custom_tool=True` — the caller must acknowledge theidempotency contract (the tool body must be a pure HITL wait with nodiff --git a/website/docs/guides/hitl/middlewares.md b/website/docs/guides/hitl/middlewares.mdindex 1184c41..8d9d5dc 100644--- a/website/docs/guides/hitl/middlewares.md+++ b/website/docs/guides/hitl/middlewares.md@@ -13,7 +13,7 @@ description: "Gate tool calls with ConfirmToolCallMiddleware / ApprovalPolicyMid"Always ask the human for tool *names* in this set."```python-from cubepi.hitl import ConfirmToolCallMiddleware+from cubeloop.hitl import ConfirmToolCallMiddleware# Set-based matching — only ask for these tool namesagent = Agent(@@ -46,7 +46,7 @@ For hosts with a **policy engine** that classifies tool calls into threetiers — auto-allow, hard-deny, or human-confirm.```python-from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny+from cubeloop.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Denydef my_policy(ctx):if ctx.tool_call.name == "read_file":@@ -79,7 +79,7 @@ The factory returns an `AgentTool` named `"ask_user"` with`execution_mode="sequential"` — it can't run in parallel with other tools.```python-from cubepi.hitl import ask_user_tool+from cubeloop.hitl import ask_user_toolagent = Agent(...,diff --git a/website/docs/guides/hitl/overview.md b/website/docs/guides/hitl/overview.mdindex 35d95c2..cbdb224 100644--- a/website/docs/guides/hitl/overview.md+++ b/website/docs/guides/hitl/overview.md@@ -1,12 +1,12 @@---title: Overviewsidebar_position: 1-description: "CubePi human-in-the-loop: the channel, the three verbs (confirm, approve, ask), and timeouts."+description: "CubeLoop human-in-the-loop: the channel, the three verbs (confirm, approve, ask), and timeouts."---# Human-in-the-Loop (HITL)-CubePi's HITL channel lets an agent **pause and ask a human** before proceeding.+CubeLoop's HITL channel lets an agent **pause and ask a human** before proceeding.It handles two recurring patterns with a single primitive:1. **Sandbox tool confirmation** — a dangerous tool (bash, file writes, API@@ -55,7 +55,7 @@ cover the full spectrum:└──────────────────────────────────────┘│┌─────────────▼──────────────┐- │ cubepi Agent loop │+ │ cubeloop Agent loop ││ (BeforeToolCallResult ││ carries hitl_trace) │└────────────────────────────┘@@ -69,7 +69,7 @@ For single-process use. Holds an `asyncio.Future` internally — the hostcalls `channel.answer()` from the same event loop.```python-from cubepi.hitl import InMemoryChannel+from cubeloop.hitl import InMemoryChannelchannel = InMemoryChannel(default_timeout=180.0, # per-call timeout; None = no timeout (default)@@ -84,8 +84,8 @@ is persisted via `Checkpointer.save_pending_request(thread_id, ...)`. Onsuspend), the pending stays so a later `Agent.respond()` can resume.```python-from cubepi.hitl import CheckpointedChannel-from cubepi.checkpointer.sqlite import SQLiteCheckpointer # or postgres / mysql+from cubeloop.hitl import CheckpointedChannel+from cubeloop.checkpointer.sqlite import SQLiteCheckpointer # or postgres / mysqlasync with SQLiteCheckpointer("path/to.db") as cp:channel = CheckpointedChannel(@@ -135,7 +135,7 @@ A structured form with one or more `Question` objects. Each question can be:- **"Other" with input** (option has `allow_input=True` — user types free text)```python-from cubepi.hitl.types import Question, Option+from cubeloop.hitl.types import Question, Optionanswers = await channel.ask([Question(key="framework", prompt="Which framework?", options=[diff --git a/website/docs/guides/hitl/reference.md b/website/docs/guides/hitl/reference.mdindex 12dbd50..a6060ba 100644--- a/website/docs/guides/hitl/reference.md+++ b/website/docs/guides/hitl/reference.md@@ -1,7 +1,7 @@---title: API, events & referencesidebar_position: 4-description: "CubePi HITL reference: Agent API, events, trace spans, error reference, testing helpers, and architecture notes."+description: "CubeLoop HITL reference: Agent API, events, trace spans, error reference, testing helpers, and architecture notes."---# API, events & reference@@ -62,7 +62,7 @@ suspended transition is committed.## Trace spans-When the `cubepi[tracing]` extra is installed, each HITL await is wrapped+When the `cubeloop[tracing]` extra is installed, each HITL await is wrappedin an OpenTelemetry span:| Span name | Attributes |@@ -92,14 +92,14 @@ channel silently falls back to a no-op span.`HitlControlException` (the parent of the four `BaseException` subclasses)is intentionally NOT caught by the existing broad `except Exception:` handlers-in `cubepi.agent.tools._prepare_tool_call` and `_execute_prepared` — this+in `cubeloop.agent.tools._prepare_tool_call` and `_execute_prepared` — thismirrors `asyncio.CancelledError`'s pattern.## Testing helpers```python-from cubepi.hitl.testing import ScriptedChannel, NoopChannel+from cubeloop.hitl.testing import ScriptedChannel, NoopChannel# ScriptedChannel: pre-programmed answers, consumed in order.ch = ScriptedChannel(answers=[@@ -123,7 +123,7 @@ assert await ch.ask([Question(key="k", prompt="p")]) == {"k": ""}raises `HitlConcurrencyError`.- **Parallel approval batches collect answers before execution.** If oneassistant turn contains multiple parallel tool calls that require approval,- CubePi still exposes one pending request at a time. Each approved answer is+ CubeLoop still exposes one pending request at a time. Each approved answer ispersisted by `question_id` and replayed on the next resume attempt. Toolbodies start only after every gate in the parallel batch has been answered.- **Prompt-cache prefix invariant.** Between pause and resume, the messages@@ -135,5 +135,5 @@ assert await ch.ask([Question(key="k", prompt="p")]) == {"k": ""}pass it directly.- **Resume re-enters the unresolved tool cycle.** The last assistant message'sunresolved tool calls dictate what prepares and executes next. Persisted HITL- answers can be replayed by `question_id`, but CubePi does not use node-based+ answers can be replayed by `question_id`, but CubeLoop does not use node-basedgraph replay semantics.diff --git a/website/docs/guides/mcp/auth.md b/website/docs/guides/mcp/auth.mdindex b67f8e5..c307458 100644--- a/website/docs/guides/mcp/auth.md+++ b/website/docs/guides/mcp/auth.md@@ -1,6 +1,6 @@---title: MCP Server Authentication-description: "Configure authentication — API keys, OAuth, and custom headers — for MCP servers in CubePi."+description: "Configure authentication — API keys, OAuth, and custom headers — for MCP servers in CubeLoop."---# MCP Server Authentication@@ -22,7 +22,7 @@ internal). Pass an `Authorization` header to `load_mcp_tools_http`:```pythonimport os-from cubepi.mcp import load_mcp_tools_http+from cubeloop.mcp import load_mcp_tools_httptools = await load_mcp_tools_http(server_url="https://mcp.example.com/sse",@@ -59,7 +59,7 @@ headers = {## HTTP: short-lived tokens / refresh-CubePi's loaders take a static `headers` dict at load time. For tokens+CubeLoop's loaders take a static `headers` dict at load time. For tokensthat expire (OAuth, JWT with short TTL), you have two options:### Option A — Re-load on expiry@@ -85,8 +85,8 @@ Build the `AgentTool` yourself with a closure that knows how torefresh:```python-from cubepi.mcp._adapter import make_mcp_agent_tool-from cubepi.mcp import load_mcp_tools_http+from cubeloop.mcp._adapter import make_mcp_agent_tool+from cubeloop.mcp import load_mcp_tools_httpasync def call_remote_with_refresh(tool_name, args):headers = {"Authorization": f"Bearer {await fetch_token()}"}@@ -118,7 +118,7 @@ Pass an `env` dict:```pythonimport os-from cubepi.mcp import load_mcp_tools_stdio+from cubeloop.mcp import load_mcp_tools_stdiotools = await load_mcp_tools_stdio(command="npx",diff --git a/website/docs/guides/mcp/loading.md b/website/docs/guides/mcp/loading.mdindex c2c1dca..027cd5c 100644--- a/website/docs/guides/mcp/loading.md+++ b/website/docs/guides/mcp/loading.md@@ -1,20 +1,20 @@---title: Loading MCP Tools-description: "Load tools from MCP servers into your CubePi agent, including SSE-based remote servers."+description: "Load tools from MCP servers into your CubeLoop agent, including SSE-based remote servers."---# Loading MCP ToolsThe [Model Context Protocol](https://modelcontextprotocol.io) definesa standard way for tool servers to expose capabilities to agents.-CubePi ships two loaders that connect to an MCP server, enumerate its+CubeLoop ships two loaders that connect to an MCP server, enumerate itstools, and turn each one into a regular `AgentTool` you can hand to`Agent(tools=…)`.Install the extra:```bash-pip install "cubepi[mcp]"+pip install "cubeloop[mcp]"```This pulls in the `mcp` SDK.@@ -27,9 +27,9 @@ Python module, an internal CLI):```pythonimport asyncioimport sys-from cubepi import Agent-from cubepi.mcp import load_mcp_tools_stdio-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.mcp import load_mcp_tools_stdio+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -70,7 +70,7 @@ Arguments:For hosted MCP servers (Sentry, GitHub, internal services):```python-from cubepi.mcp import load_mcp_tools_http+from cubeloop.mcp import load_mcp_tools_httptools = await load_mcp_tools_http(server_url="https://mcp.example.com/sse",@@ -123,14 +123,14 @@ call to the right implementation.If you wire up several MCP servers and only a few are needed perconversation, eagerly loading every schema into the system promptbecomes the dominant context cost. Wrap each server's tools in a-[`DeferredToolGroup`](../middleware/deferred-tools) — CubePi replaces+[`DeferredToolGroup`](../middleware/deferred-tools) — CubeLoop replacesthe full schemas with a compact catalog and lets the model expand agroup on demand via the built-in `load_tools` tool.:::## Per-call vs reusable connections-CubePi opens a new transport per `execute` call. That's:+CubeLoop opens a new transport per `execute` call. That's:- ✅ Simple — no pool lifecycle to manage.- ✅ Robust — a hung connection can't poison other tools.@@ -142,7 +142,7 @@ HTTP service instead and use `load_mcp_tools_http`.## Image and structured content-If an MCP tool returns image content blocks, CubePi maps them to+If an MCP tool returns image content blocks, CubeLoop maps them to`ImageContent` and includes them in the `AgentToolResult.content`.Anthropic provider relays these as image blocks in tool results;OpenAI providers currently strip them (the wire format doesn't@@ -173,7 +173,7 @@ downstream programmatic access, but not shown to the model.- [MCP Auth](./auth) — bearer tokens, headers, env-based credentials.- [Tool Use](../agents/tool-use) — how tools (MCP or otherwise) aredispatched.-- [`make_mcp_agent_tool` source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/mcp/_adapter.py)+- [`make_mcp_agent_tool` source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/mcp/_adapter.py)— the schema → Pydantic adapter, if you need to customise.- [Deferred Tool Groups](../middleware/deferred-tools) — hide MCPschemas from the system prompt and let the model expand them ondiff --git a/website/docs/guides/middleware/compaction.md b/website/docs/guides/middleware/compaction.mdindex b028ecf..8bcf146 100644--- a/website/docs/guides/middleware/compaction.md+++ b/website/docs/guides/middleware/compaction.md@@ -1,6 +1,6 @@---title: Compaction-description: "Use CompactionMiddleware to summarize older turns while preserving full CubePi history."+description: "Use CompactionMiddleware to summarize older turns while preserving full CubeLoop history."---# Compaction@@ -15,8 +15,8 @@ messages. `agent.state.messages` and checkpointer history stay complete.Use a cheaper model for the summary pass and your normal model for the agent:```python-from cubepi import Agent-from cubepi.middleware import CompactionMiddleware+from cubeloop import Agent+from cubeloop.middleware import CompactionMiddlewaremodel = main_provider.model("claude-sonnet-4-6")summary_model = cheap_provider.model("claude-haiku-4-5")@@ -48,7 +48,7 @@ The middleware writes two keys into `AgentContext.extra`:- `compaction` — the summary state and the message refs it covers.- `compaction_until_msg_index` — the history boundary summarized so far.-When a checkpointer is attached, CubePi saves `ctx.extra` at `agent_end`, so the+When a checkpointer is attached, CubeLoop saves `ctx.extra` at `agent_end`, so thenext process can resume with the existing summary. If the message refs no longermatch the current history, the middleware clears the stale state and starts overrather than sending an invalid summary.@@ -59,7 +59,7 @@ Compaction is evaluated **before every model call** — including the calls *insa single agent turn, between tool-call iterations — along two dimensions:- **Real-token threshold.** The trigger compares the *true* context fill against- `max_tokens_before_compact`. CubePi anchors the estimate to the last turn's+ `max_tokens_before_compact`. CubeLoop anchors the estimate to the last turn'sactual provider usage — `input_tokens + cache_read_tokens + cache_write_tokens`— so it stays accurate under prompt caching, where most of the prompt is servedfrom cache and would be invisible to a character-only estimate. Before the first@@ -76,11 +76,11 @@ a single agent turn, between tool-call iterations — along two dimensions:### Trailing synthetic controlsTransform middleware earlier in the chain may append synthetic `UserMessage`-controls for the next model call. CubePi keeps a maximal trailing suffix of those+controls for the next model call. CubeLoop keeps a maximal trailing suffix of thosecontrols outside the historical tail/boundary calculation: they cannot make toolevidence immediately before them look old and become eligible for pruning.-The controls still count toward the real-token threshold, and CubePi reattaches them+The controls still count toward the real-token threshold, and CubeLoop reattaches themunchanged after the original or compressed history in exact order. Only trailingsynthetic **user** messages receive this treatment. Internal synthetic messages remainordinary history, and synthetic `ToolResultMessage`s are never detached from their@@ -114,17 +114,17 @@ Override with an explicit int to pin the budget.## Tracing-When `cubepi.tracing` is attached to the agent, the summarizer call is+When `cubeloop.tracing` is attached to the agent, the summarizer call isfirst-class in the trace tree. `summarize()` opens a-`cubepi.compaction.summarize` parent span (tagged with-`cubepi.compaction.message_count`) around the LLM call, and the recorder+`cubeloop.compaction.summarize` parent span (tagged with+`cubeloop.compaction.message_count`) around the LLM call, and the recorderautomatically subscribes the summarizer provider so its `chat` span landsinside:```invoke_agent-└── cubepi.turn- ├── cubepi.compaction.summarize+└── cubeloop.turn+ ├── cubeloop.compaction.summarize│ └── chat <summary-model>└── chat <main-model>```@@ -132,7 +132,7 @@ invoke_agentThe wrapper span is a no-op context manager when OpenTelemetry isn'tinstalled, so the middleware works the same on minimal installs. Theroot `invoke_agent` span's `gen_ai.provider.name` /-`cubepi.agent.system_prompt_sha256` / `cubepi.agent.tools` continue to+`cubeloop.agent.system_prompt_sha256` / `cubeloop.agent.tools` continue toreflect the agent's main provider/model, not the summarizer's — evenwhen summarization runs first.@@ -217,7 +217,7 @@ which can blow up context in long conversations. For finer control, pass aeach `ToolResultMessage`:```python-from cubepi.providers.base import ToolResultMessage+from cubeloop.providers.base import ToolResultMessagedef my_compressor(msg: ToolResultMessage) -> str | None:if msg.tool_name == "chip_metrics":@@ -283,7 +283,7 @@ conversation still has access to the preserved data from earlier turns.## Failure behavior-If the summary provider fails, CubePi falls back to a deterministic, no-LLM+If the summary provider fails, CubeLoop falls back to a deterministic, no-LLMsummary built from message structure (user-request first lines, distincttool names) so context still shrinks. After three consecutive LLM failuresa circuit breaker opens and skips the LLM entirely; the fallback keeps@@ -303,7 +303,7 @@ later compaction does save ≥ 10%.Compaction summarizes *old* history, but it can't shrink a single tool resultthat the model must read on the **current** turn — if one tool returns more thanthe context window holds, no summary helps. Bounding that is the *application's*-job, because CubePi is environment-agnostic: it has no filesystem, session+job, because CubeLoop is environment-agnostic: it has no filesystem, sessiondirectory, or blob store to spill overflow into, and where overflow goes is yourcall.@@ -312,9 +312,9 @@ the full content wherever your environment keeps it, and return a replacementthat previews the content plus a reference the model can follow:```python-from cubepi.middleware import Middleware-from cubepi.agent.types import AfterToolCallContext, AfterToolCallResult-from cubepi.providers.base import TextContent+from cubeloop.middleware import Middleware+from cubeloop.agent.types import AfterToolCallContext, AfterToolCallResult+from cubeloop.providers.base import TextContentclass BoundToolResults(Middleware):def __init__(self, *, max_chars: int = 20_000) -> None:@@ -336,7 +336,7 @@ class BoundToolResults(Middleware):)```-CubePi never inspects `ref` — a disk path, object-store key, database id, or a+CubeLoop never inspects `ref` — a disk path, object-store key, database id, or aplain truncation marker are all equally valid. This keeps tool-output policy inthe layer that actually owns the environment.diff --git a/website/docs/guides/middleware/composition.md b/website/docs/guides/middleware/composition.mdindex c7ba1db..a08dc93 100644--- a/website/docs/guides/middleware/composition.md+++ b/website/docs/guides/middleware/composition.md@@ -1,12 +1,12 @@---title: Composition Rules-description: "Learn how CubePi composes multiple middlewares with per-hook rules: chain, last-wins, first-block-stops, and more."+description: "Learn how CubeLoop composes multiple middlewares with per-hook rules: chain, last-wins, first-block-stops, and more."---# Composition RulesWhen you pass multiple middlewares — `Agent(middleware=[m1, m2,-m3])` — CubePi composes them according to **per-hook rules** that+m3])` — CubeLoop composes them according to **per-hook rules** thatdiffer on purpose. The right way to think about it is: each hook hasthe composition rule that makes sense for its job, and you don't haveto remember "before" or "after" precedence guesses.@@ -46,7 +46,7 @@ the model receives.## `convert_to_llm`Last-wins on purpose: this is the final transform before wire-serialisation. Multiple owners would fight; pick one. CubePi enforces+serialisation. Multiple owners would fight; pick one. CubeLoop enforcesthat the **last** middleware in the list that implements`convert_to_llm` is the one that runs.@@ -95,7 +95,7 @@ hook.## `after_tool_call`Each middleware can return an `AfterToolCallResult` with some fields-set; CubePi merges them, with later results overriding earlier ones+set; CubeLoop merges them, with later results overriding earlier onesfor any field that's not `None`. The full result:```python@@ -188,7 +188,7 @@ overrides. You don't need to `pass`-implement every method.class JustTransform(Middleware):async def transform_context(self, messages, *, ctx, signal=None):return messages[-10:]- # No other hooks. CubePi won't call them.+ # No other hooks. CubeLoop won't call them.```## `on_run_end`diff --git a/website/docs/guides/middleware/deferred-tools.md b/website/docs/guides/middleware/deferred-tools.mdindex 9789eb7..9e6c136 100644--- a/website/docs/guides/middleware/deferred-tools.md+++ b/website/docs/guides/middleware/deferred-tools.md@@ -81,8 +81,8 @@ Pass `deferred_tool_groups` to `Agent`. The middleware is createdautomatically — no manual wiring needed:```python-from cubepi import Agent-from cubepi.deferred import DeferredToolGroup+from cubeloop import Agent+from cubeloop.deferred import DeferredToolGroup# load_github_tools / load_linear_tools are zero-arg async callables# returning list[AgentTool]. See "Writing a loader" below for the two@@ -125,7 +125,7 @@ agent = Agent(### Writing a loaderThe loader is a zero-argument async callable that returns-`list[AgentTool]`. CubePi only cares about its return type — where the+`list[AgentTool]`. CubeLoop only cares about its return type — where the`AgentTool` objects come from is up to you. Two common shapes:**From an MCP server.** `load_mcp_tools_stdio` / `load_mcp_tools_http`@@ -133,8 +133,8 @@ return an `MCPDiscoveryResult` whose `.tools` is the `list[AgentTool]`you want. Wrap it:```python-from cubepi.deferred import DeferredToolGroup-from cubepi.mcp import load_mcp_tools_stdio+from cubeloop.deferred import DeferredToolGroup+from cubeloop.mcp import load_mcp_tools_stdioasync def load_github_tools():result = await load_mcp_tools_stdio(@@ -164,8 +164,8 @@ name, overridable via `@tool(name="…")`). A loader for hand-writtentools is just `async lambda` over a list:```python-from cubepi import tool-from cubepi.deferred import DeferredToolGroup+from cubeloop import tool+from cubeloop.deferred import DeferredToolGroup@toolasync def create_issue(*, repo: str, title: str, body: str) -> str:@@ -258,7 +258,7 @@ handles this — the `strategy` argument is **required** and must matchthe middleware's strategy:```python-from cubepi.deferred import DeferredToolsMiddleware+from cubeloop.deferred import DeferredToolsMiddleware# saved_extra is the persisted ctx.extra from the previous runresumed = await DeferredToolsMiddleware.prepare_resumed_state(@@ -293,7 +293,7 @@ For full control over the catalog header or resume seeding, construct`DeferredToolsMiddleware` yourself:```python-from cubepi.deferred import DeferredToolsMiddleware+from cubeloop.deferred import DeferredToolsMiddlewaremw = DeferredToolsMiddleware(groups=[github_group, linear_group],@@ -325,7 +325,7 @@ is automatically bound to `self._extra`.## Migrating from 0.10-Deferred tool groups shipped in CubePi 0.10 with what is now the+Deferred tool groups shipped in CubeLoop 0.10 with what is now the`inject` strategy. Upgrading changes behavior:- **The default strategy is now `dispatch`.** The catalog wordingdiff --git a/website/docs/guides/middleware/examples.md b/website/docs/guides/middleware/examples.mdindex 8b15b9b..0b0b674 100644--- a/website/docs/guides/middleware/examples.md+++ b/website/docs/guides/middleware/examples.md@@ -1,6 +1,6 @@---title: Examples-description: "Working middleware examples for CubePi: rate limiting, retries with backoff, structured logging, context truncation, and HITL."+description: "Working middleware examples for CubeLoop: rate limiting, retries with backoff, structured logging, context truncation, and HITL."---# Middleware Examples@@ -16,8 +16,8 @@ Redis INCR, …).```pythonimport time-from cubepi import Middleware-from cubepi.agent.types import BeforeToolCallResult+from cubeloop import Middleware+from cubeloop.agent.types import BeforeToolCallResultclass RateLimitMiddleware(Middleware):@@ -54,8 +54,8 @@ exponential backoff, only for transient errors.```pythonimport asyncio-from cubepi import Middleware-from cubepi.agent.types import AfterToolCallResult+from cubeloop import Middleware+from cubeloop.agent.types import AfterToolCallResultclass RetryMiddleware(Middleware):@@ -107,9 +107,9 @@ Pairs `before_tool_call` (to record start time) with `after_tool_call````pythonimport time, logging-from cubepi import Middleware+from cubeloop import Middleware-log = logging.getLogger("cubepi.tools")+log = logging.getLogger("cubeloop.tools")class ToolLoggingMiddleware(Middleware):@@ -145,7 +145,7 @@ Keep the model's context bounded by retaining only the most recent Nmessages, plus the system prompt:```python-from cubepi import Middleware+from cubeloop import Middlewareclass SlidingWindow(Middleware):@@ -178,7 +178,7 @@ passes the model a compressed view: one summary message plus recentmessages. The full conversation history remains in `agent.state`.```python-from cubepi.middleware import CompactionMiddleware+from cubeloop.middleware import CompactionMiddlewaremain_model = main_provider.model("claude-sonnet-4-6")summary_model = cheap_provider.model("claude-haiku-4-5")@@ -202,12 +202,12 @@ The summary call uses `Provider.generate(...)` with## Built-in subagents`SubagentMiddleware` adds one `subagent` tool that runs a temporary-child `Agent` with a self-contained prompt. CubePi captures child+child `Agent` with a self-contained prompt. CubeLoop captures childevents and returns the child agent's final assistant text as the toolresult.```python-from cubepi.middleware import SubagentMiddleware, SubagentSpec+from cubeloop.middleware import SubagentMiddleware, SubagentSpecsubagents = {"researcher": SubagentSpec(@@ -252,7 +252,7 @@ class MaxTurns(Middleware):class BudgetCap(Middleware):def __init__(self, usd: float, model_cost) -> None:self.cap = usd- self.cost = model_cost # cubepi.providers.ModelCost or similar+ self.cost = model_cost # cubeloop.providers.ModelCost or similarself.spent = 0.0async def should_stop_after_turn(self, ctx):@@ -271,9 +271,9 @@ Validate JSON output and re-prompt if it doesn't parse:```pythonimport json-from cubepi import Middleware-from cubepi.middleware.base import TurnAction-from cubepi.providers.base import TextContent, UserMessage+from cubeloop import Middleware+from cubeloop.middleware.base import TurnAction+from cubeloop.providers.base import TextContent, UserMessageclass JSONOutputValidator(Middleware):@@ -302,12 +302,12 @@ model with the feedback message in context.## Human-in-the-loop tool confirmation-CubePi ships two built-in HITL middlewares in `cubepi.hitl`:+CubeLoop ships two built-in HITL middlewares in `cubeloop.hitl`:**`ConfirmToolCallMiddleware`** — "always ask the human for this tool":```python-from cubepi.hitl import ConfirmToolCallMiddleware, InMemoryChannel+from cubeloop.hitl import ConfirmToolCallMiddleware, InMemoryChannelchannel = InMemoryChannel()agent = Agent(@@ -330,7 +330,7 @@ result drives the tool: `approve` runs it, `deny` blocks with a reason,a policy engine:```python-from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny+from cubeloop.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Denydef my_policy(ctx):if ctx.tool_call.name in ("read_file", "grep"):diff --git a/website/docs/guides/middleware/goal.md b/website/docs/guides/middleware/goal.mdindex 6595805..67c35ec 100644--- a/website/docs/guides/middleware/goal.md+++ b/website/docs/guides/middleware/goal.md@@ -16,9 +16,9 @@ work, stop when a second model says the condition is satisfied.## Basic setup```python-from cubepi import Agent-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.middleware.goal import GoalMiddleware+from cubeloop import Agent+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.middleware.goal import GoalMiddlewareprovider = AnthropicProvider(api_key="...")diff --git a/website/docs/guides/middleware/hooks.md b/website/docs/guides/middleware/hooks.mdindex f2159d1..62c4799 100644--- a/website/docs/guides/middleware/hooks.md+++ b/website/docs/guides/middleware/hooks.md@@ -1,16 +1,16 @@---title: The 9 Hooks-description: "Reference for the 9 middleware hooks in CubePi — transform_context, convert_to_llm, resolve_tool_call, before_tool_call, after_tool_call, on_run_end, and more."+description: "Reference for the 9 middleware hooks in CubeLoop — transform_context, convert_to_llm, resolve_tool_call, before_tool_call, after_tool_call, on_run_end, and more."---# The 9 Hooks`Middleware` is a class with up to nine optional async methods. Eachhook fires at a precise point in the agent loop. Implement only the-ones you need — CubePi only wires in the ones you override.+ones you need — CubeLoop only wires in the ones you override.```python-from cubepi import Middleware+from cubeloop import Middlewareclass MyMiddleware(Middleware):async def transform_context(self, messages, *, ctx, signal=None):@@ -130,7 +130,7 @@ Fires **per tool call**, after argument validation, before- `ctx.context` — the full `AgentContext`.Return `BeforeToolCallResult(block=True, reason="…")` to short-circuit-— CubePi feeds the reason back as the tool result with+— CubeLoop feeds the reason back as the tool result with`is_error=True`. Return `None` (or no return) to proceed.Use for: permissions, rate limiting, dry-run modes, sandboxing,@@ -193,8 +193,8 @@ Fires **immediately after** the assistant message lands, **before**hook returns a `TurnAction`:```python-from cubepi.middleware.base import TurnAction-from cubepi.providers.base import synthetic_user_message+from cubeloop.middleware.base import TurnAction+from cubeloop.providers.base import synthetic_user_messageTurnAction(response=modified_message, # replace the message; None to keep@@ -278,7 +278,7 @@ ones you need; the base class's unimplemented hooks raiseautomatically.```python-from cubepi import Middleware+from cubeloop import Middlewareclass MaxTurnsMiddleware(Middleware):def __init__(self, max_turns: int) -> None:diff --git a/website/docs/guides/middleware/subagents.md b/website/docs/guides/middleware/subagents.mdindex d9f0c02..e7c4e03 100644--- a/website/docs/guides/middleware/subagents.md+++ b/website/docs/guides/middleware/subagents.md@@ -1,12 +1,12 @@---title: Subagents-description: "Use SubagentMiddleware to delegate self-contained work to child CubePi agents."+description: "Use SubagentMiddleware to delegate self-contained work to child CubeLoop agents."---# Subagents`SubagentMiddleware` adds a `subagent` tool. When the model calls that tool,-CubePi creates an ephemeral child `Agent`, runs a self-contained prompt, and+CubeLoop creates an ephemeral child `Agent`, runs a self-contained prompt, andreturns the child agent's final assistant text as the tool result.Use it when a parent agent needs to delegate bounded work such as research,@@ -15,8 +15,8 @@ review, extraction, or a focused implementation pass.## Define subagent specs```python-from cubepi import Agent-from cubepi.middleware import SubagentMiddleware, SubagentSpec+from cubeloop import Agent+from cubeloop.middleware import SubagentMiddleware, SubagentSpecsubagents = {"researcher": SubagentSpec(@@ -45,7 +45,7 @@ agent = Agent()```-If the model requests an unknown `subagent_type`, CubePi falls back to the+If the model requests an unknown `subagent_type`, CubeLoop falls back to the`general-purpose` subagent. If you do not define one, the middleware supplies abasic default.@@ -102,7 +102,7 @@ Mapped payloads are also stored in the parent tool result under## Tracing and abortsPass a `Tracer` via `tracer=...` to attach tracing to each child run. Nested-subagent spans share the parent trace, so `cubepi trace view <trace_id>` renders+subagent spans share the parent trace, so `cubeloop trace view <trace_id>` rendersthe parent tool call and child run together.The parent run's abort signal is forwarded to the child agent. If the parent isdiff --git a/website/docs/guides/middleware/todo.md b/website/docs/guides/middleware/todo.mdindex 0df438e..213b2aa 100644--- a/website/docs/guides/middleware/todo.md+++ b/website/docs/guides/middleware/todo.md@@ -20,8 +20,8 @@ the model to show the user a live breakdown of what it's doing.through this reference so state survives checkpointing.```python-from cubepi import Agent-from cubepi.middleware import TodoListMiddleware+from cubeloop import Agent+from cubeloop.middleware import TodoListMiddlewareagent_extra: dict = {}@@ -38,9 +38,9 @@ When the agent is checkpointed, pass the same `extra_ref` that points to`AgentContext.extra` so todo state is persisted and restored across sessions:```python-from cubepi import Agent-from cubepi.checkpointer import PostgresCheckpointer-from cubepi.middleware import TodoListMiddleware+from cubeloop import Agent+from cubeloop.checkpointer import PostgresCheckpointer+from cubeloop.middleware import TodoListMiddleware# extra_ref must return the same object as AgentContext.extra.# The helper below is the standard pattern with a checkpointed agent.diff --git a/website/docs/guides/providers/anthropic.md b/website/docs/guides/providers/anthropic.mdindex 669c48d..1d35424 100644--- a/website/docs/guides/providers/anthropic.md+++ b/website/docs/guides/providers/anthropic.md@@ -1,6 +1,6 @@---title: Anthropic-description: "Use Anthropic Claude models with CubePi's AnthropicProvider — supports thinking, caching, and tool use."+description: "Use Anthropic Claude models with CubeLoop's AnthropicProvider — supports thinking, caching, and tool use."---# Anthropic Provider@@ -12,7 +12,7 @@ caching, and tool use.## Construction```python-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(api_key="sk-ant-…", # or read from os.environ["ANTHROPIC_API_KEY"]@@ -38,13 +38,13 @@ model = provider.model(```The first argument is the model name exactly as you'd pass it to the-SDK. `provider_id` is a free-form label used by CubePi internals — keep+SDK. `provider_id` is a free-form label used by CubeLoop internals — keepit stable across your codebase, and set it when you want tracing anderror messages to show a specific source label.## Extended thinking (reasoning)-CubePi exposes a provider-independent `ReasoningControl(mode, effort,+CubeLoop exposes a provider-independent `ReasoningControl(mode, effort,summary)` and maps it onto Anthropic's `thinking` + `budget_tokens`:| `effort` | Budget |@@ -59,7 +59,7 @@ summary)` and maps it onto Anthropic's `thinking` + `budget_tokens`:the given `effort`. Set it per-agent:```python-from cubepi import ReasoningControl+from cubeloop import ReasoningControlagent = Agent(model=model,@@ -68,7 +68,7 @@ agent = Agent(```A non-reasoning model (`Model(reasoning=False)`) never receives an-enabled `thinking` payload, regardless of the requested `mode` — CubePi+enabled `thinking` payload, regardless of the requested `mode` — CubeLoopclamps it to `"off"` for you.To change the per-effort budgets, supply a@@ -76,8 +76,8 @@ To change the per-effort budgets, supply a`effort_values` map is the single source of truth for budget values:```python-from cubepi import CapabilityDescriptor, ReasoningCapability-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import CapabilityDescriptor, ReasoningCapability+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(api_key="sk-ant-…",@@ -102,11 +102,11 @@ The `thinking` / `ThinkingLevel` / `ThinkingBudgets` API (and`ReasoningCapability`. `Agent(thinking=…)` is now `Agent(reasoning=…)`.:::-When reasoning is on, CubePi **omits `temperature`** because the+When reasoning is on, CubeLoop **omits `temperature`** because theAnthropic API rejects non-default temperatures alongside extendedthinking ([feature compatibility](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#feature-compatibility)).Set `Model.temperature` to the value you want when reasoning is off;-CubePi handles the rest.+CubeLoop handles the rest.Thinking content streams as `thinking_start` / `thinking_delta` /`thinking_end` events and ends up in `AssistantMessage.content` as@@ -136,7 +136,7 @@ rate.For custom cache strategies (a different breakpoint policy), implementthe `CacheMarkerPolicy` Protocol and pass `cache_policy=…`. The-default policy lives at `cubepi.providers.anthropic.DefaultCacheMarkerPolicy`.+default policy lives at `cubeloop.providers.anthropic.DefaultCacheMarkerPolicy`.## Custom payloads with `on_payload`@@ -175,7 +175,7 @@ Both callbacks may be sync or async.## Pointing at Bedrock / Vertex / proxies-The Anthropic SDK accepts a `base_url`; CubePi forwards it:+The Anthropic SDK accepts a `base_url`; CubeLoop forwards it:```pythonprovider = AnthropicProvider(@@ -189,7 +189,7 @@ and inject it via a [custom provider](./custom).## Common pitfalls-- **`temperature` ignored** — Expected. CubePi drops it when reasoning+- **`temperature` ignored** — Expected. CubeLoop drops it when reasoningis on; that's an API constraint, not a bug.- **`effort="max"` looks the same as `"high"`** — Anthropic doesn'texpose a budget tier above `high`, so the built-in profile maps bothdiff --git a/website/docs/guides/providers/custom.md b/website/docs/guides/providers/custom.mdindex 06f3600..7bc6426 100644--- a/website/docs/guides/providers/custom.md+++ b/website/docs/guides/providers/custom.md@@ -1,6 +1,6 @@---title: Writing a Custom Provider-description: "Write a custom provider for CubePi by implementing the Provider protocol."+description: "Write a custom provider for CubeLoop by implementing the Provider protocol."---# Writing a Custom Provider@@ -42,7 +42,7 @@ pushes events into it, return the stream immediately.```pythonimport asyncioimport time-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,BaseProvider,Message,@@ -136,7 +136,7 @@ If your model emits tool calls, append `ToolCall` blocks to`toolcall_delta` / `toolcall_end`:```python-from cubepi.providers.base import ToolCall+from cubeloop.providers.base import ToolCalltc = ToolCall(id=block_id, name=tool_name, arguments={})partial.content.append(tc)@@ -148,16 +148,16 @@ ms.push(StreamEvent(type="toolcall_delta", delta=partial_json_chunk, …))# replace tc.arguments with the parsed dict, push toolcall_end```-CubePi's agent loop will dispatch the tool calls automatically once+CubeLoop's agent loop will dispatch the tool calls automatically once`done` is emitted.## Hooking `on_payload` / `on_response`If your provider sends an HTTP request, call the helpers in-`cubepi.providers.base`:+`cubeloop.providers.base`:```python-from cubepi.providers.base import (+from cubeloop.providers.base import (ProviderResponse,invoke_on_payload,invoke_on_response,@@ -177,12 +177,12 @@ inspection points for free.## Using `FauxProvider` in tests-CubePi ships `FauxProvider` for deterministic tests — no network, no+CubeLoop ships `FauxProvider` for deterministic tests — no network, noflakiness, real streaming events:```python-from cubepi import Agent-from cubepi.providers import FauxProvider, faux_assistant_message, faux_text, faux_tool_call+from cubeloop import Agent+from cubeloop.providers import FauxProvider, faux_assistant_message, faux_text, faux_tool_calldef test_my_agent():@@ -238,9 +238,9 @@ Helpers:writing a class from scratch, check whether your backend is just anOpenAI/Anthropic-compatible endpoint a `CapabilityDescriptor` orbundled preset already covers.-- [API Reference → providers/base](../../api/cubepi-providers) — the+- [API Reference → providers/base](../../api/cubeloop-providers) — thefull type list.-- [Anthropic Provider source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/anthropic.py)+- [Anthropic Provider source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/providers/anthropic.py)— a real, complete example.-- [`FauxProvider` source](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/faux.py)+- [`FauxProvider` source](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/providers/faux.py)— the testing primitive, including stream-realism details.diff --git a/website/docs/guides/providers/image-generation.md b/website/docs/guides/providers/image-generation.mdindex 3ffa88f..1ed59d8 100644--- a/website/docs/guides/providers/image-generation.md+++ b/website/docs/guides/providers/image-generation.md@@ -1,11 +1,11 @@---title: Image Generation-description: "Generate images with CubePi image providers — OpenAI, Doubao Seedream, SiliconFlow, Together AI, and other OpenAI-compatible backends."+description: "Generate images with CubeLoop image providers — OpenAI, Doubao Seedream, SiliconFlow, Together AI, and other OpenAI-compatible backends."---# Image Generation-CubePi's image-generation path mirrors the chat-provider conventions: a+CubeLoop's image-generation path mirrors the chat-provider conventions: aprovider holds the connection (`provider_id`, `api_key`, `base_url`,`capability`), a model spec holds model-level defaults, and per-call workgoes through a typed `ImagesContext` plus an optional `ImagesOptions`@@ -27,7 +27,7 @@ name, supports_seed/steps/guidance gates, …).```pythonimport os-from cubepi.providers.images import OpenAIImagesProvider, ImagesContext+from cubeloop.providers.images import OpenAIImagesProvider, ImagesContextprovider = OpenAIImagesProvider(provider_id="openai",@@ -93,7 +93,7 @@ the wire **key**.## `ImagesOptions` — per-call cross-cutting```python-from cubepi.providers.images import ImagesOptions+from cubeloop.providers.images import ImagesOptionsopts = ImagesOptions(signal=cancel_event, # asyncio.Event; set to abort@@ -114,7 +114,7 @@ plain `Exception` subclass, intentionally distinct fromfast-path before the call returns):```python-from cubepi.providers.images import ImagesAborted+from cubeloop.providers.images import ImagesAborteddef on_response(body, model, exc):if isinstance(exc, ImagesAborted):@@ -155,7 +155,7 @@ OpenAIImagesProvider(OpenAI-shape URL but field names differ:```python-from cubepi.providers.images.capability import ImagesCapabilityDescriptor, SizeSpec+from cubeloop.providers.images.capability import ImagesCapabilityDescriptor, SizeSpecOpenAIImagesProvider(provider_id="siliconflow",@@ -212,11 +212,11 @@ the base `capability`.## Error handling-All built-in image providers raise typed `cubepi.errors.ProviderError`+All built-in image providers raise typed `cubeloop.errors.ProviderError`subclasses on failure — never in-band error strings:```python-from cubepi.errors import RateLimited, ProviderAuthFailed, ProviderUnavailable+from cubeloop.errors import RateLimited, ProviderAuthFailed, ProviderUnavailabletry:result = await provider.generate_images(model, ctx)@@ -258,7 +258,7 @@ supports it:```pythonimport base64-from cubepi.providers.base import ImageContent+from cubeloop.providers.base import ImageContentwith open("source.png", "rb") as fh:source_b64 = base64.b64encode(fh.read()).decode("ascii")@@ -277,8 +277,8 @@ useful when targeting a backend whose model can't edit.## Faux provider for tests```python-from cubepi.providers.images import FauxImagesProvider-from cubepi.errors import RateLimited+from cubeloop.providers.images import FauxImagesProvider+from cubeloop.errors import RateLimited# Happy path:provider = FauxImagesProvider(png_b64="iVBORw0KGgo...")@@ -304,7 +304,7 @@ with `OpenAIImagesProvider`.will likely add an `AsyncTaskImagesProvider` base with shared pollingscaffolding.- **Tracing wiring.** This release adds the listener registry on image- providers, but `cubepi.tracing` does not yet auto-subscribe to image+ providers, but `cubeloop.tracing` does not yet auto-subscribe to imagecalls. Hosts that want image-call spans should subscribe manually fornow.@@ -315,4 +315,4 @@ with `OpenAIImagesProvider`.conventions.- [OpenAI Provider](./openai) — shared OpenAI-shape patterns on the chatside.-- [API Reference → `cubepi.providers.images`](../../api/cubepi-providers).+- [API Reference → `cubeloop.providers.images`](../../api/cubeloop-providers).diff --git a/website/docs/guides/providers/openai.md b/website/docs/guides/providers/openai.mdindex 03e805d..0d69806 100644--- a/website/docs/guides/providers/openai.md+++ b/website/docs/guides/providers/openai.md@@ -1,11 +1,11 @@---title: OpenAI-description: "Use OpenAI GPT models with CubePi's OpenAIProvider — Chat Completions API integration."+description: "Use OpenAI GPT models with CubeLoop's OpenAIProvider — Chat Completions API integration."---# OpenAI Provider-CubePi ships two OpenAI providers covering the two API surfaces:+CubeLoop ships two OpenAI providers covering the two API surfaces:- **`OpenAIProvider`** — Chat Completions API(`/v1/chat/completions`). Use this for the GPT-4/5 family and most@@ -20,7 +20,7 @@ Both implement the same `Provider` protocol; pick one per agent.## Chat Completions: `OpenAIProvider````python-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(provider_id="openai",@@ -41,12 +41,12 @@ model = provider.model(### Reasoning on Chat CompletionsOpenAI exposes reasoning content through `delta.reasoning_content` on-o-series and gpt-5 models. CubePi captures it as `ThinkingContent` and+o-series and gpt-5 models. CubeLoop captures it as `ThinkingContent` andemits `thinking_*` events identically to Anthropic. Control it with`ReasoningControl`:```python-from cubepi import ReasoningControl+from cubeloop import ReasoningControlagent = Agent(model=model,@@ -60,7 +60,7 @@ written to `reasoning_effort` on the wire (`"max"` maps to OpenAI's`reasoning_effort` field, regardless of the requested mode.Many OpenAI-compatible OSS backends emit reasoning under different-fields. CubePi understands three in priority order:+fields. CubeLoop understands three in priority order:1. `delta.reasoning_content` (DeepSeek, Qwen, DouBao)2. `delta.reasoning` (vLLM)@@ -89,10 +89,10 @@ If you need per-request mutation, use `on_payload` (see below).Wire-shape differences between OpenAI and OpenAI-compatible backends(e.g. `max_tokens` vs `max_completion_tokens`, reasoning field names,temperature handling) are configured through a-[`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html)+[`CapabilityDescriptor`](pathname:///pydoc/cubeloop/providers/capability.html)passed at construction. For example, `max_tokens_field="max_completion_tokens"`renames the key on the way out. See [Providers Overview](./overview)-for the full set of knobs (CubePi `0.5+`).+for the full set of knobs (CubeLoop `0.5+`).### Pointing at vLLM / LiteLLM / DeepSeek@@ -119,14 +119,14 @@ renames, …), see [Providers Overview](./overview).## Responses API: `OpenAIResponsesProvider````python-from cubepi.providers.openai_responses import OpenAIResponsesProvider+from cubeloop.providers.openai_responses import OpenAIResponsesProviderprovider = OpenAIResponsesProvider(provider_id="openai_responses", api_key="sk-…")model = provider.model("gpt-5", reasoning=True)```The Responses API keeps state server-side (referenced by-`previous_response_id`). CubePi tracks `AssistantMessage.response_id`+`previous_response_id`). CubeLoop tracks `AssistantMessage.response_id`and feeds it back automatically — your code looks identical to theChat Completions path.@@ -158,9 +158,9 @@ agent = Agent(model=model, on_payload=add_user_metadata)Tool definitions are auto-converted to OpenAI's`{"type": "function", "function": {...}}` shape. The streaming format-emits incremental JSON arguments under `toolcall_delta`; CubePi+emits incremental JSON arguments under `toolcall_delta`; CubeLoopbuffers and parses them through-[`cubepi.utils.json_parse.parse_streaming_json`](../../api/cubepi-utils)+[`cubeloop.utils.json_parse.parse_streaming_json`](../../api/cubeloop-utils)so partials always validate to the closest well-formed object.Multiple parallel tool calls in one assistant message just work —@@ -171,7 +171,7 @@ provider.- **`stream_options.include_usage` rejected** — Some compatiblesreject the whole `stream_options` field. **`on_payload` cannot fix- this**: CubePi 0.3 calls `kwargs.setdefault("stream_options", {})`+ this**: CubeLoop 0.3 calls `kwargs.setdefault("stream_options", {})`*after* your callback runs, so deleting the key in `on_payload` issilently undone. Workarounds:- Subclass `OpenAIProvider` and override `stream()` to skip the@@ -179,7 +179,7 @@ provider.- Set `include_usage=False` in `on_payload` (the field still goesout, but is usually accepted as a no-op even by strictbackends).- - Use a [`CapabilityDescriptor`](./overview) (CubePi `0.5+`) to+ - Use a [`CapabilityDescriptor`](./overview) (CubeLoop `0.5+`) todescribe your backend's reasoning wiring declaratively.- **Thinking events but no `thinking_*` events** — Your backendsurfaces reasoning under a non-standard field. Either add a fourthdiff --git a/website/docs/guides/providers/overview.md b/website/docs/guides/providers/overview.mdindex 81317b0..c8d1608 100644--- a/website/docs/guides/providers/overview.md+++ b/website/docs/guides/providers/overview.md@@ -1,11 +1,11 @@---title: Providers Overview-description: "Provider setup, capabilities, and presets in CubePi."+description: "Provider setup, capabilities, and presets in CubeLoop."---# Providers Overview-_Start here for provider setup in CubePi._+_Start here for provider setup in CubeLoop._This page is the entry point for provider configuration. It covers thedefault path for Anthropic and OpenAI, then explains how to describe@@ -40,7 +40,7 @@ arguments:fishing the provider back out:```python-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.providers.base import TextContent, UserMessagebound = provider.model("claude-sonnet-4-6")@@ -66,8 +66,8 @@ for utilities (summarizers, classifiers) where you already hold aall models served by that provider:```python-from cubepi import CapabilityDescriptor, ReasoningCapability-from cubepi.providers.openai import OpenAIProvider+from cubeloop import CapabilityDescriptor, ReasoningCapability+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key="...",@@ -88,8 +88,8 @@ If only one model needs an override, use`model_capability_overrides`:```python-from cubepi import CapabilityDescriptor, ReasoningCapability-from cubepi.providers.openai import OpenAIProvider+from cubeloop import CapabilityDescriptor, ReasoningCapability+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key="...",@@ -121,10 +121,10 @@ provider = OpenAIProvider(by host UI and product code.:::note Preset catalogs live in the host application-CubePi ships the **mechanism** (the `CapabilityDescriptor` and the wire+CubeLoop ships the **mechanism** (the `CapabilityDescriptor` and the wireruntime that applies it), not a catalog of vendors. A ready-made list ofproviders — base URLs, auth, regional/coding-plan endpoints, model lists —-is product data and belongs to the application embedding CubePi (for+is product data and belongs to the application embedding CubeLoop (forexample, cubebox maintains its own provider catalog). To reach a specificvendor, build the provider with the right `base_url` + `CapabilityDescriptor`as shown below.@@ -136,9 +136,9 @@ Most users never touch capabilities. The built-in providers ship withsensible defaults:```python-import cubepi-from cubepi import Agent-from cubepi.providers.anthropic import AnthropicProvider+import cubeloop+from cubeloop import Agent+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(provider_id="anthropic") # reads ANTHROPIC_API_KEYagent = Agent(model=provider.model("claude-sonnet-4-6"))@@ -146,7 +146,7 @@ await agent.prompt("Hello!")```That's the whole setup. A provider built without `capability=` produces-byte-identical output to CubePi `0.4` — the machinery below only kicks in+byte-identical output to CubeLoop `0.4` — the machinery below only kicks inwhen you ask for it.## 2. Off-default endpoints — the CapabilityDescriptor@@ -155,14 +155,14 @@ When you want a model that isn't OpenAI or Anthropic — DeepSeek, Qwen,Doubao, an OpenRouter route, a local server — the awkward part is eachone's wire dialect (does it want `max_tokens` or `max_completion_tokens`?how is reasoning toggled?). You don't subclass a provider; you describe the-quirks as a [`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html)+quirks as a [`CapabilityDescriptor`](pathname:///pydoc/cubeloop/providers/capability.html)and pass it in, along with the right `base_url` and provider class for theendpoint's wire shape:```pythonimport os-from cubepi import CapabilityDescriptor, ReasoningCapability-from cubepi.providers.openai import OpenAIProvider+from cubeloop import CapabilityDescriptor, ReasoningCapability+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key=os.environ["DEEPSEEK_API_KEY"],@@ -201,7 +201,7 @@ cap or 400s.A `TemperatureSpec` controlling how the caller's temperature is treated:```python-from cubepi import TemperatureSpec+from cubeloop import TemperatureSpecTemperatureSpec(mode="free", min=0.0, max=2.0, default=1.0) # clamp into [min, max]TemperatureSpec(mode="fixed", fixed_value=1.0) # always overwrite@@ -224,7 +224,7 @@ TemperatureSpec(mode="ignored") # drop the key`ReasoningControl.mode` is deep-merged into the request:```python-from cubepi import CapabilityDescriptor, ReasoningCapability+from cubeloop import CapabilityDescriptor, ReasoningCapabilityCapabilityDescriptor(reasoning=ReasoningCapability(@@ -255,13 +255,13 @@ You still need two call-site controls:(defaults to `mode="off"`).```python-from cubepi import (+from cubeloop import (Agent,CapabilityDescriptor,ReasoningCapability,ReasoningControl,)-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key="...",@@ -286,7 +286,7 @@ agent = Agent(``````python-from cubepi import ReasoningCapability+from cubeloop import ReasoningCapability# A token budget (Anthropic).ReasoningCapability(@@ -341,7 +341,7 @@ Resolution is exact-match on `model_id`; anything not listed falls back to## Image providers-Image generation has its own provider surface (`cubepi.providers.images`)+Image generation has its own provider surface (`cubeloop.providers.images`)that follows the same conventions described above: `provider_id` on theprovider, `provider.model("id", ...)` factory, typed `ProviderError`failures, and a capability descriptor for backend wire differences. See@@ -354,7 +354,7 @@ failures, and a capability descriptor for backend wire differences. Seea first-event stream error — it transparently tries the next model:```python-from cubepi import FallbackBoundModel+from cubeloop import FallbackBoundModelmodel = FallbackBoundModel(chain=(@@ -376,4 +376,4 @@ full guide.- [Anthropic Provider](./anthropic) — the token-budget reasoning shape in practice.- [Writing a Custom Provider](./custom) — when the endpoint isn't even OpenAI/Anthropic-shaped.- [Multi-Provider Failover](../../recipes/multi-provider-failover) — `FallbackBoundModel` in action.-- [API Reference → `cubepi.providers`](../../api/cubepi-providers).+- [API Reference → `cubeloop.providers`](../../api/cubeloop-providers).diff --git a/website/docs/guides/providers/structured-output.md b/website/docs/guides/providers/structured-output.mdindex a5d71d2..02ca0a7 100644--- a/website/docs/guides/providers/structured-output.md+++ b/website/docs/guides/providers/structured-output.md@@ -11,7 +11,7 @@ back — no JSON parsing, no schema wrangling.```pythonfrom pydantic import BaseModel-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.providers.base import TextContent, UserMessageclass Sentiment(BaseModel):label: str@@ -69,7 +69,7 @@ await model.generate_structured(`generate_structured()` raises `StructuredOutputError` in two cases:```python-from cubepi.providers.base import StructuredOutputError+from cubeloop.providers.base import StructuredOutputErrortry:result = await model.generate_structured(MySchema, messages=[...])diff --git a/website/docs/guides/tracing/cli.md b/website/docs/guides/tracing/cli.mdindex d1b5c0e..3dc058d 100644--- a/website/docs/guides/tracing/cli.md+++ b/website/docs/guides/tracing/cli.md@@ -1,29 +1,29 @@---title: The trace CLI-description: "Use the CubePi trace CLI to inspect, filter, and display OpenTelemetry trace spans."+description: "Use the CubeLoop trace CLI to inspect, filter, and display OpenTelemetry trace spans."----# Inspecting traces with `cubepi trace`+# Inspecting traces with `cubeloop trace`The `JsonlSpanExporter` writes one file per trace under-`./cubepi-traces/<date>/<trace_id>.jsonl`. The `cubepi trace` CLI (provided by+`./cubeloop-traces/<date>/<trace_id>.jsonl`. The `cubeloop trace` CLI (provided bythe `trace-cli` extra) reads those files so you can see exactly what a run did— which LLM and tool calls fired, in what order, what each returned, where iterrored, and the token counts — without re-running it.```bash-pip install 'cubepi[trace-cli]' # or: uv sync --extra trace-cli-cubepi trace --help+pip install 'cubeloop[trace-cli]' # or: uv sync --extra trace-cli+cubeloop trace --help```-`--dir` defaults to `./cubepi-traces`; pass `--dir <path>` if your traces live+`--dir` defaults to `./cubeloop-traces`; pass `--dir <path>` if your traces liveelsewhere. Each file is one **trace**: the run plus any nested subagent runs,which inherit the parent's `trace_id` and so land in the same file.## `ls` — list recent traces```bash-cubepi trace ls # newest first; -n N to limit+cubeloop trace ls # newest first; -n N to limit```| column | meaning |@@ -43,17 +43,17 @@ If the host stamped run-scoped metadata onto the trace (viajust those traces:```bash-cubepi trace ls --meta conversation_id=conv_123-cubepi trace ls --meta user_id=usr_9 --meta org_id=org_1 # repeatable = AND, exact match+cubeloop trace ls --meta conversation_id=conv_123+cubeloop trace ls --meta user_id=usr_9 --meta org_id=org_1 # repeatable = AND, exact match```-Traces produced by [`Tracer.oneshot()`](../../api/cubepi-tracing#tracer-oneshot)+Traces produced by [`Tracer.oneshot()`](../../api/cubeloop-tracing#tracer-oneshot)(background LLM calls without a full agent loop) are also indexed here. Filterthem by the `operation` name passed to `oneshot()`:```bash-cubepi trace ls --meta oneshot_operation=consolidate_memory-cubepi trace stats --by model --meta oneshot_operation=consolidate_memory+cubeloop trace ls --meta oneshot_operation=consolidate_memory+cubeloop trace stats --by model --meta oneshot_operation=consolidate_memory```Each `--meta KEY=VALUE` is matched exactly against the trace's root metadata;@@ -63,11 +63,11 @@ To **display** metadata values as columns (rather than only filter by them),add `--show-meta KEY[,KEY…]`:```bash-cubepi trace ls --show-meta conversation_id,user_id-cubepi trace ls --meta org_id=org_1 --show-meta conversation_id # filter + show+cubeloop trace ls --show-meta conversation_id,user_id+cubeloop trace ls --meta org_id=org_1 --show-meta conversation_id # filter + show```-(Or see all of a single trace's metadata with `cubepi trace view <id> -v`.)+(Or see all of a single trace's metadata with `cubeloop trace view <id> -v`.)## `view` — render a trace as a span tree@@ -75,29 +75,29 @@ A trace-id **prefix** is enough (the table truncates ids); an ambiguous prefixlists candidates.```bash-cubepi trace view 1cd97cdb+cubeloop trace view 1cd97cdb``````trace└── invoke_agent 14425.8ms [0x1cd97cdb]- ├── cubepi.turn 1283.1ms [0x5cfda93e]+ ├── cubeloop.turn 1283.1ms [0x5cfda93e]│ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]│ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]│ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested- │ └── cubepi.turn 9598.4ms [0x57c5cfc7]+ │ └── cubeloop.turn 9598.4ms [0x57c5cfc7]│ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]│ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]- └── cubepi.turn 491.9ms ERROR [0xce25f242]+ └── cubeloop.turn 491.9ms ERROR [0xce25f242]└── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]└── error: Error code: 400 - ... `tool_use` ids were found without`tool_result` blocks immediately after: call_01_...```-Read it top-down: `invoke_agent` (a run) → `cubepi.turn` (one agent-loop turn)+Read it top-down: `invoke_agent` (a run) → `cubeloop.turn` (one agent-loop turn)→ `chat <model>` (an LLM call, with `tok <input>/<output>`) and`execute_tool <name>` (a tool call). A **subagent** shows up as-`execute_tool subagent` with its own `invoke_agent → cubepi.turn → …` nested+`execute_tool subagent` with its own `invoke_agent → cubeloop.turn → …` nesteddirectly beneath it. The `[0x…]` suffix on each node is the span's `span_id` —grep it in the raw JSONL to inspect that exact span. Errors print inline underthe failing span.@@ -105,8 +105,8 @@ the failing span.Flags:```bash-cubepi trace view <id> --content # expand gen_ai prompts / tool args / results-cubepi trace view <id> -v # expand ALL span attributes (verbose, large)+cubeloop trace view <id> --content # expand gen_ai prompts / tool args / results+cubeloop trace view <id> -v # expand ALL span attributes (verbose, large)````--content` requires the run to have been recorded with@@ -115,14 +115,14 @@ cubepi trace view <id> -v # expand ALL span attributes (verbose, large)## `follow` — watch a trace live```bash-cubepi trace follow <id> # polls as spans complete; good for a run in progress+cubeloop trace follow <id> # polls as spans complete; good for a run in progress```## `stats` — aggregate across traces```bash-cubepi trace stats --by model # latency p50/p95, error rate, tokens-cubepi trace stats --by tool --since 2026-05-20+cubeloop trace stats --by model # latency p50/p95, error rate, tokens+cubeloop trace stats --by tool --since 2026-05-20````stats` also accepts `--meta KEY=VALUE` (same semantics as `ls`) to aggregate@@ -130,8 +130,8 @@ only the traces that match — e.g. latency / error-rate / tokens for one user oconversation:```bash-cubepi trace stats --by model --meta user_id=usr_9-cubepi trace stats --by tool --meta conversation_id=conv_123+cubeloop trace stats --by model --meta user_id=usr_9+cubeloop trace stats --by tool --meta conversation_id=conv_123```## `convert` — reconstruct an API request body@@ -144,16 +144,16 @@ Requires `record_content=True`.```bash# Default: last chat span in the trace, OpenAI JSON format-cubepi trace convert <trace_id>+cubeloop trace convert <trace_id># Select which LLM call to reconstruct-cubepi trace convert <trace_id> --turn 2 # 2nd chat span (1-indexed)-cubepi trace convert <trace_id> --span 0xbb7eb1 # by span_id prefix (from `view`)+cubeloop trace convert <trace_id> --turn 2 # 2nd chat span (1-indexed)+cubeloop trace convert <trace_id> --span 0xbb7eb1 # by span_id prefix (from `view`)# Output formats-cubepi trace convert <trace_id> --format openai # default — JSON request body-cubepi trace convert <trace_id> --format anthropic # Anthropic Messages API body-cubepi trace convert <trace_id> --format curl # shell-executable curl command+cubeloop trace convert <trace_id> --format openai # default — JSON request body+cubeloop trace convert <trace_id> --format anthropic # Anthropic Messages API body+cubeloop trace convert <trace_id> --format curl # shell-executable curl command```The `[0x…]` span id from `view` output goes directly into `--span`:@@ -175,11 +175,11 @@ The files are plain JSONL — one span per line — so you can parse them directspan **event** named `gen_ai.client.operation.exception`.:::tip For AI agents-A bundled `cubepi-trace` skill drives this CLI for debugging ("why did the run+A bundled `cubeloop-trace` skill drives this CLI for debugging ("why did the runend with no reply?", "the tool result is wrong"). It encodes the fast path(`ls` → `view <prefix>`) and the token/cache-rate conventions.```bash-npx skills add cubeplexai/cubepi@cubepi-trace -a claude-code+npx skills add cubeplexai/cubeloop@cubeloop-trace -a claude-code```:::diff --git a/website/docs/guides/tracing/content-recording.md b/website/docs/guides/tracing/content-recording.mdindex f6da04f..421167c 100644--- a/website/docs/guides/tracing/content-recording.md+++ b/website/docs/guides/tracing/content-recording.md@@ -1,12 +1,12 @@---title: Content & Redaction-description: "Configure prompt content recording and redaction in CubePi's OpenTelemetry tracing."+description: "Configure prompt content recording and redaction in CubeLoop's OpenTelemetry tracing."sidebar_position: 4---# Recording Prompts, Responses, and Tool Payloads-By default CubePi's tracing emits structural attributes only — operation+By default CubeLoop's tracing emits structural attributes only — operationnames, models, token counts, finish reasons, durations, and typed error classes.**No prompt content, model output, tool arguments/results, raw exception text,or exception stack traces leave the process.** This is deliberate: many agent@@ -25,7 +25,7 @@ tracer = Tracer(service_name="my-bot",agent_name="assistant",record_content=True, # ← opt-in- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],)```@@ -35,8 +35,8 @@ attributes per the OTel GenAI semconv:| Span | Content attributes added ||---|---|| `invoke_agent` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.output.messages` |-| `cubepi.turn` | `gen_ai.input.messages` (per-turn slice), `gen_ai.output.messages` (per-turn slice) |-| `chat <model>` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.tool.definitions`, `cubepi.llm.raw_request`, `cubepi.llm.raw_response` |+| `cubeloop.turn` | `gen_ai.input.messages` (per-turn slice), `gen_ai.output.messages` (per-turn slice) |+| `chat <model>` | `gen_ai.system_instructions`, `gen_ai.input.messages`, `gen_ai.tool.definitions`, `cubeloop.llm.raw_request`, `cubeloop.llm.raw_response` || `execute_tool <tool_name>` | `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result` |Developer-authored agent and tool descriptions are treated as operational@@ -64,7 +64,7 @@ def redact(key: str, value):if key in ("gen_ai.input.messages", "gen_ai.output.messages"):return _scrub_messages(value)# Don't ship raw bodies at all in prod — keep only the normalised shape.- if key in ("cubepi.llm.raw_request", "cubepi.llm.raw_response"):+ if key in ("cubeloop.llm.raw_request", "cubeloop.llm.raw_response"):return Nonereturn value@@ -129,8 +129,8 @@ main trace:tracer = Tracer(record_content=True, # needed for trace convertrecord_stream=True, # ← per-chunk event log- stream_dir="./cubepi-traces", # where to write <run_id>.stream.jsonl- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ stream_dir="./cubeloop-traces", # where to write <run_id>.stream.jsonl+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],)```@@ -144,7 +144,7 @@ events include the raw provider error message:```json{"t": 5.873, "type": "toolcall_start", "ci": 1, "id": "toolu_...", "name": "show_widget"}{"t": 5.875, "type": "toolcall_delta", "ci": 1, "chars": 11, "accumulated": 11, "preview": "{\"title\": \""}-{"t": 33.177, "type": "toolcall_end", "ci": 1, "id": "toolu_...", "args_chars": 7465, "args_preview": "{\"title\": \"CubePi..."}+{"t": 33.177, "type": "toolcall_end", "ci": 1, "id": "toolu_...", "args_chars": 7465, "args_preview": "{\"title\": \"CubeLoop..."}```This makes it straightforward to confirm whether argument chunks ever arrived, or@@ -160,7 +160,7 @@ tool-heavy agents.## Auditing what's recordedThe recorder always sets `service.name`, `gen_ai.agent.name`, and-`cubepi.run_id` on every span — regardless of `record_content`. Use these+`cubeloop.run_id` on every span — regardless of `record_content`. Use theseto filter the trace backend to a single run and visually confirm whatlanded.@@ -170,5 +170,5 @@ backend:```bashjq -r 'select(.attributes["gen_ai.input.messages"]) | .attributes["gen_ai.input.messages"]' \- cubepi-traces/2026-05-19/*.jsonl+ cubeloop-traces/2026-05-19/*.jsonl```diff --git a/website/docs/guides/tracing/getting-started.md b/website/docs/guides/tracing/getting-started.mdindex 77371b3..c41cb0b 100644--- a/website/docs/guides/tracing/getting-started.md+++ b/website/docs/guides/tracing/getting-started.md@@ -1,6 +1,6 @@---title: Getting Started-description: "Get started with OpenTelemetry tracing in CubePi — install, configure, and export spans."+description: "Get started with OpenTelemetry tracing in CubeLoop — install, configure, and export spans."sidebar_position: 2---@@ -8,14 +8,14 @@ sidebar_position: 2## Install the extra-CubePi keeps OpenTelemetry an optional dependency:+CubeLoop keeps OpenTelemetry an optional dependency:```bash-pip install "cubepi[tracing]"+pip install "cubeloop[tracing]"```This pulls in `opentelemetry-sdk` and friends. Without the extra, the-`cubepi.tracing` import raises a clear error so you find out at import time+`cubeloop.tracing` import raises a clear error so you find out at import timerather than mid-run.## Attach a Tracer@@ -24,10 +24,10 @@ The minimal end-to-end setup — local JSONL export, idiomatic RAII:```pythonimport asyncio-from cubepi import Agent-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.tracing import Tracer-from cubepi.tracing.exporters import JsonlSpanExporter+from cubeloop import Agent+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.tracing import Tracer+from cubeloop.tracing.exporters import JsonlSpanExporterasync def main() -> None:@@ -40,7 +40,7 @@ async def main() -> None:Tracer(service_name="my-bot",agent_name="assistant",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],) as tracer,tracer.attached(agent),):@@ -80,14 +80,14 @@ safety net while you're still building. (Doesn't run on `SIGKILL` orThe run produces one JSONL file per trace (sharded by `trace_id`):```text-./cubepi-traces/+./cubeloop-traces/2026-05-19/8e1c9a3f4b2d…d976a.jsonl ← one trace, one file, one span per line```A trace is the whole OTel tree, including any nested subagent runs (theyinherit the parent's `trace_id`, so they land in the same file). Each span-also carries `cubepi.run_id` — the **same** id as `agent.prompt(run_id=…)` /+also carries `cubeloop.run_id` — the **same** id as `agent.prompt(run_id=…)` /`Message.run_id` (hosts that pass a run id will see it here; otherwise theagent-minted id). Use it to filter by individual business run inside atrace that may hold several nested activations.@@ -96,9 +96,9 @@ Open it with any tool that reads OTLP/JSON or with `jq` directly:```bashjq -r '"\(.name) \(.attributes."gen_ai.operation.name" // "")"' \- cubepi-traces/2026-05-19/*.jsonl+ cubeloop-traces/2026-05-19/*.jsonl# invoke_agent invoke_agent-# cubepi.turn+# cubeloop.turn# chat claude-sonnet-4-6 chat```@@ -108,7 +108,7 @@ For a single prompt with one LLM round-trip, the recorder produces three spans:```textinvoke_agent assistant [INTERNAL] gen_ai.operation.name=invoke_agent-└── cubepi.turn [INTERNAL] cubepi.turn.index=0+└── cubeloop.turn [INTERNAL] cubeloop.turn.index=0└── chat <model> [CLIENT] gen_ai.operation.name=chat```@@ -116,17 +116,17 @@ When the model calls a tool, you get an extra layer per tool:```textinvoke_agent assistant-└── cubepi.turn ← turn index 0+└── cubeloop.turn ← turn index 0├── chat <model> ← first round trip└── execute_tool <tool_name> ← gen_ai.tool.name, gen_ai.tool.call.id-└── cubepi.turn ← turn index 1 (response after tool result)+└── cubeloop.turn ← turn index 1 (response after tool result)└── chat <model>```For MCP tools the `execute_tool` span gets a CLIENT child:```text-execute_tool <tool_name> [INTERNAL] cubepi-side wrapper+execute_tool <tool_name> [INTERNAL] cubeloop-side wrapper└── tools/call <tool_name> [CLIENT] gen_ai.operation.name=execute_toolmcp.method.name=tools/callmcp.session.id=…@@ -141,10 +141,10 @@ instrumented MCP server can continue the trace.The recorder treats cancellation as a control signal, not a failure:- `agent.abort()` or a cancelled one-shot call → affected spans close with- `cubepi.aborted=true` and `error.type=cubepi.aborted`, **status UNSET**, and no+ `cubeloop.aborted=true` and `error.type=cubeloop.aborted`, **status UNSET**, and noexception event (per OTel guidance — cancellation isn't an error).- `agent.detach()` at a durable HITL prompt → open spans close with- `cubepi.run.outcome=suspended` and no aborted/error classification. A later+ `cubeloop.run.outcome=suspended` and no aborted/error classification. A later`respond()` is a new activation trace; correlate the two with metadata such asa host run or conversation ID.- A provider or one-shot call raising → affected spans close with **status@@ -167,13 +167,13 @@ than silently disappearing.Defaults (no opt-in needed):- `invoke_agent` (root) — `gen_ai.operation.name`, `gen_ai.provider.name`,- `gen_ai.agent.name`, `cubepi.run_id` (business run id from+ `gen_ai.agent.name`, `cubeloop.run_id` (business run id from`prompt`/`resume`/`respond`, not a separate tracer uuid),- `cubepi.agent.system_prompt.sha256`, `cubepi.agent.tools` (names list),- `cubepi.input_messages.count`, `cubepi.output_messages.count`-- `cubepi.turn` — `cubepi.turn.index`, `cubepi.turn.stop_reason`,- `cubepi.turn.tool_calls.count`, `cubepi.turn.terminated_by_tool`,- `cubepi.run_id`+ `cubeloop.agent.system_prompt.sha256`, `cubeloop.agent.tools` (names list),+ `cubeloop.input_messages.count`, `cubeloop.output_messages.count`+- `cubeloop.turn` — `cubeloop.turn.index`, `cubeloop.turn.stop_reason`,+ `cubeloop.turn.tool_calls.count`, `cubeloop.turn.terminated_by_tool`,+ `cubeloop.run_id`- `chat <model>` — `gen_ai.operation.name`, `gen_ai.provider.name`,`gen_ai.request.model`, `gen_ai.request.max_tokens` / `temperature` /`top_p`, `gen_ai.request.stream`, `gen_ai.usage.input_tokens` /@@ -183,15 +183,15 @@ Defaults (no opt-in needed):OpenAI-specific extras (`openai.api.type`, service tier, system fingerprint)- `execute_tool <tool_name>` — `gen_ai.operation.name=execute_tool`,`gen_ai.tool.name`, `gen_ai.tool.call.id`, `gen_ai.tool.description`,- `gen_ai.tool.type`, `cubepi.tool.is_error`, `cubepi.tool.execution_mode`+ `gen_ai.tool.type`, `cubeloop.tool.is_error`, `cubeloop.tool.execution_mode`- `tools/call <tool_name>` (MCP only) — `mcp.method.name`, `mcp.session.id`,`mcp.protocol.version`, `server.address`, `server.port`, `gen_ai.tool.name`Optional, opt-in via `Tracer(record_content=True)`:`gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.system_instructions`,`gen_ai.tool.definitions`, `gen_ai.tool.call.arguments`,-`gen_ai.tool.call.result`, `cubepi.llm.raw_request`,-`cubepi.llm.raw_response`, provider/MCP/one-shot exception messages and stack+`gen_ai.tool.call.result`, `cubeloop.llm.raw_request`,+`cubeloop.llm.raw_response`, provider/MCP/one-shot exception messages and stacktraces, and stream-log tool-argument/error previews. See[Content & Redaction](./content-recording).@@ -216,12 +216,12 @@ async with (## Tagging individual runs-`cubepi.tracing.tracing_context` scopes per-run tags / metadata onto+`cubeloop.tracing.tracing_context` scopes per-run tags / metadata ontothe `invoke_agent` span — perfect for `user_id`, `session_id`,A/B-test arm, anything you'd want to filter by in the backend later:```python-from cubepi.tracing import tracing_context+from cubeloop.tracing import tracing_contextasync with tracer.attached(agent):with tracing_context(tags=["beta-arm"], metadata={"user_id": "u-42"}):@@ -230,21 +230,21 @@ async with tracer.attached(agent):Attributes on the span:-- `cubepi.tags = ("beta-arm",)`-- `cubepi.metadata.user_id = "u-42"`+- `cubeloop.tags = ("beta-arm",)`+- `cubeloop.metadata.user_id = "u-42"`-The `cubepi.metadata.*` prefix keeps user keys from clobbering-recorder-owned schema (e.g. `cubepi.run_id`). Tags and metadata+The `cubeloop.metadata.*` prefix keeps user keys from clobbering+recorder-owned schema (e.g. `cubeloop.run_id`). Tags and metadatacontextvars are per-asyncio-task, so concurrent agents seeindependent values, and nested `tracing_context` blocks merge(tags concatenate, metadata keys union with inner winning).## Tracing background LLM calls (`oneshot`)-`attach()` instruments a cubepi `Agent`. For background tasks that call an LLM+`attach()` instruments a cubeloop `Agent`. For background tasks that call an LLMdirectly — without a full agent loop (no tool use, no multi-turn) — use`Tracer.oneshot()` instead. It produces the same `invoke_agent` root span and-`chat` child span so the `cubepi trace` CLI indexes it alongside normal agent+`chat` child span so the `cubeloop trace` CLI indexes it alongside normal agentruns.```python@@ -260,7 +260,7 @@ async with tracer.oneshot()```-The span tree is flat (no `cubepi.turn` wrapper — there is no loop):+The span tree is flat (no `cubeloop.turn` wrapper — there is no loop):```invoke_agent 820ms@@ -270,13 +270,13 @@ invoke_agent 820msFilter these traces by operation name in the CLI:```bash-cubepi trace ls --meta oneshot_operation=consolidate_memory-cubepi trace ls --meta conversation_id=conv-123 # alongside the conversation's agent runs+cubeloop trace ls --meta oneshot_operation=consolidate_memory+cubeloop trace ls --meta conversation_id=conv-123 # alongside the conversation's agent runs```-The `operation` string is recorded as both `cubepi.oneshot.operation` (for-dashboards) and `cubepi.metadata.oneshot_operation` (so `--meta` can reach it,-since the CLI filter only reads `cubepi.metadata.*` attributes).+The `operation` string is recorded as both `cubeloop.oneshot.operation` (for+dashboards) and `cubeloop.metadata.oneshot_operation` (so `--meta` can reach it,+since the CLI filter only reads `cubeloop.metadata.*` attributes).## Nextdiff --git a/website/docs/guides/tracing/metrics.md b/website/docs/guides/tracing/metrics.mdindex cceb608..3d4263c 100644--- a/website/docs/guides/tracing/metrics.md+++ b/website/docs/guides/tracing/metrics.md@@ -1,13 +1,13 @@---title: Metrics-description: "Collect token usage, latency, and time-to-first-content metrics in CubePi tracing."+description: "Collect token usage, latency, and time-to-first-content metrics in CubeLoop tracing."sidebar_position: 5---# Metrics with `Meter`Spans tell you the shape of one run; histograms tell you the shape of the-fleet. `cubepi.tracing.Meter` mirrors `Tracer` and emits the OTel GenAI+fleet. `cubeloop.tracing.Meter` mirrors `Tracer` and emits the OTel GenAImetric set so dashboards work out of the box.## What it emits@@ -36,14 +36,14 @@ The idiomatic RAII form — `async with` everything, no manual cleanup:from opentelemetry.exporter.otlp.proto.http.metric_exporter import (OTLPMetricExporter,)-from cubepi.tracing import Tracer, Meter-from cubepi.tracing.exporters import JsonlSpanExporter+from cubeloop.tracing import Tracer, Meter+from cubeloop.tracing.exporters import JsonlSpanExporterasync with (Tracer(service_name="my-bot",agent_name="assistant",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],) as tracer,Meter(resource=tracer.resource, # share Resource so service.* matches spansdiff --git a/website/docs/guides/tracing/otlp.md b/website/docs/guides/tracing/otlp.mdindex f3245c3..17d9687 100644--- a/website/docs/guides/tracing/otlp.md+++ b/website/docs/guides/tracing/otlp.md@@ -1,26 +1,26 @@---title: OTLP & Backends-description: "Export CubePi OpenTelemetry traces to OTLP-compatible backends like Jaeger, Tempo, or Honeycomb."+description: "Export CubeLoop OpenTelemetry traces to OTLP-compatible backends like Jaeger, Tempo, or Honeycomb."sidebar_position: 3---# Exporting to OTLP Backends-`cubepi.tracing.Tracer` accepts any `opentelemetry.sdk.trace.export.SpanExporter`,+`cubeloop.tracing.Tracer` accepts any `opentelemetry.sdk.trace.export.SpanExporter`,so anything in the OpenTelemetry ecosystem works. Pick the wire format(HTTP or gRPC), point it at your collector, hand the exporter to the Tracer.## HTTP (OTLP/HTTP)```bash-pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-http+pip install "cubeloop[tracing]" opentelemetry-exporter-otlp-proto-http``````pythonfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import (OTLPSpanExporter,)-from cubepi.tracing import Tracer+from cubeloop.tracing import Tracertracer = Tracer(service_name="my-bot",@@ -44,7 +44,7 @@ config.## gRPC (OTLP/gRPC)```bash-pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-grpc+pip install "cubeloop[tracing]" opentelemetry-exporter-otlp-proto-grpc``````python@@ -109,12 +109,12 @@ spans nest under a caller's HTTP handler trace. The internal hook(`Tracer._make_parent_context`) exists for a future `run_scope` feature;until that ships, agent runs and the surrounding service trace are linkedonly by their resource attributes (`service.name`, `gen_ai.agent.name`,-`cubepi.run_id`).+`cubeloop.run_id`).-If you need the upstream trace to continue into CubePi today, the+If you need the upstream trace to continue into CubeLoop today, theworkaround is to set the OTel current span yourself before calling`agent.prompt(...)` and let the agent's spans inherit it via OTel's-ambient context — CubePi never overrides an active parent.+ambient context — CubeLoop never overrides an active parent.On the way out, MCP `tools/call` does inject W3C `traceparent` as an HTTPheader automatically, so an instrumented MCP server downstream of the@@ -129,7 +129,7 @@ pattern — JSONL for local debugging plus OTLP for the production backend:tracer = Tracer(service_name="my-bot",exporters=[- JsonlSpanExporter(directory="./cubepi-traces"),+ JsonlSpanExporter(directory="./cubeloop-traces"),OTLPSpanExporter(endpoint="https://api.honeycomb.io/v1/traces", headers={…}),],)@@ -182,7 +182,7 @@ returning ties your p99 to the slowest exporter. Use the standalone `trace()`helper with `flush="background"` instead:```python-from cubepi.tracing import trace+from cubeloop.tracing import trace@app.post("/chat")async def chat(req: ChatRequest):diff --git a/website/docs/guides/tracing/overview.md b/website/docs/guides/tracing/overview.mdindex 6632045..3bc595f 100644--- a/website/docs/guides/tracing/overview.md+++ b/website/docs/guides/tracing/overview.md@@ -1,12 +1,12 @@---title: Tracing Overview-description: "Overview of CubePi's OpenTelemetry-native tracing system — spans, attributes, exporters, and semantic conventions."+description: "Overview of CubeLoop's OpenTelemetry-native tracing system — spans, attributes, exporters, and semantic conventions."sidebar_position: 1---# Tracing Overview-CubePi emits [OpenTelemetry](https://opentelemetry.io/) spans that follow the+CubeLoop emits [OpenTelemetry](https://opentelemetry.io/) spans that follow the[GenAI Semantic Conventions v1.41](https://opentelemetry.io/docs/specs/semconv/gen-ai/)so any OTel-compatible backend (Jaeger, Tempo, Honeycomb, Datadog, AWS X-Ray,Azure Monitor, …) can ingest agent runs without custom instrumentation.@@ -17,14 +17,14 @@ can pivot, query, and join with the rest of your service traces:```trace└── invoke_agent 14425.8ms [0x1cd97cdb] ← one per agent.prompt()- ├── cubepi.turn 1283.1ms [0x5cfda93e] ← one per LLM round-trip+ ├── cubeloop.turn 1283.1ms [0x5cfda93e] ← one per LLM round-trip│ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]│ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]│ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent run, nested- │ └── cubepi.turn 9598.4ms [0x57c5cfc7]+ │ └── cubeloop.turn 9598.4ms [0x57c5cfc7]│ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]│ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]- └── cubepi.turn 491.9ms ERROR [0xce25f242]+ └── cubeloop.turn 491.9ms ERROR [0xce25f242]└── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]└── error: Error code: 400 - ... `tool_use` ids were found without`tool_result` blocks immediately after: call_01_...@@ -37,15 +37,15 @@ Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,## What ships out of the box- **Tracer** — builds an SDK `TracerProvider`, attaches one- `BatchSpanProcessor` per exporter, wires the CubePi event stream into spans.+ `BatchSpanProcessor` per exporter, wires the CubeLoop event stream into spans.- **Meter** — sibling for OTel histograms:`gen_ai.client.operation.duration`, `gen_ai.client.operation.time_to_first_chunk`,`gen_ai.client.token.usage`.- **JsonlSpanExporter** — write one JSON line per span to- `./cubepi-traces/<date>/<trace_id>.jsonl`. Files are sharded by `trace_id`,+ `./cubeloop-traces/<date>/<trace_id>.jsonl`. Files are sharded by `trace_id`,so one file holds a whole trace — the run plus any nested subagent runs(which inherit the trace). Useful for local dev and offline debugging; works- with any OTel viewer that reads JSONL, and with the [`cubepi trace`+ with any OTel viewer that reads JSONL, and with the [`cubeloop trace`CLI](./cli).- **OTLP** — bring your own exporter via `opentelemetry-exporter-otlp-proto-http`(HTTP) or `…-grpc` and hand it to `Tracer(exporters=[…])`.@@ -60,7 +60,7 @@ Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,who forget `await tracer.shutdown()` still get their spans exported onnormal exit / Ctrl-C / unhandled exception.- **`tracing_context()`** — set per-run tags and metadata- (`cubepi.tags = ("beta-arm",)`, `cubepi.metadata.user_id = "u-42"`)+ (`cubeloop.tags = ("beta-arm",)`, `cubeloop.metadata.user_id = "u-42"`)via a contextvar-scoped block. Concurrent agents each see their ownvalues.- **Middleware-owned providers traced automatically** — middleware that@@ -69,7 +69,7 @@ Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,`chat` spans land in the same trace as the agent's main call.`CompactionMiddleware` uses this to surface its summarizer LLM call asa `chat <summary-model>` span nested under- `cubepi.compaction.summarize` — see the [compaction+ `cubeloop.compaction.summarize` — see the [compactionguide](../middleware/compaction#tracing).## What it costs@@ -102,7 +102,7 @@ Each layer carries standard `gen_ai.*` attributes — `gen_ai.operation.name`,- [Getting Started](./getting-started) — install the extra and emit yourfirst spans-- [OTLP & Backends](./otlp) — point CubePi at Jaeger, Tempo, Honeycomb, …+- [OTLP & Backends](./otlp) — point CubeLoop at Jaeger, Tempo, Honeycomb, …- [Content Recording & Redaction](./content-recording) — record prompts andresponses safely- [Metrics](./metrics) — histograms via `Meter`diff --git a/website/docs/intro.mdx b/website/docs/intro.mdxindex 5df80c0..1504fb1 100644--- a/website/docs/intro.mdx+++ b/website/docs/intro.mdx@@ -1,6 +1,6 @@---id: intro-title: "CubePi — Pythonic async-native agent framework"+title: "CubeLoop — Pythonic async-native agent framework"description: "A Pythonic, async-native agent framework. Plain async functions, append-only checkpointing, three dependencies."slug: /sidebar_position: 0@@ -8,20 +8,20 @@ sidebar_position: 0import PackageVersion from '@site/src/components/PackageVersion';-# CubePi+# CubeLoop-**CubePi** is a Pythonic, async-native agent framework designed for high+**CubeLoop** is a Pythonic, async-native agent framework designed for highperformance, readability, and production-grade persistence. It provides aleaner alternative to graph-based agent runtimes by modeling agent logic asa linear `while` loop that developers can easily trace and debug.-CubePi powers [CubePlex](https://github.com/cubeplexai/cubeplex), a cloud-native+CubeLoop powers [CubePlex](https://github.com/cubeplexai/cubeplex), a cloud-nativeplatform for managed agents in team workspaces — skills, shared memory, MCPtools, persistent sandboxes, governed access, and self-hosted deploy on DockerCompose or Kubernetes.```bash-pip install cubepi+pip install cubeloop```Then jump to the [Quick Start](./getting-started/quick-start.md) to ship a@@ -76,7 +76,7 @@ the `main` branch. APIs documented here can still change before theyship in a tagged release.The latest released version is v<PackageVersion /> ([switch to it from the-version picker, top-right](pathname:///)). CubePi 0.13 adds+version picker, top-right](pathname:///)). CubeLoop 0.13 addsreasoning capability primitives and controls across all providers,run-scoped compaction with real-token triggering, tool-batch faultisolation that preserves all checkpoint state, and durable parallel@@ -85,4 +85,4 @@ now runs off the event loop, and `trace()` gains a `flush="background"` modefor serving paths where span export must not gate a user-visible response.Source, issues, and discussion live on-[GitHub](https://github.com/cubeplexai/cubepi).+[GitHub](https://github.com/cubeplexai/cubeloop).diff --git a/website/docs/migration/from-cubepi.md b/website/docs/migration/from-cubepi.mdnew file mode 100644index 0000000..327a545--- /dev/null+++ b/website/docs/migration/from-cubepi.md@@ -0,0 +1,56 @@+---+title: From cubepi+description: "CubePi was renamed to CubeLoop in 0.14. How to update installs, imports, checkpointer schema, and traces."+---++# Migrating from cubepi++0.14 renames the project from CubePi / `cubepi` to CubeLoop / `cubeloop`.+GitHub keeps the same repository (renamed in place to `cubeplexai/cubeloop`).+The docs site is https://cubeloop.dev.++## Install and imports++```bash+pip install cubeloop+# extras are unchanged: cubeloop[sqlite], cubeloop[postgres], cubeloop[mysql], …+```++```python+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider+```++`pip install -U cubepi` still works: 0.14+ is a wrapper that depends on+`cubeloop==0.14.0`, re-exports the public API, and aliases `cubepi.*` imports.+It warns on first import. Prefer depending on `cubeloop` directly.++CLI: `cubeloop trace` (the wrapper still provides `cubepi trace` and warns).++## Checkpointer schema v5 → v6++Postgres and MySQL table names moved from `cubepi_*` to `cubeloop_*`.+SQLite table names were never prefixed; they stay `messages` / `runs` / ….++Existing databases: add an Alembic revision that runs+`upgrade_v5_to_v6_op()` then `write_schema_version_op()`. Opening 0.14 against+an unmigrated v5 database raises `CubeloopSchemaMismatch` pointing at that+helper — not “tables not found”.++If you have data tables but no `*_schema_version` table, do not apply the+fresh v6 CREATE TABLE. Create `cubepi_schema_version` with version 5 first,+then run the v5→v6 helper.++## Tracing++New spans use `cubeloop.*` attributes and `cubeloop.turn` span names.+`cubeloop trace` still reads 0.13 JSONL that used `cubepi.*`.+Dashboards you own need their own attribute-name update.++Default JSONL directory is `./cubeloop-traces`.++## Environment variables++`CUBELOOP_TEST_PG_DSN`, `CUBELOOP_TEST_MYSQL_DSN`, `CUBELOOP_PG_DSN`,+`CUBELOOP_MYSQL_DSN` replace the `CUBEPI_*` names. The old names are still+read if the new one is unset, for the rest of 0.x.diff --git a/website/docs/migration/from-langgraph.md b/website/docs/migration/from-langgraph.mdindex b679f5c..5eec939 100644--- a/website/docs/migration/from-langgraph.md+++ b/website/docs/migration/from-langgraph.md@@ -1,22 +1,22 @@---title: From langgraph-description: "Learn how to migrate your agents from LangGraph to CubePi — concept mapping, side-by-side code comparisons, and a step-by-step porting guide for the Pythonic async-native alternative."+description: "Learn how to migrate your agents from LangGraph to CubeLoop — concept mapping, side-by-side code comparisons, and a step-by-step porting guide for the Pythonic async-native alternative."---# Migrating from langgraph-CubePi and [langgraph](https://github.com/langchain-ai/langgraph) both+CubeLoop and [langgraph](https://github.com/langchain-ai/langgraph) bothbuild tool-using LLM agents, but they have different mental models.-This page maps langgraph concepts onto CubePi so you can port code+This page maps langgraph concepts onto CubeLoop so you can port codewithout having to re-learn from scratch.## Mental-model shift-| langgraph | CubePi | Why |+| langgraph | CubeLoop | Why ||---|---|---|-| **State graph** with nodes, edges, channels | **Agent loop** that's a plain `while` loop you can read | A linear loop is easier to reason about than a graph; CubePi never branches at runtime — control flow lives in middleware |+| **State graph** with nodes, edges, channels | **Agent loop** that's a plain `while` loop you can read | A linear loop is easier to reason about than a graph; CubeLoop never branches at runtime — control flow lives in middleware || **Channels** (typed state slots) | **`AgentContext.extra`** + `AgentState.messages` | A single dict + a single message list cover every state shape we've seen |-| **`StateGraph.add_node(name, fn)`** | A middleware hook or a tool | Functions in langgraph nodes split into two roles in CubePi: tool execution (when the model decides) vs. middleware (always-on transforms) |+| **`StateGraph.add_node(name, fn)`** | A middleware hook or a tool | Functions in langgraph nodes split into two roles in CubeLoop: tool execution (when the model decides) vs. middleware (always-on transforms) || **`add_edge(a, b)`** / `add_conditional_edges` | Built-in: tools → next turn → tools → … | The conditional shape (tool calls → re-prompt) is the loop; you don't reify it || **`MemorySaver` / `SqliteSaver` / `PostgresSaver`** | `MemoryCheckpointer` / `SQLiteCheckpointer` / `PostgresCheckpointer` | Same idea, append-only schema instead of full snapshots || **`config: {"configurable": {"thread_id": …}}`** | `Agent(thread_id=…)` | First-class agent parameter |@@ -24,7 +24,7 @@ without having to re-learn from scratch.| **Tools as `@tool` decorated functions** | `AgentTool` with Pydantic params + async execute | Closer to OpenAI/Anthropic native shape || **`HumanMessage`, `AIMessage`** | `UserMessage`, `AssistantMessage` | Same role-tagged messages, just renamed || **Interrupts via `interrupt_before` / `interrupt_after`** | `agent.steer(...)`, `agent.follow_up(...)`, `agent.abort()` | Imperative control instead of declarative interrupt points |-| **Time travel / fork** at any checkpoint | **`Agent.fork()`** / **`Agent.fork_once()`** at run boundaries | CubePi keys off completed `run_id`s; see [Forking](../guides/agents/forking) |+| **Time travel / fork** at any checkpoint | **`Agent.fork()`** / **`Agent.fork_once()`** at run boundaries | CubeLoop keys off completed `run_id`s; see [Forking](../guides/agents/forking) || **`config_schema`** | Constructor parameters on `Agent` | No separate schema layer |## Side-by-side: a tool-using agent@@ -69,12 +69,12 @@ for chunk in app.stream({"messages": [("user", "Weather in Tokyo?")]}):print(chunk)```-### CubePi+### CubeLoop```pythonimport asyncio-from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -98,7 +98,7 @@ plain `str` return is wrapped for you. (For tools that need a shared paramsmodel or dynamic construction, the longhand `AgentTool(...)` is still there —see [Tool Use](../guides/agents/tool-use).)-CubePi version removes:+CubeLoop version removes:- The `StateGraph`, edges, nodes, `END` sentinel, conditional edges.- The `ToolNode` registry — tools go directly to the `Agent`.@@ -115,13 +115,13 @@ CubePi version removes:from langgraph.checkpoint.sqlite import SqliteSavergraph.compile(checkpointer=SqliteSaver.from_conn_string(":memory:"))-# CubePi-from cubepi.checkpointer import SQLiteCheckpointer+# CubeLoop+from cubeloop.checkpointer import SQLiteCheckpointerasync with SQLiteCheckpointer("agent.db") as cp:agent = Agent(..., checkpointer=cp, thread_id="conv-1")```-CubePi's append-only model is O(1) per message, regardless of+CubeLoop's append-only model is O(1) per message, regardless ofconversation length. langgraph saves full snapshots, which scaleslinearly with history.@@ -133,7 +133,7 @@ for chunk in app.stream(state, stream_mode="messages"):if chunk["event"] == "on_chat_model_stream":print(chunk["data"]["chunk"].content, end="")-# CubePi+# CubeLoopdef on_event(event, signal=None):if event.type == "message_update" and event.stream_event.type == "text_delta":print(event.stream_event.delta, end="")@@ -150,7 +150,7 @@ One subscriber, one stream — no mode flag.# langgraphgraph.compile(interrupt_before=["tools"])-# CubePi+# CubeLoopclass HumanApproval(Middleware):async def before_tool_call(self, ctx, *, signal=None):approved = await ask_human(f"Run {ctx.tool_call.name}({ctx.args})?")@@ -172,7 +172,7 @@ graph.add_edge("summary", END)``````python-# CubePi+# CubeLoopclass SummariseAtEnd(Middleware):async def should_stop_after_turn(self, ctx) -> bool:msg = ctx.message@@ -194,14 +194,14 @@ config = {"configurable": {"thread_id": "t1", "checkpoint_id": "<id>"}}app.update_state(config, {"messages": [...]})result = app.invoke(None, config)-# CubePi — persistent fork at a completed-run boundary+# CubeLoop — persistent fork at a completed-run boundaryawait agent.fork(src_thread_id="conv_123",new_thread_id="conv_456",after_run_id="R1",)-# CubePi — ephemeral one-shot probe (writes nothing)+# CubeLoop — ephemeral one-shot probe (writes nothing)result = await agent.fork_once(src_thread_id="conv_123",message="What if you had said yes?",@@ -210,23 +210,23 @@ result = await agent.fork_once(print(result.text)```-CubePi forks at completed-run boundaries rather than arbitrary mid-run+CubeLoop forks at completed-run boundaries rather than arbitrary mid-runcheckpoints. `fork` creates a persistent branch you can continue;`fork_once` runs a single probe and discards everything. See[Conversation Forking](../guides/agents/forking).-## What LangGraph still offers beyond CubePi+## What LangGraph still offers beyond CubeLoop-- **Graph-native multi-agent orchestration.** CubePi includes+- **Graph-native multi-agent orchestration.** CubeLoop includes`SubagentMiddleware` for tool-driven delegation: a parent agent can dispatchself-contained tasks to typed child agents with dedicated prompts, models,- tools, and middleware. What CubePi does not yet provide is LangGraph's+ tools, and middleware. What CubeLoop does not yet provide is LangGraph'sexplicit, durable graph model for supervisor routing, conditional branches,parallel fan-out/fan-in, and graph-level state management.- **Visual graph rendering.** No `app.get_graph().draw_mermaid()`- equivalent. CubePi's flow is linear so the picture would be a single+ equivalent. CubeLoop's flow is linear so the picture would be a singleline anyway.-- **First-party UI for traces.** CubePi doesn't render its own trace+- **First-party UI for traces.** CubeLoop doesn't render its own tracevisualizer the way LangSmith / Langfuse do; instead it emitsvendor-neutral OpenTelemetry — point any OTLP backend(LangSmith's OTel endpoint, Langfuse v3, Jaeger, Tempo,@@ -234,7 +234,7 @@ checkpoints. `fork` creates a persistent branch you can continue;`Tracer(exporters=[OTLPSpanExporter(...)])`. See[Tracing → OTLP & Backends](../guides/tracing/otlp).-## What CubePi does that langgraph doesn't+## What CubeLoop does that langgraph doesn't- **Native OpenTelemetry tracing** — `Tracer` + `Meter` emit OTelspans + GenAI-semconv attributes out of the box, ingestible bydiff --git a/website/docs/recipes/ask-user-form.md b/website/docs/recipes/ask-user-form.mdindex 58fd089..0499657 100644--- a/website/docs/recipes/ask-user-form.md+++ b/website/docs/recipes/ask-user-form.md@@ -1,6 +1,6 @@---title: Multi-question Form via ask_user-description: "Build a multi-question form with CubePi's ask_user HITL tool for structured user input."+description: "Build a multi-question form with CubeLoop's ask_user HITL tool for structured user input."---# Recipe: Multi-question Form via `ask_user`@@ -11,8 +11,8 @@ proceed — a configuration wizard, a preference selector, a feature toggle.## Step 1: Register the tool```python-from cubepi.agent.agent import Agent-from cubepi.hitl import InMemoryChannel, ask_user_tool+from cubeloop.agent.agent import Agent+from cubeloop.hitl import InMemoryChannel, ask_user_toolchannel = InMemoryChannel()@@ -153,8 +153,8 @@ accordingly — ask again, fall back to a default, or report to the user.```pythonimport asyncio-from cubepi.agent.agent import Agent-from cubepi.hitl import InMemoryChannel, ask_user_tool+from cubeloop.agent.agent import Agent+from cubeloop.hitl import InMemoryChannel, ask_user_toolchannel = InMemoryChannel()@@ -186,12 +186,12 @@ asyncio.run(main())## Run the exampleA self-contained, runnable version of this recipe is in the repository at-[`examples/ask_user_form.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/ask_user_form.py).+[`examples/ask_user_form.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/ask_user_form.py).The host loop answers all questions programmatically so you can observe thefull round-trip without wiring up a real UI.```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/docs/recipes/multi-provider-failover.md b/website/docs/recipes/multi-provider-failover.mdindex 68f1939..c93be0a 100644--- a/website/docs/recipes/multi-provider-failover.md+++ b/website/docs/recipes/multi-provider-failover.md@@ -7,18 +7,18 @@ description: "Automatic failover between LLM providers using FallbackBoundModel.When the primary provider is rate-limited, unavailable, or has hit its contextlimit, fall over to the next one automatically — without crashing the agent.-CubePi ships `FallbackBoundModel` for this out of the box.+CubeLoop ships `FallbackBoundModel` for this out of the box.**Time to read:** 5 minutes.-**Deps:** `cubepi`, API keys for two providers.+**Deps:** `cubeloop`, API keys for two providers.## The built-in: `FallbackBoundModel````pythonimport os-from cubepi import Agent, FallbackBoundModel-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.openai import OpenAIProvider+from cubeloop import Agent, FallbackBoundModel+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.openai import OpenAIProvideranthropic = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])openai = OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"])@@ -78,8 +78,8 @@ aggregated `ProviderUnavailable.errors` list keeps every leg.Pass `trigger_errors` to override:```python-from cubepi import FallbackBoundModel-from cubepi.errors import ProviderAuthFailed, ProviderUnavailable, RateLimited+from cubeloop import FallbackBoundModel+from cubeloop.errors import ProviderAuthFailed, ProviderUnavailable, RateLimitedmodel = FallbackBoundModel(chain=(primary, fallback),@@ -120,7 +120,7 @@ same-model retry. Optional `on_retry(failed, error, attempt, wait_s)` coversretries. Both sync and async callables are accepted. Exceptions raised insideeither callback are logged and swallowed.-When every leg fails, CubePi raises `ProviderUnavailable` whose `.errors`+When every leg fails, CubeLoop raises `ProviderUnavailable` whose `.errors`list holds the per-leg failures (typed when possible). `__cause__` is thelast typed error.@@ -156,7 +156,7 @@ really responded.A runnable version is in the repository:```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/docs/recipes/persistent-chat.md b/website/docs/recipes/persistent-chat.mdindex c828497..15882e5 100644--- a/website/docs/recipes/persistent-chat.md+++ b/website/docs/recipes/persistent-chat.md@@ -1,6 +1,6 @@---title: Persistent Chat-description: "Build a persistent chat application with CubePi and SQLiteCheckpointer."+description: "Build a persistent chat application with CubeLoop and SQLiteCheckpointer."---# Recipe: Persistent Chat (SQLite)@@ -9,7 +9,7 @@ A REPL chat that survives restarts. Conversation history is kept in aSQLite file; each user gets a `thread_id`.**Time to run:** 5 minutes.-**Deps:** `cubepi[sqlite]`, an `ANTHROPIC_API_KEY`.+**Deps:** `cubeloop[sqlite]`, an `ANTHROPIC_API_KEY`.## The script@@ -18,9 +18,9 @@ import asyncioimport osimport sys-from cubepi import Agent-from cubepi.checkpointer import SQLiteCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import SQLiteCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main(thread_id: str):@@ -63,7 +63,7 @@ if __name__ == "__main__":Run:```bash-pip install "cubepi[sqlite]"+pip install "cubeloop[sqlite]"export ANTHROPIC_API_KEY=sk-…python chat.py alice# Have a chat, then Ctrl-D.@@ -78,7 +78,7 @@ python chat.py bob## What's going on-- **First `prompt()` per process loads history.** CubePi checks the+- **First `prompt()` per process loads history.** CubeLoop checks thecheckpointer once at the start of the first prompt, restores`agent.state.messages`, and proceeds.- **Each `message_end` appends to the database.** No batching, no@@ -120,7 +120,7 @@ After a long conversation, the model's context gets expensive. Add amiddleware:```python-from cubepi import Middleware+from cubeloop import Middlewareclass SlidingWindow(Middleware):def __init__(self, n: int) -> None:@@ -147,7 +147,7 @@ complete.Same code, different checkpointer:```python-from cubepi.checkpointer import PostgresCheckpointer+from cubeloop.checkpointer import PostgresCheckpointerasync with PostgresCheckpointer("postgresql://…") as cp:agent = Agent(model=…, checkpointer=cp, thread_id=…)@@ -168,10 +168,10 @@ concurrent users — see [Postgres + FastAPI](./postgres-fastapi).## Run the exampleA self-contained, runnable version of this recipe is in the repository at-[`examples/persistent_chat.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/persistent_chat.py).+[`examples/persistent_chat.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/persistent_chat.py).```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv sync --extra sqliteexport ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/docs/recipes/postgres-fastapi.md b/website/docs/recipes/postgres-fastapi.mdindex 2a26df9..ff26ae5 100644--- a/website/docs/recipes/postgres-fastapi.md+++ b/website/docs/recipes/postgres-fastapi.md@@ -1,64 +1,33 @@---title: Postgres + FastAPI Service-description: "Deploy a FastAPI-backed CubePi agent with PostgresCheckpointer for production."+description: "Deploy a FastAPI-backed CubeLoop agent with PostgresCheckpointer for production."---# Recipe: Postgres + FastAPI Service-A production-shaped HTTP service that fronts a CubePi agent: FastAPI+A production-shaped HTTP service that fronts a CubeLoop agent: FastAPIfor routing, server-sent events for streaming, a shared`PostgresCheckpointer` for persistence, and `thread_id` derived fromthe authenticated user.**Time to run:** 30 minutes.-**Deps:** `cubepi[postgres]`, `fastapi`, `uvicorn[standard]`,-`sse-starlette`, a running Postgres with the CubePi schema applied.+**Deps:** `cubeloop[postgres]`, `fastapi`, `uvicorn[standard]`,+`sse-starlette`, a running Postgres with the CubeLoop schema applied.## Schema first-Before the service starts, run the CubePi schema migration. The+Before the service starts, run the CubeLoop schema migration. Thequickest way for this recipe:```bash-psql "$DATABASE_URL" <<'SQL'-CREATE TABLE cubepi_threads (- thread_id TEXT PRIMARY KEY,- parent_thread_id TEXT REFERENCES cubepi_threads(thread_id),- forked_at_seq BIGINT,- extra JSONB NOT NULL DEFAULT '{}'::jsonb,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT now()-);--CREATE TABLE cubepi_messages (- thread_id TEXT NOT NULL REFERENCES cubepi_threads(thread_id) ON DELETE CASCADE,- seq BIGINT NOT NULL,- role TEXT NOT NULL,- metadata JSONB NOT NULL DEFAULT '{}'::jsonb,- payload BYTEA NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),- PRIMARY KEY (thread_id, seq)-) PARTITION BY HASH (thread_id);---- 64 hash partitions-DO $$-BEGIN- FOR i IN 0..63 LOOP- EXECUTE format(- 'CREATE TABLE cubepi_messages_p%s PARTITION OF cubepi_messages FOR VALUES WITH (MODULUS 64, REMAINDER %s)',- i, i- );- END LOOP;-END$$;--CREATE INDEX ix_cubepi_messages_metadata_gin-ON cubepi_messages USING gin (metadata jsonb_path_ops);--CREATE TABLE cubepi_schema_version (version INT PRIMARY KEY);-INSERT INTO cubepi_schema_version VALUES (1);-SQL+# Throwaway / recipe: copy the v6 bootstrap from+# examples/checkpointing_postgres.py (cubeloop_threads, cubeloop_messages ++# 64 partitions, cubeloop_runs + 64 partitions, cubeloop_hitl_answers,+# cubeloop_schema_version = 6).```+Existing v5 databases must run `upgrade_v5_to_v6_op()` instead of CREATE.+For a real deployment, generate this via Alembic — see[Postgres Checkpointing → Bootstrapping via Alembic](../guides/checkpointing/postgres#bootstrapping-via-alembic).@@ -74,9 +43,9 @@ from fastapi import FastAPI, Depends, HTTPExceptionfrom pydantic import BaseModelfrom sse_starlette.sse import EventSourceResponse-from cubepi import Agent-from cubepi.checkpointer import PostgresCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import PostgresCheckpointer+from cubeloop.providers.anthropic import AnthropicProvider# --- App lifecycle ------------------------------------------------------@@ -175,8 +144,8 @@ async def get_history(Run:```bash-pip install "cubepi[postgres]" fastapi "uvicorn[standard]" sse-starlette-export DATABASE_URL=postgresql://user:pass@localhost/cubepi+pip install "cubeloop[postgres]" fastapi "uvicorn[standard]" sse-starlette+export DATABASE_URL=postgresql://user:pass@localhost/cubeloopexport ANTHROPIC_API_KEY=sk-…uvicorn service:app --reload --port 8000```@@ -237,7 +206,7 @@ If you need strict ordering, add an application-layer mutex## Common pitfalls-- **CubepiSchemaUninitialized at startup** — Your migrations didn't+- **CubeloopSchemaUninitialized at startup** — Your migrations didn'trun. Apply the schema first.- **Connection pool exhaustion** — Default `max_pool_size=10`. Bumpit if your service has more concurrent agents than that.@@ -249,13 +218,13 @@ If you need strict ordering, add an application-layer mutex## Run the exampleA self-contained service template for this recipe is in the repository at-[`examples/postgres_fastapi.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/postgres_fastapi.py).+[`examples/postgres_fastapi.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/postgres_fastapi.py).```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv sync --extra postgres-export DATABASE_URL=postgresql://user:pass@localhost/cubepi+export DATABASE_URL=postgresql://user:pass@localhost/cubeloopexport ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY [+ OPENAI_BASE_URL]uv run --with fastapi --with "uvicorn[standard]" --with sse-starlette \diff --git a/website/docs/recipes/resumable-tasks.md b/website/docs/recipes/resumable-tasks.mdindex 00b2159..14d7cf8 100644--- a/website/docs/recipes/resumable-tasks.md+++ b/website/docs/recipes/resumable-tasks.md@@ -1,6 +1,6 @@---title: Resumable Long Tasks-description: "Build crash-resilient long-running tasks with CubePi checkpointing and recovery."+description: "Build crash-resilient long-running tasks with CubeLoop checkpointing and recovery."---# Recipe: Resumable Long Tasks@@ -8,12 +8,12 @@ description: "Build crash-resilient long-running tasks with CubePi checkpointingWhen an agent is mid-flight through a long-running operation (a seriesof tool calls, a multi-turn reasoning session) and the process dies,you want to come back and pick up where it left off — not start over.-CubePi's append-only checkpointing plus `agent.resume()` makes this+CubeLoop's append-only checkpointing plus `agent.resume()` makes thistrivial *between turns*; for resumption *mid-tool*, you need a littlemore care.**Time to run:** 15 minutes.-**Deps:** `cubepi[sqlite]`, an `ANTHROPIC_API_KEY`.+**Deps:** `cubeloop[sqlite]`, an `ANTHROPIC_API_KEY`.## The pattern@@ -26,7 +26,7 @@ There are three crash points to think about:persisted. `resume()` sees the last message is a `ToolResultMessage`and re-invokes the model. *Free with the checkpointer.*3. **Mid-tool** — The tool started but didn't finish. Nothing is- persisted yet (CubePi only persists messages). You need+ persisted yet (CubeLoop only persists messages). You needtool-internal idempotency. *Requires care.*This recipe focuses on case 3.@@ -41,11 +41,11 @@ import osimport jsonfrom pathlib import Path-from cubepi import AgentToolResult, TextContent, tool+from cubeloop import AgentToolResult, TextContent, tool# Simple file-backed job store; replace with Redis / Postgres in prod.-JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubepi-jobs"))+JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubeloop-jobs"))JOB_DIR.mkdir(parents=True, exist_ok=True)@@ -91,9 +91,9 @@ import asyncioimport osimport sys-from cubepi import Agent-from cubepi.checkpointer import SQLiteCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import SQLiteCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderfrom tools import transcode_video # the @tool-decorated AgentTool from above@@ -128,7 +128,7 @@ async def main(thread_id: str, initial_prompt: str | None):# AssistantMessage with no queued steer/follow_up → raiseslast = agent.state.messages[-1]if type(last).__name__ == "AssistantMessage":- from cubepi.providers.base import ToolCall+ from cubeloop.providers.base import ToolCallhas_pending_tools = any(isinstance(c, ToolCall) for c in last.content)if not has_pending_tools:# Job finished normally — no pending tool calls.@@ -194,7 +194,7 @@ idempotency guards handle the rest.## What about persisting partial tool state?-CubePi doesn't expose a "persist a partial tool result" API. The+CubeLoop doesn't expose a "persist a partial tool result" API. Theintended pattern is: keep partial state in the tool's ownexternal store (filesystem, Redis, S3), keyed deterministically by thetool args. That's what `transcode_video` above does with `JOB_DIR`.@@ -221,10 +221,10 @@ tool args. That's what `transcode_video` above does with `JOB_DIR`.## Run the exampleA self-contained, runnable version of this recipe is in the repository at-[`examples/resumable_tasks.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/resumable_tasks.py).+[`examples/resumable_tasks.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/resumable_tasks.py).```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv sync --extra sqliteexport ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/docs/recipes/sandbox-confirm.md b/website/docs/recipes/sandbox-confirm.mdindex 9283e5b..3736dce 100644--- a/website/docs/recipes/sandbox-confirm.md+++ b/website/docs/recipes/sandbox-confirm.md@@ -1,6 +1,6 @@---title: Sandbox Confirm with ApprovalPolicyMiddleware-description: "Implement sandbox tool confirmation with CubePi's ApprovalPolicyMiddleware — auto-allow, deny, or human-confirm."+description: "Implement sandbox tool confirmation with CubeLoop's ApprovalPolicyMiddleware — auto-allow, deny, or human-confirm."---# Recipe: Sandbox Confirm with `ApprovalPolicyMiddleware`@@ -14,7 +14,7 @@ The policy receives a `BeforeToolCallContext` and returns an`ApprovalDecision` — `Approve()`, `Deny(reason)`, or `AskUser(...)`.```python-from cubepi.hitl import Approve, AskUser, Deny+from cubeloop.hitl import Approve, AskUser, Deny# Mock rule engine — replace with your actual policy catalog.def classify_command(cmd: str) -> tuple[str, str | None]:@@ -48,9 +48,9 @@ policy receives the typed model.## Step 2: Wire into the agent```python-from cubepi.agent.agent import Agent-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.hitl import ApprovalPolicyMiddleware, CheckpointedChannel+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.hitl import ApprovalPolicyMiddleware, CheckpointedChannelasync def main():async with PostgresCheckpointer("postgresql://...") as cp:@@ -94,7 +94,7 @@ async def host_loop(channel: CheckpointedChannel):timeout=timeout,)# Build an ApproveAnswer from the human's decision.- from cubepi.hitl import ApproveAnswer+ from cubeloop.hitl import ApproveAnswerhuman_answer = ApproveAnswer(decision=ui_response["decision"], # "approve" | "deny" | "edit"reason=ui_response.get("reason"), # only for deny@@ -142,12 +142,12 @@ appended for any unresolved tool calls, a terminal## Run the exampleA self-contained, runnable version of this recipe is in the repository at-[`examples/sandbox_confirm.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/sandbox_confirm.py).+[`examples/sandbox_confirm.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/sandbox_confirm.py).It wires up a simulated bash tool and a policy that auto-allows reads, deniesdestructive writes, and auto-approves everything else via the host loop.```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/docs/recipes/weather-agent.md b/website/docs/recipes/weather-agent.mdindex fc9c107..059b457 100644--- a/website/docs/recipes/weather-agent.md+++ b/website/docs/recipes/weather-agent.md@@ -1,6 +1,6 @@---title: Weather Agent-description: "Build a weather agent that fetches live API data with CubePi tools."+description: "Build a weather agent that fetches live API data with CubeLoop tools."---# Recipe: Weather Agent@@ -10,7 +10,7 @@ Demonstrates HTTP-calling tools, error handling, streaming UI, andcancellation.**Time to run:** 5 minutes.-**Deps:** `cubepi`, `httpx`, an `ANTHROPIC_API_KEY`.+**Deps:** `cubeloop`, `httpx`, an `ANTHROPIC_API_KEY`.## The script@@ -22,8 +22,8 @@ import httpxfrom typing import Annotatedfrom pydantic import Field-from cubepi import Agent, AgentToolResult, TextContent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, AgentToolResult, TextContent, tool+from cubeloop.providers.anthropic import AnthropicProvider# --- The tool -----------------------------------------------------------@@ -108,7 +108,7 @@ if __name__ == "__main__":Run:```bash-pip install cubepi httpx+pip install cubeloop httpxexport ANTHROPIC_API_KEY=sk-…python weather_agent.py```@@ -124,7 +124,7 @@ Tokyo is currently 18°C with a wind speed of 12 km/h. São Paulo is 25°C with## What's going on- **Two tools in parallel.** The model emits two `get_weather` tool- calls in the same assistant turn. CubePi runs them concurrently —+ calls in the same assistant turn. CubeLoop runs them concurrently —the second one doesn't wait for the first.- **Streaming text + tool events interleave.** The `on_event` filterhandles both `text_delta` (for the final answer) and@@ -148,10 +148,10 @@ Tokyo is currently 18°C with a wind speed of 12 km/h. São Paulo is 25°C with## Run the exampleA self-contained, runnable version of this recipe is in the repository at-[`examples/weather_agent.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/weather_agent.py).+[`examples/weather_agent.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/weather_agent.py).```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # or OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/docusaurus.config.ts b/website/docusaurus.config.tsindex d2ef7c9..b60cd7d 100644--- a/website/docusaurus.config.ts+++ b/website/docusaurus.config.ts@@ -27,7 +27,7 @@ const PACKAGE_VERSION = VERSION_MATCH ? VERSION_MATCH[1] : 'dev';const classicOptions: ClassicOptions = {docs: {sidebarPath: './sidebars.ts',- editUrl: 'https://github.com/cubeplexai/cubepi/edit/main/website/',+ editUrl: 'https://github.com/cubeplexai/cubeloop/edit/main/website/',lastVersion: '0.13',versions: {current: { label: 'Next 🚧', path: 'next', banner: 'unreleased', noIndex: true },@@ -69,15 +69,15 @@ const classicOptions: ClassicOptions = {};const config: Config = {- title: 'CubePi',+ title: 'CubeLoop',tagline: 'A Pythonic, async-native agent framework — an alternative to langgraph and pi-agent-core',- favicon: 'img/brand/cubepi-logo.svg',+ favicon: 'img/brand/cubeloop-logo.svg',- url: 'https://cubepi.ai',+ url: 'https://cubeloop.dev',baseUrl: '/',trailingSlash: false,organizationName: 'cubeplexai',- projectName: 'cubepi',+ projectName: 'cubeloop',onBrokenLinks: 'throw',onBrokenAnchors: 'throw',@@ -107,13 +107,13 @@ const config: Config = {innerHTML: JSON.stringify({'@context': 'https://schema.org','@type': 'Organization',- name: 'CubePi',- url: 'https://cubepi.ai',- logo: 'https://cubepi.ai/img/brand/cubepi-logo.png',+ name: 'CubeLoop',+ url: 'https://cubeloop.dev',+ logo: 'https://cubeloop.dev/img/brand/cubeloop-logo.png',sameAs: [- 'https://github.com/cubeplexai/cubepi',+ 'https://github.com/cubeplexai/cubeloop','https://x.com/cubeplexai',- 'https://pypi.org/project/cubepi/',+ 'https://pypi.org/project/cubeloop/',],}),},@@ -147,14 +147,14 @@ const config: Config = {themeConfig: {metadata: [- { name: 'keywords', content: 'CubePi, langgraph alternative, pi-agent-core alternative, Python agent framework, async agent, LLM agent, AI agent framework, tool-use agent, Python Agent 框架, 异步 Agent, langgraph 替代品, AI Agent 开发' },+ { name: 'keywords', content: 'CubeLoop, langgraph alternative, pi-agent-core alternative, Python agent framework, async agent, LLM agent, AI agent framework, tool-use agent, Python Agent 框架, 异步 Agent, langgraph 替代品, AI Agent 开发' },{ name: 'twitter:site', content: '@cubeplexai' },{ name: 'twitter:creator', content: '@cubeplexai' },],- image: 'img/brand/cubepi-social-preview.png',+ image: 'img/brand/cubeloop-social-preview.png',navbar: {- title: 'CubePi',- logo: { alt: 'CubePi logo', src: 'img/brand/cubepi-logo.svg' },+ title: 'CubeLoop',+ logo: { alt: 'CubeLoop logo', src: 'img/brand/cubeloop-logo.svg' },items: [// Version-aware section links (see src/components/VersionAwareDocLink):// active state is path-driven so only one lights up per page, and the@@ -178,7 +178,7 @@ const config: Config = {{ type: 'docsVersionDropdown', position: 'right' },{ type: 'localeDropdown', position: 'right' },{- href: 'https://github.com/cubeplexai/cubepi',+ href: 'https://github.com/cubeplexai/cubeloop',position: 'right',className: 'header-github-link','aria-label': 'GitHub repository',diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/api/index.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/api/index.mdxindex fa345f2..068ba46 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/api/index.mdx+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/api/index.mdx@@ -1,18 +1,18 @@---title: API 参考-description: "CubePi Python API 的参考文档。"+description: "CubeLoop Python API 的参考文档。"---# API 参考-从 CubePi 的公共模块自动生成。+从 CubeLoop 的公共模块自动生成。-- `cubepi.agent`-- `cubepi.providers`-- `cubepi.checkpointer`-- `cubepi.middleware`-- `cubepi.mcp`-- `cubepi.tracing`-- `cubepi.utils`+- `cubeloop.agent`+- `cubeloop.providers`+- `cubeloop.checkpointer`+- `cubeloop.middleware`+- `cubeloop.mcp`+- `cubeloop.tracing`+- `cubeloop.utils`上面的模块页面是在构建时从文档字符串生成的,不能手动编辑。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.mdindex cbaadb5..c13420d 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/core-concepts.md@@ -1,11 +1,11 @@---title: 核心概念-description: "了解 CubePi 的六个核心概念:Agent、Tool、Provider、Stream & Events、Middleware 和 Checkpointer。"+description: "了解 CubeLoop 的六个核心概念:Agent、Tool、Provider、Stream & Events、Middleware 和 Checkpointer。"---# 核心概念-CubePi 的全部能力可以归纳为六个概念。这一页读一遍,后面的文档基本就+CubeLoop 的全部能力可以归纳为六个概念。这一页读一遍,后面的文档基本就变成查表了。## Agent@@ -32,11 +32,11 @@ Subscriber 会收到循环发出的每一个 `AgentEvent`。可以是同步或## Tool-工具就是一个模型可以调用的 async 函数。用 `@tool` 装饰它,CubePi 会从+工具就是一个模型可以调用的 async 函数。用 `@tool` 装饰它,CubeLoop 会从参数生成输入 schema:```python-from cubepi import tool+from cubeloop import tool@toolasync def search(query: str, limit: int = 10) -> str:@@ -135,7 +135,7 @@ HITL 为跨进程挂起/恢复新增了两个可选方法:`save_pending_reques## HITL(人机协同)-CubePi 内置了 `cubepi.hitl` 模块,用于 agent 需要**暂停并等待人类输入**的+CubeLoop 内置了 `cubeloop.hitl` 模块,用于 agent 需要**暂停并等待人类输入**的场景:- **沙箱确认** —— 危险工具(bash、写入文件)在执行前需要人类@@ -143,7 +143,7 @@ CubePi 内置了 `cubepi.hitl` 模块,用于 agent 需要**暂停并等待人- **运行中提问** —— agent 在运行中途向用户弹出一个结构化表单,等待回答。```python-from cubepi.hitl import InMemoryChannel, ConfirmToolCallMiddleware, ask_user_tool+from cubeloop.hitl import InMemoryChannel, ConfirmToolCallMiddleware, ask_user_toolchannel = InMemoryChannel()@@ -177,21 +177,21 @@ Channel 是一个可 `await` 的协程协作者:工具和中间件作者写X-Ray 等)都能直接接收,无需额外 instrumentation。先装 extra:```bash-pip install "cubepi[tracing]" # OTel SDK-pip install "cubepi[tracing-otlp]" # + OTLP/HTTP 导出器+pip install "cubeloop[tracing]" # OTel SDK+pip install "cubeloop[tracing-otlp]" # + OTLP/HTTP 导出器```然后用 `async with` 包住 Agent:```python-from cubepi.tracing import Tracer-from cubepi.tracing.exporters import JsonlSpanExporter+from cubeloop.tracing import Tracer+from cubeloop.tracing.exporters import JsonlSpanExporterasync with (Tracer(service_name="my-bot",agent_name="assistant",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],) as tracer,tracer.attached(agent),):@@ -199,7 +199,7 @@ async with (```每次 run 会发出一个 `invoke_agent` 根 span,其下每轮 LLM 往返对应-一个 `cubepi.turn`,再嵌套 `chat`(CLIENT)和 `execute_tool` 子+一个 `cubeloop.turn`,再嵌套 `chat`(CLIENT)和 `execute_tool` 子span。**默认不记录任何 prompt 内容或模型输出** —— 需要的话用`Tracer(record_content=True)` 显式打开,搭配 `redact` 回调脱敏。配合 `Meter(...)` 还能拿到 token / 时延 / TTFC 直方图。完整指南:diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.mdindex 1511562..07fc28c 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/installation.md@@ -1,29 +1,29 @@---title: 安装-description: "通过 pip 安装 CubePi。需要 Python 3.11+,支持 Linux、macOS 和 Windows。"+description: "通过 pip 安装 CubeLoop。需要 Python 3.11+,支持 Linux、macOS 和 Windows。"---# 安装-CubePi 需要 **Python 3.11 或以上**。核心运行时只有三个依赖:`pydantic`、+CubeLoop 需要 **Python 3.11 或以上**。核心运行时只有三个依赖:`pydantic`、`anthropic`、`openai`。可选功能(SQLite、Postgres、MCP、OpenTelemetry追踪)通过 extras 按需安装,不用的话不会被拉进来。## 使用 pip```bash-pip install cubepi+pip install cubeloop```可选 extras:```bash-pip install "cubepi[sqlite]" # 安装 aiosqlite,启用 SQLiteCheckpointer-pip install "cubepi[postgres]" # 安装 asyncpg + sqlalchemy + msgpack-pip install "cubepi[mcp]" # 安装 MCP SDK,启用 MCP 工具加载器-pip install "cubepi[tracing]" # 安装 opentelemetry-sdk,启用 Tracer / Meter-pip install "cubepi[tracing-otlp]" # 加上 OTLP/HTTP 导出器-pip install "cubepi[sqlite,mcp,tracing]" # 组合+pip install "cubeloop[sqlite]" # 安装 aiosqlite,启用 SQLiteCheckpointer+pip install "cubeloop[postgres]" # 安装 asyncpg + sqlalchemy + msgpack+pip install "cubeloop[mcp]" # 安装 MCP SDK,启用 MCP 工具加载器+pip install "cubeloop[tracing]" # 安装 opentelemetry-sdk,启用 Tracer / Meter+pip install "cubeloop[tracing-otlp]" # 加上 OTLP/HTTP 导出器+pip install "cubeloop[sqlite,mcp,tracing]" # 组合```## 使用 uv@@ -31,8 +31,8 @@ pip install "cubepi[sqlite,mcp,tracing]" # 组合[`uv`](https://github.com/astral-sh/uv) 比 pip 快很多,是推荐的工作流:```bash-uv add cubepi-uv add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+uv add cubeloop+uv add "cubeloop[sqlite,postgres,mcp,tracing,tracing-otlp]"```在已有 uv 项目里,改完 `pyproject.toml` 后 `uv sync` 会重新锁定环境。@@ -40,15 +40,15 @@ uv add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"## 使用 Poetry```bash-poetry add cubepi-poetry add "cubepi[sqlite,postgres,mcp,tracing,tracing-otlp]"+poetry add cubeloop+poetry add "cubeloop[sqlite,postgres,mcp,tracing,tracing-otlp]"```## 验证安装```bash-python -c "import cubepi; print(cubepi.__doc__)"-# cubepi — Pythonic async-native agent framework.+python -c "import cubeloop; print(cubeloop.__doc__)"+# cubeloop — Pythonic async-native agent framework.```如果报 `ImportError`,大概率是解释器版本低于 3.11——用 `python --version`@@ -56,13 +56,13 @@ python -c "import cubepi; print(cubepi.__doc__)"## 配置 provider 凭据-CubePi 的 provider 从构造函数参数读取凭据。大多数部署会从环境变量+CubeLoop 的 provider 从构造函数参数读取凭据。大多数部署会从环境变量取出来:```pythonimport os-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.openai import OpenAIProvideranthropic = AnthropicProvider(provider_id="anthropic", api_key=os.environ["ANTHROPIC_API_KEY"])openai = OpenAIProvider(provider_id="openai", api_key=os.environ["OPENAI_API_KEY"])diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.mdindex 8065998..2ade6a4 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/getting-started/quick-start.md@@ -1,6 +1,6 @@---title: 快速开始-description: "在几分钟内构建你的第一个 CubePi agent。"+description: "在几分钟内构建你的第一个 CubeLoop agent。"---# 快速开始@@ -12,7 +12,7 @@ description: "在几分钟内构建你的第一个 CubePi agent。"## 前置条件- Python 3.11+-- 已安装 `cubepi`(`pip install cubepi`)+- 已安装 `cubeloop`(`pip install cubeloop`)- 环境变量中有 `ANTHROPIC_API_KEY`## 完整脚本@@ -23,8 +23,8 @@ description: "在几分钟内构建你的第一个 CubePi agent。"import asyncioimport os-from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -68,11 +68,11 @@ python weather_agent.py## 刚刚发生了什么-CubePi 跑了一个概念上长这样的循环:+CubeLoop 跑了一个概念上长这样的循环:1. `agent.prompt("东京现在天气怎么样?")` 把一条 `UserMessage` 入队,然后调用模型。-2. 模型决定调用 `get_weather(city="Tokyo")`——CubePi 按 `@tool` 从函数+2. 模型决定调用 `get_weather(city="Tokyo")`——CubeLoop 按 `@tool` 从函数签名生成的 schema 解析 JSON 参数,调用你的 `async def`,把结果作为`ToolResultMessage` 反馈回去。3. 模型产生最终的 assistant 回复,以 `text_delta` 事件流的形式回来。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.mdindex ae44947..e2d2753 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/first-agent.md@@ -1,6 +1,6 @@---title: 第一个 Agent-description: "从零开始创建并运行你的第一个 CubePi agent。"+description: "从零开始创建并运行你的第一个 CubeLoop agent。"---# 构建你的第一个 Agent@@ -16,7 +16,7 @@ provider 是到 LLM API 的连接;用 `provider.model("id", ...)` 把模型 ID```pythonimport os-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(provider_id="anthropic", api_key=os.environ["ANTHROPIC_API_KEY"])model = provider.model(@@ -36,7 +36,7 @@ model = provider.model(工具就是一个用 `@tool` 装饰的 async 函数:```python-from cubepi import tool+from cubeloop import tool@tool@@ -53,7 +53,7 @@ async def get_weather(city: str) -> str:- 返回 `str`(自动包成文本)、`Content`、内容列表,或在需要`details`/`is_error` 时返回完整的 `AgentToolResult`。- 需要取消或进度流?在签名里声明 `signal`(用户取消时被 set 的- `asyncio.Event`)和/或 `on_update(partial)`,CubePi 会注入它们 —— 见+ `asyncio.Event`)和/或 `on_update(partial)`,CubeLoop 会注入它们 —— 见[工具使用](./tool-use)。- 需要共享参数模型或动态构建?长写法 `AgentTool(...)` 与之等价 —— 见[工具使用](./tool-use)。@@ -61,7 +61,7 @@ async def get_weather(city: str) -> str:## 第 3 步 —— 组装 Agent```python-from cubepi import Agent+from cubeloop import Agentagent = Agent(model=model,@@ -152,10 +152,10 @@ async def main():- **没有 `text_delta` 事件** —— 是不是在 `prompt()` 之后才订阅的?Listener 只看得到注册之后的事件。- **Tool not found** —— 模型调了一个 `name` 不在 `tools=[...]` 里的- 工具。CubePi 把这种情况包装成一个 `is_error=True` 的工具结果,+ 工具。CubeLoop 把这种情况包装成一个 `is_error=True` 的工具结果,不会崩 —— 在 `tool_execution_end` 事件的 `result` 里能看到。- **Pydantic ValidationError 被吞掉了** —— 如果模型产出格式错误的- JSON,CubePi 会把 validation error 也包成工具的 error result 喂+ JSON,CubeLoop 会把 validation error 也包成工具的 error result 喂回去,模型通常下一轮自动纠正。## 下一步diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/forking.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/forking.mdindex 1c5e0ec..2f80115 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/forking.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/forking.md@@ -5,7 +5,7 @@ description: "在已完成 run 的边界处分叉会话 — 持久化分支、# 会话分叉-**分叉**在一个已完成 run 的边界处创建会话分支。CubePi 提供两种方式:+**分叉**在一个已完成 run 的边界处创建会话分支。CubeLoop 提供两种方式:- **`Agent.fork(...)`** — *持久化*分叉。将源线程中截止指定 `run_id`的消息复制到全新线程,后续可以继续与新线程对话。@@ -142,8 +142,8 @@ class ForkOnceResult:```pythonimport uuid-from cubepi import Agent-from cubepi.hitl import CheckpointedChannel, ask_user_tool+from cubeloop import Agent+from cubeloop.hitl import CheckpointedChannel, ask_user_toolrun_id = uuid.uuid4().hexchannel = CheckpointedChannel(checkpointer=cp, thread_id="conv_123", run_id=run_id)@@ -184,7 +184,7 @@ In-memory(`InMemoryChannel`)HITL 没有此要求 —— 不涉及持久化## 历史数据行为 {#legacy-data-behaviour}-CubePi 能优雅处理此功能上线前的旧消息(`run_id` 列未填充,即+CubeLoop 能优雅处理此功能上线前的旧消息(`run_id` 列未填充,即`run_id IS NULL`):- **混合线程** — 已有旧消息后又接收了升级后 `prompt()` 的线程,可从任意diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.mdindex 8a23890..3913bb1 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/multi-turn.md@@ -1,11 +1,11 @@---title: 多轮对话-description: "使用 CubePi 的有状态 agent 循环和消息历史构建多轮对话 agent。"+description: "使用 CubeLoop 的有状态 agent 循环和消息历史构建多轮对话 agent。"---# 多轮对话-在 CubePi 中,一个"轮次"(turn)是:用户输入 → 模型响应(可能包含工具调用)→ 可选的对工具结果的后续模型响应。agent 的 `_messages` 列表在多轮对话中不断增长。本指南介绍如何正确驱动多轮对话流程,以及如何在 agent 处于思考过程中注入输入。+在 CubeLoop 中,一个"轮次"(turn)是:用户输入 → 模型响应(可能包含工具调用)→ 可选的对工具结果的后续模型响应。agent 的 `_messages` 列表在多轮对话中不断增长。本指南介绍如何正确驱动多轮对话流程,以及如何在 agent 处于思考过程中注入输入。## 基本模式@@ -17,7 +17,7 @@ await agent.prompt("What's my name?")# → "Your name is Sam."```-历史消息保存在 `agent.state.messages` 中。CubePi 会追加每条用户消息、每条 assistant 消息以及每个工具结果。每次调用时 provider 都会收到完整的消息列表,因此 context window 的大小至关重要(参见下方的[上下文管理](#context-management))。+历史消息保存在 `agent.state.messages` 中。CubeLoop 会追加每条用户消息、每条 assistant 消息以及每个工具结果。每次调用时 provider 都会收到完整的消息列表,因此 context window 的大小至关重要(参见下方的[上下文管理](#context-management))。## 运行中修正:`agent.steer()`@@ -74,7 +74,7 @@ async with SQLiteCheckpointer("conv.db") as cp:## 上下文管理 {#context-management}-CubePi **不会**代替你截断或摘要上下文。每次轮次都会将完整消息列表发送给模型。几种应对策略:+CubeLoop **不会**代替你截断或摘要上下文。每次轮次都会将完整消息列表发送给模型。几种应对策略:- **手动截断** —— 实现一个 [`transform_context`](../middleware/hooks#transform_context) middleware,返回一个滑动窗口。- **摘要 pass** —— 定期注入摘要消息,并通过 `transform_context` 丢弃旧消息。@@ -94,7 +94,7 @@ await agent.wait_for_idle() # awaits the run-cleanup## 从磁盘恢复状态```python-from cubepi.checkpointer import SQLiteCheckpointer+from cubeloop.checkpointer import SQLiteCheckpointerasync with SQLiteCheckpointer("conv.db") as cp:agent = Agent(diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/prompt-caching.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/prompt-caching.mdindex cd52f94..2e278ed 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/prompt-caching.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/prompt-caching.md@@ -1,6 +1,6 @@---title: Prompt 缓存-description: "CubePi 如何最大化 prompt 缓存命中率——追加式消息存储、自动缓存断点,以及如何避免破坏缓存。"+description: "CubeLoop 如何最大化 prompt 缓存命中率——追加式消息存储、自动缓存断点,以及如何避免破坏缓存。"---# Prompt 缓存@@ -9,8 +9,8 @@ Prompt 缓存让 LLM provider 在 stable prefix 上复用 KV 计算,而不是都重新处理。收益非常可观:Anthropic 对命中缓存的 token 按**正常输入价格的 10%** 收费,命中也会降低 time-to-first-token。-CubePi 从底层架构就为最大化缓存命中而设计。这篇指南讲解缓存是怎么工作-的、为什么 CubePi 的架构能让缓存常驻,以及你可以做什么(或不要做什么)+CubeLoop 从底层架构就为最大化缓存命中而设计。这篇指南讲解缓存是怎么工作+的、为什么 CubeLoop 的架构能让缓存常驻,以及你可以做什么(或不要做什么)来保住命中率。---@@ -45,7 +45,7 @@ Request N: [system] [tools] [msg 1] [msg 2] [msg 3]序列就跟上一次的请求不一样了,于是**从那一位置开始的所有缓存断点全部miss**。-CubePi 的 checkpointer 是追加式的:只往 thread 末尾添加新消息。内存里+CubeLoop 的 checkpointer 是追加式的:只往 thread 末尾添加新消息。内存里的 `agent.state.messages` 列表通过 append 增长,从不重建、从不重排。这意味着每一次请求的前缀都和上一轮字节一致——这是命中缓存最基础的要求。@@ -70,7 +70,7 @@ tool),所以命中缓存。最后一条消息的断点向前移了一位,### 配置```python-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop.providers.anthropic import AnthropicProvider# 默认:short TTL(5 分钟),自动断点provider = AnthropicProvider(api_key="…")@@ -101,13 +101,13 @@ print(usage.cache_write_tokens) # 本轮写入缓存的 token`cache_read_tokens / (input_tokens + cache_read_tokens + cache_write_tokens)`。:::tip-CubePi 的 `Usage.input_tokens` 是**未命中缓存**的那部分——本轮真正被模型+CubeLoop 的 `Usage.input_tokens` 是**未命中缓存**的那部分——本轮真正被模型处理的 token。完整 prompt token 数是`input_tokens + cache_read_tokens + cache_write_tokens`。100% 命中时`input_tokens` 为 0。:::-`cubepi trace` CLI 输出和 `Tracer` 发出的 OTel span 里也能看到这些字段。+`cubeloop trace` CLI 输出和 `Tracer` 发出的 OTel span 里也能看到这些字段。注意 OTel span 属性 `gen_ai.usage.input_tokens` 遵循 GenAI 语义约定,报的是**包含**未命中和命中的总数:@@ -121,13 +121,13 @@ gen_ai.usage.cache_read.input_tokens = 7 980 (命中那部分)## OpenAI:自动缓存OpenAI 对超过 1 024 token 的 prompt 自动缓存——不需要显式的-`cache_control` 标记。CubePi 通过同一个 `Usage` 接口暴露命中数据:+`cache_control` 标记。CubeLoop 通过同一个 `Usage` 接口暴露命中数据:```pythonusage.cache_read_tokens # 对应 prompt_tokens_details.cached_tokens```-CubePi 端没什么可配。保持 system prompt 和 tool 定义在轮次间稳定,+CubeLoop 端没什么可配。保持 system prompt 和 tool 定义在轮次间稳定,OpenAI 的缓存会自然预热起来。---@@ -164,8 +164,8 @@ OpenAI 的缓存会自然预热起来。provider:```python-from cubepi.providers.anthropic import CacheMarkerPolicy, AnthropicProvider-from cubepi.providers.base import Message+from cubeloop.providers.anthropic import CacheMarkerPolicy, AnthropicProvider+from cubeloop.providers.base import Messageclass SystemOnlyPolicy:"""只缓存 system prompt——tool 列表经常变时有用。"""diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.mdindex d8451b6..a0939d4 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/streaming.md@@ -1,11 +1,11 @@---title: 流式输出-description: "通过 subscriber 和 MessageStream 实时流式接收 CubePi agent 的事件和 token。"+description: "通过 subscriber 和 MessageStream 实时流式接收 CubeLoop agent 的事件和 token。"---# 流式事件-CubePi 暴露两层流:+CubeLoop 暴露两层流:1. **Provider 流** —— `provider.stream(...)` 返回的 `MessageStream`,产出 `StreamEvent` 描述原始线缆输出:文本 delta、思考 delta、@@ -90,7 +90,7 @@ def on_event(event, signal=None):print(sub.delta, end="", flush=True)```-CubePi 保证的稳定结构是上面表格里那一种(`message_update.stream_event.delta`)。+CubeLoop 保证的稳定结构是上面表格里那一种(`message_update.stream_event.delta`)。代码里对内部类型做防御性判断。## Provider 的 `StreamEvent` 类型@@ -148,5 +148,5 @@ final = await stream.result() # 拿最终的 AssistantMessage- [工具使用](./tool-use) —— 详解 `tool_execution_*` 三联事件。- [多轮会话](./multi-turn) —— steering 和 resume 周边的事件顺序。-- [API Reference → StreamEvent](../../api/cubepi-providers#streamevent)+- [API Reference → StreamEvent](../../api/cubeloop-providers#streamevent)里有字段级 schema。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.mdindex 1969ae6..b3a2138 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/agents/tool-use.md@@ -5,20 +5,20 @@ description: "注册工具、并行或顺序执行、并通过 Pydantic 校验# 工具使用与并行执行-工具是 Agent 影响世界的方式。CubePi 把每个 `AgentTool` 转成模型可用+工具是 Agent 影响世界的方式。CubeLoop 把每个 `AgentTool` 转成模型可用的 JSON Schema、用 Pydantic 校验参数、执行你的代码、把结果作为`ToolResultMessage` 喂回。默认情况下,只要模型在一轮里发出多个工具调用,它们就会并行执行。## `@tool` 装饰器-定义工具最快的方式是给一个 async 函数加装饰器。CubePi 会从参数生成输入+定义工具最快的方式是给一个 async 函数加装饰器。CubeLoop 会从参数生成输入schema,不需要单独写参数模型,也不用写样板的 `execute` 签名:```pythonfrom typing import Annotatedfrom pydantic import Field-from cubepi import tool+from cubeloop import tool@tool@@ -42,7 +42,7 @@ async def search(在你需要 `details`、`is_error`、`terminate` 时返回完整的 `AgentToolResult`:```python-from cubepi import tool, AgentToolResult, TextContent+from cubeloop import tool, AgentToolResult, TextContent@tool@@ -73,7 +73,7 @@ async def long_job(prompt: str, *, signal=None, on_update=None) -> str:```pythonfrom pydantic import BaseModel, Field-from cubepi import AgentTool, AgentToolResult, TextContent+from cubeloop import AgentTool, AgentToolResult, TextContentclass SearchParams(BaseModel):@@ -102,7 +102,7 @@ search_tool = AgentTool(## 默认并行-模型在一条 assistant 消息里发多个工具调用时,CubePi 会用+模型在一条 assistant 消息里发多个工具调用时,CubeLoop 会用`asyncio.create_task()` 调度它们并 gather。这通常就是你想要的。```python@@ -181,7 +181,7 @@ async def long_running(tool_call_id, params, *, signal=None, on_update=None):两种姿势:-1. **抛异常。** CubePi 捕获后转成 `is_error=True` 的 `AgentToolResult`,+1. **抛异常。** CubeLoop 捕获后转成 `is_error=True` 的 `AgentToolResult`,异常字符串作为 `TextContent`。2. **显式返回 `is_error=True`。** 适合你想给结构化错误体的场景:@@ -209,7 +209,7 @@ async def submit_final_answer(tool_call_id, params, *, signal=None, on_update=No)```-CubePi 仅在当前批次中 *每个* 工具结果都是 `terminate=True` 时才终止。+CubeLoop 仅在当前批次中 *每个* 工具结果都是 `terminate=True` 时才终止。然后循环发 `turn_end`、`agent_end`,退出。## 工具很多?把 schema 延迟加载@@ -227,9 +227,9 @@ cache。(v1 行为——把加载的工具注入模型可见的 tools 数组仍可通过 `deferred_tool_strategy="inject"` 选用。)```python-from cubepi import Agent-from cubepi.deferred import DeferredToolGroup-from cubepi.mcp import load_mcp_tools_stdio+from cubeloop import Agent+from cubeloop.deferred import DeferredToolGroup+from cubeloop.mcp import load_mcp_tools_stdioasync def load_github_tools():result = await load_mcp_tools_stdio(@@ -274,7 +274,7 @@ loader 是一个零参 async 可调用对象,返回 `list[AgentTool]` ——给模型看。除非你下游有消费者,否则别堆大 blob。- **Pydantic 严格度的意外** —— `Field(..., min_length=1)` 让模型通过JSON Schema 看到约束 —— 约束有帮助,但模型仍然偶尔发坏 JSON。- CubePi 把 `ValidationError` 转成工具的 error result,你不用自己包。+ CubeLoop 把 `ValidationError` 转成工具的 error result,你不用自己包。- **`tools=[]` 但模型还是想用工具** —— 一般是 system prompt 里提到了工具。要么删掉提示,要么真的把工具给它。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.mdindex 1a38dd1..a7bfb40 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/custom.md@@ -1,6 +1,6 @@---title: 自定义后端-description: "使用 Checkpointer protocol 为 CubePi 实现自定义 checkpointer 后端。"+description: "使用 Checkpointer protocol 为 CubeLoop 实现自定义 checkpointer 后端。"---# 自定义 Checkpointing 后端@@ -32,8 +32,8 @@ class Checkpointer(Protocol):import jsonfrom typing import Anyimport redis.asyncio as aredis-from cubepi.checkpointer.base import CheckpointData-from cubepi.providers.base import AssistantMessage, Message, ToolResultMessage, UserMessage+from cubeloop.checkpointer.base import CheckpointData+from cubeloop.providers.base import AssistantMessage, Message, ToolResultMessage, UserMessage_ROLE_TO_CLS: dict[str, type[Message]] = {@@ -44,7 +44,7 @@ _ROLE_TO_CLS: dict[str, type[Message]] = {class RedisCheckpointer:- def __init__(self, redis_url: str, prefix: str = "cubepi:") -> None:+ def __init__(self, redis_url: str, prefix: str = "cubeloop:") -> None:self._url = redis_urlself._prefix = prefixself._r: aredis.Redis | None = None@@ -109,7 +109,7 @@ async with RedisCheckpointer("redis://localhost:6379") as cp:1. **仅追加。** 不要修改过去的消息。agent 假定它追加的历史就是你在 `load` 中返回的内容。2. **保持顺序。** `load` 按追加顺序返回消息。使用列表、排序键或序列列。-3. **`load` 幂等。** 对同一 thread 两次调用 `load` 应返回相同结果。(CubePi 只调用一次,但工具往往也需要调用。)+3. **`load` 幂等。** 对同一 thread 两次调用 `load` 应返回相同结果。(CubeLoop 只调用一次,但工具往往也需要调用。)4. **`extra` 是合并语义。** 先调用 `save_extra({"a": 1})` 后调用 `save_extra({"b": 2})` 应得到 `{"a": 1, "b": 2}`,而非仅 `{"b": 2}`。agent 携带完整字典调用,但 middleware 会分多次写入。5. **用 `model_validate` 重建消息。** 使用 role 判别符(`UserMessage` / `AssistantMessage` / `ToolResultMessage`)选择正确的类。@@ -139,8 +139,8 @@ agent = Agent(model=…, checkpointer=FileCheckpointer("/tmp/cp"), thread_id="x"使用 `FauxProvider` 的即插即用测试模式:```python-from cubepi import Agent-from cubepi.providers import FauxProvider, faux_assistant_message+from cubeloop import Agent+from cubeloop.providers import FauxProvider, faux_assistant_messageasync def test_roundtrip():cp = MyCheckpointer(…)@@ -165,13 +165,13 @@ async def test_roundtrip():## 常见陷阱-- **修改返回的 `CheckpointData`** —— 要么在传入时深拷贝,要么在文档中说明 agent 拥有该列表的所有权。CubePi 内置实现会进行拷贝。+- **修改返回的 `CheckpointData`** —— 要么在传入时深拷贝,要么在文档中说明 agent 拥有该列表的所有权。CubeLoop 内置实现会进行拷贝。- **丢失 `metadata`** —— `model_dump(mode="json")` 会保留 `metadata`。若通过 `__dict__` 序列化则会丢失。- **`save_extra` 合并的竞态问题** —— 读-改-写模式在并发写入时可能丢失数据。若有针对同一 thread 的并发写入者,请使用 SQL `JSONB ||` 或 Redis Lua 脚本。- **忘记注册 tool result 的 role** —— 容易只映射 `"user"` 和 `"assistant"` 而忘记 `"tool_result"`。三者都需要。## 另请参阅-- [`Checkpointer` Protocol API](../../api/cubepi-checkpointer) —— 完整签名。-- [SQLiteCheckpointer 源码](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/sqlite.py) —— 完整参考实现。-- [PostgresCheckpointer 源码](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/postgres/checkpointer.py) —— 生产级参考实现。+- [`Checkpointer` Protocol API](../../api/cubeloop-checkpointer) —— 完整签名。+- [SQLiteCheckpointer 源码](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/checkpointer/sqlite.py) —— 完整参考实现。+- [PostgresCheckpointer 源码](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/checkpointer/postgres/checkpointer.py) —— 生产级参考实现。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.mdindex 8329d0b..fab1637 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/mysql.md@@ -1,6 +1,6 @@---title: MySQL 检查点-description: "在 CubePi 中使用 MySQLCheckpointer 通过 MySQL 后端实现 agent 状态持久化。"+description: "在 CubeLoop 中使用 MySQLCheckpointer 通过 MySQL 后端实现 agent 状态持久化。"---# MySQL Checkpointing@@ -12,7 +12,7 @@ description: "在 CubePi 中使用 MySQLCheckpointer 通过 MySQL 后端实现 a安装额外依赖:```bash-pip install "cubepi[mysql]"+pip install "cubeloop[mysql]"```这会安装 `aiomysql`、`sqlalchemy` 和 `msgpack`。@@ -21,9 +21,9 @@ pip install "cubepi[mysql]"```pythonimport asyncio-from cubepi import Agent-from cubepi.checkpointer import MySQLCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import MySQLCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -53,47 +53,47 @@ async with MySQLCheckpointer(## Schema-Checkpointer 需要三张表:`cubepi_threads`、`cubepi_messages` 和 `cubepi_schema_version`。与 Postgres 一样(与 SQLite 不同),CubePi **不会为你创建这些表**——它会在 `__aenter__` 时验证这些表是否存在并具有预期的 `schema_version`。+Checkpointer 需要这些表:`cubeloop_threads`、`cubeloop_messages`、`cubeloop_runs`、`cubeloop_hitl_answers` 和 `cubeloop_schema_version`。与 Postgres 一样(与 SQLite 不同),CubeLoop **不会为你创建这些表**——它会在 `__aenter__` 时验证这些表是否存在并具有预期的 `schema_version`。-若表不存在,会抛出 `CubepiSchemaUninitialized`;若版本与当前 CubePi 版本不匹配,会抛出 `CubepiSchemaMismatch`。生产数据库应由宿主应用的迁移系统(Alembic 等)管理,而非由第三方库管理。+若表不存在,会抛出 `CubeloopSchemaUninitialized`;若版本与当前 CubeLoop 版本不匹配,会抛出 `CubeloopSchemaMismatch`。生产数据库应由宿主应用的迁移系统(Alembic 等)管理,而非由第三方库管理。### 通过 Alembic 初始化 Schema-CubePi 暴露了 SQLAlchemy 的 `MetaData`,供你的迁移脚本采用该 schema:+CubeLoop 暴露了 SQLAlchemy 的 `MetaData`,供你的迁移脚本采用该 schema:```python# alembic/env.py-from cubepi.checkpointer.mysql import cubepi_metadata, EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.mysql import cubeloop_metadata, EXPECTED_SCHEMA_VERSION-target_metadata = [my_app_metadata, cubepi_metadata]+target_metadata = [my_app_metadata, cubeloop_metadata]```然后自动生成一个 revision:```bash-alembic revision --autogenerate -m "add cubepi checkpointer"+alembic revision --autogenerate -m "add cubeloop checkpointer"```-`cubepi_messages` 表使用 `KEY` 分区,SQLAlchemy 的自动生成无法表达这一点,因此需要使用提供的辅助函数手动追加分区子句和 schema 版本写入:+`cubeloop_messages` 表使用 `KEY` 分区,SQLAlchemy 的自动生成无法表达这一点,因此需要使用提供的辅助函数手动追加分区子句和 schema 版本写入:```python# In a migration's upgrade():-from cubepi.checkpointer.mysql.alembic_helpers import (+from cubeloop.checkpointer.mysql.alembic_helpers import (messages_partition_clause,write_schema_version_op,)def upgrade():- op.create_table("cubepi_threads", ...)+ op.create_table("cubeloop_threads", ...)op.create_table(- "cubepi_messages", ...,+ "cubeloop_messages", ...,mysql_engine="InnoDB",)# KEY(thread_id) partitioning is not autogenerated — apply it explicitly:op.execute(- "ALTER TABLE cubepi_messages " + messages_partition_clause()+ "ALTER TABLE cubeloop_messages " + messages_partition_clause())- op.create_table("cubepi_schema_version", ...)+ op.create_table("cubeloop_schema_version", ...)# write_schema_version_op() returns two ';'-separated statements# (DELETE then INSERT). MySQL/pymysql runs one statement per execute,# so split and execute each:@@ -102,7 +102,7 @@ def upgrade():op.execute(stmt)```-`write_schema_version_op()` 是幂等的:它会删除旧 CubePi 版本的记录行并插入当前版本。当 CubePi 之后更新 `EXPECTED_SCHEMA_VERSION` 时,生成新的 revision 并再次运行即可。+`write_schema_version_op()` 是幂等的:它会删除旧 CubeLoop 版本的记录行并插入当前版本。当 CubeLoop 之后更新 `EXPECTED_SCHEMA_VERSION` 时,生成新的 revision 并再次运行即可。## 数据模型@@ -128,7 +128,7 @@ cubepi_schema_version重要特性:- **`(thread_id, seq)` 是消息的唯一标识。** `seq` 在每个 thread 内单调递增,在对 thread 行持有 `SELECT … FOR UPDATE` 行锁的情况下分配。同一 thread 的两个并发写入者可以干净地串行化。-- **`payload` 是 msgpack 编码的 `model.model_dump(mode="json")`。** CubePi 在读取时重建 Pydantic 模型。+- **`payload` 是 msgpack 编码的 `model.model_dump(mode="json")`。** CubeLoop 在读取时重建 Pydantic 模型。- **`metadata` 是 JSON,可通过 MySQL JSON 函数查询。** 它**未**建立索引——MySQL 无法直接对 JSON 列建索引。若需要按 metadata 查询消息,请在宿主侧添加生成列索引。- **消息按 `KEY(thread_id)` 分区为 64 个分区。** 分布均匀,无 per-thread 瓶颈。该表对 `cubepi_threads` **没有外键**(MySQL 禁止对分区表使用外键);完整性由 `append` 时的惰性 thread 行插入来保证。@@ -152,8 +152,8 @@ cubepi_schema_version`MySQLCheckpointer` 实现了 v4 的 `snapshot` / `fork` /`claim_run` / `mark_run_complete` / `load_pending` 协议方法,因此同时支持 `Agent.fork(...)` 和 `Agent.fork_once(...)`。-`cubepi_threads` 上的 `parent_thread_id` / `forked_at_seq` 列-用于记录 fork 谱系;v4 新增的 `cubepi_runs` 表用于追踪每个 run+`cubeloop_threads` 上的 `parent_thread_id` / `forked_at_seq` 列+用于记录 fork 谱系;v4 新增的 `cubeloop_runs` 表用于追踪每个 run的 claim/completion 状态。用户层 API 与语义详见@@ -168,7 +168,7 @@ Fork 功能将 `EXPECTED_SCHEMA_VERSION` 从 3 升到 4。升级会向```python# 在迁移的 upgrade() 中:-from cubepi.checkpointer.mysql.alembic_helpers import (+from cubeloop.checkpointer.mysql.alembic_helpers import (upgrade_v3_to_v4_op,write_schema_version_op,)@@ -186,10 +186,33 @@ def upgrade():保留 `run_id = NULL`,仍然可读;关于混合数据的 fork 资格规则,请参阅 [旧数据行为](../agents/forking#legacy-data-behaviour)。+## Schema v5 → v6 migration++0.14 把 MySQL 表从 `cubepi_*` 重命名为 `cubeloop_*`。+`EXPECTED_SCHEMA_VERSION` 为 6。在已有库上打开 0.14 checkpointer **之前**执行:++```python+from cubeloop.checkpointer.mysql.alembic_helpers import (+ upgrade_v5_to_v6_op,+ write_schema_version_op,+)++def upgrade():+ for stmt in upgrade_v5_to_v6_op().split(";"):+ if stmt.strip():+ op.execute(stmt)+ for stmt in write_schema_version_op().split(";"):+ if stmt.strip():+ op.execute(stmt)+```++不要对 v5 数据库跑 v6 的 `CREATE TABLE` helper。详见+[从 cubepi 迁移](../../migration/from-cubepi)。+## 常见陷阱-- **`CubepiSchemaUninitialized`** —— 数据库为空、迁移未执行,或 `cubepi_schema_version` 表结构有误。请先应用宿主的 alembic upgrade。-- **`CubepiSchemaMismatch`** —— 升级了 CubePi 但未生成新的迁移。生成迁移、应用后 CubePi 即可启动。+- **`CubeloopSchemaUninitialized`** —— 数据库为空、迁移未执行,或 `cubepi_schema_version` 表结构有误。请先应用宿主的 alembic upgrade。+- **`CubeloopSchemaMismatch`** —— 升级了 CubeLoop 但未生成新的迁移。生成迁移、应用后 CubeLoop 即可启动。- **旧版 MySQL 上的 JSON 默认值错误** —— JSON 列使用 `DEFAULT (JSON_OBJECT())`,需要 MySQL 8.0.13+。- **大小写不敏感的 thread ID 冲突** —— Thread ID 使用 `utf8mb4_bin` 排序规则,因此 `UserA` 和 `usera` 保持区分。若手写 DDL,请保持该排序规则。@@ -198,4 +221,4 @@ def upgrade():- [Postgres Checkpointing](./postgres) —— Postgres 后端的对应文档。- [SQLite Checkpointing](./sqlite) —— 单进程替代方案。- [Custom Backends](./custom) —— Protocol 详情。-- [Package README](https://github.com/cubeplexai/cubepi/blob/main/cubepi/checkpointer/mysql/README.md) —— 与代码同处的完整宿主集成手册。+- [Package README](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/checkpointer/mysql/README.md) —— 与代码同处的完整宿主集成手册。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.mdindex fc6209a..79dacfb 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/postgres.md@@ -12,7 +12,7 @@ description: "使用 PostgresCheckpointer 实现生产级的 agent 状态持久安装 extra:```bash-pip install "cubepi[postgres]"+pip install "cubeloop[postgres]"```会拉入 `asyncpg`、`sqlalchemy` 和 `msgpack`。@@ -21,9 +21,9 @@ pip install "cubepi[postgres]"```pythonimport asyncio-from cubepi import Agent-from cubepi.checkpointer import PostgresCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import PostgresCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -53,68 +53,81 @@ async with PostgresCheckpointer(## Schema-checkpointer 需要三张表:`cubepi_threads`、`cubepi_messages` 和-`cubepi_schema_version`。与 SQLite 不同,CubePi **不会自动创建这些表**——+checkpointer 需要这些表:`cubeloop_threads`、`cubeloop_messages`、+`cubeloop_runs`、`cubeloop_hitl_answers` 和 `cubeloop_schema_version`。+与 SQLite 不同,CubeLoop **不会自动创建这些表**——它只在 `__aenter__` 时验证它们是否存在且 `schema_version` 是否匹配预期。-如果表不存在,你会收到 `CubepiSchemaUninitialized`。如果版本与本版-CubePi 不匹配,你会收到 `CubepiSchemaMismatch`。+如果表不存在,你会收到 `CubeloopSchemaUninitialized`。如果版本与本版+CubeLoop 不匹配,你会收到 `CubeloopSchemaMismatch`。原因:生产数据库属于宿主应用的迁移系统(Alembic、Atlas……),不属于一个可能与你现有迁移冲突的第三方库。### 通过 Alembic 引导 {#bootstrapping-via-alembic}-CubePi 暴露了 SQLAlchemy `MetaData`,让你的迁移可以采用其 schema:+CubeLoop 暴露了 SQLAlchemy `MetaData`,让你的迁移可以采用其 schema:```python# alembic/env.py-from cubepi.checkpointer.postgres import cubepi_metadata, EXPECTED_SCHEMA_VERSION+from cubeloop.checkpointer.postgres import cubeloop_metadata, EXPECTED_SCHEMA_VERSION-target_metadata = [my_app_metadata, cubepi_metadata]+target_metadata = [my_app_metadata, cubeloop_metadata]```-然后生成一个 revision 并执行。迁移还必须在 `cubepi_schema_version` 中-INSERT schema 版本。使用辅助函数:+然后生成一个 revision 并执行。迁移还必须写入 `cubeloop_schema_version`。+使用辅助函数:```python# 在迁移的 upgrade() 中:-from cubepi.checkpointer.postgres.alembic_helpers import (+from cubeloop.checkpointer.postgres.alembic_helpers import (create_message_partitions_op,+ create_runs_partitions_op,write_schema_version_op,)def upgrade():- op.create_table(...) # 从 cubepi_metadata 自动生成- op.execute(create_message_partitions_op()) # 创建 64 个哈希分区+ op.create_table(...) # 从 cubeloop_metadata 自动生成+ op.execute(create_message_partitions_op()) # cubeloop_messages 的 64 个哈希分区+ op.execute(create_runs_partitions_op()) # cubeloop_runs 的 64 个哈希分区op.execute(write_schema_version_op()) # 记录 EXPECTED_SCHEMA_VERSION```两个辅助函数都返回 SQL 字符串——你需要传入 `op.execute(...)`。-`write_schema_version_op()` 是幂等的:它会删除之前 CubePi 版本的所有行,+`write_schema_version_op()` 是幂等的:它会删除之前 CubeLoop 版本的所有行,然后插入当前版本。-当 CubePi 后续升级并提升了 `EXPECTED_SCHEMA_VERSION` 时,生成一个新的+当 CubeLoop 后续升级并提升了 `EXPECTED_SCHEMA_VERSION` 时,生成一个新的revision,再次调用 `op.execute(write_schema_version_op())`。## 数据模型```-cubepi_threads+cubeloop_threadsthread_id (PK)parent_thread_id -- 用于 forkforked_at_seq -- fork 点处的序列号extra -- JSONBcreated_at / updated_at-cubepi_messages+cubeloop_messagesthread_id, seq -- 复合 PK;按 HASH(thread_id) 分为 64 个分区role -- "user" | "assistant" | "tool"metadata -- JSONB(通过 GIN 索引)payload -- bytea (msgpack)created_at-cubepi_schema_version+cubeloop_runs+ thread_id, run_id -- 复合 PK+ claimed_at / completed_at+ completion_seq++cubeloop_hitl_answers+ thread_id, run_id, question_id -- 复合 PK+ answer -- JSONB+ answered_at++cubeloop_schema_versionversion (PK)```@@ -124,7 +137,7 @@ cubepi_schema_version在 `pg_advisory_xact_lock(hashtext(thread_id))` 下分配。两个对同一线程的并发写入者会干净地序列化。- **`payload` 是 msgpack 编码的 `model.model_dump(mode="json")`。**- CubePi 在读取时重建 Pydantic 模型。+ CubeLoop 在读取时重建 Pydantic 模型。- **`metadata` 是 JSONB,可查询。** 完整消息的 payload 内部也包含`metadata`,但这一列是 SQL 查询的规范视图。- **表按 `HASH(thread_id)` 分为 64 个分区。** 跨分区均匀分布,@@ -149,7 +162,7 @@ advisory lock 让同一线程上的追加操作跨进程安全:`save_extra` 做的是 JSONB 合并,而不是替换:```sql-extra = cubepi_threads.extra || EXCLUDED.extra+extra = cubeloop_threads.extra || EXCLUDED.extra```所以先写 `{"foo": 1}` 再写 `{"bar": 2}` 会得到 `{"foo": 1, "bar": 2}`。@@ -159,7 +172,7 @@ extra = cubepi_threads.extra || EXCLUDED.extra`parent_thread_id` + `forked_at_seq` 列用于支持[会话 Fork](../agents/forking):fork 会创建一个新的 thread,并在其-`cubepi_threads` 行中写入指向源 thread 的 `parent_thread_id`,+`cubeloop_threads` 行中写入指向源 thread 的 `parent_thread_id`,以及拷贝时源 thread 末尾的 `forked_at_seq`(最后一条已拷贝消息的`seq`)。@@ -171,7 +184,7 @@ Fork 功能将 `EXPECTED_SCHEMA_VERSION` 从 3 升到 4。升级会向```python# 在迁移的 upgrade() 中:-from cubepi.checkpointer.postgres.alembic_helpers import (+from cubeloop.checkpointer.postgres.alembic_helpers import (upgrade_v3_to_v4_op,write_schema_version_op,)@@ -188,20 +201,39 @@ def upgrade():关于混合数据的 fork 资格规则,请参阅[旧数据行为](../agents/forking#legacy-data-behaviour)。+## Schema v5 → v6 migration++0.14 把 Postgres 表从 `cubepi_*` 重命名为 `cubeloop_*`。+`EXPECTED_SCHEMA_VERSION` 为 6。在已有库上打开 0.14 checkpointer **之前**执行:++```python+from cubeloop.checkpointer.postgres.alembic_helpers import (+ upgrade_v5_to_v6_op,+ write_schema_version_op,+)++def upgrade():+ op.execute(upgrade_v5_to_v6_op())+ op.execute(write_schema_version_op()) # 把 6 写入 cubeloop_schema_version+```++不要对 v5 数据库跑 v6 的 `CREATE TABLE` helper——旧表已经在,只是名字还是 `cubepi_*`。+详见 [从 cubepi 迁移](../../migration/from-cubepi)。+## 常见坑-- **`CubepiSchemaUninitialized`** —— 数据库为空或迁移未运行。+- **`CubeloopSchemaUninitialized`** —— 数据库为空或迁移未运行。先执行宿主 alembic upgrade。-- **`CubepiSchemaMismatch`** —— 你升级了 CubePi 但未生成新的迁移。- 生成一个、执行它,CubePi 就会启动。+- **`CubeloopSchemaMismatch`** —— 你升级了 CubeLoop 但未生成新的迁移。+ 生成一个、执行它,CubeLoop 就会启动。:::info Schema v2(HITL)- CubePi ≥ HITL 版本将 `EXPECTED_SCHEMA_VERSION` 从 1 提升到 2,+ CubeLoop ≥ HITL 版本将 `EXPECTED_SCHEMA_VERSION` 从 1 提升到 2,并在 `cubepi_threads` 表中新增 `pending_request JSONB NULL` 列。宿主 alembic upgrade 必须在提升 schema_version 行之前调用`add_pending_request_column_op()`(来自- `cubepi.checkpointer.postgres.alembic_helpers`)。+ `cubeloop.checkpointer.postgres.alembic_helpers`)。完整的跨进程流程请参阅 [HITL 指南](../hitl/overview)。:::- **负载下连接池耗尽** —— 默认 `max_pool_size=10`。@@ -209,7 +241,7 @@ def upgrade():- **`asyncpg.exceptions.UndefinedTableError` 在 `__aenter__` 外部** ——表示你在 `async with` 之外使用了 checkpointer。连接池尚未连接。请用 context manager 包裹。-- **混用宿主 SQLAlchemy `MetaData`** —— CubePi 自带独立的+- **混用宿主 SQLAlchemy `MetaData`** —— CubeLoop 自带独立的`MetaData` 实例,正是为了能与你的应用模型共存而不冲突。不要将它们合并到你的全局 metadata 中——分别传给 Alembic。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.mdindex 0d7db03..f678cdb 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/checkpointing/sqlite.md@@ -12,7 +12,7 @@ description: "使用 SQLiteCheckpointer 实现轻量级单进程 agent 状态持安装 extra:```bash-pip install "cubepi[sqlite]"+pip install "cubeloop[sqlite]"```会拉入 `aiosqlite`。@@ -21,9 +21,9 @@ pip install "cubepi[sqlite]"```pythonimport asyncio-from cubepi import Agent-from cubepi.checkpointer import SQLiteCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import SQLiteCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -75,7 +75,7 @@ CREATE TABLE thread_extra (- `AgentContext` 的 `extra` dict 在 `agent_end` 时持久化到 `thread_extra`。Middleware 需要持久化线程级状态时,往 `context.extra` 写。-这个 schema 是追加式的。CubePi 从不 update 或 delete 行。+这个 schema 是追加式的。CubeLoop 从不 update 或 delete 行。## HITL 挂起表@@ -91,9 +91,9 @@ CREATE TABLE IF NOT EXISTS thread_pending_request (无需手动迁移 —— `CREATE TABLE IF NOT EXISTS` 是零等的。-## CubePi 什么时候读+## CubeLoop 什么时候读-构造 Agent 后的 **第一次** `prompt()`,CubePi 会调+构造 Agent 后的 **第一次** `prompt()`,CubeLoop 会调`load(thread_id)`。如果线程存在,历史恢复到 `agent.state.messages`,`extra` 恢复到 agent 私有的 `_extra` dict。@@ -116,7 +116,7 @@ async with SQLiteCheckpointer("agent.db") as cp:## 并发模型Checkpointer 内部对每次读写都用 `asyncio.Lock`。SQLite 本身允许-多进程写,但 CubePi 的假设是单 Agent 实例独占一个 thread。多进程+多进程写,但 CubeLoop 的假设是单 Agent 实例独占一个 thread。多进程同时写同一个 `agent.db`:- 读是安全的。@@ -159,7 +159,7 @@ sqlite3 agent.db "VACUUM"一定要用 `async with` 包。- **两个进程写同一个 thread** —— 交错历史。要么用 Postgres,要么在应用层协调。-- **未启用 WAL 模式** —— CubePi 走默认 journal mode 以确保可移植性。+- **未启用 WAL 模式** —— CubeLoop 走默认 journal mode 以确保可移植性。对单写多读应用,一次性 `sqlite3 agent.db "PRAGMA journal_mode=WAL"`能显著提升并发读。- **忘传 `thread_id`** —— 不传时,Agent 没有持久化绑定。checkpointerdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/middlewares.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/middlewares.mdindex 4076a0f..3ab2ba1 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/middlewares.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/middlewares.md@@ -13,7 +13,7 @@ description: "用 ConfirmToolCallMiddleware / ApprovalPolicyMiddleware 把关工"在集合中的工具名一律询问人类。"```python-from cubepi.hitl import ConfirmToolCallMiddleware+from cubeloop.hitl import ConfirmToolCallMiddlewareagent = Agent(...,@@ -41,7 +41,7 @@ agent = Agent(human-confirm 三类的宿主。```python-from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny+from cubeloop.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Denydef my_policy(ctx):if ctx.tool_call.name == "read_file":@@ -70,7 +70,7 @@ agent = Agent(`"ask_user"` 的 `AgentTool`,`execution_mode="sequential"`。```python-from cubepi.hitl import ask_user_tool+from cubeloop.hitl import ask_user_toolagent = Agent(...,diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/overview.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/overview.mdindex 5ceb0f6..01f21d6 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/overview.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/overview.md@@ -1,12 +1,12 @@---title: 概览sidebar_position: 1-description: "CubePi 人机协同:channel、三种动词(confirm、approve、ask)与超时。"+description: "CubeLoop 人机协同:channel、三种动词(confirm、approve、ask)与超时。"---# 人机协同 (HITL)-CubePi 的 HITL channel 让 agent 能够**暂停并等待人类输入**后再继续。+CubeLoop 的 HITL channel 让 agent 能够**暂停并等待人类输入**后再继续。它用一个统一原语覆盖两种典型模式:1. **沙箱工具确认** —— 危险工具(bash、文件写入、API 变更)在运行前@@ -51,7 +51,7 @@ ID 来关联。- **"其他" 可输入**(选项有 `allow_input=True` —— 用户输入自由文本)```python-from cubepi.hitl.types import Question, Option+from cubeloop.hitl.types import Question, Optionanswers = await channel.ask([Question(key="framework", prompt="选择框架?", options=[diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/reference.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/reference.mdindex 20858c7..011ea9e 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/reference.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/hitl/reference.md@@ -1,7 +1,7 @@---title: API、事件与参考sidebar_position: 4-description: "CubePi HITL 参考:Agent API、事件、追踪 span、错误参考、测试辅助与架构说明。"+description: "CubeLoop HITL 参考:Agent API、事件、追踪 span、错误参考、测试辅助与架构说明。"---# API、事件与参考@@ -30,7 +30,7 @@ description: "CubePi HITL 参考:Agent API、事件、追踪 span、错误参## 追踪 span-安装 `cubepi[tracing]` extra 后,每次 HITL await 都会包装在一个+安装 `cubeloop[tracing]` extra 后,每次 HITL await 都会包装在一个OpenTelemetry span 中:| Span 名称 | 属性 |@@ -59,7 +59,7 @@ OpenTelemetry span 中:| `HitlDurabilityNotGuaranteed` | `Exception` | 自定义工具调了 `CheckpointedChannel.ask()` 但没有 `allow_inside_custom_tool=True` |`HitlControlException`(四个 `BaseException` 子类的父类)**故意**不被-`cubepi.agent.tools._prepare_tool_call` 和 `_execute_prepared` 中现有+`cubeloop.agent.tools._prepare_tool_call` 和 `_execute_prepared` 中现有的广泛 `except Exception:` 处理器捕获 —— 这模仿了 `asyncio.CancelledError`的模式。@@ -67,7 +67,7 @@ OpenTelemetry span 中:## 测试辅助```python-from cubepi.hitl.testing import ScriptedChannel, NoopChannel+from cubeloop.hitl.testing import ScriptedChannel, NoopChannel# ScriptedChannel:预编程答案,按顺序消费ch = ScriptedChannel(answers=[diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/auth.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/auth.mdindex 6044539..4cf50e1 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/auth.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/auth.md@@ -1,6 +1,6 @@---title: MCP 服务器认证-description: "为 CubePi 中的 MCP 服务器配置认证——API 密钥、OAuth 及自定义请求头。"+description: "为 CubeLoop 中的 MCP 服务器配置认证——API 密钥、OAuth 及自定义请求头。"---# MCP 服务器认证@@ -19,7 +19,7 @@ MCP 传输层本身不规定认证方案——由服务器自行决定。实践```pythonimport os-from cubepi.mcp import load_mcp_tools_http+from cubeloop.mcp import load_mcp_tools_httptools = await load_mcp_tools_http(server_url="https://mcp.example.com/sse",@@ -54,7 +54,7 @@ headers = {## HTTP:短期 token / 刷新-CubePi 的加载器在加载时接受静态的 `headers` 字典。对于会过期的 token(OAuth、短 TTL 的 JWT),有两种处理方案:+CubeLoop 的加载器在加载时接受静态的 `headers` 字典。对于会过期的 token(OAuth、短 TTL 的 JWT),有两种处理方案:### 方案 A——到期后重新加载@@ -78,8 +78,8 @@ tools = await load_with_fresh_token()自己构建 `AgentTool`,通过闭包持有刷新逻辑:```python-from cubepi.mcp._adapter import make_mcp_agent_tool-from cubepi.mcp import load_mcp_tools_http+from cubeloop.mcp._adapter import make_mcp_agent_tool+from cubeloop.mcp import load_mcp_tools_httpasync def call_remote_with_refresh(tool_name, args):headers = {"Authorization": f"Bearer {await fetch_token()}"}@@ -109,7 +109,7 @@ stdio 服务器从自身进程环境中读取凭据。传入 `env` 字典即可```pythonimport os-from cubepi.mcp import load_mcp_tools_stdio+from cubeloop.mcp import load_mcp_tools_stdiotools = await load_mcp_tools_stdio(command="npx",diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/loading.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/loading.mdindex ac161c7..353fcb2 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/loading.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/mcp/loading.md@@ -1,16 +1,16 @@---title: 加载 MCP 工具-description: "将 MCP 服务器中的工具加载到 CubePi agent,包括基于 SSE 的远程服务器。"+description: "将 MCP 服务器中的工具加载到 CubeLoop agent,包括基于 SSE 的远程服务器。"---# 加载 MCP 工具-[Model Context Protocol](https://modelcontextprotocol.io) 定义了一套标准方式,让工具服务器向 agent 暴露能力。CubePi 内置两个加载器,可连接 MCP 服务器、枚举其工具,并将每个工具转换为标准的 `AgentTool`,直接传给 `Agent(tools=…)` 使用。+[Model Context Protocol](https://modelcontextprotocol.io) 定义了一套标准方式,让工具服务器向 agent 暴露能力。CubeLoop 内置两个加载器,可连接 MCP 服务器、枚举其工具,并将每个工具转换为标准的 `AgentTool`,直接传给 `Agent(tools=…)` 使用。安装额外依赖:```bash-pip install "cubepi[mcp]"+pip install "cubeloop[mcp]"```这将引入 `mcp` SDK。@@ -22,9 +22,9 @@ pip install "cubepi[mcp]"```pythonimport asyncioimport sys-from cubepi import Agent-from cubepi.mcp import load_mcp_tools_stdio-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.mcp import load_mcp_tools_stdio+from cubeloop.providers.anthropic import AnthropicProviderasync def main():@@ -63,7 +63,7 @@ asyncio.run(main())适用于托管的 MCP 服务器(Sentry、GitHub、内部服务等):```python-from cubepi.mcp import load_mcp_tools_http+from cubeloop.mcp import load_mcp_tools_httptools = await load_mcp_tools_http(server_url="https://mcp.example.com/sse",@@ -106,14 +106,14 @@ agent = Agent(:::tip MCP server 很多?延迟加载它们如果你接了好几个 MCP server、但每次对话只用到其中一两个,把每个 server的 schema 全部塞进 system prompt 就成了主要的上下文成本。把每组 tool-包成一个 [`DeferredToolGroup`](../middleware/deferred-tools)——CubePi 会把+包成一个 [`DeferredToolGroup`](../middleware/deferred-tools)——CubeLoop 会把完整 schema 换成一份紧凑目录,让模型通过内置的 `load_tools` 工具按需展开。:::## 按次连接与复用连接-CubePi 每次 `execute` 调用都会建立新的传输连接。这样做:+CubeLoop 每次 `execute` 调用都会建立新的传输连接。这样做:- ✅ 简单——无需管理连接池的生命周期。- ✅ 健壮——挂起的连接不会污染其他工具。@@ -123,7 +123,7 @@ CubePi 每次 `execute` 调用都会建立新的传输连接。这样做:## 图片与结构化内容-如果 MCP 工具返回图片内容块,CubePi 会将其映射为 `ImageContent` 并包含在 `AgentToolResult.content` 中。Anthropic provider 会将其作为工具结果中的图片块转发;OpenAI provider 目前会将其去除(wire 格式不支持携带图片的工具结果)。+如果 MCP 工具返回图片内容块,CubeLoop 会将其映射为 `ImageContent` 并包含在 `AgentToolResult.content` 中。Anthropic provider 会将其作为工具结果中的图片块转发;OpenAI provider 目前会将其去除(wire 格式不支持携带图片的工具结果)。如果服务器返回 `structuredContent`,它会暴露在 `AgentToolResult.details["structuredContent"]` 下——便于下游代码访问,但不会展示给模型。@@ -138,7 +138,7 @@ CubePi 每次 `execute` 调用都会建立新的传输连接。这样做:- [MCP 认证](./auth) —— Bearer token、请求头、基于环境变量的凭据。- [工具使用](../agents/tool-use) —— 工具(MCP 或其他)的分发机制。-- [`make_mcp_agent_tool` 源码](https://github.com/cubeplexai/cubepi/blob/main/cubepi/mcp/_adapter.py) —— schema → Pydantic 适配器,如需自定义可参考。+- [`make_mcp_agent_tool` 源码](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/mcp/_adapter.py) —— schema → Pydantic 适配器,如需自定义可参考。- [延迟工具组](../middleware/deferred-tools) —— 把 MCP schema 从 systemprompt 里藏起来,让模型按需展开。当多个 MCP server 加起来构成一个上下文沉重的工具集时很有用。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.mdindex 530ed11..d49e60f 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/compaction.md@@ -1,6 +1,6 @@---title: 上下文压缩-description: "使用 CompactionMiddleware 总结较早轮次,同时保留完整 CubePi 历史。"+description: "使用 CompactionMiddleware 总结较早轮次,同时保留完整 CubeLoop 历史。"---# 上下文压缩@@ -14,8 +14,8 @@ description: "使用 CompactionMiddleware 总结较早轮次,同时保留完用便宜模型做摘要,用正常模型运行 agent:```python-from cubepi import Agent-from cubepi.middleware import CompactionMiddleware+from cubeloop import Agent+from cubeloop.middleware import CompactionMiddlewareagent = Agent(model=provider.model("claude-sonnet-4-6"),@@ -44,7 +44,7 @@ middleware 会向 `AgentContext.extra` 写入两个键:- `compaction` —— 摘要状态,以及它覆盖的消息引用。- `compaction_until_msg_index` —— 已总结到的历史边界。-绑定 checkpointer 时,CubePi 会在 `agent_end` 通过 `save_extra` 保存+绑定 checkpointer 时,CubeLoop 会在 `agent_end` 通过 `save_extra` 保存`ctx.extra`,所以下一个进程可以带着已有摘要继续。如果消息引用与当前历史不再匹配,middleware 会清除旧状态并重新开始,而不是发送无效摘要。@@ -54,7 +54,7 @@ middleware 会向 `AgentContext.extra` 写入两个键:之间的那些调用——并沿两个维度触发:- **真实 token 阈值。** 触发判据用*真实*上下文占用与 `max_tokens_before_compact`- 比较。CubePi 把估算锚定到上一轮的真实 provider usage ——+ 比较。CubeLoop 把估算锚定到上一轮的真实 provider usage ——`input_tokens + cache_read_tokens + cache_write_tokens` ——所以在 promptcaching 下依然准确(此时大部分 prompt 由缓存提供,纯字符估算根本看不到)。首次模型响应前(还没有 usage)回退到字符估算。零值的 error/abort 消息会被@@ -89,22 +89,22 @@ CompactionMiddleware(## Tracing-挂上 `cubepi.tracing` 时,摘要调用是 trace 树里的一等公民。`summarize()`-在 LLM 调用外包一个 `cubepi.compaction.summarize` 父 span(标签-`cubepi.compaction.message_count`),同时 recorder 自动订阅 summary+挂上 `cubeloop.tracing` 时,摘要调用是 trace 树里的一等公民。`summarize()`+在 LLM 调用外包一个 `cubeloop.compaction.summarize` 父 span(标签+`cubeloop.compaction.message_count`),同时 recorder 自动订阅 summaryprovider,所以它的 `chat` span 也落在里面:```invoke_agent-└── cubepi.turn- ├── cubepi.compaction.summarize+└── cubeloop.turn+ ├── cubeloop.compaction.summarize│ └── chat <summary-model>└── chat <main-model>```没装 OpenTelemetry 时,wrapper span 退化为 no-op context manager,中间件行为不变。根 `invoke_agent` span 的 `gen_ai.provider.name` /-`cubepi.agent.system_prompt_sha256` / `cubepi.agent.tools` 始终归属+`cubeloop.agent.system_prompt_sha256` / `cubeloop.agent.tools` 始终归属agent 的主 provider/model,不会被先跑的 summarizer 覆盖。## 摘要结构@@ -175,7 +175,7 @@ CompactionMiddleware(## 失败行为-如果摘要 provider 失败,CubePi 会用基于消息结构的**确定性 fallback**+如果摘要 provider 失败,CubeLoop 会用基于消息结构的**确定性 fallback**(用户请求首行 + 出现过的工具名)来生成摘要,让上下文继续收缩。连续 3 次LLM 失败后**熔断器**打开,跳过 LLM 调用——但 fallback 仍然运行,agent 不会因为 summariser 模型故障而卡在超限状态。下一次 LLM 成功调用@@ -191,16 +191,16 @@ agent 不会因为 summariser 模型故障而卡在超限状态。下一次 LLM压缩总结的是*旧*历史,但它无法缩小一个模型在**当前**轮必须读取的单个工具结果——如果某个工具返回的内容超过上下文窗口能容纳的量,再多摘要也无济于事。-限制它是*上层应用*的职责,因为 CubePi 是环境无关的:它没有文件系统、会话目录+限制它是*上层应用*的职责,因为 CubeLoop 是环境无关的:它没有文件系统、会话目录或对象存储可以把溢出内容写进去,而内容落到哪里由你决定。接入点是 `after_tool_call` middleware hook。检查结果、把完整内容持久化到你的环境里,再返回一个包含预览 + 模型可追溯引用的替换内容:```python-from cubepi.middleware import Middleware-from cubepi.agent.types import AfterToolCallContext, AfterToolCallResult-from cubepi.providers.base import TextContent+from cubeloop.middleware import Middleware+from cubeloop.agent.types import AfterToolCallContext, AfterToolCallResult+from cubeloop.providers.base import TextContentclass BoundToolResults(Middleware):def __init__(self, *, max_chars: int = 20_000) -> None:@@ -222,7 +222,7 @@ class BoundToolResults(Middleware):)```-CubePi 从不解析 `ref` ——磁盘路径、对象存储 key、数据库 id,或一个纯截断标记+CubeLoop 从不解析 `ref` ——磁盘路径、对象存储 key、数据库 id,或一个纯截断标记都同样有效。这样工具输出策略就留在真正掌握环境的那一层。## 什么时候不用diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.mdindex 2ec1903..9b417b5 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/composition.md@@ -1,11 +1,11 @@---title: 组合规则-description: "了解 CubePi 如何通过 per-hook 规则组合多个中间件。"+description: "了解 CubeLoop 如何通过 per-hook 规则组合多个中间件。"---# 组合规则-当你传入多个中间件——`Agent(middleware=[m1, m2, m3])`——CubePi 按照+当你传入多个中间件——`Agent(middleware=[m1, m2, m3])`——CubeLoop 按照**每个 hook 各自的规则**进行组合。正确的理解方式是:每个 hook 采用最适合其工作的组合规则,你不需要记忆 "before" 或 "after" 优先级猜测。@@ -42,7 +42,7 @@ agent = Agent(## `convert_to_llm`有意采用最后胜出:这是发送前的最终转换。多个所有者会打架;只选一个。-CubePi 强制**列表中的最后一个**实现了 `convert_to_llm` 的中间件运行。+CubeLoop 强制**列表中的最后一个**实现了 `convert_to_llm` 的中间件运行。如果你发现自己需要两个 `convert_to_llm` 中间件,将它们合并为一个(调用点组合:写一个调用两者的中间件)。@@ -84,7 +84,7 @@ agent = Agent(## `after_tool_call`每个中间件可以返回一个设置了部分字段的 `AfterToolCallResult`;-CubePi 合并它们,后面的结果在非 `None` 字段上覆盖前面的。完整结果:+CubeLoop 合并它们,后面的结果在非 `None` 字段上覆盖前面的。完整结果:```pythonclass AfterToolCallResult(BaseModel):@@ -166,7 +166,7 @@ agent = Agent(class JustTransform(Middleware):async def transform_context(self, messages, *, ctx, signal=None):return messages[-10:]- # 没有其他 hook。CubePi 不会调用它们。+ # 没有其他 hook。CubeLoop 不会调用它们。```## `on_run_end`diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/deferred-tools.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/deferred-tools.mdindex 8b71845..32a3be9 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/deferred-tools.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/deferred-tools.md@@ -70,8 +70,8 @@ to get their full schemas, then invoke them via向 `Agent` 传入 `deferred_tool_groups`,中间件自动创建,无需手动接线:```python-from cubepi import Agent-from cubepi.deferred import DeferredToolGroup+from cubeloop import Agent+from cubeloop.deferred import DeferredToolGroup# load_github_tools / load_linear_tools 是零参 async 可调用对象,# 返回 list[AgentTool]。具体怎么写见下面的「编写 loader」一节,@@ -113,7 +113,7 @@ agent = Agent(### 编写 loader-`loader` 是一个零参 async 可调用对象,返回 `list[AgentTool]`。CubePi+`loader` 是一个零参 async 可调用对象,返回 `list[AgentTool]`。CubeLoop只看返回类型——里面的 `AgentTool` 怎么来由你决定。两种典型写法:**从 MCP server 加载。** `load_mcp_tools_stdio` / `load_mcp_tools_http`@@ -121,8 +121,8 @@ agent = Agent(`list[AgentTool]`。包一层:```python-from cubepi.deferred import DeferredToolGroup-from cubepi.mcp import load_mcp_tools_stdio+from cubeloop.deferred import DeferredToolGroup+from cubeloop.mcp import load_mcp_tools_stdioasync def load_github_tools():result = await load_mcp_tools_stdio(@@ -150,8 +150,8 @@ server 发布的是 `github_create_issue`,选择性展开就匹配不到。loader 就是一个返回列表的 async 函数:```python-from cubepi import tool-from cubepi.deferred import DeferredToolGroup+from cubeloop import tool+from cubeloop.deferred import DeferredToolGroup@toolasync def create_issue(*, repo: str, title: str, body: str) -> str:@@ -239,7 +239,7 @@ ctx.extra["expanded_groups"] = {中间件的 strategy 一致:```python-from cubepi.deferred import DeferredToolsMiddleware+from cubeloop.deferred import DeferredToolsMiddleware# saved_extra 是上一个 run 持久化的 ctx.extraresumed = await DeferredToolsMiddleware.prepare_resumed_state(@@ -273,7 +273,7 @@ dispatch 模式下没有其他要恢复的东西:模型见过的 schema 留在`DeferredToolsMiddleware`:```python-from cubepi.deferred import DeferredToolsMiddleware+from cubeloop.deferred import DeferredToolsMiddlewaremw = DeferredToolsMiddleware(groups=[github_group, linear_group],@@ -305,7 +305,7 @@ agent = Agent(## 从 0.10 迁移-延迟工具组在 CubePi 0.10 发布时的行为即现在的 `inject` 策略。升级后+延迟工具组在 CubeLoop 0.10 发布时的行为即现在的 `inject` 策略。升级后行为变化:- **默认策略现在是 `dispatch`。** 目录措辞改变,出现 `deferred_tool_call`diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.mdindex 97eec8c..4dd0f95 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/examples.md@@ -1,6 +1,6 @@---title: 示例-description: "CubePi 中间件实用示例:速率限制、重试、结构化日志、上下文截断和 HITL。"+description: "CubeLoop 中间件实用示例:速率限制、重试、结构化日志、上下文截断和 HITL。"---# 中间件示例@@ -14,8 +14,8 @@ description: "CubePi 中间件实用示例:速率限制、重试、结构化```pythonimport time-from cubepi import Middleware-from cubepi.agent.types import BeforeToolCallResult+from cubeloop import Middleware+from cubeloop.agent.types import BeforeToolCallResultclass RateLimitMiddleware(Middleware):@@ -51,8 +51,8 @@ agent = Agent(model=…, middleware=[RateLimitMiddleware(max_calls_per_min=30)])```pythonimport asyncio-from cubepi import Middleware-from cubepi.agent.types import AfterToolCallResult+from cubeloop import Middleware+from cubeloop.agent.types import AfterToolCallResultclass RetryMiddleware(Middleware):@@ -102,9 +102,9 @@ class RetryMiddleware(Middleware):```pythonimport time, logging-from cubepi import Middleware+from cubeloop import Middleware-log = logging.getLogger("cubepi.tools")+log = logging.getLogger("cubeloop.tools")class ToolLoggingMiddleware(Middleware):@@ -138,7 +138,7 @@ class ToolLoggingMiddleware(Middleware):通过仅保留最近的 N 条消息(加上 system prompt)来保持模型上下文边界:```python-from cubepi import Middleware+from cubeloop import Middlewareclass SlidingWindow(Middleware):@@ -181,7 +181,7 @@ class MaxTurns(Middleware):class BudgetCap(Middleware):def __init__(self, usd: float, model_cost) -> None:self.cap = usd- self.cost = model_cost # cubepi.providers.ModelCost 或类似+ self.cost = model_cost # cubeloop.providers.ModelCost 或类似self.spent = 0.0async def should_stop_after_turn(self, ctx):@@ -200,9 +200,9 @@ class BudgetCap(Middleware):```pythonimport json-from cubepi import Middleware-from cubepi.middleware.base import TurnAction-from cubepi.providers.base import TextContent, UserMessage+from cubeloop import Middleware+from cubeloop.middleware.base import TurnAction+from cubeloop.providers.base import TextContent, UserMessageclass JSONOutputValidator(Middleware):@@ -230,12 +230,12 @@ Agent 将跳过工具执行,并立即用上下文中的反馈消息重新提## 人机协同工具确认-CubePi 在 `cubepi.hitl` 中内置了两个 HITL 中间件:+CubeLoop 在 `cubeloop.hitl` 中内置了两个 HITL 中间件:**`ConfirmToolCallMiddleware`** —— "对此工具始终询问人类":```python-from cubepi.hitl import ConfirmToolCallMiddleware, InMemoryChannel+from cubeloop.hitl import ConfirmToolCallMiddleware, InMemoryChannelchannel = InMemoryChannel()agent = Agent(@@ -256,7 +256,7 @@ Agent 在每次 `bash` 或 `write_file` 调用时暂停,等待宿主调用**`ApprovalPolicyMiddleware`** —— 适用于通过策略引擎对工具调用进行分类的宿主:```python-from cubepi.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Deny+from cubeloop.hitl import Approve, ApprovalPolicyMiddleware, AskUser, Denydef my_policy(ctx):if ctx.tool_call.name in ("read_file", "grep"):diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/goal.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/goal.mdindex d664a52..6fc6015 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/goal.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/goal.md@@ -15,9 +15,9 @@ description: "用 GoalMiddleware 让 agent 持续运行,直到一个独立的## 基础用法```python-from cubepi import Agent-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.middleware.goal import GoalMiddleware+from cubeloop import Agent+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.middleware.goal import GoalMiddlewareprovider = AnthropicProvider(api_key="...")diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.mdindex e2e6965..5e8f23a 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/hooks.md@@ -1,15 +1,15 @@---title: 9 个 Hook-description: "CubePi 的 9 个中间件 hook 参考——transform_context、resolve_tool_call、before_tool_call、after_tool_call、on_run_end 等。"+description: "CubeLoop 的 9 个中间件 hook 参考——transform_context、resolve_tool_call、before_tool_call、after_tool_call、on_run_end 等。"---# 9 个 Hook`Middleware` 是一个最多包含九个可选异步方法的类。每个 hook 在 agent-循环中的精确位置触发。只实现你需要的——CubePi 只会连接你重写了的方法。+循环中的精确位置触发。只实现你需要的——CubeLoop 只会连接你重写了的方法。```python-from cubepi import Middleware+from cubeloop import Middlewareclass MyMiddleware(Middleware):async def transform_context(self, messages, *, ctx, signal=None):@@ -120,7 +120,7 @@ context 提供:- `ctx.context` —— 完整的 `AgentContext`。返回 `BeforeToolCallResult(block=True, reason="…")` 以短路——-CubePi 会将该原因作为工具结果返回,并标记 `is_error=True`。+CubeLoop 会将该原因作为工具结果返回,并标记 `is_error=True`。返回 `None`(或无返回)则继续执行。用于:权限控制、速率限制、dry-run 模式、沙箱、@@ -179,8 +179,8 @@ async def after_model_response(在任何工具调用分发**之前**。该 hook 返回一个 `TurnAction`:```python-from cubepi.middleware.base import TurnAction-from cubepi.providers.base import synthetic_user_message+from cubeloop.middleware.base import TurnAction+from cubeloop.providers.base import synthetic_user_messageTurnAction(response=modified_message, # 替换消息;None 则保留原消息@@ -248,7 +248,7 @@ synthetic 标记。的 hook 会抛出 `NotImplementedError`,但 `compose_middleware` 会自动跳过它们。```python-from cubepi import Middleware+from cubeloop import Middlewareclass MaxTurnsMiddleware(Middleware):def __init__(self, max_turns: int) -> None:diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/subagents.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/subagents.mdindex 399920e..9c7935c 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/subagents.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/subagents.md@@ -1,11 +1,11 @@---title: 子 Agent-description: "使用 SubagentMiddleware 把自包含任务委派给 CubePi 子 Agent。"+description: "使用 SubagentMiddleware 把自包含任务委派给 CubeLoop 子 Agent。"---# 子 Agent-`SubagentMiddleware` 会添加一个 `subagent` 工具。模型调用该工具时,CubePi+`SubagentMiddleware` 会添加一个 `subagent` 工具。模型调用该工具时,CubeLoop创建一个临时子 `Agent`,运行一段自包含 prompt,并把子 agent 最终 assistant文本作为工具结果返回。@@ -14,8 +14,8 @@ description: "使用 SubagentMiddleware 把自包含任务委派给 CubePi 子 A## 定义子 agent```python-from cubepi import Agent-from cubepi.middleware import SubagentMiddleware, SubagentSpec+from cubeloop import Agent+from cubeloop.middleware import SubagentMiddleware, SubagentSpecsubagents = {"researcher": SubagentSpec(@@ -44,7 +44,7 @@ agent = Agent()```-如果模型请求未知 `subagent_type`,CubePi 回退到 `general-purpose` 子 agent。+如果模型请求未知 `subagent_type`,CubeLoop 回退到 `general-purpose` 子 agent。如果你没有定义它,middleware 会提供一个基础默认版本。## 工具访问和 middleware 继承@@ -85,7 +85,7 @@ SubagentMiddleware(## Tracing 和 abort通过 `tracer=...` 传入 `Tracer`,即可给每个子运行附加 tracing。嵌套子-agent span 共享父 trace,所以 `cubepi trace view <trace_id>` 会把父工具调用+agent span 共享父 trace,所以 `cubeloop trace view <trace_id>` 会把父工具调用和子运行一起渲染出来。父运行的 abort signal 会转发给子 agent。如果父运行在子 agent 执行中被diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.mdindex 14fa7a3..8e53b5c 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/middleware/todo.md@@ -14,8 +14,8 @@ description: "使用 TodoListMiddleware 给 agent 添加 write_todos 工具,`TodoListMiddleware` 需要一个 `extra_ref` 可调用对象,它必须返回 `AgentContext.extra` 的实时引用。middleware 和工具都通过这个引用读写状态,从而在 checkpoint 后存活。```python-from cubepi import Agent-from cubepi.middleware import TodoListMiddleware+from cubeloop import Agent+from cubeloop.middleware import TodoListMiddlewareagent_extra: dict = {}@@ -31,9 +31,9 @@ agent = Agent(当 agent 使用 checkpointer 时,`extra_ref` 必须指向 `AgentContext.extra` 的同一个对象,这样 todo 状态才能跨会话持久化和恢复:```python-from cubepi import Agent-from cubepi.checkpointer import PostgresCheckpointer-from cubepi.middleware import TodoListMiddleware+from cubeloop import Agent+from cubeloop.checkpointer import PostgresCheckpointer+from cubeloop.middleware import TodoListMiddlewarectx_holder: dict[str, dict] = {}diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.mdindex c493b22..711848a 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/anthropic.md@@ -1,6 +1,6 @@---title: Anthropic-description: "通过 AnthropicProvider 在 CubePi 中使用 Claude 模型——支持思考、缓存和工具调用。"+description: "通过 AnthropicProvider 在 CubeLoop 中使用 Claude 模型——支持思考、缓存和工具调用。"---# Anthropic Provider@@ -11,7 +11,7 @@ description: "通过 AnthropicProvider 在 CubePi 中使用 Claude 模型——## 构造```python-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(api_key="sk-ant-…", # 也可让 SDK 自己读 ANTHROPIC_API_KEY@@ -35,13 +35,13 @@ model = provider.model()```-第一个参数就是你传给 SDK 的模型名。`provider_id` 是 CubePi 内部用的+第一个参数就是你传给 SDK 的模型名。`provider_id` 是 CubeLoop 内部用的自由标签 —— 保持稳定即可,需要时可以让 tracing 和错误信息显示一个明确的来源标签。## 扩展思考-CubePi 把 `ThinkingLevel` 枚举映射到 Anthropic 的 `budget_tokens`:+CubeLoop 把 `ThinkingLevel` 枚举映射到 Anthropic 的 `budget_tokens`:| Level | 默认 budget ||---|---|@@ -60,9 +60,9 @@ agent = Agent(model=model, thinking="medium")要自定义 budget,可以通过自己的 `on_payload` hook 传入`StreamOptions(thinking_budgets=ThinkingBudgets(low=4096, medium=12288))`。-思考打开时,CubePi **会把 `temperature` 字段省掉** —— 因为 Anthropic+思考打开时,CubeLoop **会把 `temperature` 字段省掉** —— 因为 AnthropicAPI 在扩展思考模式下不接受非默认的 temperature([兼容性文档](https://platform.claude.com/docs/en/build-with-claude/extended-thinking#feature-compatibility))。-关闭思考时再按 `Model.temperature` 走;CubePi 自己处理切换。+关闭思考时再按 `Model.temperature` 走;CubeLoop 自己处理切换。思考内容以 `thinking_start` / `thinking_delta` / `thinking_end` 事件流式产出,最终作为 `ThinkingContent` 块保存在 `AssistantMessage.content`@@ -89,7 +89,7 @@ AnthropicProvider(provider_id="anthropic", api_key=…, cache_retention="none")需要自定义缓存策略(比如换个断点策略)?实现 `CacheMarkerPolicy`Protocol 然后 `cache_policy=…` 传入。默认策略类位于-`cubepi.providers.anthropic.DefaultCacheMarkerPolicy`。+`cubeloop.providers.anthropic.DefaultCacheMarkerPolicy`。## 用 `on_payload` 自定义请求@@ -125,7 +125,7 @@ agent = Agent(model=model, on_response=my_response)## 指向 Bedrock / Vertex / 代理-Anthropic SDK 接受 `base_url`,CubePi 透传:+Anthropic SDK 接受 `base_url`,CubeLoop 透传:```pythonprovider = AnthropicProvider(@@ -139,10 +139,10 @@ provider = AnthropicProvider(## 常见坑-- **`temperature` 被忽略** —— 预期之内。思考打开时 CubePi 故意 drop+- **`temperature` 被忽略** —— 预期之内。思考打开时 CubeLoop 故意 drop掉,这是 API 约束,不是 bug。- **`xhigh` 和 `high` 看起来一样** —— Anthropic 没有更高一档的 budget,- 所以 CubePi 把 `xhigh` clamp 到 `high`,token budget 相同。+ 所以 CubeLoop 把 `xhigh` clamp 到 `high`,token budget 相同。- **缓存未命中** —— 缓存按 (内容, ttl) 索引。改 system prompt 会让整块失效;改工具列表则从工具往后失效。要最大化命中,保持这两个跨轮稳定。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/custom.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/custom.mdindex dc1d97c..5120bb1 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/custom.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/custom.md@@ -1,6 +1,6 @@---title: 自定义 Provider-description: "通过实现 Provider 协议,为 CubePi 编写自定义 provider。"+description: "通过实现 Provider 协议,为 CubeLoop 编写自定义 provider。"---# 自定义 Provider@@ -34,7 +34,7 @@ class Provider(Protocol):```pythonimport asyncioimport time-from cubepi.providers.base import (+from cubeloop.providers.base import (AssistantMessage,Message,MessageStream,@@ -118,7 +118,7 @@ class MyProvider:如果你的模型会产生工具调用,在流式传输时将 `ToolCall` 块追加到 `partial.content`,并发出 `toolcall_start` / `toolcall_delta` / `toolcall_end` 事件:```python-from cubepi.providers.base import ToolCall+from cubeloop.providers.base import ToolCalltc = ToolCall(id=block_id, name=tool_name, arguments={})partial.content.append(tc)@@ -130,14 +130,14 @@ ms.push(StreamEvent(type="toolcall_delta", delta=partial_json_chunk, …))# replace tc.arguments with the parsed dict, push toolcall_end```-CubePi 的 agent 循环会在收到 `done` 事件后自动分发工具调用。+CubeLoop 的 agent 循环会在收到 `done` 事件后自动分发工具调用。## 挂钩 `on_payload` / `on_response`-如果你的 provider 发送 HTTP 请求,请调用 `cubepi.providers.base` 中的辅助函数:+如果你的 provider 发送 HTTP 请求,请调用 `cubeloop.providers.base` 中的辅助函数:```python-from cubepi.providers.base import (+from cubeloop.providers.base import (ProviderResponse,invoke_on_payload,invoke_on_response,@@ -156,11 +156,11 @@ await invoke_on_response(## 在测试中使用 `FauxProvider` {#using-fauxprovider-in-tests}-CubePi 内置 `FauxProvider`,用于确定性测试——无网络调用,无不稳定性,且有真实的流式事件:+CubeLoop 内置 `FauxProvider`,用于确定性测试——无网络调用,无不稳定性,且有真实的流式事件:```python-from cubepi import Agent-from cubepi.providers import FauxProvider, faux_assistant_message, faux_text, faux_tool_call+from cubeloop import Agent+from cubeloop.providers import FauxProvider, faux_assistant_message, faux_text, faux_tool_calldef test_my_agent():@@ -204,6 +204,6 @@ def test_my_agent():- [图片生成](./image-generation) —— 使用 `openai-images` 与 OpenAI 图片模型。- [Providers Overview](./overview) —— 在从头编写类之前,先检查你的后端是否只是一个 `CapabilityDescriptor` 或内置预设已经覆盖的 OpenAI/Anthropic 兼容端点。-- [API 参考 → providers/base](../../api/cubepi-providers) —— 完整类型列表。-- [Anthropic Provider 源码](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/anthropic.py) —— 一个真实完整的示例。-- [`FauxProvider` 源码](https://github.com/cubeplexai/cubepi/blob/main/cubepi/providers/faux.py) —— 测试原语,包含流式真实性的细节。+- [API 参考 → providers/base](../../api/cubeloop-providers) —— 完整类型列表。+- [Anthropic Provider 源码](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/providers/anthropic.py) —— 一个真实完整的示例。+- [`FauxProvider` 源码](https://github.com/cubeplexai/cubeloop/blob/main/cubeloop/providers/faux.py) —— 测试原语,包含流式真实性的细节。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.mdindex cf0bdc2..0f658ba 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/image-generation.md@@ -1,11 +1,11 @@---title: 图片生成-description: "用 CubePi 的 image provider 生成图片 —— OpenAI、豆包 Seedream、SiliconFlow、Together AI 等 OpenAI 兼容后端。"+description: "用 CubeLoop 的 image provider 生成图片 —— OpenAI、豆包 Seedream、SiliconFlow、Together AI 等 OpenAI 兼容后端。"---# 图片生成-CubePi 的图片生成路径与 chat provider 范式同构:Provider 装连接信息+CubeLoop 的图片生成路径与 chat provider 范式同构:Provider 装连接信息(`provider_id`、`api_key`、`base_url`、`capability`),model spec 装模型级默认值,per-call 走类型化的 `ImagesContext` 加可选的 `ImagesOptions`跨切面选项。调用失败抛出类型化的 `ProviderError` 子类——UI 端跟 chat@@ -24,7 +24,7 @@ OpenAI 形态的后端(OpenAI 官方、豆包 Seedream、SiliconFlow、Togethe```pythonimport os-from cubepi.providers.images import OpenAIImagesProvider, ImagesContext+from cubeloop.providers.images import OpenAIImagesProvider, ImagesContextprovider = OpenAIImagesProvider(provider_id="openai",@@ -88,7 +88,7 @@ ctx = ImagesContext(## `ImagesOptions` — per-call 跨切面选项```python-from cubepi.providers.images import ImagesOptions+from cubeloop.providers.images import ImagesOptionsopts = ImagesOptions(signal=cancel_event, # asyncio.Event;set 后中止当前调用@@ -107,7 +107,7 @@ Response 观察者通过 `ImagesAborted` 异常(普通 `Exception` 子类,**在 generate 返回前完成)来看到 abort:```python-from cubepi.providers.images import ImagesAborted+from cubeloop.providers.images import ImagesAborteddef on_response(body, model, exc):if isinstance(exc, ImagesAborted):@@ -148,7 +148,7 @@ OpenAIImagesProvider(URL 长得像 OpenAI,但字段名要换:```python-from cubepi.providers.images.capability import ImagesCapabilityDescriptor, SizeSpec+from cubeloop.providers.images.capability import ImagesCapabilityDescriptor, SizeSpecOpenAIImagesProvider(provider_id="siliconflow",@@ -203,11 +203,11 @@ provider = OpenAIImagesProvider(## 错误处理-所有内置 image provider 在失败时抛出类型化的 `cubepi.errors.ProviderError`+所有内置 image provider 在失败时抛出类型化的 `cubeloop.errors.ProviderError`子类——不再用 in-band 错误字符串:```python-from cubepi.errors import RateLimited, ProviderAuthFailed, ProviderUnavailable+from cubeloop.errors import RateLimited, ProviderAuthFailed, ProviderUnavailabletry:result = await provider.generate_images(model, ctx)@@ -246,7 +246,7 @@ provider.subscribe_response(lambda body, model, exc: log_response(body, exc))```pythonimport base64-from cubepi.providers.base import ImageContent+from cubeloop.providers.base import ImageContentwith open("source.png", "rb") as fh:source_b64 = base64.b64encode(fh.read()).decode("ascii")@@ -264,8 +264,8 @@ result = await provider.generate_images(model, ctx)## 测试 stub `FauxImagesProvider````python-from cubepi.providers.images import FauxImagesProvider-from cubepi.errors import RateLimited+from cubeloop.providers.images import FauxImagesProvider+from cubeloop.errors import RateLimited# 正常路径:provider = FauxImagesProvider(png_b64="iVBORw0KGgo...")@@ -288,7 +288,7 @@ provider = FauxImagesProvider(今天可以继承 `BaseImagesProvider` 自己实现;未来版本会加 `AsyncTaskImagesProvider`这种共享 polling 脚手架。- **Tracing 接入**:本版加了 image provider 的 listener 注册表,但- `cubepi.tracing` 还没自动订阅 image 调用。需要 image 调用 span 的+ `cubeloop.tracing` 还没自动订阅 image 调用。需要 image 调用 span 的Host 暂时手动 `subscribe_*`。## 另见@@ -296,4 +296,4 @@ provider = FauxImagesProvider(- [Providers Overview](./overview) —— chat-provider 的配置方式;imageprovider 跟它共享 `provider_id` / `.model()` / capability 范式。- [OpenAI Provider](./openai) —— chat 那边 OpenAI 形态的共通配置。-- [API Reference → `cubepi.providers.images`](../../api/cubepi-providers)。+- [API Reference → `cubeloop.providers.images`](../../api/cubeloop-providers)。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/openai.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/openai.mdindex 601ab2b..a5257ac 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/openai.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/openai.md@@ -1,11 +1,11 @@---title: OpenAI-description: "在 CubePi 中使用 OpenAI GPT 模型——OpenAIProvider 与 Chat Completions API 集成。"+description: "在 CubeLoop 中使用 OpenAI GPT 模型——OpenAIProvider 与 Chat Completions API 集成。"---# OpenAI Provider-CubePi 内置两个 OpenAI provider,分别覆盖两种 API 接口:+CubeLoop 内置两个 OpenAI provider,分别覆盖两种 API 接口:- **`OpenAIProvider`** —— Chat Completions API(`/v1/chat/completions`)。适用于 GPT-4/5 系列以及大多数 OpenAI 兼容服务器(vLLM、LiteLLM、DeepSeek、Qwen、MiniMax、豆包……)。- **`OpenAIResponsesProvider`** —— Responses API(`/v1/responses`)。适用于需要服务端状态和推理摘要的场景。@@ -15,7 +15,7 @@ CubePi 内置两个 OpenAI provider,分别覆盖两种 API 接口:## Chat Completions:`OpenAIProvider````python-from cubepi.providers.openai import OpenAIProvider+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(provider_id="openai",@@ -35,9 +35,9 @@ model = provider.model(### Chat Completions 中的推理-OpenAI 通过 o 系列和 gpt-5 模型的 `delta.reasoning_content` 暴露推理内容。CubePi 将其捕获为 `ThinkingContent`,并以与 Anthropic 完全相同的方式发出 `thinking_*` 事件。相同的 `ThinkingLevel` 枚举(`"off"` → `"high"`)同样适用。+OpenAI 通过 o 系列和 gpt-5 模型的 `delta.reasoning_content` 暴露推理内容。CubeLoop 将其捕获为 `ThinkingContent`,并以与 Anthropic 完全相同的方式发出 `thinking_*` 事件。相同的 `ThinkingLevel` 枚举(`"off"` → `"high"`)同样适用。-许多 OpenAI 兼容的开源后端在不同字段下暴露推理内容。CubePi 按优先级顺序识别以下三种:+许多 OpenAI 兼容的开源后端在不同字段下暴露推理内容。CubeLoop 按优先级顺序识别以下三种:1. `delta.reasoning_content`(DeepSeek、Qwen、豆包)2. `delta.reasoning`(vLLM)@@ -61,7 +61,7 @@ provider = OpenAIProvider(### 能力描述符-OpenAI 与 OpenAI 兼容后端之间的 wire 格式差异(如 `max_tokens` vs `max_completion_tokens`、推理字段名称、temperature 处理方式)可通过构造时传入的 [`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html) 来配置。例如,`max_tokens_field="max_completion_tokens"` 会在请求发出前重命名该 key。详见 [能力描述符](./overview) 了解完整配置项(CubePi `0.5+`)。+OpenAI 与 OpenAI 兼容后端之间的 wire 格式差异(如 `max_tokens` vs `max_completion_tokens`、推理字段名称、temperature 处理方式)可通过构造时传入的 [`CapabilityDescriptor`](pathname:///pydoc/cubeloop/providers/capability.html) 来配置。例如,`max_tokens_field="max_completion_tokens"` 会在请求发出前重命名该 key。详见 [能力描述符](./overview) 了解完整配置项(CubeLoop `0.5+`)。### 指向 vLLM / LiteLLM / DeepSeek@@ -87,13 +87,13 @@ provider = OpenAIProvider(## Responses API:`OpenAIResponsesProvider````python-from cubepi.providers.openai_responses import OpenAIResponsesProvider+from cubeloop.providers.openai_responses import OpenAIResponsesProviderprovider = OpenAIResponsesProvider(provider_id="openai_responses", api_key="sk-…")model = provider.model("gpt-5", reasoning=True)```-Responses API 在服务端维护状态(通过 `previous_response_id` 引用)。CubePi 追踪 `AssistantMessage.response_id` 并自动回传——你的代码看起来与 Chat Completions 路径完全相同。+Responses API 在服务端维护状态(通过 `previous_response_id` 引用)。CubeLoop 追踪 `AssistantMessage.response_id` 并自动回传——你的代码看起来与 Chat Completions 路径完全相同。在以下情况下使用 Responses provider:@@ -116,16 +116,16 @@ agent = Agent(model=model, on_payload=add_user_metadata)## 工具调用-工具定义会自动转换为 OpenAI 的 `{"type": "function", "function": {...}}` 格式。流式格式在 `toolcall_delta` 下发出增量 JSON 参数;CubePi 通过 [`cubepi.utils.json_parse.parse_streaming_json`](../../api/cubepi-utils) 对其进行缓冲和解析,确保部分内容始终能校验为最接近的合法对象。+工具定义会自动转换为 OpenAI 的 `{"type": "function", "function": {...}}` 格式。流式格式在 `toolcall_delta` 下发出增量 JSON 参数;CubeLoop 通过 [`cubeloop.utils.json_parse.parse_streaming_json`](../../api/cubeloop-utils) 对其进行缓冲和解析,确保部分内容始终能校验为最接近的合法对象。一条 assistant 消息中的多个并行工具调用开箱即用——它们与 Anthropic provider 使用相同的并行执行器进行路由。## 常见问题-- **`stream_options.include_usage` 被拒绝** —— 部分兼容服务器会拒绝整个 `stream_options` 字段。**`on_payload` 无法修复此问题**:CubePi 0.3 在你的回调执行**之后**才调用 `kwargs.setdefault("stream_options", {})`,因此在 `on_payload` 中删除该 key 会被静默地撤销。解决方案:+- **`stream_options.include_usage` 被拒绝** —— 部分兼容服务器会拒绝整个 `stream_options` 字段。**`on_payload` 无法修复此问题**:CubeLoop 0.3 在你的回调执行**之后**才调用 `kwargs.setdefault("stream_options", {})`,因此在 `on_payload` 中删除该 key 会被静默地撤销。解决方案:- 子类化 `OpenAIProvider` 并覆盖 `stream()`,对你的后端跳过 `setdefault`。- 在 `on_payload` 中设置 `include_usage=False`(字段仍会发出,但通常被严格后端接受为无操作)。- - 使用 [`CapabilityDescriptor`](./overview)(CubePi `0.5+`)以声明式方式描述你的后端推理配置。+ - 使用 [`CapabilityDescriptor`](./overview)(CubeLoop `0.5+`)以声明式方式描述你的后端推理配置。- **有推理内容但没有 `thinking_*` 事件** —— 你的后端在非标准字段下暴露推理内容。可通过 PR 添加第四个分支,或使用 `on_payload` 进行转码。- **同一进程中混用多个 provider** —— 每个 provider 持有自己的 HTTP 客户端。按 `(base_url, api_key)` 对复用单个实例,而非每个 agent 各创建一个。- **usage 显示 0 个输入 token** —— 大多数兼容服务器完全省略 usage,或只在最后一个 chunk 中发出。可在 `on_payload` 中检查尾部 chunk 获取提示,或将 token 计数视为这些后端的尽力而为值。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/overview.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/overview.mdindex 5537541..1bb43ad 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/overview.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/overview.md@@ -1,6 +1,6 @@---title: Providers Overview-description: "CubePi 的 provider 配置、能力和预设总览。"+description: "CubeLoop 的 provider 配置、能力和预设总览。"---# Providers Overview@@ -32,8 +32,8 @@ _从这里开始看 provider 配置。_后端在 wire 上的差异。```python-from cubepi import CapabilityDescriptor-from cubepi.providers.openai import OpenAIProvider+from cubeloop import CapabilityDescriptor+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key="...",@@ -49,8 +49,8 @@ provider = OpenAIProvider(如果只有部分模型例外,使用 `model_capability_overrides`:```python-from cubepi import CapabilityDescriptor-from cubepi.providers.openai import OpenAIProvider+from cubeloop import CapabilityDescriptor+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key="...",@@ -78,7 +78,7 @@ provider = OpenAIProvider(- `supports_tools` / `supports_images` / `supports_streaming` — 供宿主应用或前端消费的能力元数据。:::note 预设目录由宿主应用维护-CubePi 提供的是**机制**(`CapabilityDescriptor` 及其 wire 运行时),而非厂商目录。包含 base URL、认证、区域/代码规划端点、模型列表的现成 provider 列表属于产品数据,应由嵌入 CubePi 的应用自行维护(例如,cubebox 维护自己的 provider 目录)。如需接入特定厂商,请按下文所示,使用正确的 `base_url` + `CapabilityDescriptor` 构建 provider。+CubeLoop 提供的是**机制**(`CapabilityDescriptor` 及其 wire 运行时),而非厂商目录。包含 base URL、认证、区域/代码规划端点、模型列表的现成 provider 列表属于产品数据,应由嵌入 CubeLoop 的应用自行维护(例如,cubebox 维护自己的 provider 目录)。如需接入特定厂商,请按下文所示,使用正确的 `base_url` + `CapabilityDescriptor` 构建 provider。:::## 1. 简单场景——完全零配置@@ -86,25 +86,25 @@ CubePi 提供的是**机制**(`CapabilityDescriptor` 及其 wire 运行时)大多数用户无需关心能力描述符。内置 provider 已有合理的默认值:```python-import cubepi-from cubepi import Agent-from cubepi.providers.anthropic import AnthropicProvider+import cubeloop+from cubeloop import Agent+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(provider_id="anthropic") # reads ANTHROPIC_API_KEYagent = Agent(model=provider.model("claude-sonnet-4-6"))await agent.prompt("Hello!")```-这就是全部配置。不带 `capability=` 构建的 provider,其输出与 CubePi `0.4` 完全一致——下文的机制仅在显式使用时才会生效。+这就是全部配置。不带 `capability=` 构建的 provider,其输出与 CubeLoop `0.4` 完全一致——下文的机制仅在显式使用时才会生效。## 2. 非默认端点——CapabilityDescriptor-当你需要使用 OpenAI 或 Anthropic 之外的模型——DeepSeek、Qwen、豆包、OpenRouter 路由、本地服务器——麻烦在于每家的 wire 方言不同(是用 `max_tokens` 还是 `max_completion_tokens`?如何开关推理?)。你不需要子类化 provider;只需将差异描述为一个 [`CapabilityDescriptor`](pathname:///pydoc/cubepi/providers/capability.html),连同正确的 `base_url` 和对应端点 wire 形状的 provider 类一起传入:+当你需要使用 OpenAI 或 Anthropic 之外的模型——DeepSeek、Qwen、豆包、OpenRouter 路由、本地服务器——麻烦在于每家的 wire 方言不同(是用 `max_tokens` 还是 `max_completion_tokens`?如何开关推理?)。你不需要子类化 provider;只需将差异描述为一个 [`CapabilityDescriptor`](pathname:///pydoc/cubeloop/providers/capability.html),连同正确的 `base_url` 和对应端点 wire 形状的 provider 类一起传入:```pythonimport os-from cubepi import CapabilityDescriptor-from cubepi.providers.openai import OpenAIProvider+from cubeloop import CapabilityDescriptor+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key=os.environ["DEEPSEEK_API_KEY"],@@ -135,7 +135,7 @@ provider = OpenAIProvider(`TemperatureSpec` 控制调用方传入的 temperature 如何处理:```python-from cubepi import TemperatureSpec+from cubeloop import TemperatureSpecTemperatureSpec(mode="free", min=0.0, max=2.0, default=1.0) # clamp into [min, max]TemperatureSpec(mode="fixed", fixed_value=1.0) # always overwrite@@ -161,7 +161,7 @@ CapabilityDescriptor(### 推理级别:`reasoning_level`(三种形状)-在开/关之外,CubePi 将 `ThinkingLevel`(`off`/`low`/`medium`/`high`/`xhigh`)映射到通过点路径 `path` 写入的具体 wire 值。`kind` 决定形状:+在开/关之外,CubeLoop 将 `ThinkingLevel`(`off`/`low`/`medium`/`high`/`xhigh`)映射到通过点路径 `path` 写入的具体 wire 值。`kind` 决定形状:`ReasoningLevelSpec` 只负责「`thinking`/`low`/... 具体映射成后端字段」;要真正生效,还要配两个参数:@@ -169,8 +169,8 @@ CapabilityDescriptor(- 在 `Agent(...)` 初始化时把 `thinking` 设成 `off|low|medium|high|xhigh`(默认 `off`)```python-from cubepi import Agent, CapabilityDescriptor, ReasoningLevelSpec-from cubepi.providers.openai import OpenAIProvider+from cubeloop import Agent, CapabilityDescriptor, ReasoningLevelSpec+from cubeloop.providers.openai import OpenAIProviderprovider = OpenAIProvider(api_key="...",@@ -194,7 +194,7 @@ agent = Agent(model=provider.model("deepseek-r1", reasoning=True), thinking="hig``````python-from cubepi import ReasoningLevelSpec+from cubeloop import ReasoningLevelSpec# int_budget — a token budget (Anthropic).ReasoningLevelSpec(@@ -242,7 +242,7 @@ provider = OpenAIProvider(## 图片生成 provider-图片生成有独立的 provider 表面(`cubepi.providers.images`),范式与上文+图片生成有独立的 provider 表面(`cubeloop.providers.images`),范式与上文描述完全一致:provider 上的 `provider_id`、`provider.model("id", ...)`工厂、类型化的 `ProviderError` 错误,以及处理后端字段差异的 capabilitydescriptor。完整指南见 [图片生成](./image-generation)。@@ -252,4 +252,4 @@ descriptor。完整指南见 [图片生成](./image-generation)。- [OpenAI Provider](./openai) —— OpenAI / OpenAI 兼容端点的具体配置。- [Anthropic Provider](./anthropic) —— `int_budget` 推理形状的实际用法。- [自定义 Provider](./custom) —— 当端点甚至不是 OpenAI/Anthropic 形状时。-- [API 参考 → `cubepi.providers`](../../api/cubepi-providers)。+- [API 参考 → `cubeloop.providers`](../../api/cubeloop-providers)。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/structured-output.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/structured-output.mdindex eda0054..8a8bbff 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/structured-output.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/providers/structured-output.md@@ -11,7 +11,7 @@ description: "通过 generate_structured() 和 tool_choice 从 LLM 调用获得```pythonfrom pydantic import BaseModel-from cubepi.providers.base import TextContent, UserMessage+from cubeloop.providers.base import TextContent, UserMessageclass Sentiment(BaseModel):label: str@@ -69,7 +69,7 @@ await model.generate_structured(`generate_structured()` 在两种情况下抛 `StructuredOutputError`:```python-from cubepi.providers.base import StructuredOutputError+from cubeloop.providers.base import StructuredOutputErrortry:result = await model.generate_structured(MySchema, messages=[...])diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/cli.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/cli.mdindex 57e823d..1af3a61 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/cli.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/cli.md@@ -1,28 +1,28 @@---title: Trace CLI-description: "使用 CubePi trace CLI 检查、过滤并展示 OpenTelemetry trace span。"+description: "使用 CubeLoop trace CLI 检查、过滤并展示 OpenTelemetry trace span。"----# 使用 `cubepi trace` 检查 trace+# 使用 `cubeloop trace` 检查 trace-`JsonlSpanExporter` 在 `./cubepi-traces/<date>/<trace_id>.jsonl` 下每条-trace 写入一个文件。`cubepi trace` CLI(由 `trace-cli` extra 提供)读取这些+`JsonlSpanExporter` 在 `./cubeloop-traces/<date>/<trace_id>.jsonl` 下每条+trace 写入一个文件。`cubeloop trace` CLI(由 `trace-cli` extra 提供)读取这些文件,让你无需重新运行即可了解一次运行的详细情况——哪些 LLM 和工具调用被触发、顺序如何、各自返回什么、在哪里出错以及 token 数量。```bash-pip install 'cubepi[trace-cli]' # 或:uv sync --extra trace-cli-cubepi trace --help+pip install 'cubeloop[trace-cli]' # 或:uv sync --extra trace-cli+cubeloop trace --help```-`--dir` 默认为 `./cubepi-traces`;若 trace 文件存放在其他位置,传入+`--dir` 默认为 `./cubeloop-traces`;若 trace 文件存放在其他位置,传入`--dir <path>` 即可。每个文件是一条 **trace**:运行本身加上所有嵌套subagent 运行(它们继承父级的 `trace_id`,因此写入同一文件)。## `ls` —— 列出近期 trace```bash-cubepi trace ls # 最新优先;-n N 限制数量+cubeloop trace ls # 最新优先;-n N 限制数量```| 列 | 含义 |@@ -41,8 +41,8 @@ cubepi trace ls # 最新优先;-n N 限制数量`user_id`、`org_id`、`workspace_id`),可以只过滤出匹配的 trace:```bash-cubepi trace ls --meta conversation_id=conv_123-cubepi trace ls --meta user_id=usr_9 --meta org_id=org_1 # 可重复 = AND,精确匹配+cubeloop trace ls --meta conversation_id=conv_123+cubeloop trace ls --meta user_id=usr_9 --meta org_id=org_1 # 可重复 = AND,精确匹配```每个 `--meta KEY=VALUE` 与 trace 根节点元数据精确匹配;重复该标志表示 AND 关系。@@ -50,48 +50,48 @@ cubepi trace ls --meta user_id=usr_9 --meta org_id=org_1 # 可重复 = AND,如需将元数据值**显示**为列(而不只是过滤),添加 `--show-meta KEY[,KEY…]`:```bash-cubepi trace ls --show-meta conversation_id,user_id-cubepi trace ls --meta org_id=org_1 --show-meta conversation_id # 过滤 + 显示+cubeloop trace ls --show-meta conversation_id,user_id+cubeloop trace ls --meta org_id=org_1 --show-meta conversation_id # 过滤 + 显示```-(或通过 `cubepi trace view <id> -v` 查看单条 trace 的所有元数据。)+(或通过 `cubeloop trace view <id> -v` 查看单条 trace 的所有元数据。)## `view` —— 将 trace 渲染为 span 树trace-id 的**前缀**即可(表格会截断 ID);如果前缀不唯一,会列出候选结果。```bash-cubepi trace view 1cd97cdb+cubeloop trace view 1cd97cdb``````trace└── invoke_agent 14425.8ms [0x1cd97cdb]- ├── cubepi.turn 1283.1ms [0x5cfda93e]+ ├── cubeloop.turn 1283.1ms [0x5cfda93e]│ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]│ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]│ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent 运行,嵌套其中- │ └── cubepi.turn 9598.4ms [0x57c5cfc7]+ │ └── cubeloop.turn 9598.4ms [0x57c5cfc7]│ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]│ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]- └── cubepi.turn 491.9ms ERROR [0xce25f242]+ └── cubeloop.turn 491.9ms ERROR [0xce25f242]└── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]└── error: Error code: 400 - ... `tool_use` ids were found without`tool_result` blocks immediately after: call_01_...```-从上到下阅读:`invoke_agent`(一次运行)→ `cubepi.turn`(一个 agent 循环+从上到下阅读:`invoke_agent`(一次运行)→ `cubeloop.turn`(一个 agent 循环turn)→ `chat <model>`(一次 LLM 调用,含 `tok <input>/<output>`)和`execute_tool <name>`(一次工具调用)。**subagent** 显示为-`execute_tool subagent`,其自身的 `invoke_agent → cubepi.turn → …` 直接+`execute_tool subagent`,其自身的 `invoke_agent → cubeloop.turn → …` 直接嵌套在其下方。每个节点后缀的 `[0x…]` 是该 span 的 `span_id`——在原始JSONL 中 grep 它即可检查对应的具体 span。错误信息内联显示在失败 span 的下方。标志:```bash-cubepi trace view <id> --content # 展开 gen_ai prompt / 工具参数 / 结果-cubepi trace view <id> -v # 展开所有 span 属性(详细,输出量大)+cubeloop trace view <id> --content # 展开 gen_ai prompt / 工具参数 / 结果+cubeloop trace view <id> -v # 展开所有 span 属性(详细,输出量大)````--content` 要求该运行以 `record_content=True` 方式录制@@ -100,22 +100,22 @@ cubepi trace view <id> -v # 展开所有 span 属性(详细,输出## `follow` —— 实时观察 trace```bash-cubepi trace follow <id> # 轮询 span 完成情况;适合正在进行中的运行+cubeloop trace follow <id> # 轮询 span 完成情况;适合正在进行中的运行```## `stats` —— 跨 trace 聚合统计```bash-cubepi trace stats --by model # 延迟 p50/p95、错误率、token 数量-cubepi trace stats --by tool --since 2026-05-20+cubeloop trace stats --by model # 延迟 p50/p95、错误率、token 数量+cubeloop trace stats --by tool --since 2026-05-20````stats` 同样接受 `--meta KEY=VALUE`(语义与 `ls` 相同),仅对匹配的 trace进行聚合——例如按单个用户或对话统计延迟/错误率/token:```bash-cubepi trace stats --by model --meta user_id=usr_9-cubepi trace stats --by tool --meta conversation_id=conv_123+cubeloop trace stats --by model --meta user_id=usr_9+cubeloop trace stats --by tool --meta conversation_id=conv_123```## `convert` —— 重建 API 请求体@@ -128,16 +128,16 @@ cubepi trace stats --by tool --meta conversation_id=conv_123```bash# 默认:trace 中最后一个 chat span,OpenAI JSON 格式-cubepi trace convert <trace_id>+cubeloop trace convert <trace_id># 选择要重建的 LLM 调用-cubepi trace convert <trace_id> --turn 2 # 第 2 个 chat span(从 1 计数)-cubepi trace convert <trace_id> --span 0xbb7eb1 # 按 span_id 前缀(来自 `view`)+cubeloop trace convert <trace_id> --turn 2 # 第 2 个 chat span(从 1 计数)+cubeloop trace convert <trace_id> --span 0xbb7eb1 # 按 span_id 前缀(来自 `view`)# 输出格式-cubepi trace convert <trace_id> --format openai # 默认——JSON 请求体-cubepi trace convert <trace_id> --format anthropic # Anthropic Messages API 请求体-cubepi trace convert <trace_id> --format curl # 可直接执行的 curl 命令+cubeloop trace convert <trace_id> --format openai # 默认——JSON 请求体+cubeloop trace convert <trace_id> --format anthropic # Anthropic Messages API 请求体+cubeloop trace convert <trace_id> --format curl # 可直接执行的 curl 命令````view` 输出中的 `[0x…]` span id 可直接传给 `--span`:@@ -159,11 +159,11 @@ cubepi trace convert <trace_id> --format curl # 可直接执行的 curl`gen_ai.client.operation.exception` 的 span **event** 中。:::tip 为 AI agent 准备-内置的 `cubepi-trace` skill 可驱动此 CLI 进行调试("这次运行为何没有回复?"、+内置的 `cubeloop-trace` skill 可驱动此 CLI 进行调试("这次运行为何没有回复?"、"工具结果不对")。它内置了快速路径(`ls` → `view <prefix>`)以及token/缓存命中率的约定。```bash-npx skills add cubeplexai/cubepi@cubepi-trace -a claude-code+npx skills add cubeplexai/cubeloop@cubeloop-trace -a claude-code```:::diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/content-recording.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/content-recording.mdindex 671efe1..d612560 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/content-recording.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/content-recording.md@@ -1,12 +1,12 @@---title: 内容记录与脱敏-description: "在 CubePi 的 OpenTelemetry tracing 中配置 prompt 内容记录与脱敏。"+description: "在 CubeLoop 的 OpenTelemetry tracing 中配置 prompt 内容记录与脱敏。"sidebar_position: 4---# 记录 Prompt、响应与工具 Payload-CubePi 的 tracing 默认只发出结构性属性——操作名称、模型、token 数量、+CubeLoop 的 tracing 默认只发出结构性属性——操作名称、模型、token 数量、结束原因、耗时。**不会有 prompt 内容、模型输出、工具参数或结果离开进程。**这是有意为之:很多 agent 场景处理 PII、客户数据或商业机密 prompt,这些内容不应发送到第三方可观测性后端。@@ -22,7 +22,7 @@ tracer = Tracer(service_name="my-bot",agent_name="assistant",record_content=True, # ← 显式开启- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],)```@@ -32,8 +32,8 @@ tracer = Tracer(| Span | 新增内容属性 ||---|---|| `invoke_agent` | `gen_ai.system_instructions`、`gen_ai.input.messages`、`gen_ai.output.messages` |-| `cubepi.turn` | `gen_ai.input.messages`(per-turn 切片)、`gen_ai.output.messages`(per-turn 切片) |-| `chat <model>` | `gen_ai.system_instructions`、`gen_ai.input.messages`、`gen_ai.tool.definitions`、`cubepi.llm.raw_request`、`cubepi.llm.raw_response` |+| `cubeloop.turn` | `gen_ai.input.messages`(per-turn 切片)、`gen_ai.output.messages`(per-turn 切片) |+| `chat <model>` | `gen_ai.system_instructions`、`gen_ai.input.messages`、`gen_ai.tool.definitions`、`cubeloop.llm.raw_request`、`cubeloop.llm.raw_response` || `execute_tool <tool_name>` | `gen_ai.tool.call.arguments`、`gen_ai.tool.call.result` |`chat` span 的 `gen_ai.input.messages` 包含 provider 请求实际携带的@@ -56,7 +56,7 @@ def redact(key: str, value):if key in ("gen_ai.input.messages", "gen_ai.output.messages"):return _scrub_messages(value)# 在生产环境中不发送原始请求/响应体——只保留规范化后的结构。- if key in ("cubepi.llm.raw_request", "cubepi.llm.raw_response"):+ if key in ("cubeloop.llm.raw_request", "cubeloop.llm.raw_response"):return Nonereturn value@@ -116,8 +116,8 @@ OTel 属性值在 recorder 内部以 JSON 序列化。大多数后端会截断tracer = Tracer(record_content=True, # trace convert 所需record_stream=True, # ← 逐块事件日志- stream_dir="./cubepi-traces", # <run_id>.stream.jsonl 的写入目录- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ stream_dir="./cubeloop-traces", # <run_id>.stream.jsonl 的写入目录+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],)```@@ -129,7 +129,7 @@ tracer = Tracer(```json{"t": 5.873, "type": "toolcall_start", "ci": 1, "id": "toolu_...", "name": "show_widget"}{"t": 5.875, "type": "toolcall_delta", "ci": 1, "chars": 11, "accumulated": 11, "preview": "{\"title\": \""}-{"t": 33.177, "type": "toolcall_end", "ci": 1, "id": "toolu_...", "args_chars": 7465, "args_preview": "{\"title\": \"CubePi..."}+{"t": 33.177, "type": "toolcall_end", "ci": 1, "id": "toolu_...", "args_chars": 7465, "args_preview": "{\"title\": \"CubeLoop..."}```通过这些数据,可以方便地确认参数 chunk 是否按预期到达,或者同一事件是否@@ -142,7 +142,7 @@ tracer = Tracer(## 审计已记录的内容recorder 始终在每个 span 上设置 `service.name`、`gen_ai.agent.name` 和-`cubepi.run_id`——无论 `record_content` 是否开启。使用这些属性在 trace+`cubeloop.run_id`——无论 `record_content` 是否开启。使用这些属性在 trace后端过滤到单次运行,并直观确认哪些数据已落地。如需深度审计,`JsonlSpanExporter` 每行写入一个 span,因此可以在将同一@@ -150,5 +150,5 @@ exporter 指向远程后端之前,先对本地文件进行 grep / `jq` 检查```bashjq -r 'select(.attributes["gen_ai.input.messages"]) | .attributes["gen_ai.input.messages"]' \- cubepi-traces/2026-05-19/*.jsonl+ cubeloop-traces/2026-05-19/*.jsonl```diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/getting-started.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/getting-started.mdindex 2ef5e7d..be0cdd2 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/getting-started.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/getting-started.md@@ -1,6 +1,6 @@---title: 快速开始-description: "在 CubePi 中快速上手 OpenTelemetry tracing——安装、配置并导出 span。"+description: "在 CubeLoop 中快速上手 OpenTelemetry tracing——安装、配置并导出 span。"sidebar_position: 2---@@ -8,13 +8,13 @@ sidebar_position: 2## 安装 extra-CubePi 将 OpenTelemetry 作为可选依赖:+CubeLoop 将 OpenTelemetry 作为可选依赖:```bash-pip install "cubepi[tracing]"+pip install "cubeloop[tracing]"```-这会拉取 `opentelemetry-sdk` 及相关包。若未安装该 extra,导入 `cubepi.tracing`+这会拉取 `opentelemetry-sdk` 及相关包。若未安装该 extra,导入 `cubeloop.tracing`时会抛出清晰的错误提示,让你在导入阶段就能发现问题,而不是运行到一半才报错。## 挂载 Tracer@@ -23,10 +23,10 @@ pip install "cubepi[tracing]"```pythonimport asyncio-from cubepi import Agent-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.tracing import Tracer-from cubepi.tracing.exporters import JsonlSpanExporter+from cubeloop import Agent+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.tracing import Tracer+from cubeloop.tracing.exporters import JsonlSpanExporterasync def main() -> None:@@ -39,7 +39,7 @@ async def main() -> None:Tracer(service_name="my-bot",agent_name="assistant",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],) as tracer,tracer.attached(agent),):@@ -75,22 +75,22 @@ finally:每次运行产生一个 JSONL 文件,按 `trace_id` 分片:```text-./cubepi-traces/+./cubeloop-traces/2026-05-19/8e1c9a3f4b2d…d976a.jsonl ← 一条 trace,一个文件,每行一个 span```一条 trace 代表整次运行,包括所有嵌套 subagent 运行(它们继承父级的-`trace_id`,因此写入同一文件)。每个 span 仍携带 `cubepi.run_id` 属性,+`trace_id`,因此写入同一文件)。每个 span 仍携带 `cubeloop.run_id` 属性,可按单次运行过滤。用任何支持 OTLP/JSON 的工具,或直接用 `jq` 打开:```bashjq -r '"\(.name) \(.attributes."gen_ai.operation.name" // "")"' \- cubepi-traces/2026-05-19/*.jsonl+ cubeloop-traces/2026-05-19/*.jsonl# invoke_agent invoke_agent-# cubepi.turn+# cubeloop.turn# chat claude-sonnet-4-6 chat```@@ -100,7 +100,7 @@ jq -r '"\(.name) \(.attributes."gen_ai.operation.name" // "")"' \```textinvoke_agent assistant [INTERNAL] gen_ai.operation.name=invoke_agent-└── cubepi.turn [INTERNAL] cubepi.turn.index=0+└── cubeloop.turn [INTERNAL] cubeloop.turn.index=0└── chat <model> [CLIENT] gen_ai.operation.name=chat```@@ -108,10 +108,10 @@ invoke_agent assistant [INTERNAL] gen_ai.operation.name=invoke_ag```textinvoke_agent assistant-└── cubepi.turn ← turn index 0+└── cubeloop.turn ← turn index 0├── chat <model> ← 第一轮往返└── execute_tool <tool_name> ← gen_ai.tool.name, gen_ai.tool.call.id-└── cubepi.turn ← turn index 1(工具结果返回后的响应)+└── cubeloop.turn ← turn index 1(工具结果返回后的响应)└── chat <model>```@@ -132,8 +132,8 @@ MCP 服务器能够续接 trace。recorder 将取消视为控制信号,而非失败:-- 流式传输中调用 `agent.abort()` → span 以 `cubepi.aborted=true` 和- `error.type=cubepi.aborted` 关闭,**状态为 UNSET**(遵循 OTel 指导原则——+- 流式传输中调用 `agent.abort()` → span 以 `cubeloop.aborted=true` 和+ `error.type=cubeloop.aborted` 关闭,**状态为 UNSET**(遵循 OTel 指导原则——取消不是错误)。- provider 抛出异常 → chat/turn/root 以 **状态 ERROR** 关闭,chat span 上有`exception` 事件,`error.type` 由异常类派生(`timeout`、`connection_error`、@@ -149,12 +149,12 @@ recorder 将取消视为控制信号,而非失败:默认(无需额外开启):- `invoke_agent`(根节点)—— `gen_ai.operation.name`、`gen_ai.provider.name`、- `gen_ai.agent.name`、`cubepi.run_id`、`cubepi.agent.system_prompt.sha256`、- `cubepi.agent.tools`(名称列表)、`cubepi.input_messages.count`、- `cubepi.output_messages.count`-- `cubepi.turn` —— `cubepi.turn.index`、`cubepi.turn.stop_reason`、- `cubepi.turn.tool_calls.count`、`cubepi.turn.terminated_by_tool`、- `cubepi.run_id`+ `gen_ai.agent.name`、`cubeloop.run_id`、`cubeloop.agent.system_prompt.sha256`、+ `cubeloop.agent.tools`(名称列表)、`cubeloop.input_messages.count`、+ `cubeloop.output_messages.count`+- `cubeloop.turn` —— `cubeloop.turn.index`、`cubeloop.turn.stop_reason`、+ `cubeloop.turn.tool_calls.count`、`cubeloop.turn.terminated_by_tool`、+ `cubeloop.run_id`- `chat <model>` —— `gen_ai.operation.name`、`gen_ai.provider.name`、`gen_ai.request.model`、`gen_ai.request.max_tokens` / `temperature` /`top_p`、`gen_ai.request.stream`、`gen_ai.usage.input_tokens` /@@ -164,15 +164,15 @@ recorder 将取消视为控制信号,而非失败:OpenAI 专属字段(`openai.api.type`、service tier、system fingerprint)- `execute_tool <tool_name>` —— `gen_ai.operation.name=execute_tool`、`gen_ai.tool.name`、`gen_ai.tool.call.id`、`gen_ai.tool.description`、- `gen_ai.tool.type`、`cubepi.tool.is_error`、`cubepi.tool.execution_mode`+ `gen_ai.tool.type`、`cubeloop.tool.is_error`、`cubeloop.tool.execution_mode`- `tools/call <tool_name>`(仅 MCP)—— `mcp.method.name`、`mcp.session.id`、`mcp.protocol.version`、`server.address`、`server.port`、`gen_ai.tool.name`可选,通过 `Tracer(record_content=True)` 开启:`gen_ai.input.messages`、`gen_ai.output.messages`、`gen_ai.system_instructions`、`gen_ai.tool.definitions`、`gen_ai.tool.call.arguments`、-`gen_ai.tool.call.result`、`cubepi.llm.raw_request`、-`cubepi.llm.raw_response`。详见[内容记录与脱敏](./content-recording)。+`gen_ai.tool.call.result`、`cubeloop.llm.raw_request`、+`cubeloop.llm.raw_response`。详见[内容记录与脱敏](./content-recording)。## 多 agent 单进程@@ -194,12 +194,12 @@ async with (## 为单次运行打标签-`cubepi.tracing.tracing_context` 将 per-run 标签和元数据作用于+`cubeloop.tracing.tracing_context` 将 per-run 标签和元数据作用于`invoke_agent` span,非常适合记录 `user_id`、`session_id`、A/B 测试分组等需要在后端过滤的字段:```python-from cubepi.tracing import tracing_context+from cubeloop.tracing import tracing_contextasync with tracer.attached(agent):with tracing_context(tags=["beta-arm"], metadata={"user_id": "u-42"}):@@ -208,10 +208,10 @@ async with tracer.attached(agent):span 上的属性:-- `cubepi.tags = ("beta-arm",)`-- `cubepi.metadata.user_id = "u-42"`+- `cubeloop.tags = ("beta-arm",)`+- `cubeloop.metadata.user_id = "u-42"`-`cubepi.metadata.*` 前缀防止用户键与 recorder 自有 schema(如 `cubepi.run_id`)+`cubeloop.metadata.*` 前缀防止用户键与 recorder 自有 schema(如 `cubeloop.run_id`)冲突。标签和元数据的 contextvar 均为 per-asyncio-task 作用域,并发 agent各自看到独立的值;嵌套的 `tracing_context` 块会合并(标签追加,元数据键取并集,内层优先)。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/metrics.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/metrics.mdindex 5d4db43..f58f5d0 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/metrics.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/metrics.md@@ -1,13 +1,13 @@---title: Metrics-description: "在 CubePi tracing 中收集 token 用量、延迟和首包时间指标。"+description: "在 CubeLoop tracing 中收集 token 用量、延迟和首包时间指标。"sidebar_position: 5---# 使用 `Meter` 采集指标Span 描述单次运行的形态;直方图描述整个集群的形态。-`cubepi.tracing.Meter` 与 `Tracer` 对称,发出 OTel GenAI 指标集,让 dashboard+`cubeloop.tracing.Meter` 与 `Tracer` 对称,发出 OTel GenAI 指标集,让 dashboard开箱即用。## 发出的指标@@ -35,14 +35,14 @@ RAII 惯用形式——`async with` 全包,无需手动清理:from opentelemetry.exporter.otlp.proto.http.metric_exporter import (OTLPMetricExporter,)-from cubepi.tracing import Tracer, Meter-from cubepi.tracing.exporters import JsonlSpanExporter+from cubeloop.tracing import Tracer, Meter+from cubeloop.tracing.exporters import JsonlSpanExporterasync with (Tracer(service_name="my-bot",agent_name="assistant",- exporters=[JsonlSpanExporter(directory="./cubepi-traces")],+ exporters=[JsonlSpanExporter(directory="./cubeloop-traces")],) as tracer,Meter(resource=tracer.resource, # 共享 Resource,使 service.* 与 span 匹配diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/otlp.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/otlp.mdindex c0172ab..f2c862e 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/otlp.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/otlp.md@@ -1,26 +1,26 @@---title: OTLP 与后端-description: "将 CubePi OpenTelemetry trace 导出到 Jaeger、Tempo、Honeycomb 等兼容 OTLP 的后端。"+description: "将 CubeLoop OpenTelemetry trace 导出到 Jaeger、Tempo、Honeycomb 等兼容 OTLP 的后端。"sidebar_position: 3---# 导出到 OTLP 后端-`cubepi.tracing.Tracer` 接受任何 `opentelemetry.sdk.trace.export.SpanExporter`,+`cubeloop.tracing.Tracer` 接受任何 `opentelemetry.sdk.trace.export.SpanExporter`,因此 OpenTelemetry 生态中的所有 exporter 均可直接使用。选择传输协议(HTTP 或 gRPC),指向你的 collector,将 exporter 传入 Tracer 即可。## HTTP(OTLP/HTTP)```bash-pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-http+pip install "cubeloop[tracing]" opentelemetry-exporter-otlp-proto-http``````pythonfrom opentelemetry.exporter.otlp.proto.http.trace_exporter import (OTLPSpanExporter,)-from cubepi.tracing import Tracer+from cubeloop.tracing import Tracertracer = Tracer(service_name="my-bot",@@ -43,7 +43,7 @@ tracer = Tracer(## gRPC(OTLP/gRPC)```bash-pip install "cubepi[tracing]" opentelemetry-exporter-otlp-proto-grpc+pip install "cubeloop[tracing]" opentelemetry-exporter-otlp-proto-grpc``````python@@ -104,11 +104,11 @@ OTel collector 内置 AWS X-Ray exporter;与其他 OTLP 目标的配置方式暂无公开 API 可传入入站 `traceparent`,使 span 嵌套到调用方 HTTP handler的 trace 中。内部钩子(`Tracer._make_parent_context`)为未来的 `run_scope`特性预留;在该特性发布之前,agent 运行与周边服务 trace 仅通过 resource-属性(`service.name`、`gen_ai.agent.name`、`cubepi.run_id`)关联。+属性(`service.name`、`gen_ai.agent.name`、`cubeloop.run_id`)关联。-如果需要立即将上游 trace 延续到 CubePi,可以在调用 `agent.prompt(...)` 之前+如果需要立即将上游 trace 延续到 CubeLoop,可以在调用 `agent.prompt(...)` 之前手动设置 OTel 当前 span,让 agent 的 span 通过 OTel 的环境上下文继承它——-CubePi 不会覆盖已有的活跃父节点。+CubeLoop 不会覆盖已有的活跃父节点。出站方向,MCP `tools/call` 会自动将 W3C `traceparent` 注入 HTTP 头,让下游已埋点的 MCP 服务器能够续接 trace 并写入其自己的后端。@@ -122,7 +122,7 @@ OTLP 用于生产后端:tracer = Tracer(service_name="my-bot",exporters=[- JsonlSpanExporter(directory="./cubepi-traces"),+ JsonlSpanExporter(directory="./cubeloop-traces"),OTLPSpanExporter(endpoint="https://api.honeycomb.io/v1/traces", headers={…}),],)@@ -171,7 +171,7 @@ finally:改用独立的 `trace()` 辅助函数并传入 `flush="background"`:```python-from cubepi.tracing import trace+from cubeloop.tracing import trace@app.post("/chat")async def chat(req: ChatRequest):diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/overview.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/overview.mdindex 20bb738..06fe8cb 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/overview.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/guides/tracing/overview.md@@ -1,12 +1,12 @@---title: Tracing 概览-description: "CubePi 基于 OpenTelemetry 的 tracing 系统概览——span、属性、exporter 与语义约定。"+description: "CubeLoop 基于 OpenTelemetry 的 tracing 系统概览——span、属性、exporter 与语义约定。"sidebar_position: 1---# Tracing 概览-CubePi 发出符合+CubeLoop 发出符合[GenAI Semantic Conventions v1.41](https://opentelemetry.io/docs/specs/semconv/gen-ai/)的 [OpenTelemetry](https://opentelemetry.io/) span,任何兼容 OTel 的后端(Jaeger、Tempo、Honeycomb、Datadog、AWS X-Ray、Azure Monitor……)都能直接接收@@ -18,14 +18,14 @@ agent 运行数据,无需额外自定义埋点。```trace└── invoke_agent 14425.8ms [0x1cd97cdb] ← 每次 agent.prompt() 一个- ├── cubepi.turn 1283.1ms [0x5cfda93e] ← 每次 LLM 往返一个+ ├── cubeloop.turn 1283.1ms [0x5cfda93e] ← 每次 LLM 往返一个│ ├── chat deepseek-v4-flash 1208.7ms tok 6845/68 [0x0d130229]│ └── execute_tool subagent 9610.2ms subagent [0x38bdd10a]│ └── invoke_agent 9601.0ms [0x8094f99b] ← subagent 运行,嵌套其中- │ └── cubepi.turn 9598.4ms [0x57c5cfc7]+ │ └── cubeloop.turn 9598.4ms [0x57c5cfc7]│ ├── chat deepseek-v4-flash 1190.3ms [0x8205ca6b]│ └── execute_tool web_search 6500.2ms web_search [0xca4e59fc]- └── cubepi.turn 491.9ms ERROR [0xce25f242]+ └── cubeloop.turn 491.9ms ERROR [0xce25f242]└── chat deepseek-v4-flash 427.2ms ERROR [0x0bff68ec]└── error: Error code: 400 - ... `tool_use` ids were found without`tool_result` blocks immediately after: call_01_...@@ -38,15 +38,15 @@ trace## 开箱即用的功能- **Tracer** —— 构建 SDK `TracerProvider`,为每个 exporter 挂载一个- `BatchSpanProcessor`,将 CubePi 事件流接入 span。+ `BatchSpanProcessor`,将 CubeLoop 事件流接入 span。- **Meter** —— 用于 OTel 直方图的同级组件:`gen_ai.client.operation.duration`、`gen_ai.client.operation.time_to_first_chunk`、`gen_ai.client.token.usage`。- **JsonlSpanExporter** —— 将每条 span 以 JSON 单行写入- `./cubepi-traces/<date>/<trace_id>.jsonl`。文件按 `trace_id` 分片,+ `./cubeloop-traces/<date>/<trace_id>.jsonl`。文件按 `trace_id` 分片,因此一个文件包含整条 trace——运行本身加上所有嵌套 subagent 运行(继承同一trace)。适合本地开发与离线调试;可与任何支持 JSONL 的 OTel 查看工具配合,- 也可与 [`cubepi trace` CLI](./cli) 配合。+ 也可与 [`cubeloop trace` CLI](./cli) 配合。- **OTLP** —— 通过 `opentelemetry-exporter-otlp-proto-http`(HTTP)或`…-grpc` 带入自己的 exporter,传入 `Tracer(exporters=[…])` 即可。- **W3C trace context 传播** —— 出站 MCP 调用会自动将当前 `traceparent`@@ -58,14 +58,14 @@ trace进程退出处理程序,在进程正常退出时同步 flush 缓冲 span,即使忘记调用`await tracer.shutdown()` 也不会丢失数据。- **`tracing_context()`** —— 通过 contextvar 作用域块为单次运行设置标签和- 元数据(`cubepi.tags = ("beta-arm",)`、`cubepi.metadata.user_id = "u-42"`),+ 元数据(`cubeloop.tags = ("beta-arm",)`、`cubeloop.metadata.user_id = "u-42"`),并发 agent 各自看到独立的值。- **中间件自有 provider 自动接入 trace** —— 中间件通过`Middleware.providers()` 暴露自己持有的 `BaseProvider`,`Recorder.attach()` 会自动给这些 provider 接上 listener 注册表,它们的`chat` span 就和 agent 主调用落进同一条 trace。`CompactionMiddleware`就用这个机制把摘要 LLM 调用呈现为嵌在- `cubepi.compaction.summarize` 下的 `chat <summary-model>` —— 详见+ `cubeloop.compaction.summarize` 下的 `chat <summary-model>` —— 详见[compaction 指南](../middleware/compaction#tracing)。## 开销@@ -94,6 +94,6 @@ trace## 下一步- [快速开始](./getting-started) —— 安装 extra 并发出第一批 span-- [OTLP 与后端](./otlp) —— 将 CubePi 接入 Jaeger、Tempo、Honeycomb……+- [OTLP 与后端](./otlp) —— 将 CubeLoop 接入 Jaeger、Tempo、Honeycomb……- [内容记录与脱敏](./content-recording) —— 安全地记录 prompt 与响应- [Metrics](./metrics) —— 通过 `Meter` 使用直方图diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdxindex 5994851..57dbb3f 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/intro.mdx@@ -1,6 +1,6 @@---id: intro-title: CubePi+title: CubeLoopdescription: "一个 Pythonic、原生异步的 Agent 框架。普通的 async 函数、追加式 checkpointing、三个依赖。"slug: /sidebar_position: 0@@ -8,17 +8,17 @@ sidebar_position: 0import PackageVersion from '@site/src/components/PackageVersion';-# CubePi+# CubeLoop-**CubePi** 是一个 Pythonic、原生异步的 Agent 框架,为高性能、可读性和+**CubeLoop** 是一个 Pythonic、原生异步的 Agent 框架,为高性能、可读性和生产级持久化而设计。它把一次 Agent 运行建模为一个线性的 `while`循环——可追踪、可调试,没有 DAG、没有图 DSL、没有出人意料的控制流。整个核心循环你五分钟就能读完。-[CubePlex](https://github.com/cubeplexai/cubeplex) 基于 CubePi 构建,是面向团队工作区的云原生托管 Agent 平台——技能、共享记忆、MCP 工具、持久化沙箱、权限治理,并可在 Docker Compose 或 Kubernetes 上自托管。+[CubePlex](https://github.com/cubeplexai/cubeplex) 基于 CubeLoop 构建,是面向团队工作区的云原生托管 Agent 平台——技能、共享记忆、MCP 工具、持久化沙箱、权限治理,并可在 Docker Compose 或 Kubernetes 上自托管。```bash-pip install cubepi+pip install cubeloop```然后跳到 [快速开始](./getting-started/quick-start.md),五分钟内跑通一个@@ -70,11 +70,11 @@ pip install cubepi这里描述的 API 在打 tag 发布之前还可能变动。最新已发布版本是 v<PackageVersion />([从右上角版本选择器切换](pathname:///))。-CubePi 0.13 新增所有 provider 的推理能力原语和控制、运行内作用域的+CubeLoop 0.13 新增所有 provider 的推理能力原语和控制、运行内作用域的压缩和真实令牌触发、工具批处理故障隔离保留所有检查点状态、以及耐用的并行 HITL 批准重放。0.13.1 修复了 tracing flush 路径:`force_flush`现在脱离 event loop 运行,`trace()` 新增 `flush="background"` 模式,适用于不能让 span 导出阻塞用户响应的服务路径。源代码、Issue 和讨论都在-[GitHub](https://github.com/cubeplexai/cubepi)。+[GitHub](https://github.com/cubeplexai/cubeloop)。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-cubepi.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-cubepi.mdnew file mode 100644index 0000000..327a545--- /dev/null+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-cubepi.md@@ -0,0 +1,56 @@+---+title: From cubepi+description: "CubePi was renamed to CubeLoop in 0.14. How to update installs, imports, checkpointer schema, and traces."+---++# Migrating from cubepi++0.14 renames the project from CubePi / `cubepi` to CubeLoop / `cubeloop`.+GitHub keeps the same repository (renamed in place to `cubeplexai/cubeloop`).+The docs site is https://cubeloop.dev.++## Install and imports++```bash+pip install cubeloop+# extras are unchanged: cubeloop[sqlite], cubeloop[postgres], cubeloop[mysql], …+```++```python+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider+```++`pip install -U cubepi` still works: 0.14+ is a wrapper that depends on+`cubeloop==0.14.0`, re-exports the public API, and aliases `cubepi.*` imports.+It warns on first import. Prefer depending on `cubeloop` directly.++CLI: `cubeloop trace` (the wrapper still provides `cubepi trace` and warns).++## Checkpointer schema v5 → v6++Postgres and MySQL table names moved from `cubepi_*` to `cubeloop_*`.+SQLite table names were never prefixed; they stay `messages` / `runs` / ….++Existing databases: add an Alembic revision that runs+`upgrade_v5_to_v6_op()` then `write_schema_version_op()`. Opening 0.14 against+an unmigrated v5 database raises `CubeloopSchemaMismatch` pointing at that+helper — not “tables not found”.++If you have data tables but no `*_schema_version` table, do not apply the+fresh v6 CREATE TABLE. Create `cubepi_schema_version` with version 5 first,+then run the v5→v6 helper.++## Tracing++New spans use `cubeloop.*` attributes and `cubeloop.turn` span names.+`cubeloop trace` still reads 0.13 JSONL that used `cubepi.*`.+Dashboards you own need their own attribute-name update.++Default JSONL directory is `./cubeloop-traces`.++## Environment variables++`CUBELOOP_TEST_PG_DSN`, `CUBELOOP_TEST_MYSQL_DSN`, `CUBELOOP_PG_DSN`,+`CUBELOOP_MYSQL_DSN` replace the `CUBEPI_*` names. The old names are still+read if the new one is unset, for the rest of 0.x.diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.mdindex 4c8d842..6453f48 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/migration/from-langgraph.md@@ -1,21 +1,21 @@---title: 从 langgraph 迁移-description: "将你的 agent 从 LangGraph 迁移到 CubePi。"+description: "将你的 agent 从 LangGraph 迁移到 CubeLoop。"---# 从 langgraph 迁移-CubePi 和 [langgraph](https://github.com/langchain-ai/langgraph) 都用于构建+CubeLoop 和 [langgraph](https://github.com/langchain-ai/langgraph) 都用于构建使用工具的 LLM agent,但两者的思维模型有所不同。-本页将 langgraph 概念映射到 CubePi,让你无需从头学起就能移植代码。+本页将 langgraph 概念映射到 CubeLoop,让你无需从头学起就能移植代码。## 思维模型转换-| langgraph | CubePi | 原因 |+| langgraph | CubeLoop | 原因 ||---|---|---|-| **状态图**,包含节点、边、channel | **Agent 循环**,就是一个可读的普通 `while` 循环 | 线性循环比图更易于推理;CubePi 在运行时从不分支 —— 控制流在 middleware 中 |+| **状态图**,包含节点、边、channel | **Agent 循环**,就是一个可读的普通 `while` 循环 | 线性循环比图更易于推理;CubeLoop 在运行时从不分支 —— 控制流在 middleware 中 || **Channels**(类型化状态槽) | **`AgentContext.extra`** + `AgentState.messages` | 一个 dict 加一个消息列表,覆盖了我们见过的所有状态结构 |-| **`StateGraph.add_node(name, fn)`** | middleware hook 或一个工具 | langgraph 节点中的函数在 CubePi 中分为两种角色:工具执行(由模型决定时)和 middleware(始终生效的变换) |+| **`StateGraph.add_node(name, fn)`** | middleware hook 或一个工具 | langgraph 节点中的函数在 CubeLoop 中分为两种角色:工具执行(由模型决定时)和 middleware(始终生效的变换) || **`add_edge(a, b)`** / `add_conditional_edges` | 内置:工具 → 下一轮 → 工具 → … | 条件形式(工具调用 → 重新提示)就是循环本身,无需显式构建 || **`MemorySaver` / `SqliteSaver` / `PostgresSaver`** | `MemoryCheckpointer` / `SQLiteCheckpointer` / `PostgresCheckpointer` | 思路相同,但采用追加写入 schema,而非完整快照 || **`config: {"configurable": {"thread_id": …}}`** | `Agent(thread_id=…)` | 作为 agent 的一等参数 |@@ -23,7 +23,7 @@ CubePi 和 [langgraph](https://github.com/langchain-ai/langgraph) 都用于构| **以 `@tool` 装饰器修饰的工具函数** | 带有 Pydantic 参数和 async execute 的 `AgentTool` | 更接近 OpenAI/Anthropic 原生形式 || **`HumanMessage`、`AIMessage`** | `UserMessage`、`AssistantMessage` | 相同的角色标记消息,只是重命名 || **通过 `interrupt_before` / `interrupt_after` 中断** | `agent.steer(...)`、`agent.follow_up(...)`、`agent.abort()` | 命令式控制,而非声明式中断点 |-| **任意检查点的时间旅行 / 分叉** | **`Agent.fork()`** / **`Agent.fork_once()`**,在 run 边界处 | CubePi 以已完成的 `run_id` 为基准;参见 [会话分叉](../guides/agents/forking) |+| **任意检查点的时间旅行 / 分叉** | **`Agent.fork()`** / **`Agent.fork_once()`**,在 run 边界处 | CubeLoop 以已完成的 `run_id` 为基准;参见 [会话分叉](../guides/agents/forking) || **`config_schema`** | `Agent` 的构造函数参数 | 没有独立的 schema 层 |## 并排对比:一个使用工具的 agent@@ -68,12 +68,12 @@ for chunk in app.stream({"messages": [("user", "Weather in Tokyo?")]}):print(chunk)```-### CubePi+### CubeLoop```pythonimport asyncio-from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -96,7 +96,7 @@ docstring 作为描述,返回的普通 `str` 会自动包装。(若工具需要或动态构建,完整的 `AgentTool(...)` 写法依然可用 —— 见[工具使用](../guides/agents/tool-use)。)-CubePi 版本去除了:+CubeLoop 版本去除了:- `StateGraph`、边、节点、`END` 哨兵、条件边。- `ToolNode` 注册表 —— 工具直接传给 `Agent`。@@ -112,13 +112,13 @@ CubePi 版本去除了:from langgraph.checkpoint.sqlite import SqliteSavergraph.compile(checkpointer=SqliteSaver.from_conn_string(":memory:"))-# CubePi-from cubepi.checkpointer import SQLiteCheckpointer+# CubeLoop+from cubeloop.checkpointer import SQLiteCheckpointerasync with SQLiteCheckpointer("agent.db") as cp:agent = Agent(..., checkpointer=cp, thread_id="conv-1")```-CubePi 的追加写入模型每条消息的复杂度为 O(1),与对话长度无关。+CubeLoop 的追加写入模型每条消息的复杂度为 O(1),与对话长度无关。langgraph 保存完整快照,随历史记录线性增长。### 流式输出@@ -129,7 +129,7 @@ for chunk in app.stream(state, stream_mode="messages"):if chunk["event"] == "on_chat_model_stream":print(chunk["data"]["chunk"].content, end="")-# CubePi+# CubeLoopdef on_event(event, signal=None):if event.type == "message_update" and event.stream_event.type == "text_delta":print(event.stream_event.delta, end="")@@ -146,7 +146,7 @@ await agent.prompt("…")# langgraphgraph.compile(interrupt_before=["tools"])-# CubePi+# CubeLoopclass HumanApproval(Middleware):async def before_tool_call(self, ctx, *, signal=None):approved = await ask_human(f"Run {ctx.tool_call.name}({ctx.args})?")@@ -168,7 +168,7 @@ graph.add_edge("summary", END)``````python-# CubePi+# CubeLoopclass SummariseAtEnd(Middleware):async def should_stop_after_turn(self, ctx) -> bool:msg = ctx.message@@ -190,14 +190,14 @@ config = {"configurable": {"thread_id": "t1", "checkpoint_id": "<id>"}}app.update_state(config, {"messages": [...]})result = app.invoke(None, config)-# CubePi — 在已完成的 run 边界处持久化分叉+# CubeLoop — 在已完成的 run 边界处持久化分叉await agent.fork(src_thread_id="conv_123",new_thread_id="conv_456",after_run_id="R1",)-# CubePi — 临时一次性探针(不写入任何线程)+# CubeLoop — 临时一次性探针(不写入任何线程)result = await agent.fork_once(src_thread_id="conv_123",message="如果你当时回答了'是'呢?",@@ -206,19 +206,19 @@ result = await agent.fork_once(print(result.text)```-CubePi 在已完成的 run 边界处分叉,而非任意 mid-run 检查点。`fork`+CubeLoop 在已完成的 run 边界处分叉,而非任意 mid-run 检查点。`fork`创建可继续对话的持久化分支;`fork_once` 运行单次探针并丢弃所有内容。参见[会话分叉](../guides/agents/forking)。-## LangGraph 仍优于 CubePi 的能力+## LangGraph 仍优于 CubeLoop 的能力-- **图原生的多智能体编排。** CubePi 提供 `SubagentMiddleware`,支持工具驱动的委派:+- **图原生的多智能体编排。** CubeLoop 提供 `SubagentMiddleware`,支持工具驱动的委派:父 Agent 可以将自包含任务分派给具有专属 prompt、model、tools 和 middleware 的- 类型化子 Agent。CubePi 目前尚未提供 LangGraph 那种显式、可持久化的图模型,+ 类型化子 Agent。CubeLoop 目前尚未提供 LangGraph 那种显式、可持久化的图模型,用于 supervisor 路由、条件分支、并行 fan-out/fan-in 以及图级状态管理。- **可视化图渲染。** 没有 `app.get_graph().draw_mermaid()` 的等价物。- CubePi 的流程是线性的,画出来也只是一条直线。-- **原生 trace 可视化 UI。** CubePi 不像 LangSmith / Langfuse 那样+ CubeLoop 的流程是线性的,画出来也只是一条直线。+- **原生 trace 可视化 UI。** CubeLoop 不像 LangSmith / Langfuse 那样渲染自己的 trace 可视化界面;它改为发射符合厂商中立标准的OpenTelemetry —— 通过`Tracer(exporters=[OTLPSpanExporter(...)])` 将任意 OTLP 后端@@ -226,7 +226,7 @@ CubePi 在已完成的 run 边界处分叉,而非任意 mid-run 检查点。`fHoneycomb、Datadog 等)接入。参见[Tracing → OTLP & Backends](../guides/tracing/otlp)。-## CubePi 有而 langgraph 没有的功能+## CubeLoop 有而 langgraph 没有的功能- **原生 OpenTelemetry tracing** —— `Tracer` + `Meter` 开箱即用地发射带 GenAI-semconv 属性的 OTel span,可被任意 OTLP 后端采集。diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/ask-user-form.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/ask-user-form.mdindex 71b1f88..e78b07b 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/ask-user-form.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/ask-user-form.md@@ -1,6 +1,6 @@---title: 通过 ask_user 实现多问题表单-description: "使用 CubePi 的 ask_user HITL 工具构建多问题表单以收集结构化用户输入。"+description: "使用 CubeLoop 的 ask_user HITL 工具构建多问题表单以收集结构化用户输入。"---# 配方:通过 `ask_user` 实现多问题表单@@ -11,8 +11,8 @@ description: "使用 CubePi 的 ask_user HITL 工具构建多问题表单以收## 步骤 1:注册工具```python-from cubepi.agent.agent import Agent-from cubepi.hitl import InMemoryChannel, ask_user_tool+from cubeloop.agent.agent import Agent+from cubeloop.hitl import InMemoryChannel, ask_user_toolchannel = InMemoryChannel()@@ -151,8 +151,8 @@ tool_result.details["hitl"]["seconds"] = 30.0```pythonimport asyncio-from cubepi.agent.agent import Agent-from cubepi.hitl import InMemoryChannel, ask_user_tool+from cubeloop.agent.agent import Agent+from cubeloop.hitl import InMemoryChannel, ask_user_toolchannel = InMemoryChannel()@@ -184,11 +184,11 @@ asyncio.run(main())## 运行示例仓库中有一份完整可运行的代码,位于-[`examples/ask_user_form.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/ask_user_form.py)。+[`examples/ask_user_form.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/ask_user_form.py)。Host 循环以编程方式回答所有问题,无需接入真实 UI 即可观察完整的交互过程。```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # 或 OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.mdindex 47142e9..5b595ea 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/multi-provider-failover.md@@ -6,7 +6,7 @@ description: "用内置 FallbackBoundModel 在 LLM provider 之间自动降级# Recipe:多 Provider 故障转移主 provider 限流、不可用或撞上上下文窗口时,自动切到下一条,不要把 agent 打崩。-CubePi 内置 `FallbackBoundModel`,不必再手写适配器。+CubeLoop 内置 `FallbackBoundModel`,不必再手写适配器。**预计耗时:** 5 分钟。**依赖:** `cubepi`,以及至少两套 provider API key。@@ -15,9 +15,9 @@ CubePi 内置 `FallbackBoundModel`,不必再手写适配器。```pythonimport os-from cubepi import Agent, FallbackBoundModel-from cubepi.providers.anthropic import AnthropicProvider-from cubepi.providers.openai import OpenAIProvider+from cubeloop import Agent, FallbackBoundModel+from cubeloop.providers.anthropic import AnthropicProvider+from cubeloop.providers.openai import OpenAIProvideranthropic = AnthropicProvider(api_key=os.environ["ANTHROPIC_API_KEY"])openai = OpenAIProvider(api_key=os.environ["OPENAI_API_KEY"])@@ -74,8 +74,8 @@ await agent.prompt("Capital of Mongolia?")用 `trigger_errors` 覆盖默认集合:```python-from cubepi import FallbackBoundModel-from cubepi.errors import ProviderAuthFailed, ProviderUnavailable, RateLimited+from cubeloop import FallbackBoundModel+from cubeloop.errors import ProviderAuthFailed, ProviderUnavailable, RateLimitedmodel = FallbackBoundModel(chain=(primary, fallback),@@ -143,7 +143,7 @@ error: BaseException | str)`,**只在真正 hop 时**触发,同模型重试仓库里有可运行版本:```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # 或 OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/persistent-chat.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/persistent-chat.mdindex 06a3c86..496a962 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/persistent-chat.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/persistent-chat.md@@ -1,6 +1,6 @@---title: 持久化聊天-description: "使用 CubePi 和 SQLiteCheckpointer 构建持久化聊天应用。"+description: "使用 CubeLoop 和 SQLiteCheckpointer 构建持久化聊天应用。"---# Recipe:持久化聊天(SQLite)@@ -9,7 +9,7 @@ description: "使用 CubePi 和 SQLiteCheckpointer 构建持久化聊天应用每位用户拥有独立的 `thread_id`。**预计耗时:** 5 分钟。-**依赖:** `cubepi[sqlite]`、`ANTHROPIC_API_KEY`。+**依赖:** `cubeloop[sqlite]`、`ANTHROPIC_API_KEY`。## 脚本@@ -18,9 +18,9 @@ import asyncioimport osimport sys-from cubepi import Agent-from cubepi.checkpointer import SQLiteCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import SQLiteCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderasync def main(thread_id: str):@@ -63,7 +63,7 @@ if __name__ == "__main__":运行:```bash-pip install "cubepi[sqlite]"+pip install "cubeloop[sqlite]"export ANTHROPIC_API_KEY=sk-…python chat.py alice# 聊一会儿,然后按 Ctrl-D。@@ -78,7 +78,7 @@ python chat.py bob## 运行原理-- **每个进程的第一次 `prompt()` 会加载历史记录。** CubePi 在第一次+- **每个进程的第一次 `prompt()` 会加载历史记录。** CubeLoop 在第一次prompt 开始时检查一次 checkpointer,恢复 `agent.state.messages`,然后继续。- **每个 `message_end` 追加写入数据库。** 没有批处理,没有有损缓冲。@@ -119,7 +119,7 @@ sqlite3 chat.db "DELETE FROM messages WHERE thread_id='alice'; DELETE FROM threamiddleware:```python-from cubepi import Middleware+from cubeloop import Middlewareclass SlidingWindow(Middleware):def __init__(self, n: int) -> None:@@ -145,7 +145,7 @@ agent = Agent(代码相同,仅替换 checkpointer:```python-from cubepi.checkpointer import PostgresCheckpointer+from cubeloop.checkpointer import PostgresCheckpointerasync with PostgresCheckpointer("postgresql://…") as cp:agent = Agent(model=…, checkpointer=cp, thread_id=…)@@ -172,10 +172,10 @@ Postgres 适合多实例服务或大量并发用户 ——## 运行示例仓库中有一份完整可运行的代码,位于-[`examples/persistent_chat.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/persistent_chat.py)。+[`examples/persistent_chat.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/persistent_chat.py)。```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv sync --extra sqliteexport ANTHROPIC_API_KEY=sk-ant-... # 或 OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/postgres-fastapi.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/postgres-fastapi.mdindex abb3069..ac3fa7c 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/postgres-fastapi.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/postgres-fastapi.md@@ -1,21 +1,21 @@---title: Postgres + FastAPI 服务-description: "使用 PostgresCheckpointer 将 FastAPI 后端的 CubePi agent 部署到生产环境。"+description: "使用 PostgresCheckpointer 将 FastAPI 后端的 CubeLoop agent 部署到生产环境。"---# Recipe:Postgres + FastAPI 服务-一个生产形态的 HTTP 服务,用于封装 CubePi agent:以 FastAPI 做路由,+一个生产形态的 HTTP 服务,用于封装 CubeLoop agent:以 FastAPI 做路由,Server-Sent Events 做流式传输,共享的 `PostgresCheckpointer` 做持久化,`thread_id` 从已认证用户派生。**预计耗时:** 30 分钟。-**依赖:** `cubepi[postgres]`、`fastapi`、`uvicorn[standard]`、-`sse-starlette`、已运行并应用 CubePi schema 的 Postgres 实例。+**依赖:** `cubeloop[postgres]`、`fastapi`、`uvicorn[standard]`、+`sse-starlette`、已运行并应用 CubeLoop schema 的 Postgres 实例。## 先建 Schema-在服务启动之前,运行 CubePi schema 迁移。本 recipe 最快捷的方式:+在服务启动之前,运行 CubeLoop schema 迁移。本 recipe 最快捷的方式:```bashpsql "$DATABASE_URL" <<'SQL'@@ -72,9 +72,9 @@ from fastapi import FastAPI, Depends, HTTPExceptionfrom pydantic import BaseModelfrom sse_starlette.sse import EventSourceResponse-from cubepi import Agent-from cubepi.checkpointer import PostgresCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import PostgresCheckpointer+from cubeloop.providers.anthropic import AnthropicProvider# --- 应用生命周期 ----------------------------------------------------------@@ -173,8 +173,8 @@ async def get_history(运行:```bash-pip install "cubepi[postgres]" fastapi "uvicorn[standard]" sse-starlette-export DATABASE_URL=postgresql://user:pass@localhost/cubepi+pip install "cubeloop[postgres]" fastapi "uvicorn[standard]" sse-starlette+export DATABASE_URL=postgresql://user:pass@localhost/cubeloopexport ANTHROPIC_API_KEY=sk-…uvicorn service:app --reload --port 8000```@@ -233,7 +233,7 @@ curl -N -X POST http://localhost:8000/chat/conv1/messages \## 常见陷阱-- **启动时 CubepiSchemaUninitialized** —— 迁移未运行。请先应用 schema。+- **启动时 CubeloopSchemaUninitialized** —— 迁移未运行。请先应用 schema。- **连接池耗尽** —— 默认 `max_pool_size=10`。如果服务的并发 agent数量超过此值,请调大。- **SSE 在负载均衡器后面** —— 某些负载均衡器会缓冲 SSE。禁用缓冲@@ -250,13 +250,13 @@ curl -N -X POST http://localhost:8000/chat/conv1/messages \## 运行示例仓库中有一份完整可运行的代码,位于-[`examples/postgres_fastapi.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/postgres_fastapi.py)。+[`examples/postgres_fastapi.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/postgres_fastapi.py)。```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv sync --extra postgres-export DATABASE_URL=postgresql://user:pass@localhost/cubepi+export DATABASE_URL=postgresql://user:pass@localhost/cubeloopexport ANTHROPIC_API_KEY=sk-ant-... # 或 OPENAI_API_KEY [+ OPENAI_BASE_URL]uv run --with fastapi --with "uvicorn[standard]" --with sse-starlette \diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.mdindex 35391ac..43bab42 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/resumable-tasks.md@@ -1,17 +1,17 @@---title: 可恢复长任务-description: "使用 CubePi checkpointing 和恢复机制构建崩溃容错的长时间运行任务。"+description: "使用 CubeLoop checkpointing 和恢复机制构建崩溃容错的长时间运行任务。"---# Recipe:可恢复长任务当 agent 正在执行一个长时间运行的操作(一系列工具调用、多轮推理会话)时,如果进程崩溃,你希望能从中断处继续,而不是从头开始。-CubePi 的追加写入 checkpointing 加上 `agent.resume()` 让**轮次之间**+CubeLoop 的追加写入 checkpointing 加上 `agent.resume()` 让**轮次之间**的恢复变得轻而易举;而**工具执行中途**的恢复则需要多一些准备。**预计耗时:** 15 分钟。-**依赖:** `cubepi[sqlite]`、`ANTHROPIC_API_KEY`。+**依赖:** `cubeloop[sqlite]`、`ANTHROPIC_API_KEY`。## 模式概述@@ -23,7 +23,7 @@ CubePi 的追加写入 checkpointing 加上 `agent.resume()` 让**轮次之间**看到最后一条消息是 `ToolResultMessage`,重新调用模型。*使用 checkpointer 即免费获得。*3. **工具执行中途** —— 工具已启动但未完成。尚未持久化任何内容- (CubePi 只持久化消息)。需要工具内部的幂等性。*需要额外处理。*+ (CubeLoop 只持久化消息)。需要工具内部的幂等性。*需要额外处理。*本 recipe 重点关注第 3 种情况。@@ -37,11 +37,11 @@ import osimport jsonfrom pathlib import Path-from cubepi import AgentToolResult, TextContent, tool+from cubeloop import AgentToolResult, TextContent, tool# 简单的文件支撑 job store;生产中替换为 Redis / Postgres。-JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubepi-jobs"))+JOB_DIR = Path(os.environ.get("JOB_DIR", "/tmp/cubeloop-jobs"))JOB_DIR.mkdir(parents=True, exist_ok=True)@@ -86,9 +86,9 @@ import asyncioimport osimport sys-from cubepi import Agent-from cubepi.checkpointer import SQLiteCheckpointer-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent+from cubeloop.checkpointer import SQLiteCheckpointer+from cubeloop.providers.anthropic import AnthropicProviderfrom tools import transcode_video # 上面用 @tool 装饰的 AgentTool@@ -123,7 +123,7 @@ async def main(thread_id: str, initial_prompt: str | None):# 没有排队 steer/follow_up 的 AssistantMessage → 抛出异常last = agent.state.messages[-1]if type(last).__name__ == "AssistantMessage":- from cubepi.providers.base import ToolCall+ from cubeloop.providers.base import ToolCallhas_pending_tools = any(isinstance(c, ToolCall) for c in last.content)if not has_pending_tools:# 任务已正常完成,无待执行的工具调用。@@ -187,7 +187,7 @@ async def smart_resume(agent, cp, thread_id):## 关于持久化部分工具状态-CubePi 不提供"持久化部分工具结果"的 API。预期的模式是:将部分状态+CubeLoop 不提供"持久化部分工具结果"的 API。预期的模式是:将部分状态保存在工具自己的外部存储中(文件系统、Redis、S3),以工具参数为键进行确定性寻址。上面的 `transcode_video` 用 `JOB_DIR` 实现的就是这种模式。@@ -217,10 +217,10 @@ CubePi 不提供"持久化部分工具结果"的 API。预期的模式是:将## 运行示例仓库中有一份完整可运行的代码,位于-[`examples/resumable_tasks.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/resumable_tasks.py)。+[`examples/resumable_tasks.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/resumable_tasks.py)。```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv sync --extra sqliteexport ANTHROPIC_API_KEY=sk-ant-... # 或 OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.mdindex 3d1ff4d..decaeb9 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/sandbox-confirm.md@@ -1,6 +1,6 @@---title: 使用 ApprovalPolicyMiddleware 做沙箱确认-description: "使用 CubePi 的 ApprovalPolicyMiddleware 实现沙箱工具确认——自动放行、拒绝或人工确认。"+description: "使用 CubeLoop 的 ApprovalPolicyMiddleware 实现沙箱工具确认——自动放行、拒绝或人工确认。"---# 配方:使用 `ApprovalPolicyMiddleware` 做沙箱确认@@ -14,7 +14,7 @@ description: "使用 CubePi 的 ApprovalPolicyMiddleware 实现沙箱工具确`Approve()`、`Deny(reason)` 或 `AskUser(...)`。```python-from cubepi.hitl import Approve, AskUser, Deny+from cubeloop.hitl import Approve, AskUser, Deny# 模拟规则引擎 —— 替换为你实际的策略目录。def classify_command(cmd: str) -> tuple[str, str | None]:@@ -47,9 +47,9 @@ def sandbox_policy(ctx):## 步骤 2:接入 agent```python-from cubepi.agent.agent import Agent-from cubepi.checkpointer.postgres import PostgresCheckpointer-from cubepi.hitl import ApprovalPolicyMiddleware, CheckpointedChannel+from cubeloop.agent.agent import Agent+from cubeloop.checkpointer.postgres import PostgresCheckpointer+from cubeloop.hitl import ApprovalPolicyMiddleware, CheckpointedChannelasync def main():async with PostgresCheckpointer("postgresql://...") as cp:@@ -93,7 +93,7 @@ async def host_loop(channel: CheckpointedChannel):timeout=timeout,)# 根据人类的决定构建 ApproveAnswer。- from cubepi.hitl import ApproveAnswer+ from cubeloop.hitl import ApproveAnswerhuman_answer = ApproveAnswer(decision=ui_response["decision"], # "approve" | "deny" | "edit"reason=ui_response.get("reason"), # 仅用于 deny@@ -139,11 +139,11 @@ await agent.abort_pending(reason="user closed tab")## 运行示例仓库中有一份完整可运行的代码,位于-[`examples/sandbox_confirm.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/sandbox_confirm.py)。+[`examples/sandbox_confirm.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/sandbox_confirm.py)。示例接入了一个模拟的 bash 工具和一个策略函数:读操作自动允许、危险写操作硬拒绝、其他操作由 host 循环自动确认。```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # 或 OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.mdindex 95f69af..ccb0ac2 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/recipes/weather-agent.md@@ -1,6 +1,6 @@---title: 天气 Agent-description: "使用 CubePi 工具构建一个调用真实 API 数据的天气 agent。"+description: "使用 CubeLoop 工具构建一个调用真实 API 数据的天气 agent。"---# Recipe:天气 Agent@@ -21,8 +21,8 @@ import httpxfrom typing import Annotatedfrom pydantic import Field-from cubepi import Agent, AgentToolResult, TextContent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, AgentToolResult, TextContent, tool+from cubeloop.providers.anthropic import AnthropicProvider# --- 工具 -----------------------------------------------------------------@@ -107,7 +107,7 @@ if __name__ == "__main__":运行:```bash-pip install cubepi httpx+pip install cubeloop httpxexport ANTHROPIC_API_KEY=sk-…python weather_agent.py```@@ -123,7 +123,7 @@ Tokyo is currently 18°C with a wind speed of 12 km/h. São Paulo is 25°C with## 运行原理- **两个工具并行执行。** 模型在同一个 assistant 轮次中发出两次- `get_weather` 工具调用。CubePi 并发运行它们 ——+ `get_weather` 工具调用。CubeLoop 并发运行它们 ——第二个不等第一个完成。- **流式文本和工具事件交错。** `on_event` 过滤器同时处理`text_delta`(用于最终答案)和 `tool_execution_start`(用于"思考中"指示器)。@@ -150,10 +150,10 @@ Tokyo is currently 18°C with a wind speed of 12 km/h. São Paulo is 25°C with## 运行示例仓库中有一份完整可运行的代码,位于-[`examples/weather_agent.py`](https://github.com/cubeplexai/cubepi/blob/main/examples/weather_agent.py)。+[`examples/weather_agent.py`](https://github.com/cubeplexai/cubeloop/blob/main/examples/weather_agent.py)。```bash-git clone https://github.com/cubeplexai/cubepi && cd cubepi+git clone https://github.com/cubeplexai/cubeloop && cd cubeloopuv syncexport ANTHROPIC_API_KEY=sk-ant-... # 或 OPENAI_API_KEY [+ OPENAI_BASE_URL]diff --git a/website/scripts/build_api_reference.py b/website/scripts/build_api_reference.pyindex 79f7397..bfe2797 100644--- a/website/scripts/build_api_reference.py+++ b/website/scripts/build_api_reference.py@@ -1,4 +1,4 @@-"""Generate Docusaurus-compatible MDX from cubepi public API via griffe.+"""Generate Docusaurus-compatible MDX from cubeloop public API via griffe.Pipeline:@@ -40,13 +40,13 @@ import griffefrom griffe import AliasResolutionErrorMODULES = [- ("cubepi.agent", "Agents", 1),- ("cubepi.providers", "Providers", 2),- ("cubepi.checkpointer", "Checkpointing", 3),- ("cubepi.middleware", "Middleware", 4),- ("cubepi.mcp", "MCP", 5),- ("cubepi.tracing", "Tracing", 6),- ("cubepi.utils", "Utils", 7),+ ("cubeloop.agent", "Agents", 1),+ ("cubeloop.providers", "Providers", 2),+ ("cubeloop.checkpointer", "Checkpointing", 3),+ ("cubeloop.middleware", "Middleware", 4),+ ("cubeloop.mcp", "MCP", 5),+ ("cubeloop.tracing", "Tracing", 6),+ ("cubeloop.utils", "Utils", 7),]REPO_ROOT = Path(__file__).resolve().parents[2]@@ -166,7 +166,7 @@ def _source_relpath(filepath: str | Path) -> str:except ValueError:parts = path.as_posix().split("/")for index in range(len(parts) - 1, -1, -1):- if parts[index] == "cubepi":+ if parts[index] == "cubeloop":return "/".join(parts[index:])return path.as_posix()@@ -712,7 +712,7 @@ def emit_module("---\n\n")body = [f"# `{module_name}`", ""]- github_blob_root = f"https://github.com/cubeplexai/cubepi/blob/{source_ref}"+ github_blob_root = f"https://github.com/cubeplexai/cubeloop/blob/{source_ref}"for sym in symbols:body.append(render_symbol(sym, ref_index, github_blob_root))body.append("")@@ -724,7 +724,9 @@ def emit_module(def resolve_source_ref(cli_ref: str | None) -> str:if cli_ref:return cli_ref- env = os.environ.get("CUBEPI_DOCS_SOURCE_REF")+ env = os.environ.get("CUBELOOP_DOCS_SOURCE_REF") or os.environ.get(+ "CUBEPI_DOCS_SOURCE_REF"+ )if env:return envreturn "main"@@ -750,7 +752,7 @@ def main() -> int:args.out.mkdir(parents=True, exist_ok=True)source_ref = resolve_source_ref(args.ref)- top: griffe.Module = griffe.load("cubepi") # type: ignore[assignment]+ top: griffe.Module = griffe.load("cubeloop") # type: ignore[assignment]# Two-pass: collect symbols first, build the cross-ref index, then# render. This lets RST refs in any module link to symbols defineddiff --git a/website/scripts/tests/test_build_api_reference.py b/website/scripts/tests/test_build_api_reference.pyindex 88a78ce..e270e73 100644--- a/website/scripts/tests/test_build_api_reference.py+++ b/website/scripts/tests/test_build_api_reference.py@@ -45,11 +45,11 @@ def test_render_docstring_parses_google_sections():def test_rst_class_ref_links_when_in_index():mod = _load_module()- ref_index = {"Tracer": "./cubepi-tracing#tracer"}+ ref_index = {"Tracer": "./cubeloop-tracing#tracer"}out = mod._rst_to_mdx_refs("Build a :class:`Tracer`, attach it.", ref_index=ref_index)- assert "[`Tracer`](./cubepi-tracing#tracer)" in out+ assert "[`Tracer`](./cubeloop-tracing#tracer)" in outdef test_rst_class_ref_falls_back_to_inline_code():@@ -64,23 +64,23 @@ def test_rst_class_ref_falls_back_to_inline_code():def test_rst_class_ref_with_tilde_shortens_display():mod = _load_module()- ref_index = {"Tracer": "./cubepi-tracing#tracer"}+ ref_index = {"Tracer": "./cubeloop-tracing#tracer"}out = mod._rst_to_mdx_refs(- "See :class:`~cubepi.tracing.Tracer` for details.",+ "See :class:`~cubeloop.tracing.Tracer` for details.",ref_index=ref_index,)# ~ prefix means show only the last componentassert "[`Tracer`]" in out- assert "[`cubepi.tracing.Tracer`]" not in out+ assert "[`cubeloop.tracing.Tracer`]" not in outdef test_rst_meth_ref_resolves_class_member():mod = _load_module()- ref_index = {"Tracer.attach": "./cubepi-tracing#tracer-attach"}+ ref_index = {"Tracer.attach": "./cubeloop-tracing#tracer-attach"}out = mod._rst_to_mdx_refs("Each :meth:`Tracer.attach` call wires…", ref_index=ref_index)- assert "[`Tracer.attach`](./cubepi-tracing#tracer-attach)" in out+ assert "[`Tracer.attach`](./cubeloop-tracing#tracer-attach)" in outdef test_strip_rst_double_backticks():@@ -93,12 +93,12 @@ def test_rst_literal_block_marker_starts_code_fence():mod = _load_module()doc = ("Use it like this::\n\n"- " from cubepi import Agent\n"+ " from cubeloop import Agent\n"" agent = Agent(...)\n")out = mod.render_docstring(doc, ref_index={})assert "```python" in out- assert "from cubepi import Agent" in out+ assert "from cubeloop import Agent" in outdef test_rst_underline_heading_converts_to_bold():@@ -126,10 +126,10 @@ def test_source_relpath_strips_worktree_prefix():mod = _load_module()path = ("/home/chris/cubepi/.worktrees/2026-06-05-release-0.7-review/"- "cubepi/agent/agent.py"+ "cubeloop/agent/agent.py")- assert mod._source_relpath(path) == "cubepi/agent/agent.py"+ assert mod._source_relpath(path) == "cubeloop/agent/agent.py"def test_build_ref_index_includes_class_members():@@ -146,19 +146,19 @@ def test_build_ref_index_includes_class_members():tracer = _FakeClass("Tracer", {"attach": _FakeMember(), "_private": _FakeMember()})- index = mod.build_ref_index({"cubepi.tracing": [tracer]})- assert index["Tracer"] == "./cubepi-tracing#tracer"- assert index["Tracer.attach"] == "./cubepi-tracing#tracer-attach"+ index = mod.build_ref_index({"cubeloop.tracing": [tracer]})+ assert index["Tracer"] == "./cubeloop-tracing#tracer"+ assert index["Tracer.attach"] == "./cubeloop-tracing#tracer-attach"# Private members are skippedassert "Tracer._private" not in indexdef test_emit_module_writes_generated_marker(tmp_path):mod = _load_module()- module_path = tmp_path / "cubepi-utils.mdx"+ module_path = tmp_path / "cubeloop-utils.mdx"mod.emit_module(out_path=module_path,- module_name="cubepi.utils",+ module_name="cubeloop.utils",sidebar_position=6,symbols=[],ref_index={},@@ -166,5 +166,5 @@ def test_emit_module_writes_generated_marker(tmp_path):)body = module_path.read_text(encoding="utf-8")assert body.startswith("---\n")- assert "title: cubepi.utils" in body+ assert "title: cubeloop.utils" in bodyassert "<!-- GENERATED by build_api_reference.py — DO NOT EDIT -->" in bodydiff --git a/website/sidebars.ts b/website/sidebars.tsindex 64211dd..273d7fd 100644--- a/website/sidebars.ts+++ b/website/sidebars.ts@@ -74,13 +74,13 @@ const sidebars: SidebarsConfig = {label: 'API Reference',link: { type: 'doc', id: 'api/index' },items: [- 'api/cubepi-agent',- 'api/cubepi-providers',- 'api/cubepi-checkpointer',- 'api/cubepi-middleware',- 'api/cubepi-mcp',- 'api/cubepi-tracing',- 'api/cubepi-utils',+ 'api/cubeloop-agent',+ 'api/cubeloop-providers',+ 'api/cubeloop-checkpointer',+ 'api/cubeloop-middleware',+ 'api/cubeloop-mcp',+ 'api/cubeloop-tracing',+ 'api/cubeloop-utils',],},{@@ -99,7 +99,7 @@ const sidebars: SidebarsConfig = {{type: 'category',label: 'Migration',- items: ['migration/from-langgraph'],+ items: ['migration/from-cubepi', 'migration/from-langgraph'],},],};diff --git a/website/src/clientModules/posthog.ts b/website/src/clientModules/posthog.tsindex 2c1457b..45b8d4b 100644--- a/website/src/clientModules/posthog.ts+++ b/website/src/clientModules/posthog.ts@@ -14,7 +14,7 @@ if (typeof window !== 'undefined' && key) {autocapture: false,disable_session_recording: true,});- (window as any).__cubepi_posthog = posthog;+ (window as any).__cubeloop_posthog = posthog;}export {};diff --git a/website/src/components/Compare/ComparePage.tsx b/website/src/components/Compare/ComparePage.tsxindex a5c6b6d..859d6f8 100644--- a/website/src/components/Compare/ComparePage.tsx+++ b/website/src/components/Compare/ComparePage.tsx@@ -28,7 +28,7 @@ export interface CompareCode {export interface CompareContent {/** The competitor's display name, e.g. "LangGraph". */them: string;- /** <title> — must NOT lead with "CubePi" (the brand is appended). */+ /** <title> — must NOT lead with "CubeLoop" (the brand is appended). */title: string;description: string;keywords: string;@@ -53,8 +53,8 @@ export default function ComparePage({ content }: { content: CompareContent }): R'@type': 'TechArticle',headline: content.h1,description: content.description,- author: { '@type': 'Organization', name: 'CubePi', url: 'https://cubepi.ai' },- publisher: { '@type': 'Organization', name: 'CubePi', url: 'https://cubepi.ai' },+ author: { '@type': 'Organization', name: 'CubeLoop', url: 'https://cubeloop.dev' },+ publisher: { '@type': 'Organization', name: 'CubeLoop', url: 'https://cubeloop.dev' },})}</script></Head>@@ -71,7 +71,7 @@ export default function ComparePage({ content }: { content: CompareContent }): R<tr><th></th><th>{content.them}</th>- <th>CubePi</th>+ <th>CubeLoop</th></tr></thead><tbody>diff --git a/website/src/components/DocFeedback/index.test.tsx b/website/src/components/DocFeedback/index.test.tsxindex bc87cf5..201377a 100644--- a/website/src/components/DocFeedback/index.test.tsx+++ b/website/src/components/DocFeedback/index.test.tsx@@ -2,10 +2,10 @@ 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 } } }+declare global { interface Window { __cubeloop_posthog?: { capture: (e: string, p: object) => void } } }beforeEach(() => {- window.__cubepi_posthog = { capture: vi.fn() };+ window.__cubeloop_posthog = { capture: vi.fn() };});describe('DocFeedback', () => {@@ -18,7 +18,7 @@ describe('DocFeedback', () => {it('captures a doc_feedback event with helpful=true on 👍', () => {const capture = vi.fn();- window.__cubepi_posthog = { capture };+ window.__cubeloop_posthog = { capture };render(<DocFeedback slug="/foo" version="0.3" locale="en" />);fireEvent.click(screen.getByRole('button', { name: /yes/i }));expect(capture).toHaveBeenCalledWith('doc_feedback', {@@ -29,7 +29,7 @@ describe('DocFeedback', () => {it('shows a comment textarea on 👎 and captures doc_feedback_comment on submit', () => {const capture = vi.fn();- window.__cubepi_posthog = { capture };+ window.__cubeloop_posthog = { capture };render(<DocFeedback slug="/foo" version="0.3" locale="en" />);fireEvent.click(screen.getByRole('button', { name: /no/i }));expect(capture).toHaveBeenCalledWith('doc_feedback', {diff --git a/website/src/components/DocFeedback/index.tsx b/website/src/components/DocFeedback/index.tsxindex 1a4d60b..2c02668 100644--- a/website/src/components/DocFeedback/index.tsx+++ b/website/src/components/DocFeedback/index.tsx@@ -10,7 +10,7 @@ interface Props {type Phase = 'ask' | 'thanks' | 'comment' | 'submitted';function capture(event: string, payload: object) {- const ph = (window as any).__cubepi_posthog;+ const ph = (window as any).__cubeloop_posthog;if (ph && typeof ph.capture === 'function') ph.capture(event, payload);}diff --git a/website/src/components/Home/HelloAgent.tsx b/website/src/components/Home/HelloAgent.tsxindex fb878cf..e671ff0 100644--- a/website/src/components/Home/HelloAgent.tsx+++ b/website/src/components/Home/HelloAgent.tsx@@ -5,8 +5,8 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';import styles from './HelloAgent.module.css';const SAMPLE = `import asyncio-from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(api_key="sk-...")diff --git a/website/src/components/Home/Hero.tsx b/website/src/components/Home/Hero.tsxindex c80009f..9ac45cd 100644--- a/website/src/components/Home/Hero.tsx+++ b/website/src/components/Home/Hero.tsx@@ -6,8 +6,8 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';import styles from './Hero.module.css';export default function Hero() {- const social = useBaseUrl('/img/brand/cubepi-social-preview.png');- const installCmd = 'pip install cubepi';+ const social = useBaseUrl('/img/brand/cubeloop-social-preview.png');+ const installCmd = 'pip install cubeloop';const { siteConfig } = useDocusaurusContext();const zh = useIsZhHans();// Sourced from siteConfig.customFields.PACKAGE_VERSION (parsed from@@ -21,18 +21,18 @@ export default function Hero() {<imgclassName={styles.banner}src={social}- alt="CubePi · A Pythonic, async-native agent framework"+ alt="CubeLoop · A Pythonic, async-native agent framework"width={1280}height={640}fetchPriority="high"/>- <div className={styles.eyebrow}>cubepi · v{version}</div>+ <div className={styles.eyebrow}>cubeloop · v{version}</div>{/* Tagline lives inside the <h1> (as a styled subline) so the page'ssingle H1 carries the descriptive keyword phrase, not just the brandname — while rendering identically to the previous brand + taglinestack. */}<h1 className={styles.h1}>- CubePi+ CubeLoop<span className={styles.h1sub}>{zh ? '一个 Pythonic 原生异步 Agent 框架。' : 'A Pythonic, async-native agent framework.'}</span>@@ -40,13 +40,13 @@ export default function Hero() {<p className={styles.lead}>{zh ? (<>- CubePi 是一个 Pythonic 原生异步 Agent 框架,专为高性能、高可读性和生产级持久化而设计。+ CubeLoop 是一个 Pythonic 原生异步 Agent 框架,专为高性能、高可读性和生产级持久化而设计。它以线性 <code>while</code> 循环建模 agent 逻辑,提供比图结构 agent 运行时更轻量的替代方案,开发者可以轻松追踪和调试。</>) : (<>- CubePi is a Pythonic, async-native agent framework designed for high+ CubeLoop is a Pythonic, async-native agent framework designed for highperformance, readability, and production-grade persistence. It providesa leaner alternative to graph-based agent runtimes by modeling agentlogic as a linear <code>while</code> loop that developers can easily@@ -65,12 +65,12 @@ export default function Hero() {CubePlex</a>{' '}- 基于 CubePi 构建,是面向团队工作区的云原生托管 Agent 平台——技能、共享记忆、MCP 工具、+ 基于 CubeLoop 构建,是面向团队工作区的云原生托管 Agent 平台——技能、共享记忆、MCP 工具、持久化沙箱、权限治理,并可在 Docker Compose 或 Kubernetes 上自托管。</>) : (<>- CubePi powers{' '}+ CubeLoop powers{' '}<ahref="https://github.com/cubeplexai/cubeplex"target="_blank"diff --git a/website/src/components/Home/InstallMatrix.tsx b/website/src/components/Home/InstallMatrix.tsxindex 6c85371..e66f6c2 100644--- a/website/src/components/Home/InstallMatrix.tsx+++ b/website/src/components/Home/InstallMatrix.tsx@@ -3,10 +3,10 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';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,tracing,tracing-otlp]' },+ { tool: 'pip', cmd: 'pip install cubeloop' },+ { tool: 'uv', cmd: 'uv add cubeloop' },+ { tool: 'poetry', cmd: 'poetry add cubeloop' },+ { tool: 'extras', cmd: 'pip install cubeloop[sqlite,postgres,mcp,tracing,tracing-otlp]' },];export default function InstallMatrix() {diff --git a/website/src/components/Home/WhyTable.tsx b/website/src/components/Home/WhyTable.tsxindex 729a692..41945f0 100644--- a/website/src/components/Home/WhyTable.tsx+++ b/website/src/components/Home/WhyTable.tsx@@ -3,26 +3,26 @@ import Link from '@docusaurus/Link';import { useIsZhHans } from '@site/src/hooks/useIsZhHans';import styles from './WhyTable.module.css';-const ROWS_EN: { 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: '8 typed hooks with declarative composition rules' },- { label: 'Observability', langgraph: 'LangSmith / Langfuse integration', cubepi: 'Native OpenTelemetry — Tracer, Meter, GenAI semconv, OTLP / JSONL out of the box' },+const ROWS_EN: { label: string; langgraph: string; cubeloop: string }[] = [+ { label: 'Abstraction', langgraph: 'Graph nodes + edges + channels', cubeloop: 'Plain async functions — run_agent_loop is a while loop' },+ { label: 'Streaming', langgraph: 'Callback-based, multiple handler types', cubeloop: 'async for event in stream — one pattern everywhere' },+ { label: 'Checkpointing', langgraph: 'Full snapshot per step; serializes entire message list', cubeloop: 'Append-only — O(1) DB I/O regardless of conversation length' },+ { label: 'Dependencies', langgraph: 'langchain-core, langgraph-sdk, and transitive deps', cubeloop: '3 core deps: pydantic, anthropic, openai' },+ { label: 'Tool execution', langgraph: 'Tools are graph nodes with manual wiring', cubeloop: 'Declare tools as functions; framework routes and parallelizes' },+ { label: 'Multi-provider', langgraph: 'Via langchain chat model adapters', cubeloop: 'Native Provider protocol — Anthropic, OpenAI built in' },+ { label: 'Middleware', langgraph: 'Graph-level middleware on node entry/exit', cubeloop: '8 typed hooks with declarative composition rules' },+ { label: 'Observability', langgraph: 'LangSmith / Langfuse integration', cubeloop: 'Native OpenTelemetry — Tracer, Meter, GenAI semconv, OTLP / JSONL out of the box' },];-const ROWS_ZH: { label: string; langgraph: string; cubepi: string }[] = [- { label: '抽象模型', langgraph: '图节点 + 边 + 通道', cubepi: '普通 async 函数 — run_agent_loop 就是一个 while 循环' },- { label: '流式输出', langgraph: '基于回调,多种 handler 类型', cubepi: 'async for event in stream — 统一模式' },- { label: '检查点', langgraph: '每步全量快照,序列化整个消息列表', cubepi: '追加式 — 无论对话多长,每轮 O(1) DB I/O' },- { label: '依赖项', langgraph: 'langchain-core、langgraph-sdk 及传递依赖', cubepi: '3 个核心依赖:pydantic、anthropic、openai' },- { label: '工具执行', langgraph: '工具是需要手动连线的图节点', cubepi: '声明为函数;框架自动路由并并行执行' },- { label: '多 Provider', langgraph: '通过 langchain chat model 适配器', cubepi: '原生 Provider 协议 — 内置 Anthropic、OpenAI' },- { label: 'Middleware', langgraph: '图级中间件,在节点进出时触发', cubepi: '8 种类型化 hook,声明式组合规则' },- { label: '可观测性', langgraph: 'LangSmith / Langfuse 集成', cubepi: '原生 OpenTelemetry — Tracer、Meter、GenAI semconv,开箱即用 OTLP / JSONL' },+const ROWS_ZH: { label: string; langgraph: string; cubeloop: string }[] = [+ { label: '抽象模型', langgraph: '图节点 + 边 + 通道', cubeloop: '普通 async 函数 — run_agent_loop 就是一个 while 循环' },+ { label: '流式输出', langgraph: '基于回调,多种 handler 类型', cubeloop: 'async for event in stream — 统一模式' },+ { label: '检查点', langgraph: '每步全量快照,序列化整个消息列表', cubeloop: '追加式 — 无论对话多长,每轮 O(1) DB I/O' },+ { label: '依赖项', langgraph: 'langchain-core、langgraph-sdk 及传递依赖', cubeloop: '3 个核心依赖:pydantic、anthropic、openai' },+ { label: '工具执行', langgraph: '工具是需要手动连线的图节点', cubeloop: '声明为函数;框架自动路由并并行执行' },+ { label: '多 Provider', langgraph: '通过 langchain chat model 适配器', cubeloop: '原生 Provider 协议 — 内置 Anthropic、OpenAI' },+ { label: 'Middleware', langgraph: '图级中间件,在节点进出时触发', cubeloop: '8 种类型化 hook,声明式组合规则' },+ { label: '可观测性', langgraph: 'LangSmith / Langfuse 集成', cubeloop: '原生 OpenTelemetry — Tracer、Meter、GenAI semconv,开箱即用 OTLP / JSONL' },];export default function WhyTable() {@@ -31,7 +31,7 @@ export default function WhyTable() {return (<section className={styles.section}><h2 className={styles.h2}>- {zh ? '为什么选择 CubePi — langgraph 和 pi-agent-core 的替代方案' : 'Why CubePi — a langgraph and pi-agent-core alternative'}+ {zh ? '为什么选择 CubeLoop — langgraph 和 pi-agent-core 的替代方案' : 'Why CubeLoop — a langgraph and pi-agent-core alternative'}</h2><div className={styles.tableWrap}><table className={styles.table}>@@ -39,7 +39,7 @@ export default function WhyTable() {<tr><th></th><th>langgraph</th>- <th>CubePi</th>+ <th>CubeLoop</th></tr></thead><tbody>@@ -47,7 +47,7 @@ export default function WhyTable() {<tr key={r.label}><td className={styles.label}>{r.label}</td><td>{r.langgraph}</td>- <td className={styles.us}>{r.cubepi}</td>+ <td className={styles.us}>{r.cubeloop}</td></tr>))}</tbody>@@ -55,11 +55,11 @@ export default function WhyTable() {</div><p className={styles.more}><Link to="/compare/langgraph">- {zh ? '完整对比:CubePi vs LangGraph →' : 'Full comparison: CubePi vs LangGraph →'}+ {zh ? '完整对比:CubeLoop vs LangGraph →' : 'Full comparison: CubeLoop vs LangGraph →'}</Link>{' · '}<Link to="/compare/pi-agent-core">- {zh ? 'CubePi vs pi-agent-core →' : 'CubePi vs pi-agent-core →'}+ {zh ? 'CubeLoop vs pi-agent-core →' : 'CubeLoop vs pi-agent-core →'}</Link></p></section>diff --git a/website/src/components/PackageVersion/index.tsx b/website/src/components/PackageVersion/index.tsxindex 72409bc..2292e06 100644--- a/website/src/components/PackageVersion/index.tsx+++ b/website/src/components/PackageVersion/index.tsx@@ -2,7 +2,7 @@ import React from 'react';import useDocusaurusContext from '@docusaurus/useDocusaurusContext';/**- * Inline component that renders the current cubepi package version,+ * Inline component that renders the current cubeloop package version,* sourced from `siteConfig.customFields.PACKAGE_VERSION` which* `docusaurus.config.ts` parses out of `pyproject.toml` at* config-load time.diff --git a/website/src/pages/changelog.mdx b/website/src/pages/changelog.mdxindex bb91b31..bdcc187 100644--- a/website/src/pages/changelog.mdx+++ b/website/src/pages/changelog.mdx@@ -1,6 +1,6 @@---title: Changelog-description: Release notes for CubePi.+description: Release notes for CubeLoop.---import Changelog from '../../../CHANGELOG.md';diff --git a/website/src/pages/compare/crewai.tsx b/website/src/pages/compare/crewai.tsxindex 5106664..c5946da 100644--- a/website/src/pages/compare/crewai.tsx+++ b/website/src/pages/compare/crewai.tsx@@ -4,15 +4,15 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';const EN: CompareContent = {them: 'CrewAI',- title: 'CubePi vs CrewAI — a leaner Python agent framework',+ title: 'CubeLoop vs CrewAI — a leaner Python agent framework',description:- 'CubePi vs CrewAI: a side-by-side comparison. CrewAI models agents as role-playing crew members with assigned tasks. CubePi models the agent as a plain async while-loop with typed middleware, append-only checkpointing, and 3 core dependencies.',+ 'CubeLoop vs CrewAI: a side-by-side comparison. CrewAI models agents as role-playing crew members with assigned tasks. CubeLoop models the agent as a plain async while-loop with typed middleware, append-only checkpointing, and 3 core dependencies.',keywords:- 'CubePi vs CrewAI, CrewAI alternative, Python agent framework, async agent framework, CrewAI vs CubePi, multi-agent framework, crewai 替代品',- h1: 'CubePi vs CrewAI',+ 'CubeLoop vs CrewAI, CrewAI alternative, Python agent framework, async agent framework, CrewAI vs CubeLoop, multi-agent framework, crewai 替代品',+ h1: 'CubeLoop vs CrewAI',intro: [- 'CrewAI organises your agent system around role-playing metaphors — crews, agents with roles and backstories, and tasks that agents are assigned to. CubePi starts from a different premise: an agent is a plain async while-loop that calls the model, runs tools, and repeats.',- 'If the role-based abstraction is solving a problem you do not have, CubePi removes that layer. Here is how the two compare.',+ 'CrewAI organises your agent system around role-playing metaphors — crews, agents with roles and backstories, and tasks that agents are assigned to. CubeLoop starts from a different premise: an agent is a plain async while-loop that calls the model, runs tools, and repeats.',+ 'If the role-based abstraction is solving a problem you do not have, CubeLoop removes that layer. Here is how the two compare.',],tableHeading: 'Side-by-side',rows: [@@ -63,9 +63,9 @@ task = Task(crew = Crew(agents=[agent], tasks=[task], process=Process.sequential)result = crew.kickoff(inputs={"city": "Tokyo"})`,- usTitle: '# CubePi',- us: `from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+ usTitle: '# CubeLoop',+ us: `from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -87,20 +87,20 @@ await agent.prompt("What's the weather in Tokyo?"){h2: 'Roles, goals, and backstories — or just a system prompt',body: [- 'CrewAI\'s "role", "goal", and "backstory" fields are a structured way to write a system prompt. When you have one agent doing one job, the role metaphor adds ceremony without adding capability. In CubePi, `system_prompt` is a string you own completely — no framework vocabulary to learn, no structure to maintain.',- 'For genuine multi-agent scenarios, CubePi provides a `SubagentsMiddleware` that spawns child agents and wires their results back to the parent — without the crew/process/task object model.',+ 'CrewAI\'s "role", "goal", and "backstory" fields are a structured way to write a system prompt. When you have one agent doing one job, the role metaphor adds ceremony without adding capability. In CubeLoop, `system_prompt` is a string you own completely — no framework vocabulary to learn, no structure to maintain.',+ 'For genuine multi-agent scenarios, CubeLoop provides a `SubagentsMiddleware` that spawns child agents and wires their results back to the parent — without the crew/process/task object model.',],},{h2: 'Persistence that does not require you to wire it yourself',body: [- 'CrewAI does not ship a built-in checkpointing layer. If you want conversations to survive restarts you add your own database logic. CubePi\'s append-only checkpointing ships out of the box — `SQLiteCheckpointer`, `PostgresCheckpointer`, and `MySQLCheckpointer` each write only the new messages from each turn, so write cost stays O(1) regardless of how long the thread grows.',+ 'CrewAI does not ship a built-in checkpointing layer. If you want conversations to survive restarts you add your own database logic. CubeLoop\'s append-only checkpointing ships out of the box — `SQLiteCheckpointer`, `PostgresCheckpointer`, and `MySQLCheckpointer` each write only the new messages from each turn, so write cost stays O(1) regardless of how long the thread grows.',],},{h2: 'When CrewAI is the better fit',body: [- 'CrewAI is a reasonable choice if your workflow maps naturally onto the crew metaphor — a team of specialist agents each assigned a discrete task in a pipeline. If you are building a single conversational agent, a stateful assistant, or anything that needs production-grade persistence or OTel observability, CubePi is the leaner path.',+ 'CrewAI is a reasonable choice if your workflow maps naturally onto the crew metaphor — a team of specialist agents each assigned a discrete task in a pipeline. If you are building a single conversational agent, a stateful assistant, or anything that needs production-grade persistence or OTel observability, CubeLoop is the leaner path.',],},],@@ -112,15 +112,15 @@ await agent.prompt("What's the weather in Tokyo?")const ZH: CompareContent = {them: 'CrewAI',- title: 'CubePi vs CrewAI — 更精简的 Python Agent 框架',+ title: 'CubeLoop vs CrewAI — 更精简的 Python Agent 框架',description:- 'CubePi 与 CrewAI 对比:CrewAI 将 Agent 建模为具有角色和背景故事的"角色扮演"团队成员。CubePi 将 Agent 建模为普通的异步 while 循环,具备类型化中间件、追加式 checkpointing 和 3 个核心依赖。',+ 'CubeLoop 与 CrewAI 对比:CrewAI 将 Agent 建模为具有角色和背景故事的"角色扮演"团队成员。CubeLoop 将 Agent 建模为普通的异步 while 循环,具备类型化中间件、追加式 checkpointing 和 3 个核心依赖。',keywords:- 'CubePi vs CrewAI, CrewAI 替代品, Python Agent 框架, 异步 Agent 框架, CrewAI vs CubePi, 多 Agent 框架, crewai 替代品',- h1: 'CubePi vs CrewAI',+ 'CubeLoop vs CrewAI, CrewAI 替代品, Python Agent 框架, 异步 Agent 框架, CrewAI vs CubeLoop, 多 Agent 框架, crewai 替代品',+ h1: 'CubeLoop vs CrewAI',intro: [- 'CrewAI 围绕角色扮演的隐喻组织 Agent 系统 —— 团队(crew)、带有角色和背景故事的 Agent,以及分配给 Agent 的任务。CubePi 从不同的前提出发:Agent 是一个普通的异步 while 循环,调用模型、执行工具、循环往复。',- '如果角色抽象并不能解决你的问题,CubePi 直接省去这一层。以下是两者的详细对比。',+ 'CrewAI 围绕角色扮演的隐喻组织 Agent 系统 —— 团队(crew)、带有角色和背景故事的 Agent,以及分配给 Agent 的任务。CubeLoop 从不同的前提出发:Agent 是一个普通的异步 while 循环,调用模型、执行工具、循环往复。',+ '如果角色抽象并不能解决你的问题,CubeLoop 直接省去这一层。以下是两者的详细对比。',],tableHeading: '并排对比',rows: [@@ -138,20 +138,20 @@ const ZH: CompareContent = {{h2: '角色、目标、背景故事 —— 还是直接写 system prompt',body: [- 'CrewAI 的"角色"、"目标"和"背景故事"字段本质上是一种结构化写 system prompt 的方式。当你只有一个 Agent 做一件事时,角色隐喻增加的是仪式感而非能力。在 CubePi 中,`system_prompt` 就是你完全掌控的一个字符串 —— 没有框架词汇要学,没有结构要维护。',- '对于真正的多 Agent 场景,CubePi 提供 `SubagentsMiddleware`,可以派生子 Agent 并将其结果回传给父 Agent —— 无需 crew/process/task 对象模型。',+ 'CrewAI 的"角色"、"目标"和"背景故事"字段本质上是一种结构化写 system prompt 的方式。当你只有一个 Agent 做一件事时,角色隐喻增加的是仪式感而非能力。在 CubeLoop 中,`system_prompt` 就是你完全掌控的一个字符串 —— 没有框架词汇要学,没有结构要维护。',+ '对于真正的多 Agent 场景,CubeLoop 提供 `SubagentsMiddleware`,可以派生子 Agent 并将其结果回传给父 Agent —— 无需 crew/process/task 对象模型。',],},{h2: '开箱即用的持久化,无需自己接线',body: [- 'CrewAI 没有内置的 checkpointing 层。如果你希望对话在重启后依然存在,需要自己添加数据库逻辑。CubePi 的追加式 checkpointing 开箱即用 —— `SQLiteCheckpointer`、`PostgresCheckpointer` 和 `MySQLCheckpointer` 每轮只写入新消息,无论对话多长,写入成本保持 O(1)。',+ 'CrewAI 没有内置的 checkpointing 层。如果你希望对话在重启后依然存在,需要自己添加数据库逻辑。CubeLoop 的追加式 checkpointing 开箱即用 —— `SQLiteCheckpointer`、`PostgresCheckpointer` 和 `MySQLCheckpointer` 每轮只写入新消息,无论对话多长,写入成本保持 O(1)。',],},{h2: 'CrewAI 更适合的场景',body: [- '如果你的工作流自然地映射到 crew 的隐喻 —— 一组专家 Agent 各自负责流水线中的一个离散任务 —— CrewAI 是合理的选择。如果你在构建单一的对话 Agent、有状态的助手,或任何需要生产级持久化或 OTel 可观测性的系统,CubePi 是更精简的路径。',+ '如果你的工作流自然地映射到 crew 的隐喻 —— 一组专家 Agent 各自负责流水线中的一个离散任务 —— CrewAI 是合理的选择。如果你在构建单一的对话 Agent、有状态的助手,或任何需要生产级持久化或 OTel 可观测性的系统,CubeLoop 是更精简的路径。',],},],diff --git a/website/src/pages/compare/langgraph.tsx b/website/src/pages/compare/langgraph.tsxindex 0f379ff..7dfb281 100644--- a/website/src/pages/compare/langgraph.tsx+++ b/website/src/pages/compare/langgraph.tsx@@ -4,15 +4,15 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';const EN: CompareContent = {them: 'LangGraph',- title: 'CubePi vs LangGraph — a leaner Python agent framework',+ title: 'CubeLoop vs LangGraph — a leaner Python agent framework',description:- 'CubePi vs LangGraph: a side-by-side comparison of two Python agent frameworks. CubePi models the agent as a plain async while-loop with append-only checkpointing and 3 core dependencies, instead of a state graph of nodes, edges, and channels.',+ 'CubeLoop vs LangGraph: a side-by-side comparison of two Python agent frameworks. CubeLoop models the agent as a plain async while-loop with append-only checkpointing and 3 core dependencies, instead of a state graph of nodes, edges, and channels.',keywords:- 'CubePi vs LangGraph, LangGraph alternative, Python agent framework, async agent framework, LangGraph vs CubePi, state graph alternative, langgraph 替代品',- h1: 'CubePi vs LangGraph',+ 'CubeLoop vs LangGraph, LangGraph alternative, Python agent framework, async agent framework, LangGraph vs CubeLoop, state graph alternative, langgraph 替代品',+ h1: 'CubeLoop vs LangGraph',intro: [- 'CubePi and LangGraph both build tool-using LLM agents in Python, but they start from opposite mental models. LangGraph asks you to express your agent as a state graph — nodes, edges, and typed channels you wire together. CubePi models the same agent as a plain async while-loop you can read top to bottom.',- 'If you find yourself drawing graphs to express what is fundamentally a linear "call the model → run tools → repeat" loop, CubePi is the leaner alternative. Here is how the two compare.',+ 'CubeLoop and LangGraph both build tool-using LLM agents in Python, but they start from opposite mental models. LangGraph asks you to express your agent as a state graph — nodes, edges, and typed channels you wire together. CubeLoop models the same agent as a plain async while-loop you can read top to bottom.',+ 'If you find yourself drawing graphs to express what is fundamentally a linear "call the model → run tools → repeat" loop, CubeLoop is the leaner alternative. Here is how the two compare.',],tableHeading: 'Side-by-side',rows: [@@ -59,9 +59,9 @@ graph.add_conditional_edges("llm", should_continue)graph.add_edge("tools", "llm")app = graph.compile()`,- usTitle: '# CubePi',- us: `from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+ usTitle: '# CubeLoop',+ us: `from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -82,20 +82,20 @@ await agent.prompt("Weather in Tokyo?"){h2: 'Why the loop instead of a graph',body: [- 'A LangGraph agent never branches at runtime the way a general graph suggests — the "graph" is almost always the same shape: call the model, and if it asked for tools, run them and call the model again. CubePi makes that shape the runtime. There is no StateGraph, no END sentinel, no should_continue function, no ToolNode registry, and no State TypedDict to keep in sync.',+ 'A LangGraph agent never branches at runtime the way a general graph suggests — the "graph" is almost always the same shape: call the model, and if it asked for tools, run them and call the model again. CubeLoop makes that shape the runtime. There is no StateGraph, no END sentinel, no should_continue function, no ToolNode registry, and no State TypedDict to keep in sync.','Flow control that does need to vary — stop early, summarize, gate a tool behind human approval — lives in typed middleware hooks instead of conditional edges, so it is imperative and testable in isolation.',],},{h2: 'Persistence that does not grow with the conversation',body: [- 'LangGraph checkpointers snapshot the full state at every step, so write cost grows linearly with conversation length. CubePi checkpointing is append-only: each turn writes O(1) regardless of how long the thread is, and messages stay JSONB-queryable. The same MemorySaver / SqliteSaver / PostgresSaver idea maps onto MemoryCheckpointer / SQLiteCheckpointer / PostgresCheckpointer.',+ 'LangGraph checkpointers snapshot the full state at every step, so write cost grows linearly with conversation length. CubeLoop checkpointing is append-only: each turn writes O(1) regardless of how long the thread is, and messages stay JSONB-queryable. The same MemorySaver / SqliteSaver / PostgresSaver idea maps onto MemoryCheckpointer / SQLiteCheckpointer / PostgresCheckpointer.',],},{h2: 'When LangGraph is the better fit',body: [- 'LangGraph is the better choice if you need explicit, durable multi-agent graphs for supervisor routing, conditional branches, or parallel fan-out/fan-in, or if you need visual graph rendering. CubePi supports tool-driven delegation through `SubagentMiddleware`: a parent agent can dispatch self-contained work to typed child agents with dedicated prompts, models, tools, and middleware. CubePi keeps its core flow linear by design and emits vendor-neutral OpenTelemetry rather than shipping its own trace UI. CubePi has `Agent.fork()` and `Agent.fork_once()` for branching at completed-run boundaries; LangGraph supports finer-grained mid-run checkpoint forks if you need that granularity. If your agent is fundamentally a loop, CubePi removes the graph machinery you were not really using.',+ 'LangGraph is the better choice if you need explicit, durable multi-agent graphs for supervisor routing, conditional branches, or parallel fan-out/fan-in, or if you need visual graph rendering. CubeLoop supports tool-driven delegation through `SubagentMiddleware`: a parent agent can dispatch self-contained work to typed child agents with dedicated prompts, models, tools, and middleware. CubeLoop keeps its core flow linear by design and emits vendor-neutral OpenTelemetry rather than shipping its own trace UI. CubeLoop has `Agent.fork()` and `Agent.fork_once()` for branching at completed-run boundaries; LangGraph supports finer-grained mid-run checkpoint forks if you need that granularity. If your agent is fundamentally a loop, CubeLoop removes the graph machinery you were not really using.',],},],@@ -107,15 +107,15 @@ await agent.prompt("Weather in Tokyo?")const ZH: CompareContent = {them: 'LangGraph',- title: 'CubePi vs LangGraph — 更精简的 Python Agent 框架',+ title: 'CubeLoop vs LangGraph — 更精简的 Python Agent 框架',description:- 'CubePi 与 LangGraph 对比:两个 Python Agent 框架的并排比较。CubePi 用普通的 async while 循环建模 agent,配合追加式 checkpointing 和 3 个核心依赖,而非由节点、边、通道组成的状态图。',+ 'CubeLoop 与 LangGraph 对比:两个 Python Agent 框架的并排比较。CubeLoop 用普通的 async while 循环建模 agent,配合追加式 checkpointing 和 3 个核心依赖,而非由节点、边、通道组成的状态图。',keywords:- 'CubePi vs LangGraph, LangGraph 替代品, Python Agent 框架, 异步 Agent 框架, 状态图替代方案, langgraph alternative',- h1: 'CubePi vs LangGraph',+ 'CubeLoop vs LangGraph, LangGraph 替代品, Python Agent 框架, 异步 Agent 框架, 状态图替代方案, langgraph alternative',+ h1: 'CubeLoop vs LangGraph',intro: [- 'CubePi 和 LangGraph 都用 Python 构建会调用工具的 LLM agent,但出发点完全相反。LangGraph 要求你把 agent 表达成一张状态图 —— 手动连接节点、边和类型化通道。CubePi 则把同样的 agent 建模为一个可以从上读到下的普通 async while 循环。',- '如果你发现自己在用画图的方式去表达本质上线性的「调用模型 → 执行工具 → 重复」循环,CubePi 就是更精简的替代方案。下面是两者的对比。',+ 'CubeLoop 和 LangGraph 都用 Python 构建会调用工具的 LLM agent,但出发点完全相反。LangGraph 要求你把 agent 表达成一张状态图 —— 手动连接节点、边和类型化通道。CubeLoop 则把同样的 agent 建模为一个可以从上读到下的普通 async while 循环。',+ '如果你发现自己在用画图的方式去表达本质上线性的「调用模型 → 执行工具 → 重复」循环,CubeLoop 就是更精简的替代方案。下面是两者的对比。',],tableHeading: '并排对比',rows: [@@ -162,9 +162,9 @@ graph.add_conditional_edges("llm", should_continue)graph.add_edge("tools", "llm")app = graph.compile()`,- usTitle: '# CubePi',- us: `from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+ usTitle: '# CubeLoop',+ us: `from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -185,20 +185,20 @@ await agent.prompt("Weather in Tokyo?"){h2: '为什么用循环而不是图',body: [- 'LangGraph 的 agent 在运行时其实从不像通用图那样随意分支 —— 那张「图」几乎永远是同一个形状:调用模型,如果它请求了工具就执行,然后再次调用模型。CubePi 直接把这个形状变成运行时。没有 StateGraph、没有 END 哨兵、没有 should_continue 函数、没有 ToolNode 注册表,也没有需要同步维护的 State TypedDict。',+ 'LangGraph 的 agent 在运行时其实从不像通用图那样随意分支 —— 那张「图」几乎永远是同一个形状:调用模型,如果它请求了工具就执行,然后再次调用模型。CubeLoop 直接把这个形状变成运行时。没有 StateGraph、没有 END 哨兵、没有 should_continue 函数、没有 ToolNode 注册表,也没有需要同步维护的 State TypedDict。','确实需要变化的流程控制 —— 提前停止、生成总结、把某个工具放到人工审批之后 —— 都放在类型化的 middleware hook 里,而非条件边,因此是命令式的,也能单独测试。',],},{h2: '不随对话增长的持久化',body: [- 'LangGraph 的 checkpointer 在每一步都对完整状态做快照,写入成本随对话长度线性增长。CubePi 的 checkpointing 是追加式的:无论线程多长,每轮写入都是 O(1),且消息保持 JSONB 可查询。MemorySaver / SqliteSaver / PostgresSaver 的思路对应到 MemoryCheckpointer / SQLiteCheckpointer / PostgresCheckpointer。',+ 'LangGraph 的 checkpointer 在每一步都对完整状态做快照,写入成本随对话长度线性增长。CubeLoop 的 checkpointing 是追加式的:无论线程多长,每轮写入都是 O(1),且消息保持 JSONB 可查询。MemorySaver / SqliteSaver / PostgresSaver 的思路对应到 MemoryCheckpointer / SQLiteCheckpointer / PostgresCheckpointer。',],},{h2: '什么时候 LangGraph 更合适',body: [- '如果你需要用于 supervisor 路由、条件分支或并行 fan-out/fan-in 的显式、可持久化多智能体图,或需要可视化图渲染,LangGraph 更合适。CubePi 通过 `SubagentMiddleware` 支持工具驱动的委派:父 Agent 可以将自包含任务分派给具有专属 prompt、model、tools 和 middleware 的类型化子 Agent。CubePi 在设计上保持核心流程线性,并输出厂商中立的 OpenTelemetry,而不是自带一套 trace UI。CubePi 已有 `Agent.fork()` 和 `Agent.fork_once()` 在已完成的 run 边界处分叉;如果你需要 mid-run 粒度的任意检查点分叉,LangGraph 粒度更细。但如果你的 agent 本质上就是一个循环,CubePi 帮你去掉了那些你其实没真正用上的图机制。',+ '如果你需要用于 supervisor 路由、条件分支或并行 fan-out/fan-in 的显式、可持久化多智能体图,或需要可视化图渲染,LangGraph 更合适。CubeLoop 通过 `SubagentMiddleware` 支持工具驱动的委派:父 Agent 可以将自包含任务分派给具有专属 prompt、model、tools 和 middleware 的类型化子 Agent。CubeLoop 在设计上保持核心流程线性,并输出厂商中立的 OpenTelemetry,而不是自带一套 trace UI。CubeLoop 已有 `Agent.fork()` 和 `Agent.fork_once()` 在已完成的 run 边界处分叉;如果你需要 mid-run 粒度的任意检查点分叉,LangGraph 粒度更细。但如果你的 agent 本质上就是一个循环,CubeLoop 帮你去掉了那些你其实没真正用上的图机制。',],},],diff --git a/website/src/pages/compare/pi-agent-core.tsx b/website/src/pages/compare/pi-agent-core.tsxindex f732337..b34b80d 100644--- a/website/src/pages/compare/pi-agent-core.tsx+++ b/website/src/pages/compare/pi-agent-core.tsx@@ -4,15 +4,15 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';const EN: CompareContent = {them: 'pi-agent-core',- title: 'CubePi vs pi-agent-core — the Python-native sibling',+ title: 'CubeLoop vs pi-agent-core — the Python-native sibling',description:- 'CubePi vs pi-agent-core: pi-agent-core is a TypeScript agent framework; CubePi is an independent Python reimplementation of the same linear agent-loop architecture, with Pydantic v2 models, asyncio-native primitives, and built-in append-only checkpointing.',+ 'CubeLoop vs pi-agent-core: pi-agent-core is a TypeScript agent framework; CubeLoop is an independent Python reimplementation of the same linear agent-loop architecture, with Pydantic v2 models, asyncio-native primitives, and built-in append-only checkpointing.',keywords:- 'CubePi vs pi-agent-core, pi-agent-core alternative, pi-agent-core Python, Python agent framework, async agent framework, TypeScript to Python agent',- h1: 'CubePi vs pi-agent-core',+ 'CubeLoop vs pi-agent-core, pi-agent-core alternative, pi-agent-core Python, Python agent framework, async agent framework, TypeScript to Python agent',+ h1: 'CubeLoop vs pi-agent-core',intro: [- 'pi-agent-core is a TypeScript agent framework. CubePi is an independent Python reimplementation of the same architecture — the linear agent loop (agent.ts + agent-loop.ts maps onto CubePi’s agent.py + loop.py) — rebuilt around Pydantic v2, asyncio-native primitives, and built-in checkpointing.',- 'So this is less a "which is better" question and more a "which ecosystem are you in" one. If your stack is TypeScript/Node, pi-agent-core fits natively. If your stack is Python, CubePi gives you the same mental model without dragging a JS runtime into your services.',+ 'pi-agent-core is a TypeScript agent framework. CubeLoop is an independent Python reimplementation of the same architecture — the linear agent loop (agent.ts + agent-loop.ts maps onto CubeLoop’s agent.py + loop.py) — rebuilt around Pydantic v2, asyncio-native primitives, and built-in checkpointing.',+ 'So this is less a "which is better" question and more a "which ecosystem are you in" one. If your stack is TypeScript/Node, pi-agent-core fits natively. If your stack is Python, CubeLoop gives you the same mental model without dragging a JS runtime into your services.',],tableHeading: 'Moving from TypeScript to Python',rows: [@@ -26,21 +26,21 @@ const EN: CompareContent = {{h2: 'Same architecture, Pythonic surface',body: [- 'CubePi deliberately keeps pi-agent-core’s core idea: an agent is a loop, not a graph. What changes is the surface. Tools are plain async functions whose parameters are Pydantic models, so arguments coming back from the model are validated at runtime, not just type-hinted. Streaming is a single async iterator. The result reads like idiomatic Python rather than a TypeScript API transliterated into Python.',+ 'CubeLoop deliberately keeps pi-agent-core’s core idea: an agent is a loop, not a graph. What changes is the surface. Tools are plain async functions whose parameters are Pydantic models, so arguments coming back from the model are validated at runtime, not just type-hinted. Streaming is a single async iterator. The result reads like idiomatic Python rather than a TypeScript API transliterated into Python.',],},{- h2: 'What CubePi adds on the Python side',+ h2: 'What CubeLoop adds on the Python side',body: ['Built-in checkpointing: an append-only persistence layer with memory, SQLite, and Postgres backends, where each turn is O(1) to write regardless of conversation length.',- 'Native OpenTelemetry: a Tracer and Meter emit OTel spans with GenAI semantic-convention attributes out of the box, exportable to any OTLP backend (Jaeger, Tempo, Honeycomb, Langfuse, Datadog, …) — plus a cubepi trace CLI for local JSONL traces.',+ 'Native OpenTelemetry: a Tracer and Meter emit OTel spans with GenAI semantic-convention attributes out of the box, exportable to any OTLP backend (Jaeger, Tempo, Honeycomb, Langfuse, Datadog, …) — plus a cubeloop trace CLI for local JSONL traces.','MCP loaders for HTTP and stdio transports, a streaming-realistic FauxProvider for deterministic tests, and a lean dependency footprint: pydantic, anthropic, and openai are the only core dependencies; everything else is an optional extra.',],},{h2: 'Which should you choose',body: [- 'Choose pi-agent-core if your services are TypeScript/Node and you want to stay in that runtime. Choose CubePi if you are building in Python and want the same linear-loop agent model with first-class asyncio, Pydantic-validated tools, append-only persistence, and native OpenTelemetry — without running a JavaScript runtime alongside your Python.',+ 'Choose pi-agent-core if your services are TypeScript/Node and you want to stay in that runtime. Choose CubeLoop if you are building in Python and want the same linear-loop agent model with first-class asyncio, Pydantic-validated tools, append-only persistence, and native OpenTelemetry — without running a JavaScript runtime alongside your Python.',],},],@@ -52,15 +52,15 @@ const EN: CompareContent = {const ZH: CompareContent = {them: 'pi-agent-core',- title: 'CubePi vs pi-agent-core — Python 原生的同源框架',+ title: 'CubeLoop vs pi-agent-core — Python 原生的同源框架',description:- 'CubePi 与 pi-agent-core 对比:pi-agent-core 是一个 TypeScript Agent 框架;CubePi 是同一套线性 agent-loop 架构的 Python 独立重实现,采用 Pydantic v2 模型、asyncio 原生原语,以及内置的追加式 checkpointing。',+ 'CubeLoop 与 pi-agent-core 对比:pi-agent-core 是一个 TypeScript Agent 框架;CubeLoop 是同一套线性 agent-loop 架构的 Python 独立重实现,采用 Pydantic v2 模型、asyncio 原生原语,以及内置的追加式 checkpointing。',keywords:- 'CubePi vs pi-agent-core, pi-agent-core 替代品, pi-agent-core Python, Python Agent 框架, 异步 Agent 框架',- h1: 'CubePi vs pi-agent-core',+ 'CubeLoop vs pi-agent-core, pi-agent-core 替代品, pi-agent-core Python, Python Agent 框架, 异步 Agent 框架',+ h1: 'CubeLoop vs pi-agent-core',intro: [- 'pi-agent-core 是一个 TypeScript Agent 框架。CubePi 是同一套架构的 Python 独立重实现 —— 同样的线性 agent 循环(agent.ts + agent-loop.ts 对应 CubePi 的 agent.py + loop.py)—— 围绕 Pydantic v2、asyncio 原生原语和内置 checkpointing 重新构建。',- '所以这与其说是「谁更好」,不如说是「你在哪个生态」。如果你的技术栈是 TypeScript/Node,pi-agent-core 原生契合。如果你的技术栈是 Python,CubePi 给你同样的心智模型,而无需把 JS 运行时拖进你的服务里。',+ 'pi-agent-core 是一个 TypeScript Agent 框架。CubeLoop 是同一套架构的 Python 独立重实现 —— 同样的线性 agent 循环(agent.ts + agent-loop.ts 对应 CubeLoop 的 agent.py + loop.py)—— 围绕 Pydantic v2、asyncio 原生原语和内置 checkpointing 重新构建。',+ '所以这与其说是「谁更好」,不如说是「你在哪个生态」。如果你的技术栈是 TypeScript/Node,pi-agent-core 原生契合。如果你的技术栈是 Python,CubeLoop 给你同样的心智模型,而无需把 JS 运行时拖进你的服务里。',],tableHeading: '从 TypeScript 迁移到 Python',rows: [@@ -74,21 +74,21 @@ const ZH: CompareContent = {{h2: '同一套架构,Pythonic 的表层',body: [- 'CubePi 刻意保留了 pi-agent-core 的核心理念:agent 是一个循环,而不是一张图。改变的是表层。工具是普通的 async 函数,其参数是 Pydantic 模型,因此模型返回的参数会在运行时被校验,而不只是类型提示。流式输出是单个 async 迭代器。最终代码读起来像地道的 Python,而非把 TypeScript API 直译成 Python。',+ 'CubeLoop 刻意保留了 pi-agent-core 的核心理念:agent 是一个循环,而不是一张图。改变的是表层。工具是普通的 async 函数,其参数是 Pydantic 模型,因此模型返回的参数会在运行时被校验,而不只是类型提示。流式输出是单个 async 迭代器。最终代码读起来像地道的 Python,而非把 TypeScript API 直译成 Python。',],},{- h2: 'CubePi 在 Python 侧带来的增量',+ h2: 'CubeLoop 在 Python 侧带来的增量',body: ['内置 checkpointing:追加式持久化层,提供 memory、SQLite、Postgres 后端,无论对话多长,每轮写入都是 O(1)。',- '原生 OpenTelemetry:Tracer 与 Meter 开箱即用地输出带 GenAI 语义约定属性的 OTel span,可导出到任意 OTLP 后端(Jaeger、Tempo、Honeycomb、Langfuse、Datadog……),并附带 cubepi trace CLI 用于本地 JSONL trace。',+ '原生 OpenTelemetry:Tracer 与 Meter 开箱即用地输出带 GenAI 语义约定属性的 OTel span,可导出到任意 OTLP 后端(Jaeger、Tempo、Honeycomb、Langfuse、Datadog……),并附带 cubeloop trace CLI 用于本地 JSONL trace。','MCP 加载器(支持 HTTP 与 stdio 传输)、用于确定性测试的流式仿真 FauxProvider,以及精简的依赖足迹:核心依赖只有 pydantic、anthropic、openai,其余皆为可选 extra。',],},{h2: '该怎么选',body: [- '如果你的服务是 TypeScript/Node 并希望留在该运行时,选 pi-agent-core。如果你用 Python 构建,并想要同样的线性循环 agent 模型 —— 一等公民的 asyncio、Pydantic 校验的工具、追加式持久化、原生 OpenTelemetry —— 而不想在 Python 旁边再跑一个 JavaScript 运行时,选 CubePi。',+ '如果你的服务是 TypeScript/Node 并希望留在该运行时,选 pi-agent-core。如果你用 Python 构建,并想要同样的线性循环 agent 模型 —— 一等公民的 asyncio、Pydantic 校验的工具、追加式持久化、原生 OpenTelemetry —— 而不想在 Python 旁边再跑一个 JavaScript 运行时,选 CubeLoop。',],},],diff --git a/website/src/pages/compare/pydantic-ai.tsx b/website/src/pages/compare/pydantic-ai.tsxindex 667da79..3fd7cb6 100644--- a/website/src/pages/compare/pydantic-ai.tsx+++ b/website/src/pages/compare/pydantic-ai.tsx@@ -4,15 +4,15 @@ import { useIsZhHans } from '@site/src/hooks/useIsZhHans';const EN: CompareContent = {them: 'PydanticAI',- title: 'CubePi vs PydanticAI — Python agent frameworks compared',+ title: 'CubeLoop vs PydanticAI — Python agent frameworks compared',description:- 'CubePi vs PydanticAI: both are async-first Python agent frameworks built on Pydantic. PydanticAI centres on dependency injection and structured output. CubePi centres on append-only checkpointing, composable middleware, and vendor-neutral OpenTelemetry observability.',+ 'CubeLoop vs PydanticAI: both are async-first Python agent frameworks built on Pydantic. PydanticAI centres on dependency injection and structured output. CubeLoop centres on append-only checkpointing, composable middleware, and vendor-neutral OpenTelemetry observability.',keywords:- 'CubePi vs PydanticAI, PydanticAI alternative, pydantic-ai alternative, Python agent framework, async agent framework, PydanticAI vs CubePi, pydantic ai 替代品',- h1: 'CubePi vs PydanticAI',+ 'CubeLoop vs PydanticAI, PydanticAI alternative, pydantic-ai alternative, Python agent framework, async agent framework, PydanticAI vs CubeLoop, pydantic ai 替代品',+ h1: 'CubeLoop vs PydanticAI',intro: [- 'PydanticAI and CubePi share the same foundation — Pydantic v2, asyncio-native design, and a belief that agents should be plain Python rather than graph-based state machines. Where they diverge is in the abstractions built on top.',- 'PydanticAI centres on type-safe structured output and dependency injection via `RunContext`. CubePi centres on persistent multi-turn conversations, composable middleware hooks, and vendor-neutral OpenTelemetry tracing. Here is how the two compare.',+ 'PydanticAI and CubeLoop share the same foundation — Pydantic v2, asyncio-native design, and a belief that agents should be plain Python rather than graph-based state machines. Where they diverge is in the abstractions built on top.',+ 'PydanticAI centres on type-safe structured output and dependency injection via `RunContext`. CubeLoop centres on persistent multi-turn conversations, composable middleware hooks, and vendor-neutral OpenTelemetry tracing. Here is how the two compare.',],tableHeading: 'Side-by-side',rows: [@@ -48,9 +48,9 @@ async def get_weather(city: str) -> str:result = await agent.run("What's the weather in Tokyo?")print(result.output)`,- usTitle: '# CubePi',- us: `from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+ usTitle: '# CubeLoop',+ us: `from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProvider@tool@@ -72,28 +72,28 @@ await agent.prompt("What's the weather in Tokyo?"){h2: 'Where structured output sits in the API',body: [- 'Both frameworks ship first-class structured output backed by Pydantic. CubePi 0.10 added `BoundModel.generate_structured(Pydantic, ...)`, which injects a synthetic tool from the model\'s JSON schema, forces the call via `tool_choice`, and validates the response through `output_type.model_validate()` — the same `ToolOutput` mode PydanticAI uses by default.',- 'Where the two diverge is which abstraction owns the contract. PydanticAI lifts the output type up to the agent itself: `Agent[Deps, Sentiment].run(...)` types the whole run as `Sentiment`, and the framework offers `NativeOutput` (provider `response_format` / JSON-schema endpoints) and `PromptedOutput` as alternative modes alongside `ToolOutput`. CubePi keeps the agent loop as free-form text plus tool calls and exposes structured output as a one-shot `BoundModel` call you reach for when you need it — well-suited for extraction subroutines inside a larger multi-turn agent.',- 'CubePi optimises a different primary axis: multi-turn conversations that survive restarts. Append-only checkpointing keeps a thread\'s write cost flat regardless of conversation length, which matters when you have thousands of concurrent long-lived sessions.',+ 'Both frameworks ship first-class structured output backed by Pydantic. CubeLoop 0.10 added `BoundModel.generate_structured(Pydantic, ...)`, which injects a synthetic tool from the model\'s JSON schema, forces the call via `tool_choice`, and validates the response through `output_type.model_validate()` — the same `ToolOutput` mode PydanticAI uses by default.',+ 'Where the two diverge is which abstraction owns the contract. PydanticAI lifts the output type up to the agent itself: `Agent[Deps, Sentiment].run(...)` types the whole run as `Sentiment`, and the framework offers `NativeOutput` (provider `response_format` / JSON-schema endpoints) and `PromptedOutput` as alternative modes alongside `ToolOutput`. CubeLoop keeps the agent loop as free-form text plus tool calls and exposes structured output as a one-shot `BoundModel` call you reach for when you need it — well-suited for extraction subroutines inside a larger multi-turn agent.',+ 'CubeLoop optimises a different primary axis: multi-turn conversations that survive restarts. Append-only checkpointing keeps a thread\'s write cost flat regardless of conversation length, which matters when you have thousands of concurrent long-lived sessions.',],},{h2: 'Dependency injection vs middleware',body: [- 'PydanticAI\'s `RunContext[Deps]` is a clean pattern for injecting services (databases, HTTP clients) into tool functions. CubePi achieves the same via closures — capture your dependencies when you define the tool function — which requires no new abstraction to learn.',- 'Where CubePi adds structure is in cross-cutting concerns: middleware hooks (`before_tool_call`, `transform_context`, `should_stop_after_turn`, etc.) let you add rate-limiting, safety checks, compaction, or subagent orchestration without touching the core agent loop.',+ 'PydanticAI\'s `RunContext[Deps]` is a clean pattern for injecting services (databases, HTTP clients) into tool functions. CubeLoop achieves the same via closures — capture your dependencies when you define the tool function — which requires no new abstraction to learn.',+ 'Where CubeLoop adds structure is in cross-cutting concerns: middleware hooks (`before_tool_call`, `transform_context`, `should_stop_after_turn`, etc.) let you add rate-limiting, safety checks, compaction, or subagent orchestration without touching the core agent loop.',],},{h2: 'Observability: Logfire vs vendor-neutral OTel',body: [- 'PydanticAI integrates with Logfire, Pydantic\'s own observability platform. It works well if Logfire fits your stack. CubePi emits standard OpenTelemetry spans with GenAI semantic-convention attributes that land in any OTLP-compatible backend — Jaeger, Grafana Tempo, Honeycomb, Datadog, AWS X-Ray — with no vendor dependency. The `cubepi trace` CLI also lets you inspect traces locally from JSONL files without a backend at all.',+ 'PydanticAI integrates with Logfire, Pydantic\'s own observability platform. It works well if Logfire fits your stack. CubeLoop emits standard OpenTelemetry spans with GenAI semantic-convention attributes that land in any OTLP-compatible backend — Jaeger, Grafana Tempo, Honeycomb, Datadog, AWS X-Ray — with no vendor dependency. The `cubeloop trace` CLI also lets you inspect traces locally from JSONL files without a backend at all.',],},{h2: 'When PydanticAI is the better fit',body: [- 'PydanticAI is the stronger choice when you want the agent itself typed by its output (`Agent[Deps, OutputType]`), when you need provider-native JSON-schema endpoints (`NativeOutput`) instead of the tool-output mode CubePi uses, or if you are already on Logfire and want tight integration. Choose CubePi when you need production-grade multi-turn persistence, composable middleware, provider failover, or vendor-neutral observability — and you are happy to reach for `BoundModel.generate_structured(...)` as a one-shot when you do need a validated Pydantic instance.',+ 'PydanticAI is the stronger choice when you want the agent itself typed by its output (`Agent[Deps, OutputType]`), when you need provider-native JSON-schema endpoints (`NativeOutput`) instead of the tool-output mode CubeLoop uses, or if you are already on Logfire and want tight integration. Choose CubeLoop when you need production-grade multi-turn persistence, composable middleware, provider failover, or vendor-neutral observability — and you are happy to reach for `BoundModel.generate_structured(...)` as a one-shot when you do need a validated Pydantic instance.',],},],@@ -105,15 +105,15 @@ await agent.prompt("What's the weather in Tokyo?")const ZH: CompareContent = {them: 'PydanticAI',- title: 'CubePi vs PydanticAI — Python Agent 框架对比',+ title: 'CubeLoop vs PydanticAI — Python Agent 框架对比',description:- 'CubePi 与 PydanticAI 对比:两者都是基于 Pydantic 的异步优先 Python Agent 框架。PydanticAI 聚焦于依赖注入和结构化输出;CubePi 聚焦于追加式 checkpointing、可组合中间件和厂商中立的 OpenTelemetry 可观测性。',+ 'CubeLoop 与 PydanticAI 对比:两者都是基于 Pydantic 的异步优先 Python Agent 框架。PydanticAI 聚焦于依赖注入和结构化输出;CubeLoop 聚焦于追加式 checkpointing、可组合中间件和厂商中立的 OpenTelemetry 可观测性。',keywords:- 'CubePi vs PydanticAI, PydanticAI 替代品, pydantic-ai 替代品, Python Agent 框架, 异步 Agent 框架, pydantic ai 替代品',- h1: 'CubePi vs PydanticAI',+ 'CubeLoop vs PydanticAI, PydanticAI 替代品, pydantic-ai 替代品, Python Agent 框架, 异步 Agent 框架, pydantic ai 替代品',+ h1: 'CubeLoop vs PydanticAI',intro: [- 'PydanticAI 和 CubePi 共享同一基础 —— Pydantic v2、asyncio 原生设计,以及"Agent 应该是普通 Python 而非基于图的状态机"的理念。两者的分歧在于在此之上构建的抽象。',- 'PydanticAI 聚焦于通过 `RunContext` 实现类型安全的结构化输出和依赖注入。CubePi 聚焦于持久化多轮对话、可组合的中间件钩子和厂商中立的 OpenTelemetry 追踪。以下是两者的详细对比。',+ 'PydanticAI 和 CubeLoop 共享同一基础 —— Pydantic v2、asyncio 原生设计,以及"Agent 应该是普通 Python 而非基于图的状态机"的理念。两者的分歧在于在此之上构建的抽象。',+ 'PydanticAI 聚焦于通过 `RunContext` 实现类型安全的结构化输出和依赖注入。CubeLoop 聚焦于持久化多轮对话、可组合的中间件钩子和厂商中立的 OpenTelemetry 追踪。以下是两者的详细对比。',],tableHeading: '并排对比',rows: [@@ -133,28 +133,28 @@ const ZH: CompareContent = {{h2: '结构化输出在 API 里的位置',body: [- '两者都把结构化输出做成一等公民、并以 Pydantic 为校验后端。CubePi 0.10 加了 `BoundModel.generate_structured(Pydantic, ...)`:它从模型的 JSON schema 注入一个合成 tool、通过 `tool_choice` 强制调用、再用 `output_type.model_validate()` 校验回来——这正是 PydanticAI 默认的 `ToolOutput` 模式。',- '真正的差异是「契约绑在哪个抽象上」。PydanticAI 把输出类型抬到 Agent 本身:`Agent[Deps, Sentiment].run(...)` 把整个 run 的类型签到 `Sentiment`,且除了 `ToolOutput` 之外还提供 `NativeOutput`(Provider 的 `response_format` / JSON schema 端点)和 `PromptedOutput` 两种备选。CubePi 保持 agent 循环为自由文本 + 工具调用,把结构化输出做成一次性的 `BoundModel` 调用——适合作为多轮 agent 里的「抽取子例程」按需取用。',- 'CubePi 的主轴在另一边:可在重启后存活的多轮对话。追加式 checkpointing 让单线程的写入成本不随对话长度增长,在你有数千个并发长存会话时尤其重要。',+ '两者都把结构化输出做成一等公民、并以 Pydantic 为校验后端。CubeLoop 0.10 加了 `BoundModel.generate_structured(Pydantic, ...)`:它从模型的 JSON schema 注入一个合成 tool、通过 `tool_choice` 强制调用、再用 `output_type.model_validate()` 校验回来——这正是 PydanticAI 默认的 `ToolOutput` 模式。',+ '真正的差异是「契约绑在哪个抽象上」。PydanticAI 把输出类型抬到 Agent 本身:`Agent[Deps, Sentiment].run(...)` 把整个 run 的类型签到 `Sentiment`,且除了 `ToolOutput` 之外还提供 `NativeOutput`(Provider 的 `response_format` / JSON schema 端点)和 `PromptedOutput` 两种备选。CubeLoop 保持 agent 循环为自由文本 + 工具调用,把结构化输出做成一次性的 `BoundModel` 调用——适合作为多轮 agent 里的「抽取子例程」按需取用。',+ 'CubeLoop 的主轴在另一边:可在重启后存活的多轮对话。追加式 checkpointing 让单线程的写入成本不随对话长度增长,在你有数千个并发长存会话时尤其重要。',],},{h2: '依赖注入 vs 中间件',body: [- 'PydanticAI 的 `RunContext[Deps]` 是将服务(数据库、HTTP 客户端)注入工具函数的简洁模式。CubePi 通过闭包实现同样效果 —— 在定义工具函数时捕获依赖 —— 无需学习新抽象。',- 'CubePi 在横切关注点上增加了结构:中间件钩子(`before_tool_call`、`transform_context`、`should_stop_after_turn` 等)让你在不触碰核心 agent 循环的情况下添加限速、安全检查、上下文压缩或子 Agent 编排。',+ 'PydanticAI 的 `RunContext[Deps]` 是将服务(数据库、HTTP 客户端)注入工具函数的简洁模式。CubeLoop 通过闭包实现同样效果 —— 在定义工具函数时捕获依赖 —— 无需学习新抽象。',+ 'CubeLoop 在横切关注点上增加了结构:中间件钩子(`before_tool_call`、`transform_context`、`should_stop_after_turn` 等)让你在不触碰核心 agent 循环的情况下添加限速、安全检查、上下文压缩或子 Agent 编排。',],},{h2: '可观测性:Logfire vs 厂商中立的 OTel',body: [- 'PydanticAI 与 Logfire(Pydantic 自有的可观测性平台)集成。如果 Logfire 适合你的技术栈,效果很好。CubePi 输出带有 GenAI 语义约定属性的标准 OpenTelemetry span,可以落入任何 OTLP 兼容后端 —— Jaeger、Grafana Tempo、Honeycomb、Datadog、AWS X-Ray —— 无厂商依赖。`cubepi trace` CLI 也可以让你在没有后端的情况下从 JSONL 文件本地检查追踪。',+ 'PydanticAI 与 Logfire(Pydantic 自有的可观测性平台)集成。如果 Logfire 适合你的技术栈,效果很好。CubeLoop 输出带有 GenAI 语义约定属性的标准 OpenTelemetry span,可以落入任何 OTLP 兼容后端 —— Jaeger、Grafana Tempo、Honeycomb、Datadog、AWS X-Ray —— 无厂商依赖。`cubeloop trace` CLI 也可以让你在没有后端的情况下从 JSONL 文件本地检查追踪。',],},{h2: 'PydanticAI 更适合的场景',body: [- '如果你希望 agent 本身被它的输出类型化(`Agent[Deps, OutputType]`)、需要 Provider 原生 JSON-schema 端点(`NativeOutput`)而不是 CubePi 现在用的 tool-output 模式、或者你已经在 Logfire 上希望紧密集成,那么 PydanticAI 是更强的选择。当你需要生产级多轮持久化、可组合中间件、Provider 故障转移或厂商中立可观测性,并且能接受用 `BoundModel.generate_structured(...)` 作为一次性子例程获取已校验的 Pydantic 实例时,选择 CubePi。',+ '如果你希望 agent 本身被它的输出类型化(`Agent[Deps, OutputType]`)、需要 Provider 原生 JSON-schema 端点(`NativeOutput`)而不是 CubeLoop 现在用的 tool-output 模式、或者你已经在 Logfire 上希望紧密集成,那么 PydanticAI 是更强的选择。当你需要生产级多轮持久化、可组合中间件、Provider 故障转移或厂商中立可观测性,并且能接受用 `BoundModel.generate_structured(...)` 作为一次性子例程获取已校验的 Pydantic 实例时,选择 CubeLoop。',],},],diff --git a/website/src/pages/faq.tsx b/website/src/pages/faq.tsxindex 2abe476..c6ef564 100644--- a/website/src/pages/faq.tsx+++ b/website/src/pages/faq.tsx@@ -24,10 +24,10 @@ function reactNodeToText(node: React.ReactNode): string {const EN_ITEMS: FaqItem[] = [{- q: 'What is CubePi?',+ q: 'What is CubeLoop?',a: (<>- CubePi is a Pythonic, async-native agent framework for building LLM-powered agents in Python.+ CubeLoop is a Pythonic, async-native agent framework for building LLM-powered agents in Python.It models the agent as a plain async while-loop — no state graphs, no nodes/edges to wire — so thecore algorithm is readable in five minutes. It ships with append-only checkpointing, composablemiddleware, native OpenTelemetry tracing, MCP support, and a <code>FauxProvider</code> for@@ -36,45 +36,45 @@ const EN_ITEMS: FaqItem[] = [),},{- q: 'How is CubePi different from LangGraph?',+ q: 'How is CubeLoop different from LangGraph?',a: (<>LangGraph models an agent as a state graph you wire together with nodes, edges, and typed channels.- CubePi models the same agent as a plain <code>async while</code> loop. There is no <code>StateGraph</code>,+ CubeLoop models the same agent as a plain <code>async while</code> loop. There is no <code>StateGraph</code>,no <code>add_edge</code>, no <code>ToolNode</code>, and no <code>TypedDict</code> to maintain.- CubePi also checkpoints append-only (O(1) per turn vs. full snapshot per step) and has only three core+ CubeLoop also checkpoints append-only (O(1) per turn vs. full snapshot per step) and has only three coredependencies. See the full <Link to="/compare/langgraph">LangGraph comparison</Link>.</>),},{- q: 'How is CubePi different from CrewAI?',+ q: 'How is CubeLoop different from CrewAI?',a: (<>CrewAI organises agents around role-playing metaphors — crews, roles, goals, and backstories.- CubePi skips the metaphor: an agent is a function with a system prompt. CubePi also ships+ CubeLoop skips the metaphor: an agent is a function with a system prompt. CubeLoop also shipsbuilt-in append-only checkpointing (CrewAI has none), is async-first, and has native OpenTelemetry.See the full <Link to="/compare/crewai">CrewAI comparison</Link>.</>),},{- q: 'How is CubePi different from PydanticAI?',+ q: 'How is CubeLoop different from PydanticAI?',a: (<>Both frameworks are async-first and built on Pydantic. PydanticAI focuses on structured output and- dependency injection via <code>RunContext</code>; CubePi focuses on persistent multi-turn conversations,+ dependency injection via <code>RunContext</code>; CubeLoop focuses on persistent multi-turn conversations,composable middleware hooks, provider fallback, and vendor-neutral OpenTelemetry (vs. Logfire).- CubePi also ships built-in checkpointing that PydanticAI lacks.+ CubeLoop also ships built-in checkpointing that PydanticAI lacks.See the full <Link to="/compare/pydantic-ai">PydanticAI comparison</Link>.</>),},{- q: 'Does CubePi support multiple LLM providers?',+ q: 'Does CubeLoop support multiple LLM providers?',a: (<>- Yes. CubePi ships <code>AnthropicProvider</code> and <code>OpenAIProvider</code> (plus{' '}+ Yes. CubeLoop ships <code>AnthropicProvider</code> and <code>OpenAIProvider</code> (plus{' '}<code>OpenAIResponsesProvider</code> for the Responses API) out of the box. You can add your ownprovider with a single class that implements the <code>Provider</code> protocol. Use{' '}<code>FallbackBoundModel</code> to chain providers — on a rate-limit or outage the next model in the@@ -83,10 +83,10 @@ const EN_ITEMS: FaqItem[] = [),},{- q: 'What databases does CubePi support for checkpointing?',+ q: 'What databases does CubeLoop support for checkpointing?',a: (<>- CubePi ships four checkpointer backends: <code>MemoryCheckpointer</code> (development/testing),{' '}+ CubeLoop ships four checkpointer backends: <code>MemoryCheckpointer</code> (development/testing),{' '}<code>SQLiteCheckpointer</code> (lightweight single-node), <code>PostgresCheckpointer</code>{' '}(production), and <code>MySQLCheckpointer</code> (production). All use append-only writes — eachturn writes only the new messages, so write cost stays O(1) regardless of conversation length.@@ -99,31 +99,31 @@ const EN_ITEMS: FaqItem[] = [a: (<>Most agent frameworks checkpoint by snapshotting the entire message list on every step. As- conversations grow, write cost grows linearly. CubePi writes only the new messages produced in+ conversations grow, write cost grows linearly. CubeLoop writes only the new messages produced ineach turn — O(1) regardless of how long the thread is. This matters at scale: thousands ofconcurrent long-lived sessions with frequent turns.</>),},{- q: 'Does CubePi support MCP (Model Context Protocol)?',+ q: 'Does CubeLoop support MCP (Model Context Protocol)?',a: (<>- Yes. Install <code>pip install cubepi[mcp]</code> and use <code>StdioMCPLoader</code> or{' '}+ Yes. Install <code>pip install cubeloop[mcp]</code> and use <code>StdioMCPLoader</code> or{' '}<code>HttpMCPLoader</code> to load tools from any MCP-compatible server. Loaded tools plug intothe same <code>AgentTool</code> interface as hand-written tools.</>),},{- q: 'How does CubePi handle observability?',+ q: 'How does CubeLoop handle observability?',a: (<>- CubePi includes a <code>Tracer</code> and <code>Meter</code> that emit OpenTelemetry spans+ CubeLoop includes a <code>Tracer</code> and <code>Meter</code> that emit OpenTelemetry spansand metrics aligned with the GenAI Semantic Conventions. Spans export via OTLP/HTTP to anycompatible backend (Jaeger, Grafana Tempo, Honeycomb, Datadog, AWS X-Ray, Langfuse, …) or- to local JSONL files. The <code>cubepi trace</code> CLI lets you inspect JSONL traces in the- terminal without a backend. Install with <code>pip install cubepi[tracing,trace-cli]</code>.+ to local JSONL files. The <code>cubeloop trace</code> CLI lets you inspect JSONL traces in the+ terminal without a backend. Install with <code>pip install cubeloop[tracing,trace-cli]</code>.</>),},@@ -139,14 +139,14 @@ const EN_ITEMS: FaqItem[] = [),},{- q: 'What Python versions does CubePi support?',- a: 'CubePi supports Python 3.11, 3.12, 3.13, and 3.14. CI runs on all four versions.',+ q: 'What Python versions does CubeLoop support?',+ a: 'CubeLoop supports Python 3.11, 3.12, 3.13, and 3.14. CI runs on all four versions.',},{- q: 'Is CubePi production-ready?',+ q: 'Is CubeLoop production-ready?',a: (<>- CubePi is in beta (v0.9). The core agent loop, checkpointing, middleware, and tracing APIs are+ CubeLoop is in beta (v0.9). The core agent loop, checkpointing, middleware, and tracing APIs arestable. Breaking changes follow semantic versioning and are documented in the{' '}<Link to="/changelog">changelog</Link>. The Postgres and MySQL checkpointers are used inproduction by early adopters.@@ -154,25 +154,25 @@ const EN_ITEMS: FaqItem[] = [),},{- q: 'How do I install CubePi?',+ q: 'How do I install CubeLoop?',a: (<>- <code>pip install cubepi</code> for the core. Add extras for optional features:{' '}- <code>pip install cubepi[sqlite,postgres,mcp,tracing,trace-cli]</code>.- With uv: <code>uv add cubepi</code> or <code>uv add cubepi[sqlite,postgres,mcp,tracing]</code>.+ <code>pip install cubeloop</code> for the core. Add extras for optional features:{' '}+ <code>pip install cubeloop[sqlite,postgres,mcp,tracing,trace-cli]</code>.+ With uv: <code>uv add cubeloop</code> or <code>uv add cubeloop[sqlite,postgres,mcp,tracing]</code>.</>),},{- q: 'Is CubePi cache-friendly?',+ q: 'Is CubeLoop cache-friendly?',a: (<>- Yes — CubePi is designed to maximise prompt cache hit rates. LLM providers (Anthropic, OpenAI) let+ Yes — CubeLoop is designed to maximise prompt cache hit rates. LLM providers (Anthropic, OpenAI) letyou cache the stable prefix of a request so repeated turns don't re-process the same tokens, cutting- costs by up to 90% and reducing latency. Two CubePi design decisions work together to make this+ costs by up to 90% and reducing latency. Two CubeLoop design decisions work together to make thisreliable:<br /><br />- <strong>Append-only message storage.</strong> CubePi never rewrites or reorders history — it only+ <strong>Append-only message storage.</strong> CubeLoop never rewrites or reorders history — it onlyappends new messages. This means the prefix of every request is byte-identical to the previous turn,which is exactly what the cache needs to get a hit. Frameworks that rebuild the full message listfrom a snapshot on every step silently break the cache if any serialisation detail changes.@@ -186,11 +186,11 @@ const EN_ITEMS: FaqItem[] = [),},{- q: 'Is CubePi open source?',+ q: 'Is CubeLoop open source?',a: (<>- Yes. CubePi is MIT licensed. Source code is on{' '}- <a href="https://github.com/cubeplexai/cubepi" target="_blank" rel="noopener noreferrer">GitHub</a>.+ Yes. CubeLoop is MIT licensed. Source code is on{' '}+ <a href="https://github.com/cubeplexai/cubeloop" target="_blank" rel="noopener noreferrer">GitHub</a>.</>),},@@ -198,62 +198,62 @@ const EN_ITEMS: FaqItem[] = [const ZH_ITEMS: FaqItem[] = [{- q: 'CubePi 是什么?',+ q: 'CubeLoop 是什么?',a: (<>- CubePi 是一个 Pythonic、异步原生的 Agent 框架,用于在 Python 中构建 LLM 驱动的 Agent。+ CubeLoop 是一个 Pythonic、异步原生的 Agent 框架,用于在 Python 中构建 LLM 驱动的 Agent。它将 Agent 建模为普通的异步 while 循环 —— 无状态图,无需连接节点/边 —— 核心算法五分钟内可读懂。它内置追加式 checkpointing、可组合中间件、原生 OpenTelemetry 追踪、MCP 支持,以及用于确定性测试的 <code>FauxProvider</code>。</>),},{- q: 'CubePi 与 LangGraph 有何不同?',+ q: 'CubeLoop 与 LangGraph 有何不同?',a: (<>- LangGraph 将 Agent 建模为需要手动连接节点、边和类型化通道的状态图。CubePi 将同样的 Agent 建模为普通的 <code>async while</code> 循环。+ LangGraph 将 Agent 建模为需要手动连接节点、边和类型化通道的状态图。CubeLoop 将同样的 Agent 建模为普通的 <code>async while</code> 循环。没有 <code>StateGraph</code>,没有 <code>add_edge</code>,没有 <code>ToolNode</code>,也没有需要维护的 <code>TypedDict</code>。- CubePi 还采用追加式 checkpointing(每轮 O(1) vs. 每步全量快照),且只有三个核心依赖。+ CubeLoop 还采用追加式 checkpointing(每轮 O(1) vs. 每步全量快照),且只有三个核心依赖。查看完整的 <Link to="/compare/langgraph">LangGraph 对比</Link>。</>),},{- q: 'CubePi 与 CrewAI 有何不同?',+ q: 'CubeLoop 与 CrewAI 有何不同?',a: (<>- CrewAI 围绕角色扮演的隐喻组织 Agent —— 团队、角色、目标和背景故事。CubePi 省去了这层隐喻:Agent 就是一个带有 system prompt 的函数。- CubePi 还内置了追加式 checkpointing(CrewAI 没有),异步优先,并具有原生 OpenTelemetry。+ CrewAI 围绕角色扮演的隐喻组织 Agent —— 团队、角色、目标和背景故事。CubeLoop 省去了这层隐喻:Agent 就是一个带有 system prompt 的函数。+ CubeLoop 还内置了追加式 checkpointing(CrewAI 没有),异步优先,并具有原生 OpenTelemetry。查看完整的 <Link to="/compare/crewai">CrewAI 对比</Link>。</>),},{- q: 'CubePi 与 PydanticAI 有何不同?',+ q: 'CubeLoop 与 PydanticAI 有何不同?',a: (<>两者都是异步优先且基于 Pydantic 的框架。PydanticAI 聚焦于结构化输出和通过 <code>RunContext</code> 实现的依赖注入;- CubePi 聚焦于持久化多轮对话、可组合的中间件钩子、Provider 故障转移,以及厂商中立的 OpenTelemetry(而非 Logfire)。- CubePi 还内置了 PydanticAI 所缺乏的 checkpointing。+ CubeLoop 聚焦于持久化多轮对话、可组合的中间件钩子、Provider 故障转移,以及厂商中立的 OpenTelemetry(而非 Logfire)。+ CubeLoop 还内置了 PydanticAI 所缺乏的 checkpointing。查看完整的 <Link to="/compare/pydantic-ai">PydanticAI 对比</Link>。</>),},{- q: 'CubePi 支持多个 LLM Provider 吗?',+ q: 'CubeLoop 支持多个 LLM Provider 吗?',a: (<>- 支持。CubePi 内置 <code>AnthropicProvider</code> 和 <code>OpenAIProvider</code>(以及用于 Responses API 的{' '}+ 支持。CubeLoop 内置 <code>AnthropicProvider</code> 和 <code>OpenAIProvider</code>(以及用于 Responses API 的{' '}<code>OpenAIResponsesProvider</code>)。你可以用一个实现 <code>Provider</code> 协议的类添加自定义 Provider。使用 <code>FallbackBoundModel</code> 链式连接 Provider —— 在限速或故障时自动切换到链中的下一个模型。</>),},{- q: 'CubePi 的 checkpointing 支持哪些数据库?',+ q: 'CubeLoop 的 checkpointing 支持哪些数据库?',a: (<>- CubePi 提供四种 checkpointer 后端:<code>MemoryCheckpointer</code>(开发/测试)、+ CubeLoop 提供四种 checkpointer 后端:<code>MemoryCheckpointer</code>(开发/测试)、<code>SQLiteCheckpointer</code>(轻量级单节点)、<code>PostgresCheckpointer</code>(生产环境)和 <code>MySQLCheckpointer</code>(生产环境)。所有后端均使用追加式写入 —— 每轮只写入新消息,无论对话多长,写入成本保持 O(1)。@@ -265,27 +265,27 @@ const ZH_ITEMS: FaqItem[] = [a: (<>大多数 Agent 框架通过每步快照整个消息列表来进行 checkpoint。随着对话增长,写入成本线性增长。- CubePi 只写入每轮产生的新消息 —— 无论线程多长,都是 O(1)。这在规模化时至关重要:数千个并发的长存会话,频繁轮次。+ CubeLoop 只写入每轮产生的新消息 —— 无论线程多长,都是 O(1)。这在规模化时至关重要:数千个并发的长存会话,频繁轮次。</>),},{- q: 'CubePi 支持 MCP(模型上下文协议)吗?',+ q: 'CubeLoop 支持 MCP(模型上下文协议)吗?',a: (<>- 支持。安装 <code>pip install cubepi[mcp]</code>,使用 <code>StdioMCPLoader</code> 或{' '}+ 支持。安装 <code>pip install cubeloop[mcp]</code>,使用 <code>StdioMCPLoader</code> 或{' '}<code>HttpMCPLoader</code> 从任何兼容 MCP 的服务器加载工具。加载的工具与手写工具使用相同的 <code>AgentTool</code> 接口。</>),},{- q: 'CubePi 如何处理可观测性?',+ q: 'CubeLoop 如何处理可观测性?',a: (<>- CubePi 内置 <code>Tracer</code> 和 <code>Meter</code>,输出符合 GenAI 语义约定的 OpenTelemetry span 和指标。+ CubeLoop 内置 <code>Tracer</code> 和 <code>Meter</code>,输出符合 GenAI 语义约定的 OpenTelemetry span 和指标。Span 通过 OTLP/HTTP 导出到任何兼容后端(Jaeger、Grafana Tempo、Honeycomb、Datadog、AWS X-Ray、Langfuse……)- 或本地 JSONL 文件。<code>cubepi trace</code> CLI 可在终端中无需后端直接检查 JSONL trace。- 安装:<code>pip install cubepi[tracing,trace-cli]</code>。+ 或本地 JSONL 文件。<code>cubeloop trace</code> CLI 可在终端中无需后端直接检查 JSONL trace。+ 安装:<code>pip install cubeloop[tracing,trace-cli]</code>。</>),},@@ -300,37 +300,37 @@ const ZH_ITEMS: FaqItem[] = [),},{- q: 'CubePi 支持哪些 Python 版本?',- a: 'CubePi 支持 Python 3.11、3.12、3.13 和 3.14。CI 在所有四个版本上运行。',+ q: 'CubeLoop 支持哪些 Python 版本?',+ a: 'CubeLoop 支持 Python 3.11、3.12、3.13 和 3.14。CI 在所有四个版本上运行。',},{- q: 'CubePi 是否可用于生产环境?',+ q: 'CubeLoop 是否可用于生产环境?',a: (<>- CubePi 处于 Beta 阶段(v0.9)。核心 agent 循环、checkpointing、中间件和追踪 API 均已稳定。+ CubeLoop 处于 Beta 阶段(v0.9)。核心 agent 循环、checkpointing、中间件和追踪 API 均已稳定。重大变更遵循语义化版本管理,并记录在 <Link to="/changelog">更新日志</Link> 中。Postgres 和 MySQL checkpointer 已被早期用户用于生产环境。</>),},{- q: '如何安装 CubePi?',+ q: '如何安装 CubeLoop?',a: (<>- 核心安装:<code>pip install cubepi</code>。通过 extras 添加可选功能:- <code>pip install cubepi[sqlite,postgres,mcp,tracing,trace-cli]</code>。- 使用 uv:<code>uv add cubepi</code> 或 <code>uv add cubepi[sqlite,postgres,mcp,tracing]</code>。+ 核心安装:<code>pip install cubeloop</code>。通过 extras 添加可选功能:+ <code>pip install cubeloop[sqlite,postgres,mcp,tracing,trace-cli]</code>。+ 使用 uv:<code>uv add cubeloop</code> 或 <code>uv add cubeloop[sqlite,postgres,mcp,tracing]</code>。</>),},{- q: 'CubePi 对缓存友好吗?',+ q: 'CubeLoop 对缓存友好吗?',a: (<>- 是的 —— CubePi 的设计目标之一就是最大化 prompt 缓存命中率。LLM 提供商(Anthropic、OpenAI)允许你缓存请求的稳定前缀,- 这样相同的 token 不需要在每轮都重新处理,可降低最高 90% 的费用并减少延迟。CubePi 有两个设计决策共同保障了这一点:+ 是的 —— CubeLoop 的设计目标之一就是最大化 prompt 缓存命中率。LLM 提供商(Anthropic、OpenAI)允许你缓存请求的稳定前缀,+ 这样相同的 token 不需要在每轮都重新处理,可降低最高 90% 的费用并减少延迟。CubeLoop 有两个设计决策共同保障了这一点:<br /><br />- <strong>追加式消息存储。</strong>CubePi 从不重写或重排历史消息 —— 只追加新消息。这意味着每次请求的前缀与上一轮完全相同,+ <strong>追加式消息存储。</strong>CubeLoop 从不重写或重排历史消息 —— 只追加新消息。这意味着每次请求的前缀与上一轮完全相同,正是缓存命中所需要的。那些每步都从快照重建完整消息列表的框架,一旦序列化细节有任何变化,就会悄悄破坏缓存。<br /><br /><strong>自动缓存断点(Anthropic)。</strong><code>AnthropicProvider</code> 默认标记三个缓存断点:system prompt、@@ -341,11 +341,11 @@ const ZH_ITEMS: FaqItem[] = [),},{- q: 'CubePi 是开源的吗?',+ q: 'CubeLoop 是开源的吗?',a: (<>- 是的。CubePi 采用 MIT 许可证。源代码托管在{' '}- <a href="https://github.com/cubeplexai/cubepi" target="_blank" rel="noopener noreferrer">GitHub</a> 上。+ 是的。CubeLoop 采用 MIT 许可证。源代码托管在{' '}+ <a href="https://github.com/cubeplexai/cubeloop" target="_blank" rel="noopener noreferrer">GitHub</a> 上。</>),},@@ -389,10 +389,10 @@ function FaqSection({ items }: { items: FaqItem[] }) {export default function FAQ(): React.ReactElement {const zh = useIsZhHans();- const title = zh ? 'CubePi 常见问题' : 'Frequently Asked Questions — CubePi';+ const title = zh ? 'CubeLoop 常见问题' : 'Frequently Asked Questions — CubeLoop';const description = zh- ? 'CubePi 常见问题:与 LangGraph、CrewAI、PydanticAI 的区别,checkpointing、MCP、OpenTelemetry 支持,安装方式,以及生产可用性。'- : 'Answers to common questions about CubePi — how it compares to LangGraph, CrewAI, and PydanticAI; checkpointing, MCP, OpenTelemetry, installation, and production readiness.';+ ? 'CubeLoop 常见问题:与 LangGraph、CrewAI、PydanticAI 的区别,checkpointing、MCP、OpenTelemetry 支持,安装方式,以及生产可用性。'+ : 'Answers to common questions about CubeLoop — how it compares to LangGraph, CrewAI, and PydanticAI; checkpointing, MCP, OpenTelemetry, installation, and production readiness.';const faqJsonLd = {'@context': 'https://schema.org',@@ -412,7 +412,7 @@ export default function FAQ(): React.ReactElement {<Head><metaname="keywords"- content="CubePi FAQ, CubePi vs LangGraph, CubePi vs CrewAI, CubePi vs PydanticAI, Python agent framework FAQ, async agent FAQ"+ content="CubeLoop FAQ, CubeLoop vs LangGraph, CubeLoop vs CrewAI, CubeLoop vs PydanticAI, Python agent framework FAQ, async agent FAQ"/><script type="application/ld+json">{JSON.stringify(faqJsonLd)}</script></Head>@@ -428,8 +428,8 @@ export default function FAQ(): React.ReactElement {<h1>{zh ? '常见问题' : 'Frequently Asked Questions'}</h1><p style={{ fontSize: '1.1rem', color: 'var(--ifm-color-content-secondary)' }}>{zh- ? '关于 CubePi 的常见问题解答'- : 'Common questions about CubePi, how it compares to alternatives, and how to get started.'}+ ? '关于 CubeLoop 的常见问题解答'+ : 'Common questions about CubeLoop, how it compares to alternatives, and how to get started.'}</p></div><FaqSection items={zh ? ZH_ITEMS : EN_ITEMS} />diff --git a/website/src/pages/index.tsx b/website/src/pages/index.tsxindex 637a20d..92da058 100644--- a/website/src/pages/index.tsx+++ b/website/src/pages/index.tsx@@ -23,32 +23,32 @@ export default function Home(): React.ReactElement {const softwareJsonLd = {'@context': 'https://schema.org','@type': 'SoftwareApplication',- name: 'CubePi',+ name: 'CubeLoop',description:'A Pythonic, async-native agent framework — a leaner alternative to langgraph and pi-agent-core. Plain async functions, append-only checkpointing, minimal dependencies.',- url: 'https://cubepi.ai',+ url: 'https://cubeloop.dev',applicationCategory: 'DeveloperApplication',operatingSystem: 'Linux, macOS, Windows',programmingLanguage: 'Python',softwareVersion: version,- downloadUrl: 'https://pypi.org/project/cubepi/',- softwareHelp: 'https://cubepi.ai/docs/',- license: 'https://github.com/cubeplexai/cubepi/blob/main/LICENSE',+ downloadUrl: 'https://pypi.org/project/cubeloop/',+ softwareHelp: 'https://cubeloop.dev/docs/',+ license: 'https://github.com/cubeplexai/cubeloop/blob/main/LICENSE',offers: { '@type': 'Offer', price: '0', priceCurrency: 'USD' },- author: { '@type': 'Organization', name: 'CubePi', url: 'https://cubepi.ai' },+ author: { '@type': 'Organization', name: 'CubeLoop', url: 'https://cubeloop.dev' },};return (<Layout- // The site title ("CubePi") is appended via the title delimiter, so the+ // The site title ("CubeLoop") is appended via the title delimiter, so the// page title here must NOT lead with the brand or it double-brands the- // <title>/og:title (e.g. "CubePi — … | CubePi").+ // <title>/og:title (e.g. "CubeLoop — … | CubeLoop").title={zh? 'Pythonic 异步原生 Agent 框架': 'A Pythonic, async-native agent framework'}description={zh- ? 'CubePi 是 langgraph 和 pi-agent-core 的 Pythonic 异步原生替代方案。普通 async 函数、追加式持久化、3 个核心依赖。'- : 'CubePi is a Pythonic async-native agent framework — a leaner alternative to langgraph and pi-agent-core. Plain async functions, append-only checkpointing, 3 core dependencies.'}+ ? 'CubeLoop 是 langgraph 和 pi-agent-core 的 Pythonic 异步原生替代方案。普通 async 函数、追加式持久化、3 个核心依赖。'+ : 'CubeLoop is a Pythonic async-native agent framework — a leaner alternative to langgraph and pi-agent-core. Plain async functions, append-only checkpointing, 3 core dependencies.'}><Head><script type="application/ld+json">{JSON.stringify(softwareJsonLd)}</script>diff --git a/website/static/_worker.js b/website/static/_worker.jsindex ed2d996..aba2812 100644--- a/website/static/_worker.js+++ b/website/static/_worker.js@@ -1,10 +1,11 @@// Cloudflare Pages "advanced mode" Worker.//-// The site moved from the default *.pages.dev hostname to the custom domain-// cubepi.ai, but only the root path was redirecting — deep pages still served-// 200 on cubepi.pages.dev (duplicate content on two domains). This 301-redirects-// the production pages.dev hostname to the matching cubepi.ai path so the domain-// migration sends search engines one clean 1:1 signal.+// The site moved from cubepi.pages.dev → cubepi.ai → cubeloop.dev. The Pages+// project is still named `cubepi`, so the production pages.dev hostname remains+// cubepi.pages.dev (preview URLs are <hash>.cubepi.pages.dev). This 301s that+// hostname — and cubeloop.pages.dev if the project is later renamed — to the+// matching cubeloop.dev path. Search Console Change of Address requires a+// single hop; chaining through cubepi.ai fails Google's 301 check.//// Why _worker.js (advanced mode) and not functions/_middleware.js:// The site is deployed via Direct Upload (cloudflare/pages-action uploads@@ -22,8 +23,11 @@export default {async fetch(request, env) {const url = new URL(request.url);- if (url.hostname === "cubepi.pages.dev") {- url.hostname = "cubepi.ai";+ if (+ url.hostname === "cubepi.pages.dev" ||+ url.hostname === "cubeloop.pages.dev"+ ) {+ url.hostname = "cubeloop.dev";url.protocol = "https:";url.port = "";return Response.redirect(url.toString(), 301);diff --git a/website/static/img/brand/cubepi-logo.png b/website/static/img/brand/cubeloop-logo.pngsimilarity index 100%rename from website/static/img/brand/cubepi-logo.pngrename to website/static/img/brand/cubeloop-logo.pngdiff --git a/website/static/img/brand/cubepi-logo.svg b/website/static/img/brand/cubeloop-logo.svgsimilarity index 93%rename from website/static/img/brand/cubepi-logo.svgrename to website/static/img/brand/cubeloop-logo.svgindex 657fb5f..a07612c 100644--- a/website/static/img/brand/cubepi-logo.svg+++ b/website/static/img/brand/cubeloop-logo.svg@@ -1,5 +1,5 @@<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-labelledby="title desc">- <title id="title">cubepi logo</title>+ <title id="title">cubeloop logo</title><desc id="desc">An isometric cube shell with two vertical operator eyes on the open front face.</desc><defs><style>diff --git a/website/static/img/brand/cubeloop-social-preview.png b/website/static/img/brand/cubeloop-social-preview.pngnew file mode 100644index 0000000..80e646bBinary files /dev/null and b/website/static/img/brand/cubeloop-social-preview.png differdiff --git a/website/static/img/brand/cubepi-social-preview.svg b/website/static/img/brand/cubeloop-social-preview.svgsimilarity index 94%rename from website/static/img/brand/cubepi-social-preview.svgrename to website/static/img/brand/cubeloop-social-preview.svgindex 9ae39aa..303e48e 100644--- a/website/static/img/brand/cubepi-social-preview.svg+++ b/website/static/img/brand/cubeloop-social-preview.svg@@ -1,6 +1,6 @@<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 640" role="img" aria-labelledby="title desc">- <title id="title">cubepi social preview</title>- <desc id="desc">Social preview for cubepi, a Pythonic async-native agent framework.</desc>+ <title id="title">cubeloop social preview</title>+ <desc id="desc">Social preview for CubeLoop, a Pythonic async-native agent framework.</desc><defs><style>.ink { fill: #050608; }@@ -51,7 +51,7 @@</g><g transform="translate(552 222)">- <text x="0" y="0" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="96" font-weight="700" fill="#050608">CubePi</text>+ <text x="0" y="0" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="96" font-weight="700" fill="#050608">CubeLoop</text><text x="4" y="68" font-family="DejaVu Sans, Liberation Sans, Arial, sans-serif" font-size="31" font-weight="400" fill="#52525b">Pythonic async-native agent framework</text><g transform="translate(4 120)"><path d="M0 0h536" class="line" stroke-width="1"/>diff --git a/website/static/img/brand/cubepi-social-preview.png b/website/static/img/brand/cubepi-social-preview.pngdeleted file mode 100644index a12bc25..0000000Binary files a/website/static/img/brand/cubepi-social-preview.png and /dev/null differdiff --git a/website/static/llms.txt b/website/static/llms.txtindex ed31b1d..49fbf66 100644--- a/website/static/llms.txt+++ b/website/static/llms.txt@@ -1,8 +1,10 @@-# CubePi+# CubeLoop-> CubePi is a Pythonic, async-native agent framework for building LLM-powered agents in Python. It is a leaner alternative to LangGraph, CrewAI, and PydanticAI.+> CubeLoop is a Pythonic, async-native agent framework for building LLM-powered agents in Python. It is a leaner alternative to LangGraph, CrewAI, and PydanticAI.-CubePi models an agent as a plain async while-loop — no state graphs, no nodes/edges, no channel wiring. The core loop (`run_agent_loop`) is a readable while-loop you can trace top to bottom in five minutes. This makes CubePi easier to debug, test, and extend than graph-based runtimes.+CubeLoop models an agent as a plain async while-loop — no state graphs, no nodes/edges, no channel wiring. The core loop (`run_agent_loop`) is a readable while-loop you can trace top to bottom in five minutes. This makes CubeLoop easier to debug, test, and extend than graph-based runtimes.++CubeLoop was renamed from CubePi in 0.14. `pip install cubepi` still works as a transitional wrapper; new code should `pip install cubeloop` and `import cubeloop`. See https://cubeloop.dev/docs/migration/from-cubepi## Key features@@ -15,27 +17,27 @@ CubePi models an agent as a plain async while-loop — no state graphs, no nodes- **Middleware**: 8 typed hooks (`transform_context`, `before_tool_call`, `after_tool_call`, etc.) with declarative composition rules- **MCP support**: load tools from any MCP server over stdio or HTTP- **Human-in-the-loop (HITL)**: `ask_user` channel for mid-run approvals and interrupts-- **OpenTelemetry tracing**: GenAI semantic conventions, OTLP/JSONL exporters, `cubepi trace` terminal viewer+- **OpenTelemetry tracing**: GenAI semantic conventions, OTLP/JSONL exporters, `cubeloop trace` terminal viewer- **FauxProvider**: deterministic test provider — no API calls, realistic streaming deltas## Install```-pip install cubepi-pip install cubepi[sqlite] # SQLite checkpointer-pip install cubepi[postgres] # PostgreSQL checkpointer-pip install cubepi[mysql] # MySQL checkpointer-pip install cubepi[mcp] # MCP tool loaders-pip install cubepi[tracing] # OpenTelemetry tracing-pip install cubepi[trace-cli] # cubepi trace terminal viewer+pip install cubeloop+pip install cubeloop[sqlite] # SQLite checkpointer+pip install cubeloop[postgres] # PostgreSQL checkpointer+pip install cubeloop[mysql] # MySQL checkpointer+pip install cubeloop[mcp] # MCP tool loaders+pip install cubeloop[tracing] # OpenTelemetry tracing+pip install cubeloop[trace-cli] # cubeloop trace terminal viewer```## Minimal example```pythonimport asyncio-from cubepi import Agent, tool-from cubepi.providers.anthropic import AnthropicProvider+from cubeloop import Agent, tool+from cubeloop.providers.anthropic import AnthropicProviderprovider = AnthropicProvider(provider_id="anthropic", api_key="sk-...")@@ -55,7 +57,7 @@ asyncio.run(agent.prompt("What's the weather in Tokyo?"))## Comparison with alternatives-| | LangGraph | CrewAI | PydanticAI | CubePi |+| | LangGraph | CrewAI | PydanticAI | CubeLoop ||---|---|---|---|---|| Abstraction | State graph (nodes + edges) | Role-based crews and tasks | Typed agents with dependency injection | Plain async while-loop || Streaming | Callback-based, multiple modes | Limited | `async for` | `async for event in stream` |@@ -65,14 +67,15 @@ asyncio.run(agent.prompt("What's the weather in Tokyo?"))## Links-- Homepage: https://cubepi.ai-- Documentation: https://cubepi.ai/docs-- GitHub: https://github.com/cubeplexai/cubepi-- PyPI: https://pypi.org/project/cubepi/-- Changelog: https://cubepi.ai/changelog-- vs LangGraph: https://cubepi.ai/compare/langgraph-- vs pi-agent-core: https://cubepi.ai/compare/pi-agent-core+- Homepage: https://cubeloop.dev+- Documentation: https://cubeloop.dev/docs+- GitHub: https://github.com/cubeplexai/cubeloop+- PyPI: https://pypi.org/project/cubeloop/+- Changelog: https://cubeloop.dev/changelog+- vs LangGraph: https://cubeloop.dev/compare/langgraph+- vs pi-agent-core: https://cubeloop.dev/compare/pi-agent-core- Twitter/X: https://x.com/cubeplexai+- Migration from CubePi: https://cubeloop.dev/docs/migration/from-cubepi## Licensediff --git a/website/static/robots.txt b/website/static/robots.txtindex 547384e..d6213c3 100644--- a/website/static/robots.txt+++ b/website/static/robots.txt@@ -1,8 +1,8 @@User-agent: *Allow: /-Sitemap: https://cubepi.ai/sitemap.xml-Sitemap: https://cubepi.ai/zh-Hans/sitemap.xml+Sitemap: https://cubeloop.dev/sitemap.xml+Sitemap: https://cubeloop.dev/zh-Hans/sitemap.xml# AI/LLM crawlers — explicitly allowedUser-agent: GPTBot@@ -18,4 +18,4 @@ User-agent: anthropic-aiAllow: /# LLM context file (https://llmstxt.org)-LLMs: https://cubepi.ai/llms.txt+LLMs: https://cubeloop.dev/llms.txt