Skip to content

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

style: ruff format

xf gongee007e78a7ab
diff --git a/cubepi/checkpointer/__init__.py b/cubepi/checkpointer/__init__.py
index 6b06a8a..9c40a4b 100644
--- a/cubepi/checkpointer/__init__.py
+++ b/cubepi/checkpointer/__init__.py
@@ -6,6 +6,7 @@ from cubepi.checkpointer.sqlite import SQLiteCheckpointer
def __getattr__(name: str) -> object:
if name == "PostgresCheckpointer":
from cubepi.checkpointer.postgres.checkpointer import PostgresCheckpointer
+
return PostgresCheckpointer
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
diff --git a/cubepi/checkpointer/postgres/checkpointer.py b/cubepi/checkpointer/postgres/checkpointer.py
index 1debd10..0fb959c 100644
--- a/cubepi/checkpointer/postgres/checkpointer.py
+++ b/cubepi/checkpointer/postgres/checkpointer.py
@@ -3,6 +3,7 @@
Append-only message log + per-thread KV (extra). Uses asyncpg pool +
msgpack payload encoding. Schema version verified on context entry.
"""
+
from __future__ import annotations
import json
@@ -156,7 +157,8 @@ class PostgresCheckpointer:
async with conn.transaction():
# Per-thread advisory lock for monotonic seq allocation
await conn.execute(
- "SELECT pg_advisory_xact_lock(hashtext($1))", thread_id,
+ "SELECT pg_advisory_xact_lock(hashtext($1))",
+ thread_id,
)
# Lazy thread row creation
await conn.execute(
@@ -164,23 +166,30 @@ class PostgresCheckpointer:
"VALUES ($1) ON CONFLICT DO NOTHING",
thread_id,
)
- last_seq = await conn.fetchval(
- "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "
- "WHERE thread_id = $1",
- thread_id,
- ) or 0
+ last_seq = (
+ await conn.fetchval(
+ "SELECT COALESCE(MAX(seq), 0) FROM cubepi_messages "
+ "WHERE thread_id = $1",
+ thread_id,
+ )
+ or 0
+ )
rows = []
for i, m in enumerate(messages):
seq = last_seq + i + 1
- payload = msgpack.packb(m.model_dump(mode="json"), use_bin_type=True)
- rows.append((
- thread_id,
- seq,
- _role_of(m),
- json.dumps(m.metadata),
- payload,
- ))
+ payload = msgpack.packb(
+ m.model_dump(mode="json"), use_bin_type=True
+ )
+ rows.append(
+ (
+ thread_id,
+ seq,
+ _role_of(m),
+ json.dumps(m.metadata),
+ payload,
+ )
+ )
await conn.executemany(
"INSERT INTO cubepi_messages "
"(thread_id, seq, role, metadata, payload) "
diff --git a/cubepi/checkpointer/postgres/models.py b/cubepi/checkpointer/postgres/models.py
index 1db5ab6..8ada2e5 100644
--- a/cubepi/checkpointer/postgres/models.py
+++ b/cubepi/checkpointer/postgres/models.py
@@ -5,6 +5,7 @@ so downstreams can compose it into alembic regardless of which ORM
they use. SQLAlchemy 2.0 declarative is the chosen style for cubepi
internal definitions.
"""
+
from __future__ import annotations
import datetime as _dt
@@ -35,7 +36,9 @@ class CubepiThread(CubepiBase):
)
forked_at_seq: Mapped[int | None] = mapped_column(sa.BigInteger, nullable=True)
extra: Mapped[dict[str, Any]] = mapped_column(
- JSONB, nullable=False, server_default=sa.text("'{}'::jsonb"),
+ JSONB,
+ nullable=False,
+ server_default=sa.text("'{}'::jsonb"),
)
created_at: Mapped[_dt.datetime] = mapped_column(
sa.TIMESTAMP(timezone=True),
diff --git a/cubepi/mcp/__init__.py b/cubepi/mcp/__init__.py
index 9da8ad2..fb96668 100644
--- a/cubepi/mcp/__init__.py
+++ b/cubepi/mcp/__init__.py
@@ -2,6 +2,7 @@
cubepi[mcp] extra required.
"""
+
from cubepi.mcp.http_loader import load_mcp_tools_http
from cubepi.mcp.stdio_loader import load_mcp_tools_stdio
diff --git a/cubepi/mcp/_adapter.py b/cubepi/mcp/_adapter.py
index 0e0dc94..922ad46 100644
--- a/cubepi/mcp/_adapter.py
+++ b/cubepi/mcp/_adapter.py
@@ -1,4 +1,5 @@
"""MCP tool descriptor → cubepi.AgentTool adapter."""
+
from __future__ import annotations
from typing import Any, Awaitable, Callable
@@ -67,7 +68,8 @@ def make_mcp_agent_tool(
{"content": [{"type": "text", "text": ...}, ...], "isError": bool}
"""
parameters_model = mcp_schema_to_pydantic_model(
- tool_name=name, input_schema=input_schema,
+ tool_name=name,
+ input_schema=input_schema,
)
async def _execute(args) -> AgentToolResult:
diff --git a/cubepi/mcp/http_loader.py b/cubepi/mcp/http_loader.py
index c2dda76..0013c3f 100644
--- a/cubepi/mcp/http_loader.py
+++ b/cubepi/mcp/http_loader.py
@@ -1,4 +1,5 @@
"""HTTP/SSE transport MCP tool loader."""
+
from __future__ import annotations
from typing import Any
@@ -48,7 +49,7 @@ async def load_mcp_tools_http(
def _serialize_call_tool_response(resp: Any) -> dict[str, Any]:
"""Normalize mcp SDK CallToolResult → dict for adapter."""
content = []
- for c in (resp.content or []):
+ for c in resp.content or []:
if getattr(c, "type", None) == "text":
content.append({"type": "text", "text": c.text})
return {
diff --git a/cubepi/mcp/stdio_loader.py b/cubepi/mcp/stdio_loader.py
index 7485cb6..b2b35c6 100644
--- a/cubepi/mcp/stdio_loader.py
+++ b/cubepi/mcp/stdio_loader.py
@@ -1,4 +1,5 @@
"""stdio transport MCP tool loader."""
+
from __future__ import annotations
from typing import Any
@@ -31,7 +32,10 @@ async def load_mcp_tools_stdio(
from mcp.client.stdio import stdio_client
server_params = StdioServerParameters(
- command=command, args=args, env=env, cwd=cwd,
+ command=command,
+ args=args,
+ env=env,
+ cwd=cwd,
)
async def _call_remote(tool_name: str, args_dict: dict[str, Any]) -> dict[str, Any]:
@@ -60,7 +64,7 @@ async def load_mcp_tools_stdio(
def _serialize_call_tool_response(resp: Any) -> dict[str, Any]:
content = []
- for c in (resp.content or []):
+ for c in resp.content or []:
if getattr(c, "type", None) == "text":
content.append({"type": "text", "text": c.text})
return {
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.py
index efdf0d3..d7ee1d8 100644
--- a/cubepi/providers/anthropic.py
+++ b/cubepi/providers/anthropic.py
@@ -69,7 +69,9 @@ class AnthropicProvider:
self._client = anthropic.AsyncAnthropic(api_key=api_key)
self._cache_retention = cache_retention
- self._cache_policy: CacheMarkerPolicy = cache_policy or DefaultCacheMarkerPolicy()
+ self._cache_policy: CacheMarkerPolicy = (
+ cache_policy or DefaultCacheMarkerPolicy()
+ )
async def stream(
self,
@@ -219,7 +221,11 @@ class AnthropicProvider:
content[-1] = {**last_block, "cache_control": cache_control}
elif isinstance(content, str):
msg["content"] = [
- {"type": "text", "text": content, "cache_control": cache_control}
+ {
+ "type": "text",
+ "text": content,
+ "cache_control": cache_control,
+ }
]
@staticmethod
diff --git a/tests/checkpointer/test_postgres.py b/tests/checkpointer/test_postgres.py
index ee55d04..e9b3b11 100644
--- a/tests/checkpointer/test_postgres.py
+++ b/tests/checkpointer/test_postgres.py
@@ -13,6 +13,7 @@ def test_models_import() -> None:
CubepiThread,
cubepi_metadata,
)
+
assert EXPECTED_SCHEMA_VERSION == 1
assert PARTITION_COUNT == 64
# All three model classes are reachable via the public model module
@@ -45,7 +46,10 @@ def test_cubepi_message_has_gin_index() -> None:
def test_create_message_partitions_op_yields_64_statements() -> None:
- from cubepi.checkpointer.postgres.alembic_helpers import create_message_partitions_op
+ from cubepi.checkpointer.postgres.alembic_helpers import (
+ create_message_partitions_op,
+ )
+
sql = create_message_partitions_op()
assert sql.count("CREATE TABLE cubepi_messages_p") == 64
assert "modulus 64, remainder 0" in sql
@@ -53,7 +57,10 @@ def test_create_message_partitions_op_yields_64_statements() -> None:
def test_create_message_partitions_op_partitions_are_zero_padded() -> None:
- from cubepi.checkpointer.postgres.alembic_helpers import create_message_partitions_op
+ from cubepi.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
@@ -62,6 +69,7 @@ def test_create_message_partitions_op_partitions_are_zero_padded() -> None:
def test_write_schema_version_op_includes_expected_version() -> None:
from cubepi.checkpointer.postgres.alembic_helpers import write_schema_version_op
+
sql = write_schema_version_op()
assert "INSERT INTO cubepi_schema_version" in sql
assert "VALUES (1)" in sql
@@ -73,12 +81,14 @@ def test_schema_uninitialized_is_schema_error() -> None:
CubepiSchemaError,
CubepiSchemaUninitialized,
)
+
err = CubepiSchemaUninitialized("tables missing")
assert isinstance(err, CubepiSchemaError)
def test_schema_mismatch_carries_expected_actual() -> None:
from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch
+
err = CubepiSchemaMismatch(expected=2, actual=1, hint="run alembic")
assert err.expected == 2
assert err.actual == 1
@@ -89,6 +99,7 @@ def test_schema_mismatch_carries_expected_actual() -> None:
def test_schema_mismatch_without_hint() -> None:
from cubepi.checkpointer.postgres.exceptions import CubepiSchemaMismatch
+
err = CubepiSchemaMismatch(expected=2, actual=1)
# No hint suffix
assert "expected=2" in str(err)
@@ -132,6 +143,7 @@ async def _setup_schema(dsn: str) -> None:
create_message_partitions_op,
write_schema_version_op,
)
+
await conn.execute(create_message_partitions_op())
await conn.execute("""
CREATE INDEX ix_cubepi_messages_metadata_gin
@@ -152,7 +164,10 @@ async 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 (
- AssistantMessage, TextContent, Usage, UserMessage,
+ AssistantMessage,
+ TextContent,
+ Usage,
+ UserMessage,
)
await _setup_schema(clean_db)
diff --git a/tests/mcp/_fake_stdio_server.py b/tests/mcp/_fake_stdio_server.py
index 4f3ce6e..5f7e880 100644
--- a/tests/mcp/_fake_stdio_server.py
+++ b/tests/mcp/_fake_stdio_server.py
@@ -4,6 +4,7 @@ Uses the mcp SDK's server primitives. Advertises one 'echo' tool.
Run as: python -m tests.mcp._fake_stdio_server
"""
+
import asyncio
diff --git a/tests/mcp/test_adapter.py b/tests/mcp/test_adapter.py
index a1d3276..959cc52 100644
--- a/tests/mcp/test_adapter.py
+++ b/tests/mcp/test_adapter.py
@@ -94,6 +94,7 @@ async def test_make_mcp_agent_tool_routes_to_call_remote() -> None:
assert called == {"name": "search", "args": {"query": "cats"}}
assert len(result.content) == 1
from cubepi.providers.base import TextContent
+
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "result"
@@ -111,4 +112,6 @@ async def test_make_mcp_agent_tool_carries_raw_response_in_details() -> None:
)
args = tool.parameters()
result = await tool.execute(args)
- assert result.details == {"raw_mcp_response": {"content": [], "isError": True, "errorMessage": "boom"}}
+ assert result.details == {
+ "raw_mcp_response": {"content": [], "isError": True, "errorMessage": "boom"}
+ }
diff --git a/tests/mcp/test_http_loader.py b/tests/mcp/test_http_loader.py
index 7a95687..15e9c04 100644
--- a/tests/mcp/test_http_loader.py
+++ b/tests/mcp/test_http_loader.py
@@ -11,6 +11,7 @@ import pytest
def test_import_http_loader() -> None:
"""Loader function is importable from the public module path."""
from cubepi.mcp import load_mcp_tools_http
+
assert callable(load_mcp_tools_http)
@@ -22,6 +23,7 @@ async def test_load_mcp_tools_http_against_test_server() -> None:
pytest.skip("Set CUBEPI_TEST_MCP_HTTP_URL to run this test")
from cubepi.mcp import load_mcp_tools_http
+
tools = await load_mcp_tools_http(server_url)
assert len(tools) > 0
first = tools[0]
diff --git a/tests/mcp/test_stdio_loader.py b/tests/mcp/test_stdio_loader.py
index 7d0997b..acb4e81 100644
--- a/tests/mcp/test_stdio_loader.py
+++ b/tests/mcp/test_stdio_loader.py
@@ -7,6 +7,7 @@ import pytest
def test_import_stdio_loader() -> None:
from cubepi.mcp import load_mcp_tools_stdio
+
assert callable(load_mcp_tools_stdio)
@@ -27,5 +28,6 @@ async def test_stdio_loader_against_fake_server() -> None:
result = await echo.execute(args)
assert len(result.content) == 1
from cubepi.providers.base import TextContent
+
assert isinstance(result.content[0], TextContent)
assert result.content[0].text == "hello"
diff --git a/tests/middleware/test_after_model_response.py b/tests/middleware/test_after_model_response.py
index a11a971..ac119b6 100644
--- a/tests/middleware/test_after_model_response.py
+++ b/tests/middleware/test_after_model_response.py
@@ -128,10 +128,12 @@ async def test_agent_stops_when_middleware_returns_stop() -> None:
"""decision='stop' terminates after the first model response."""
provider = FauxProvider()
# Two responses queued; second should never fire because we stop after first.
- provider.set_responses([
- faux_assistant_message("first"),
- faux_assistant_message("should not fire"),
- ])
+ provider.set_responses(
+ [
+ faux_assistant_message("first"),
+ faux_assistant_message("should not fire"),
+ ]
+ )
agent = Agent(
model=Model(id="test", provider="faux"),
provider=provider,
@@ -147,10 +149,12 @@ async def test_agent_stops_when_middleware_returns_stop() -> None:
async def test_agent_loops_when_middleware_returns_loop_to_model() -> None:
"""decision='loop_to_model' re-invokes the model with inject_messages."""
provider = FauxProvider()
- provider.set_responses([
- faux_assistant_message("first"),
- faux_assistant_message("second"),
- ])
+ provider.set_responses(
+ [
+ faux_assistant_message("first"),
+ faux_assistant_message("second"),
+ ]
+ )
call_count = 0
@@ -161,9 +165,7 @@ async def test_agent_loops_when_middleware_returns_loop_to_model() -> None:
if call_count == 1:
return TurnAction(
decision="loop_to_model",
- inject_messages=[
- UserMessage(content=[TextContent(text="retry")])
- ],
+ inject_messages=[UserMessage(content=[TextContent(text="retry")])],
)
return None
diff --git a/tests/middleware/test_transform_system_prompt.py b/tests/middleware/test_transform_system_prompt.py
index 904f7b8..9b7ef3e 100644
--- a/tests/middleware/test_transform_system_prompt.py
+++ b/tests/middleware/test_transform_system_prompt.py
@@ -36,8 +36,10 @@ async def test_chain_order_preserved() -> None:
def test_no_middleware_hook_absent() -> None:
"""If no middleware implements transform_system_prompt, the hook is not in the dict."""
+
class Plain(Middleware):
pass
+
hooks = compose_middleware([Plain()])
assert "transform_system_prompt" not in hooks
@@ -85,7 +87,9 @@ async def test_agent_without_middleware_passes_system_prompt_unchanged() -> None
async def _capturing_stream(self, model, messages, *, system_prompt="", **kw): # type: ignore[override]
received.append(system_prompt)
- return await orig_stream(self, model, messages, system_prompt=system_prompt, **kw)
+ return await orig_stream(
+ self, model, messages, system_prompt=system_prompt, **kw
+ )
provider = FauxProvider()
provider.set_responses([faux_assistant_message("ok")])
diff --git a/tests/providers/test_anthropic_cache_policy.py b/tests/providers/test_anthropic_cache_policy.py
index 525078f..440e01f 100644
--- a/tests/providers/test_anthropic_cache_policy.py
+++ b/tests/providers/test_anthropic_cache_policy.py
@@ -39,8 +39,10 @@ def test_provider_uses_custom_policy() -> None:
class _NoSystem:
def mark_system(self) -> bool:
return False
+
def mark_last_tool(self) -> bool:
return False
+
def message_breakpoint_indices(self, messages):
return []
@@ -55,7 +57,9 @@ def test_apply_indices_markers_marks_specified_indices() -> None:
{"role": "user", "content": [{"type": "text", "text": "a"}]},
{"role": "user", "content": [{"type": "text", "text": "b"}]},
]
- p._apply_indices_markers(api_messages, indices=[0], cache_control={"type": "ephemeral"})
+ p._apply_indices_markers(
+ api_messages, indices=[0], cache_control={"type": "ephemeral"}
+ )
assert api_messages[0]["content"][-1].get("cache_control") == {"type": "ephemeral"}
# message 1 untouched
assert "cache_control" not in api_messages[1]["content"][-1]
@@ -67,7 +71,9 @@ def test_apply_indices_markers_converts_string_content() -> None:
api_messages = [
{"role": "user", "content": "plain string"},
]
- p._apply_indices_markers(api_messages, indices=[0], cache_control={"type": "ephemeral"})
+ p._apply_indices_markers(
+ api_messages, indices=[0], cache_control={"type": "ephemeral"}
+ )
assert isinstance(api_messages[0]["content"], list)
assert api_messages[0]["content"][0] == {
"type": "text",
@@ -79,11 +85,14 @@ def test_apply_indices_markers_converts_string_content() -> None:
@pytest.mark.asyncio
async def test_custom_policy_drives_message_marker_placement() -> None:
"""Custom policy that marks index 0 should result in marker on first message, not last."""
+
class _FirstOnly:
def mark_system(self) -> bool:
return False
+
def mark_last_tool(self) -> bool:
return False
+
def message_breakpoint_indices(self, messages):
return [0] if messages else []
diff --git a/tests/providers/test_openai_reasoning.py b/tests/providers/test_openai_reasoning.py
index 902cc87..d677492 100644
--- a/tests/providers/test_openai_reasoning.py
+++ b/tests/providers/test_openai_reasoning.py
@@ -1,4 +1,5 @@
"""OpenAIProvider OSS reasoning extraction + payload_quirks tests (D4)."""
+
from __future__ import annotations
from types import SimpleNamespace
@@ -445,7 +446,9 @@ class TestPayloadQuirks:
"""payload_quirks parameter is accepted and stored."""
with patch("openai.AsyncOpenAI") as mock_openai:
mock_openai.return_value = MagicMock()
- p = OpenAIProvider(api_key="x", payload_quirks=["max_completion_tokens_alias"])
+ p = OpenAIProvider(
+ api_key="x", payload_quirks=["max_completion_tokens_alias"]
+ )
assert "max_completion_tokens_alias" in p._payload_quirks
def test_constructor_default_empty_quirks(self):