Skip to content

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

chore: add README, GitHub CI, PyPI publish workflow, and update gitignore

xf gong6789a30562ed
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..12cea50
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,51 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ python-version: ["3.11", "3.12", "3.13"]
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: astral-sh/setup-uv@v6
+ with:
+ version: "latest"
+
+ - name: Set up Python ${{ matrix.python-version }}
+ run: uv python install ${{ matrix.python-version }}
+
+ - name: Install dependencies
+ run: uv sync --all-extras --dev
+
+ - name: Run tests
+ run: uv run pytest tests/ -v --cov=cubepi --cov-report=term-missing
+
+ - name: Check import
+ run: uv run python -c "import cubepi; print(cubepi.__all__)"
+
+ lint:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: astral-sh/setup-uv@v6
+ with:
+ version: "latest"
+
+ - name: Install dependencies
+ run: uv sync --all-extras --dev
+
+ - name: Ruff check
+ run: uv run ruff check cubepi/ tests/
+
+ - name: Ruff format check
+ run: uv run ruff format --check cubepi/ tests/
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
new file mode 100644
index 0000000..626c715
--- /dev/null
+++ b/.github/workflows/publish.yml
@@ -0,0 +1,55 @@
+name: Publish to PyPI
+
+on:
+ release:
+ types: [published]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: astral-sh/setup-uv@v6
+ with:
+ version: "latest"
+
+ - name: Build package
+ run: uv build
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: dist
+ path: dist/
+
+ publish-testpypi:
+ needs: build
+ runs-on: ubuntu-latest
+ environment: testpypi
+ permissions:
+ id-token: write
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ name: dist
+ path: dist/
+
+ - name: Publish to TestPyPI
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ repository-url: https://test.pypi.org/legacy/
+
+ publish-pypi:
+ needs: publish-testpypi
+ runs-on: ubuntu-latest
+ environment: pypi
+ permissions:
+ id-token: write
+ steps:
+ - uses: actions/download-artifact@v4
+ with:
+ name: dist
+ path: dist/
+
+ - name: Publish to PyPI
+ uses: pypa/gh-action-pypi-publish@release/v1
diff --git a/.gitignore b/.gitignore
index 9b74228..4c8a5e9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,28 @@
docs/specs
docs/plans
+
+# Python
__pycache__/
*.pyc
+*.pyo
+*.egg-info/
+dist/
+build/
+
+# Virtual environments
.venv/
+
+# Testing / coverage
+.coverage
+.pytest_cache/
+htmlcov/
+
+# IDE
+.idea/
+.vscode/
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..40fce17
--- /dev/null
+++ b/README.md
@@ -0,0 +1,225 @@
+# cubepi
+
+Pythonic async-native agent framework. Built to replace [langgraph](https://github.com/langchain-ai/langgraph) with something simpler, faster, and easier to reason about.
+
+Inspired by [pi-agent-core](https://github.com/anthropics/pi-agent-core) (TypeScript), redesigned for Python.
+
+## Why cubepi
+
+### vs langgraph
+
+| | langgraph | cubepi |
+|---|---|---|
+| **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 |
+| **Checkpointing** | Full snapshot per step — serializes entire message list on every channel change | Append-only — writes only new messages, O(1) DB I/O regardless of conversation length |
+| **Dependencies** | Pulls in langchain-core, langgraph-sdk, and transitive deps | 3 core deps: `pydantic`, `anthropic`, `openai` |
+| **Tool execution** | Tools are graph nodes with manual wiring | Declare tools as functions, framework handles routing and parallel execution |
+| **Multi-provider** | Via langchain chat model adapters | Native Provider protocol — Anthropic, OpenAI built in, add your own with one class |
+| **Middleware** | Not built in — use langchain callbacks or custom graph nodes | First-class middleware protocol with 5 composable hooks |
+| **Debuggability** | Trace through graph execution, channel updates, checkpoint diffs | Linear execution flow — set a breakpoint in the loop, see exactly what's happening |
+
+### vs pi-agent-core
+
+cubepi is a Python port of pi's architecture with Pythonic improvements:
+
+| | pi-agent-core | cubepi |
+|---|---|---|
+| **Language** | TypeScript | Python (async-native) |
+| **Type system** | Zod schemas | Pydantic v2 — validation, serialization, JSON Schema generation in one |
+| **Cancel signal** | `AbortSignal` (Web API) | `asyncio.Event` — same semantics, native to Python |
+| **Middleware** | Hooks only (callbacks on Agent) | Hooks + composable Middleware protocol with `compose_middleware()` |
+| **Checkpointing** | Not built in | Built-in `MemoryCheckpointer` + `SQLiteCheckpointer` |
+| **Test utility** | Internal test helpers | `FauxProvider` as public API — ship it, use it in your tests |
+
+## Install
+
+```bash
+pip install cubepi
+
+# With SQLite checkpointer
+pip install cubepi[sqlite]
+```
+
+Or with [uv](https://github.com/astral-sh/uv):
+
+```bash
+uv add cubepi
+uv add cubepi[sqlite]
+```
+
+## Quick Start
+
+```python
+import asyncio
+from cubepi import Agent, AgentTool, Model
+from cubepi.providers import AnthropicProvider
+
+provider = AnthropicProvider(api_key="sk-...")
+
+def get_weather(city: str) -> str:
+ """Get current weather for a city."""
+ return f"72°F and sunny in {city}"
+
+agent = Agent(
+ model=Model(provider=provider, model="claude-sonnet-4-20250514"),
+ tools=[
+ AgentTool(
+ name="get_weather",
+ description="Get current weather for a city",
+ parameters={
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ execute=get_weather,
+ ),
+ ],
+ system_prompt="You are a helpful weather assistant.",
+)
+
+async def main():
+ stream = await agent.prompt("What's the weather in Tokyo?")
+ async for event in stream:
+ if event.type == "text_delta":
+ print(event.delta, end="", flush=True)
+ print()
+
+asyncio.run(main())
+```
+
+## Architecture
+
+```
+cubepi/
+├── providers/ # LLM provider abstraction
+│ ├── base.py # Provider protocol, message types, MessageStream
+│ ├── anthropic.py # Anthropic provider
+│ ├── openai.py # OpenAI provider
+│ └── faux.py # Test utility — pre-configured responses with realistic streaming
+├── agent/ # Agent runtime
+│ ├── agent.py # Stateful Agent class
+│ ├── loop.py # Stateless core loop (the actual algorithm)
+│ ├── tools.py # Tool execution engine (sequential + parallel)
+│ └── types.py # Events, AgentTool, AgentContext, hook types
+├── middleware/ # Composable middleware protocol
+│ └── base.py # 5 hooks with distinct composition rules
+└── checkpointer/ # Persistence
+ ├── base.py # Checkpointer protocol
+ ├── memory.py # In-memory (dev/test)
+ └── sqlite.py # SQLite (lightweight persistence)
+```
+
+## Core Concepts
+
+### Providers
+
+Abstract LLM interaction behind a `Provider` protocol. All providers return `MessageStream` — an async iterator of `StreamEvent`s.
+
+```python
+from cubepi.providers import AnthropicProvider, OpenAIProvider, FauxProvider
+
+# Real providers
+anthropic = AnthropicProvider(api_key="...")
+openai = OpenAIProvider(api_key="...")
+
+# Test provider — no API calls, fully deterministic
+faux = FauxProvider()
+faux.set_responses(["Hello!", "How can I help?"])
+```
+
+### Tools
+
+Declare tools with a name, JSON Schema parameters, and a sync or async execute function. The framework handles argument parsing, parallel execution, and error wrapping.
+
+```python
+from cubepi import AgentTool
+
+tool = AgentTool(
+ name="search",
+ description="Search the web",
+ parameters={
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ },
+ execute=lambda query: f"Results for: {query}",
+ sequential=False, # allow parallel execution (default)
+)
+```
+
+### Middleware
+
+Composable hooks that modify behavior without touching the core loop:
+
+```python
+from cubepi import Middleware, compose_middleware
+
+class LoggingMiddleware(Middleware):
+ async def transform_context(self, messages, *, signal=None):
+ print(f"Context has {len(messages)} messages")
+ return messages
+
+class SafetyMiddleware(Middleware):
+ async def before_tool_call(self, ctx, *, signal=None):
+ if ctx.tool_call.name == "dangerous_tool":
+ return BeforeToolCallResult(block=True, content="Blocked by policy")
+ return None
+
+hooks = compose_middleware([LoggingMiddleware(), SafetyMiddleware()])
+```
+
+**Composition rules:**
+
+| Hook | Rule |
+|------|------|
+| `transform_context` | Chained — each receives previous result |
+| `convert_to_llm` | Last implementation wins |
+| `before_tool_call` | Any block stops execution |
+| `after_tool_call` | Later overrides earlier |
+| `should_stop_after_turn` | Any true stops |
+
+### Checkpointer
+
+Persist conversation state with append-only semantics:
+
+```python
+from cubepi.checkpointer import MemoryCheckpointer, SQLiteCheckpointer
+
+# In-memory for dev/test
+cp = MemoryCheckpointer()
+
+# SQLite for lightweight persistence
+async with SQLiteCheckpointer("agent.db") as cp:
+ agent = Agent(model=model, checkpointer=cp, thread_id="conv-1")
+```
+
+### FauxProvider for Testing
+
+Ship your agent tests without API keys:
+
+```python
+from cubepi.providers import FauxProvider, faux_text, faux_tool_call, faux_assistant_message
+
+provider = FauxProvider()
+provider.set_responses([
+ faux_assistant_message([
+ faux_tool_call("search", {"query": "python"}),
+ ]),
+ faux_assistant_message("Here are the results..."),
+])
+
+agent = Agent(model=Model(provider=provider, model="test"), tools=[search_tool])
+stream = await agent.prompt("Search for python")
+# Streams realistic deltas — content_block_start, text_delta, etc.
+```
+
+## Requirements
+
+- Python >= 3.11
+- Core: `pydantic`, `anthropic`, `openai`
+- Optional: `aiosqlite` (for `SQLiteCheckpointer`)
+
+## License
+
+MIT
diff --git a/pyproject.toml b/pyproject.toml
index d039dac..f4c2748 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -2,7 +2,19 @@
name = "cubepi"
version = "0.1.0"
description = "Pythonic async-native agent framework"
+readme = "README.md"
+license = "MIT"
requires-python = ">=3.11"
+classifiers = [
+ "Development Status :: 3 - Alpha",
+ "Framework :: AsyncIO",
+ "Intended Audience :: Developers",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Typing :: Typed",
+]
dependencies = [
"anthropic>=0.100.0",
"openai>=2.36.0",
@@ -19,6 +31,7 @@ dev = [
"pytest>=9.0.3",
"pytest-asyncio>=1.3.0",
"pytest-cov>=7.1.0",
+ "ruff>=0.15.12",
]
[tool.pytest.ini_options]
diff --git a/uv.lock b/uv.lock
index 7d6a8e2..16a73fa 100644
--- a/uv.lock
+++ b/uv.lock
@@ -194,6 +194,7 @@ dev = [
{ name = "pytest" },
{ name = "pytest-asyncio" },
{ name = "pytest-cov" },
+ { name = "ruff" },
]
[package.metadata]
@@ -210,6 +211,7 @@ dev = [
{ name = "pytest", specifier = ">=9.0.3" },
{ name = "pytest-asyncio", specifier = ">=1.3.0" },
{ name = "pytest-cov", specifier = ">=7.1.0" },
+ { name = "ruff", specifier = ">=0.15.12" },
]
[[package]]
@@ -581,6 +583,31 @@ wheels = [
{ url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/9d/7a/d968e294073affff457b041c2be9868a40c1c71f4a35fcc1e45e5493067b/pytest_cov-7.1.0-py3-none-any.whl", hash = "sha256:a0461110b7865f9a271aa1b51e516c9a95de9d696734a2f71e3e78f46e1d4678", size = 22876, upload-time = "2026-03-21T20:11:14.438Z" },
]
+[[package]]
+name = "ruff"
+version = "0.15.12"
+source = { registry = "https://mirrors.bfsu.edu.cn/pypi/web/simple/" }
+sdist = { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/99/43/3291f1cc9106f4c63bdce7a8d0df5047fe8422a75b091c16b5e9355e0b11/ruff-0.15.12.tar.gz", hash = "sha256:ecea26adb26b4232c0c2ca19ccbc0083a68344180bba2a600605538ce51a40a6", size = 4643852, upload-time = "2026-04-24T18:17:14.305Z" }
+wheels = [
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/c3/6e/e78ffb61d4686f3d96ba3df2c801161843746dcbcbb17a1e927d4829312b/ruff-0.15.12-py3-none-linux_armv6l.whl", hash = "sha256:f86f176e188e94d6bdbc09f09bfd9dc729059ad93d0e7390b5a73efe19f8861c", size = 10640713, upload-time = "2026-04-24T18:17:22.841Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/ae/08/a317bc231fb9e7b93e4ef3089501e51922ff88d6936ce5cf870c4fe55419/ruff-0.15.12-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:e3bcd123364c3770b8e1b7baaf343cc99a35f197c5c6e8af79015c666c423a6c", size = 11069267, upload-time = "2026-04-24T18:17:30.105Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/aa/a4/f828e9718d3dce1f5f11c39c4f65afd32783c8b2aebb2e3d259e492c47bd/ruff-0.15.12-py3-none-macosx_11_0_arm64.whl", hash = "sha256:fe87510d000220aa1ed530d4448a7c696a0cae1213e5ec30e5874287b66557b5", size = 10397182, upload-time = "2026-04-24T18:17:07.177Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/71/e0/3310fc6d1b5e1fdea22bf3b1b807c7e187b581021b0d7d4514cccdb5fb71/ruff-0.15.12-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:84a1630093121375a3e2a95b4a6dc7b59e2b4ee76216e32d81aae550a832d002", size = 10758012, upload-time = "2026-04-24T18:16:55.759Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/11/c1/a606911aee04c324ddaa883ae418f3569792fd3c4a10c50e0dd0a2311e1e/ruff-0.15.12-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fb129f40f114f089ebe0ca56c0d251cf2061b17651d464bb6478dc01e69f11f5", size = 10447479, upload-time = "2026-04-24T18:16:51.677Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/9d/68/4201e8444f0894f21ab4aeeaee68aa4f10b51613514a20d80bd628d57e88/ruff-0.15.12-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0c862b172d695db7598426b8af465e7e9ac00a3ea2a3630ee67eb82e366aaa6", size = 11234040, upload-time = "2026-04-24T18:17:16.529Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/34/ff/8a6d6cf4ccc23fd67060874e832c18919d1557a0611ebef03fdb01fff11e/ruff-0.15.12-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2849ea9f3484c3aca43a82f484210370319e7170df4dfe4843395ddf6c57bc33", size = 12087377, upload-time = "2026-04-24T18:17:04.944Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/85/f6/c669cf73f5152f623d34e69866a46d5e6185816b19fcd5b6dd8a2d299922/ruff-0.15.12-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9e77c7e51c07fe396826d5969a5b846d9cd4c402535835fb6e21ce8b28fef847", size = 11367784, upload-time = "2026-04-24T18:17:25.409Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/e8/39/c61d193b8a1daaa8977f7dea9e8d8ba866e02ea7b65d32f6861693aa4c12/ruff-0.15.12-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:83b2f4f2f3b1026b5fb449b467d9264bf22067b600f7b6f41fc5958909f449d0", size = 11344088, upload-time = "2026-04-24T18:17:12.258Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/c2/8d/49afab3645e31e12c590acb6d3b5b69d7aab5b81926dbaf7461f9441f37a/ruff-0.15.12-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:9ba3b8f1afd7e2e43d8943e55f249e13f9682fde09711644a6e7290eb4f3e339", size = 11271770, upload-time = "2026-04-24T18:17:02.457Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/46/06/33f41fe94403e2b755481cdfb9b7ef3e4e0ed031c4581124658d935d52b4/ruff-0.15.12-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:e852ba9fdc890655e1d78f2df1499efbe0e54126bd405362154a75e2bde159c5", size = 10719355, upload-time = "2026-04-24T18:17:27.648Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/0d/59/18aa4e014debbf559670e4048e39260a85c7fcee84acfd761ac01e7b8d35/ruff-0.15.12-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:dd8aed930da53780d22fc70bdf84452c843cf64f8cb4eb38984319c24c5cd5fd", size = 10462758, upload-time = "2026-04-24T18:17:32.347Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/25/e7/cc9f16fd0f3b5fddcbd7ec3d6ae30c8f3fde1047f32a4093a98d633c6570/ruff-0.15.12-py3-none-musllinux_1_2_i686.whl", hash = "sha256:01da3988d225628b709493d7dc67c3b9b12c0210016b08690ef9bd27970b262b", size = 10953498, upload-time = "2026-04-24T18:17:20.674Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/72/7a/a9ba7f98c7a575978698f4230c5e8cc54bbc761af34f560818f933dafa0c/ruff-0.15.12-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:9cae0f92bd5700d1213188b31cd3bdd2b315361296d10b96b8e2337d3d11f53e", size = 11447765, upload-time = "2026-04-24T18:17:09.755Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/ea/f9/0ae446942c846b8266059ad8a30702a35afae55f5cdc54c5adf8d7afdc27/ruff-0.15.12-py3-none-win32.whl", hash = "sha256:d0185894e038d7043ba8fd6aee7499ece6462dc0ea9f1e260c7451807c714c20", size = 10657277, upload-time = "2026-04-24T18:17:18.591Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/33/f1/9614e03e1cdcbf9437570b5400ced8a720b5db22b28d8e0f1bda429f660d/ruff-0.15.12-py3-none-win_amd64.whl", hash = "sha256:c87a162d61ab3adca47c03f7f717c68672edec7d1b5499e652331780fe74950d", size = 11837758, upload-time = "2026-04-24T18:17:00.113Z" },
+ { url = "https://mirrors.bfsu.edu.cn/pypi/web/packages/c0/98/6beb4b351e472e5f4c4613f7c35a5290b8be2497e183825310c4c3a3984b/ruff-0.15.12-py3-none-win_arm64.whl", hash = "sha256:a538f7a82d061cee7be55542aca1d86d1393d55d81d4fcc314370f4340930d4f", size = 11120821, upload-time = "2026-04-24T18:16:57.979Z" },
+]
+
[[package]]
name = "sniffio"
version = "1.3.1"