CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
docs(plan,spec): incorporate codex review pass 3 (3 BLOCKING + 3 SHOULD-FIX)
xf gong10a0fc6d8b5d
diff --git a/dev/plans/2026-05-28-hitl-channel.md b/dev/plans/2026-05-28-hitl-channel.mdindex a5f7ffe..8e141d2 100644--- a/dev/plans/2026-05-28-hitl-channel.md+++ b/dev/plans/2026-05-28-hitl-channel.md@@ -847,11 +847,14 @@ class _BaseChannel:self._pending = reqself._future = asyncio.get_event_loop().create_future()- await self._on_pending_set(req)-exc_caught: BaseException | None = Nonesignal_task: asyncio.Future[Any] | None = None+ # CRITICAL: _on_pending_set is called INSIDE the try/finally so that+ # if it raises (e.g. CheckpointedChannel's HitlDurabilityNotGuaranteed+ # guard), the finally still clears _pending/_future. Otherwise the+ # channel would be permanently wedged.try:+ await self._on_pending_set(req)if signal is None and effective_timeout is None:return await self._futuretasks: list[asyncio.Future[Any]] = [self._future]@@ -2698,28 +2701,35 @@ Add to `cubepi/checkpointer/mysql/checkpointer.py`, mirroring the Postgres metho```pythonasync def save_pending_request(self, thread_id, request):+ # Matches the explicit-begin/commit/rollback pattern used by+ # save_extra and append (see cubepi/checkpointer/mysql/checkpointer.py:244).assert self._pool is not Noneasync with self._pool.acquire() as conn:- async with conn.cursor() as cur:- await cur.execute(- "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "- "ON DUPLICATE KEY UPDATE thread_id = thread_id",- (thread_id,),- )- if request is None:+ await conn.begin()+ try:+ async with conn.cursor() as cur:await cur.execute(- "UPDATE cubepi_threads SET pending_request = NULL, "- "updated_at = NOW() WHERE thread_id = %s",+ "INSERT INTO cubepi_threads (thread_id) VALUES (%s) "+ "ON DUPLICATE KEY UPDATE thread_id = thread_id",(thread_id,),)- else:- payload = request.model_dump_json()- await cur.execute(- "UPDATE cubepi_threads SET pending_request = %s, "- "updated_at = NOW() WHERE thread_id = %s",- (payload, thread_id),- )- await conn.commit()+ if request is None:+ await cur.execute(+ "UPDATE cubepi_threads SET pending_request = NULL, "+ "updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",+ (thread_id,),+ )+ else:+ payload = request.model_dump_json()+ await cur.execute(+ "UPDATE cubepi_threads SET pending_request = %s, "+ "updated_at = CURRENT_TIMESTAMP WHERE thread_id = %s",+ (payload, thread_id),+ )+ await conn.commit()+ except BaseException: # pragma: no cover - defensive txn rollback+ await conn.rollback()+ raiseasync def load_pending_request(self, thread_id):from cubepi.hitl.types import HitlRequest@@ -3091,6 +3101,17 @@ class CheckpointedChannel(_BaseChannel):def __init__(self, *, checkpointer, thread_id: str,default_timeout: float | None = None,allow_inside_custom_tool: bool = False) -> None:+ # Validate the checkpointer has the HITL methods early — better to+ # fail at construction than at first ask/approve/confirm (codex pass 3).+ if not (hasattr(checkpointer, "save_pending_request") and+ hasattr(checkpointer, "load_pending_request")):+ from cubepi.hitl.exceptions import HitlError+ raise HitlError(+ "CheckpointedChannel requires a checkpointer with "+ "save_pending_request and load_pending_request methods. "+ "First-party checkpointers (Memory/SQLite/Postgres/MySQL) "+ "implement these; third-party Protocol-only impls may not."+ )super().__init__(default_timeout=default_timeout, thread_id=thread_id)self._checkpointer = checkpointerself._allow_inside_custom_tool = allow_inside_custom_tool@@ -3103,6 +3124,7 @@ class CheckpointedChannel(_BaseChannel):"Use ApprovalPolicyMiddleware or ask_user_tool, or pass ""allow_inside_custom_tool=True to opt in.")+ # Direct call OK: __init__ validated this method exists.await self._checkpointer.save_pending_request(self._thread_id, req)await super()._on_pending_set(req)@@ -3110,6 +3132,7 @@ class CheckpointedChannel(_BaseChannel):from cubepi.hitl.exceptions import HitlDetachedif isinstance(exc, HitlDetached):return+ # Direct call OK: __init__ validated this method exists.await self._checkpointer.save_pending_request(self._thread_id, None)```@@ -3198,7 +3221,10 @@ Edit `cubepi/agent/agent.py`. Add inside the class:async def load_pending_hitl_request(self):if self.checkpointer is None or self.thread_id is None:return None- return await self.checkpointer.load_pending_request(self.thread_id)+ load_pending = getattr(self.checkpointer, "load_pending_request", None)+ if load_pending is None:+ return None # checkpointer doesn't support HITL — graceful None+ return await load_pending(self.thread_id)async def respond(self, *, question_id=None, answer):from cubepi.hitl.exceptions import (@@ -3209,6 +3235,13 @@ Edit `cubepi/agent/agent.py`. Add inside the class:if not (self.thread_id and self.checkpointer):raise RuntimeError("respond() requires thread_id + checkpointer")+ load_pending = getattr(self.checkpointer, "load_pending_request", None)+ if load_pending is None:+ raise HitlError(+ "respond() requires a checkpointer that implements "+ "load_pending_request (and save_pending_request)"+ )+async with self._run_lock:if not self._state._messages:data = await self.checkpointer.load(self.thread_id)@@ -3216,7 +3249,7 @@ Edit `cubepi/agent/agent.py`. Add inside the class:self._state._messages = list(data.messages or [])self._extra = dict(data.extra or {})- pending = await self.checkpointer.load_pending_request(self.thread_id)+ pending = await load_pending(self.thread_id)if pending is None:raise HitlNoPendingRequest("no pending request on this thread")if question_id is None:@@ -3230,56 +3263,97 @@ Edit `cubepi/agent/agent.py`. Add inside the class:await self._run_hitl_resume()async def abort_pending(self, reason: str = "aborted by host") -> None:+ """Abort a pending HITL request.++ Two cases, handled WITHOUT a single lock acquisition (codex pass 3:+ holding _run_lock here would deadlock against prompt() which holds it+ for the entire HITL await):++ Case A (in-flight, same process):+ - prompt() is currently holding _run_lock and is suspended in+ channel.{ask,confirm,approve}.+ - We MUST NOT acquire _run_lock — call channel.cancel() without it.+ The cancel surfaces HitlCancelled in the awaiter (which ask_user+ translates to is_error=True tool_result, or ApprovalPolicyMiddleware+ translates to a deny block). prompt() proceeds to its natural end+ via the loop's normal post-tool-call flow, releasing _run_lock.+ - No synthetic-deny writing needed; the conversation closes the same+ way any cancelled HITL closes (the model sees a tool error and the+ loop produces the next assistant turn that handles it, or+ should_stop_after_turn ends the run).++ Case B (cross-process, no in-flight await on this channel instance):+ - We are a fresh agent instance loaded from the checkpointer.+ channel.pending is None but checkpointer has a pending_request.+ - SAFE to acquire _run_lock (no in-flight prompt to deadlock with).+ - Synthesize a deny tool_result + terminal stop_reason="aborted"+ assistant, persist, clear pending, emit AgentAbortedEvent.+ """from cubepi.agent.types import AgentAbortedEvent- from cubepi.providers.base import AssistantMessage, ToolResultMessage, TextContent+ from cubepi.providers.base import (+ AssistantMessage, TextContent, ToolCall, ToolResultMessage,+ )if self._channel is None:raise HitlError("agent has no channel bound")if not (self.thread_id and self.checkpointer):raise RuntimeError("abort_pending() requires thread_id + checkpointer")+ # === Case A: same-process in-flight ===+ # Take the channel's _pending atomically; if it's set, cancel and return.+ # Do NOT take _run_lock — that would deadlock against prompt().+ in_flight = self._channel.pending+ if in_flight is not None:+ await self._channel.cancel(in_flight.question_id, reason=reason)+ return++ # === Case B: cross-process post-detach ===async with self._run_lock:- # 1. If something is pending in-flight (same process), cancel it.- if self._channel.pending is not None:- await self._channel.cancel(self._channel.pending.question_id, reason=reason)-- # 2. Load pending from checkpointer (the in-flight cancel may have- # already cleared it via _on_pending_cleared); if still set, build- # the synthetic deny and clear.- pending = await self.checkpointer.load_pending_request(self.thread_id)+ load_pending = getattr(self.checkpointer, "load_pending_request", None)+ save_pending = getattr(self.checkpointer, "save_pending_request", None)+ if load_pending is None or save_pending is None:+ raise HitlError(+ "abort_pending() requires a checkpointer that implements "+ "load_pending_request and save_pending_request"+ )+ pending = await load_pending(self.thread_id)if pending is None:return # nothing to abort- # Find the gated tool_call_id in the last assistant message.+ # Ensure messages are loaded from checkpoint.if not self._state._messages:data = await self.checkpointer.load(self.thread_id)self._state._messages = list(data.messages or []) if data else []- from cubepi.providers.base import AssistantMessage- last = self._state._messages[-1]- if isinstance(last, AssistantMessage):- from cubepi.providers.base import ToolCall- for content in last.content:- if isinstance(content, ToolCall):- synthetic = ToolResultMessage(- tool_call_id=content.id,- tool_name=content.name,- content=[TextContent(text=f"aborted: {reason}")],- details={"hitl": {"decision": "aborted", "reason": reason}},- is_error=True,- timestamp=time.time(),- )- self._state._messages.append(synthetic)- if self.checkpointer:- await self.checkpointer.append(self.thread_id, [synthetic])- # Append a terminal aborted assistant- term = AssistantMessage(- content=[TextContent(text=f"Conversation aborted: {reason}")],- stop_reason="aborted",++ if not self._state._messages or not isinstance(+ self._state._messages[-1], AssistantMessage+ ):+ raise HitlInconsistentState(+ "abort_pending: thread has pending_request but last message "+ "is not AssistantMessage")- self._state._messages.append(term)- if self.checkpointer:- await self.checkpointer.append(self.thread_id, [term])- await self.checkpointer.save_pending_request(self.thread_id, None)+ last = self._state._messages[-1]+ for content in last.content:+ if isinstance(content, ToolCall):+ synthetic = ToolResultMessage(+ tool_call_id=content.id,+ tool_name=content.name,+ content=[TextContent(text=f"aborted: {reason}")],+ details={"hitl": {"decision": "aborted", "reason": reason}},+ is_error=True,+ timestamp=time.time(),+ )+ self._state._messages.append(synthetic)+ await self.checkpointer.append(self.thread_id, [synthetic])++ term = AssistantMessage(+ content=[TextContent(text=f"Conversation aborted: {reason}")],+ stop_reason="aborted",+ )+ self._state._messages.append(term)+ await self.checkpointer.append(self.thread_id, [term])++ await save_pending(self.thread_id, None)await self._process_event(AgentAbortedEvent(reason=reason))async def _run_hitl_resume(self) -> None:@@ -3414,6 +3488,18 @@ async def run_agent_loop_resume(# right payload (codex BLOCKING: previous draft emitted []).await emit_event(emit, TurnEndEvent(message=last, tool_results=batch_tool_results))+ # Drain steering AFTER tool_results, BEFORE termination check — preserves+ # the Anthropic adjacency invariant (no user/system message wedged between+ # tool_use and tool_result) AND matches existing _run_loop ordering, which+ # drains steering before its terminal AgentEndEvent.+ if get_steering_messages:+ steering = await get_steering_messages() or []+ for msg in steering:+ await emit_event(emit, MessageStartEvent(message=msg))+ await emit_event(emit, MessageEndEvent(message=msg))+ current_context.messages.append(msg)+ new_messages.append(msg)+# Honor should_stop_after_turn (codex BLOCKING: previous draft skipped this).if should_stop_after_turn:stop_ctx = ShouldStopAfterTurnContext(@@ -3431,17 +3517,6 @@ async def run_agent_loop_resume(await emit_event(emit, AgentEndEvent(messages=new_messages))return new_messages- # Drain steering AFTER tool_results — preserves the Anthropic adjacency- # invariant the existing loop enforces (no user/system message wedged- # between tool_use and tool_result).- if get_steering_messages:- steering = await get_steering_messages() or []- for msg in steering:- await emit_event(emit, MessageStartEvent(message=msg))- await emit_event(emit, MessageEndEvent(message=msg))- current_context.messages.append(msg)- new_messages.append(msg)-# Fall through to the normal loop for the next model turn.await _run_loop(current_context=current_context,diff --git a/dev/specs/2026-05-28-hitl-channel.md b/dev/specs/2026-05-28-hitl-channel.mdindex 565537d..d4b8ed1 100644--- a/dev/specs/2026-05-28-hitl-channel.md+++ b/dev/specs/2026-05-28-hitl-channel.md@@ -383,7 +383,7 @@ Cross-process concurrency (two processes both calling `respond()` on the same `t#### Detecting suspension from `agent.prompt(...)`-When `Agent.detach()` is called during a pending HITL request (see §4.5), the loop catches `HitlDetached`, exits cleanly, and emits a new `AgentSuspendedEvent(pending_request=...)` so listeners can react. The assistant message keeps its unresolved tool calls; the next `respond()` will pick up from there.+When `Agent.detach()` is called during a pending HITL request (see §4.5), `Agent.detach()` itself emits `AgentSuspendedEvent(pending_request=self._channel.pending)` *before* triggering the exception, then the loop catches `HitlDetached` and exits silently. (Earlier drafts had the loop emit the event, but the loop has no channel handle — emitting with `pending_request=None` violated the event contract. The Agent layer has the real handle and emits with the proper payload.) The assistant message keeps its unresolved tool calls; the next `respond()` will pick up from there.For hosts that need to probe pending state, `Agent` exposes **two** APIs — sync and async — because the in-memory channel slot is cheap to read but the checkpointer is not:@@ -548,7 +548,7 @@ if before_result:Same selective catch is added around `tool.execute(...)` in `_execute_prepared`.-At the `_run_loop` level, a new outer try-block wraps the inner `_run_loop` body to catch `HitlDetached` / `HitlAborted` and exit cleanly (emit `AgentSuspendedEvent` for detach, `AgentAbortedEvent` for abort).+At the `_run_loop` level, a new outer try-block wraps the inner `_run_loop` body to catch `HitlDetached` / `HitlAborted` and exit cleanly **without** emitting any extra event — the Agent caller (`Agent.detach()` / `Agent.abort_pending()`) is responsible for emitting `AgentSuspendedEvent` / `AgentAbortedEvent` with the real payload before triggering the exception.`_PreparedToolCall` and `_ImmediateOutcome`/`_FinalizedOutcome` gain a `hitl_trace: dict | None = None` field. `_make_tool_result_message` merges it defensively (the existing `AgentToolResult.details` is typed `Any`, not `dict` — see SHOULD-FIX 13):@@ -768,7 +768,7 @@ class AgentSuspendedEvent(AgentEvent):pending_request: HitlRequest```-Channel implementations emit `HitlRequestEvent` / `HitlAnswerEvent` via the same `emit` callable used by `_run_loop` (wired in by Agent at construction). `AgentSuspendedEvent` is emitted by the loop itself when it catches `HitlDetached`.+Channel implementations emit `HitlRequestEvent` / `HitlAnswerEvent` via the same `emit` callable used by `_run_loop` (wired in by Agent at construction). `AgentSuspendedEvent` and `AgentAbortedEvent` are emitted by the **Agent layer** (`Agent.detach()` / `Agent.abort_pending()`), not the loop — the Agent has the channel handle needed to populate `pending_request` with the real payload.### 6.5 Trace spans@@ -794,7 +794,7 @@ The trace CLI (`cubepi trace view`) renders these spans inline in the run tree,| `timeout` exceeded in **ask_user tool** context | Same shape as cancel-in-ask, but `HitlTimedOut(seconds=N)`; `details["hitl"]={"outcome":"timed_out","seconds":N}`. || `timeout` exceeded in **approve middleware** context | Translated to `deny_reason="approval_timeout"` + `hitl_trace={"decision":"timed_out"}` — a clean fake-deny, *not* a tool error. Matches cubebox's "timeout → fake-deny so LLM keeps reasoning" requirement. || `signal.set()` during pending | Channel observes the `asyncio.Event` (passed in via tool's `execute(signal=...)` and `Middleware.before_tool_call(signal=...)`) racing it against the answer future; if signal wins, channel raises `HitlAborted`. `HitlAborted` propagates through the selective handlers up to `_run_loop`, which emits `AgentAbortedEvent`. `pending_request` is cleared. |-| `Agent.detach()` | Channel raises `HitlDetached`. `_run_loop` catches at the outer level, emits `AgentSuspendedEvent(pending_request=...)`, exits cleanly with assistant message intact (tool_calls still unresolved). `pending_request` stays persisted; the next `respond()` picks up. |+| `Agent.detach()` | `Agent.detach()` emits `AgentSuspendedEvent(pending_request=channel.pending)` then sets `HitlDetached` on the channel's future. Channel raises `HitlDetached`; `_run_loop` catches at the outer level and exits silently (no event from loop). Assistant message intact, tool_calls still unresolved, `pending_request` stays persisted; the next `respond()` picks up. || `answer(qid)` with unknown / stale qid | `HitlStaleAnswer` (`HitlError`, regular `Exception`). Host code is expected to log / discard. || `respond(answer=...)` but no `pending_request` | `HitlNoPendingRequest`. || `respond()` (no answer) when there IS a pending | `HitlMissingAnswer`. |