Skip to content

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

feat(hitl): pending_request storage on Memory + SQLite checkpointers

xf gong58a8c87f52ce
diff --git a/cubepi/checkpointer/base.py b/cubepi/checkpointer/base.py
index 9d31643..bd14b4e 100644
--- a/cubepi/checkpointer/base.py
+++ b/cubepi/checkpointer/base.py
@@ -15,3 +15,19 @@ class Checkpointer(Protocol):
async def load(self, thread_id: str) -> CheckpointData | None: ...
async def append(self, thread_id: str, messages: list[Any]) -> None: ...
async def save_extra(self, thread_id: str, extra: dict[str, Any]) -> None: ...
+
+ async def save_pending_request(self, thread_id: str, request: Any) -> None:
+ """Persist (or clear, if request is None) the pending HITL request for a thread.
+
+ First-party implementations (Memory, SQLite, Postgres, MySQL) all implement this.
+ HITL-requiring features (Agent.respond, CheckpointedChannel) use
+ ``getattr(checkpointer, "save_pending_request", None)`` for graceful degradation.
+ """
+ ...
+
+ async def load_pending_request(self, thread_id: str) -> Any:
+ """Load the persisted pending HITL request for a thread, or None.
+
+ Returns a ``HitlRequest`` instance or ``None``.
+ """
+ ...
diff --git a/cubepi/checkpointer/memory.py b/cubepi/checkpointer/memory.py
index 8a59c3d..c7659af 100644
--- a/cubepi/checkpointer/memory.py
+++ b/cubepi/checkpointer/memory.py
@@ -3,11 +3,13 @@ from __future__ import annotations
from typing import Any
from cubepi.checkpointer.base import CheckpointData
+from cubepi.hitl.types import HitlRequest
class MemoryCheckpointer:
def __init__(self) -> None:
self._store: dict[str, CheckpointData] = {}
+ self._pending: dict[str, HitlRequest] = {}
async def load(self, thread_id: str) -> CheckpointData | None:
return self._store.get(thread_id)
@@ -21,3 +23,12 @@ class MemoryCheckpointer:
if thread_id not in self._store:
self._store[thread_id] = CheckpointData()
self._store[thread_id].extra.update(extra)
+
+ async def save_pending_request(self, thread_id: str, request: Any) -> None:
+ if request is None:
+ self._pending.pop(thread_id, None)
+ else:
+ self._pending[thread_id] = request
+
+ async def load_pending_request(self, thread_id: str) -> Any:
+ return self._pending.get(thread_id)
diff --git a/cubepi/checkpointer/sqlite.py b/cubepi/checkpointer/sqlite.py
index a6ecd49..632093d 100644
--- a/cubepi/checkpointer/sqlite.py
+++ b/cubepi/checkpointer/sqlite.py
@@ -31,6 +31,13 @@ class SQLiteCheckpointer:
" extra_json TEXT NOT NULL DEFAULT '{}'"
")"
)
+ await self._db.execute(
+ "CREATE TABLE IF NOT EXISTS thread_pending_request ("
+ " thread_id TEXT PRIMARY KEY,"
+ " request_json TEXT NOT NULL,"
+ " created_at REAL NOT NULL DEFAULT (julianday('now'))"
+ ")"
+ )
await self._db.commit()
return self
@@ -98,6 +105,35 @@ class SQLiteCheckpointer:
)
await self._db.commit()
+ async def save_pending_request(self, thread_id: str, request: Any) -> None:
+ assert self._db is not None
+ async with self._lock:
+ if request is None:
+ await self._db.execute(
+ "DELETE FROM thread_pending_request WHERE thread_id = ?",
+ (thread_id,),
+ )
+ else:
+ payload = request.model_dump_json()
+ await self._db.execute(
+ "INSERT OR REPLACE INTO thread_pending_request "
+ "(thread_id, request_json) VALUES (?, ?)",
+ (thread_id, payload),
+ )
+ await self._db.commit()
+
+ async def load_pending_request(self, thread_id: str) -> Any:
+ from cubepi.hitl.types import HitlRequest
+
+ assert self._db is not None
+ async with self._lock:
+ cursor = await self._db.execute(
+ "SELECT request_json FROM thread_pending_request WHERE thread_id = ?",
+ (thread_id,),
+ )
+ row = await cursor.fetchone()
+ return HitlRequest.model_validate_json(row[0]) if row else None
+
def _serialize_message(msg: Any) -> str:
if hasattr(msg, "model_dump"):
diff --git a/tests/hitl/test_checkpointer_pending_request.py b/tests/hitl/test_checkpointer_pending_request.py
new file mode 100644
index 0000000..0482e73
--- /dev/null
+++ b/tests/hitl/test_checkpointer_pending_request.py
@@ -0,0 +1,65 @@
+import tempfile
+import pytest
+
+from cubepi.checkpointer.memory import MemoryCheckpointer
+from cubepi.checkpointer.sqlite import SQLiteCheckpointer
+from cubepi.hitl.types import ApproveRequest, HitlRequest
+
+
+def _req(thread_id="t-1", qid="q-1") -> HitlRequest:
+ return HitlRequest(
+ question_id=qid,
+ thread_id=thread_id,
+ payload=ApproveRequest(tool_name="bash", tool_call_id=qid, args={"cmd": "ls"}),
+ created_at=0.0,
+ timeout_seconds=30.0,
+ )
+
+
+async def sqlite_cp():
+ with tempfile.NamedTemporaryFile(suffix=".db") as f:
+ async with SQLiteCheckpointer(f.name) as cp:
+ yield cp
+
+
+async def test_memory_save_and_load_pending():
+ cp = MemoryCheckpointer()
+ assert await cp.load_pending_request("t-1") is None
+ req = _req()
+ await cp.save_pending_request("t-1", req)
+ loaded = await cp.load_pending_request("t-1")
+ assert loaded == req
+
+
+async def test_memory_clear_pending():
+ cp = MemoryCheckpointer()
+ await cp.save_pending_request("t-1", _req())
+ await cp.save_pending_request("t-1", None)
+ assert await cp.load_pending_request("t-1") is None
+
+
+async def test_sqlite_save_and_load_pending(sqlite_cp):
+ assert await sqlite_cp.load_pending_request("t-1") is None
+ req = _req()
+ await sqlite_cp.save_pending_request("t-1", req)
+ loaded = await sqlite_cp.load_pending_request("t-1")
+ assert loaded == req
+
+
+async def test_sqlite_clear_pending(sqlite_cp):
+ await sqlite_cp.save_pending_request("t-1", _req())
+ await sqlite_cp.save_pending_request("t-1", None)
+ assert await sqlite_cp.load_pending_request("t-1") is None
+
+
+async def test_sqlite_create_table_idempotent(sqlite_cp):
+ """Re-opening a checkpointer DB with existing pending_request table is safe."""
+ await sqlite_cp.save_pending_request("t-1", _req())
+ # Re-entering the context manager would call CREATE TABLE IF NOT EXISTS again
+ # against an existing table — must not raise.
+ await sqlite_cp._db.execute(
+ "CREATE TABLE IF NOT EXISTS thread_pending_request ("
+ "thread_id TEXT PRIMARY KEY, request_json TEXT NOT NULL, "
+ "created_at REAL NOT NULL DEFAULT (julianday('now')))"
+ )