Skip to content

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

feat(hitl): CheckpointedChannel, Agent.respond/detach/abort_pending, resume loop

xf gong3f7917239db4
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index ba0f8e3..b89036d 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -5,9 +5,14 @@ import time
from dataclasses import dataclass, field
from typing import Any, Callable, Generic, TypeVar
-from cubepi.agent.loop import run_agent_loop, run_agent_loop_continue
+from cubepi.agent.loop import (
+ run_agent_loop,
+ run_agent_loop_continue,
+ run_agent_loop_resume,
+)
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 (
AgentContext,
@@ -373,6 +378,200 @@ class Agent(Generic[TMessage]):
extra=self._extra,
)
+ async def detach(self) -> None:
+ from cubepi.agent.types import AgentSuspendedEvent
+
+ if self._channel is None:
+ raise HitlError("agent has no channel bound")
+ pending = self._channel.pending
+ if (
+ pending is None
+ or self._channel._future is None
+ or self._channel._future.done()
+ ):
+ return # nothing to detach
+ # Emit the suspended event BEFORE triggering the exception, so listeners
+ # see the real pending payload (codex pass 2 BLOCKING: previous draft
+ # emitted from the loop with pending=None — fundamentally wrong).
+ await self._process_event(AgentSuspendedEvent(pending_request=pending))
+ self._channel._future.set_exception(HitlDetached())
+
+ async def load_pending_hitl_request(self) -> HitlRequest | None:
+ if self.checkpointer is None or self.thread_id is None:
+ return None
+ 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: str | None = None, answer: Any) -> None:
+ from cubepi.hitl.exceptions import (
+ HitlNoPendingRequest,
+ HitlStaleAnswer,
+ )
+
+ if self._channel is None:
+ raise HitlError("agent has no channel bound")
+ 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)
+ if data:
+ self._state._messages = list(data.messages or [])
+ self._extra = dict(data.extra or {})
+
+ pending = await load_pending(self.thread_id)
+ if pending is None:
+ raise HitlNoPendingRequest("no pending request on this thread")
+ if question_id is None:
+ question_id = pending.question_id
+ if question_id != pending.question_id:
+ raise HitlStaleAnswer(
+ f"answer for {question_id}, pending is {pending.question_id}"
+ )
+
+ self._channel.attach_resume_answer(question_id, answer)
+ await self._run_hitl_resume()
+
+ async def abort_pending(self, reason: str = "aborted by host") -> None:
+ """Abort a pending HITL request and CLOSE the conversation.
+
+ Per spec §5.2 "abort closes the conversation" — no new model call.
+ Two-phase: Phase 1 (no lock) interrupts any in-flight HITL await via
+ the agent signal; Phase 2 (with lock) appends synthetic deny
+ tool_results + a terminal stop_reason="aborted" assistant message
+ and emits AgentAbortedEvent.
+ """
+ from cubepi.agent.types import AgentAbortedEvent
+
+ 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")
+
+ # ============= Phase 1: interrupt any in-flight HITL await =============
+ # If prompt() is currently suspended in channel.{ask,confirm,approve},
+ # set the agent signal. _BaseChannel._await_answer races signal vs
+ # future and raises HitlAborted when signal wins. HitlAborted
+ # propagates through tool/middleware (HitlControlException is re-raised
+ # by the selective handler in _execute_prepared) up to _run_loop's
+ # outer silent catch. The HITL channel's finally calls
+ # _on_pending_cleared(exc=HitlAborted) which clears persisted pending
+ # (HitlAborted != HitlDetached).
+ #
+ # CRITICAL: do NOT acquire _run_lock here — prompt() holds it.
+ in_flight = self._channel.pending
+ if in_flight is not None:
+ if self._active_signal is not None:
+ self._active_signal.set()
+ else:
+ # Edge: channel has pending but agent has no active signal
+ # (e.g. respond() race window). Cancel directly.
+ await self._channel.cancel(in_flight.question_id, reason=reason)
+
+ # ============= Phase 2: append synthetic deny + close conversation =====
+ async with self._run_lock:
+ save_pending = getattr(self.checkpointer, "save_pending_request", None)
+ if save_pending is None:
+ raise HitlError(
+ "abort_pending() requires a checkpointer that implements "
+ "save_pending_request"
+ )
+
+ # Reload messages from checkpoint to see whatever prompt() persisted.
+ data = await self.checkpointer.load(self.thread_id)
+ self._state._messages = list(data.messages or []) if data else []
+ if not self._state._messages:
+ # Nothing to close (no in-flight, no persisted history).
+ await self._process_event(AgentAbortedEvent(reason=reason))
+ return
+
+ last = self._state._messages[-1]
+ if not isinstance(last, AssistantMessage):
+ # No unresolved tool_calls in tail — conversation already ended
+ # by some other path. Still emit the event for observability.
+ await save_pending(self.thread_id, None)
+ await self._process_event(AgentAbortedEvent(reason=reason))
+ return
+
+ # Find unresolved tool_calls in `last` (those without a matching
+ # ToolResultMessage anywhere later in the conversation).
+ tool_call_ids = [c.id for c in last.content if isinstance(c, ToolCall)]
+ asst_pos = len(self._state._messages) - 1
+ already_resolved = {
+ m.tool_call_id
+ for m in self._state._messages[asst_pos + 1 :]
+ if isinstance(m, ToolResultMessage)
+ }
+ unresolved = [
+ tc_id for tc_id in tool_call_ids if tc_id not in already_resolved
+ ]
+
+ # Synthesize deny tool_result for each unresolved tool_call.
+ for tc_id in unresolved:
+ tc = next(
+ c for c in last.content if isinstance(c, ToolCall) and c.id == tc_id
+ )
+ synthetic = ToolResultMessage(
+ tool_call_id=tc_id,
+ tool_name=tc.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])
+
+ # Append terminal aborted assistant only if we actually appended
+ # synthetic denials — otherwise the conversation already closed.
+ if unresolved:
+ term = AssistantMessage(
+ content=[TextContent(text=f"Conversation aborted: {reason}")],
+ stop_reason="aborted",
+ usage=Usage(),
+ timestamp=time.time(),
+ )
+ self._state._messages.append(term)
+ await self.checkpointer.append(self.thread_id, [term])
+
+ # Defensive clear (Phase 1's _on_pending_cleared usually did this,
+ # but cross-process abort_pending may bypass Phase 1 entirely).
+ await save_pending(self.thread_id, None)
+ await self._process_event(AgentAbortedEvent(reason=reason))
+
+ async def _run_hitl_resume(self) -> None:
+ await self._run_with_lifecycle(
+ lambda signal: run_agent_loop_resume(
+ context=self._create_context_snapshot(),
+ provider=self._provider,
+ model=self._state.model,
+ convert_to_llm=self.convert_to_llm,
+ transform_context=self.transform_context,
+ transform_system_prompt=self.transform_system_prompt,
+ after_model_response=self.after_model_response,
+ before_tool_call=self.before_tool_call,
+ after_tool_call=self.after_tool_call,
+ should_stop_after_turn=self.should_stop_after_turn,
+ get_steering_messages=self._make_async_drain(self._steering_queue),
+ get_follow_up_messages=self._make_async_drain(self._follow_up_queue),
+ stream_options=self._build_stream_options(signal),
+ tool_execution=self.tool_execution,
+ emit=lambda e: self._process_event(e),
+ checkpointer=self.checkpointer,
+ thread_id=self.thread_id,
+ )
+ )
+
async def _run_with_lifecycle(self, executor: Callable) -> None:
signal = asyncio.Event()
done = asyncio.Event()
diff --git a/cubepi/agent/loop.py b/cubepi/agent/loop.py
index 1dd78b3..a62816b 100644
--- a/cubepi/agent/loop.py
+++ b/cubepi/agent/loop.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import asyncio
-from typing import Callable
+from typing import Any, Callable
from cubepi.agent.tools import execute_tool_calls
from cubepi.agent.types import (
@@ -141,6 +141,174 @@ async def run_agent_loop_continue(
return new_messages
+async def run_agent_loop_resume(
+ *,
+ context: AgentContext,
+ provider: Provider,
+ model: Model,
+ convert_to_llm: Callable,
+ emit: Callable,
+ transform_context: Callable | None = None,
+ transform_system_prompt: Callable | None = None,
+ after_model_response: Callable | None = None,
+ before_tool_call: Callable | None = None,
+ after_tool_call: Callable | None = None,
+ should_stop_after_turn: Callable | None = None,
+ get_steering_messages: Callable | None = None,
+ get_follow_up_messages: Callable | None = None,
+ stream_options: StreamOptions | None = None,
+ tool_execution: str = "parallel",
+ system_prompt: str | None = None,
+ checkpointer: Any = None,
+ thread_id: str | None = None,
+) -> list[Message]:
+ from cubepi.hitl.exceptions import HitlInconsistentState
+
+ new_messages: list[Message] = []
+
+ # Sanity check
+ if not context.messages:
+ raise HitlInconsistentState("resume called with empty message history")
+ last = context.messages[-1]
+ if not isinstance(last, AssistantMessage):
+ raise HitlInconsistentState(
+ f"resume requires last message to be AssistantMessage, got "
+ f"{type(last).__name__}"
+ )
+ unresolved = [c for c in last.content if isinstance(c, ToolCall)]
+ if not unresolved:
+ raise HitlInconsistentState(
+ "resume requires unresolved tool_calls in last message"
+ )
+
+ # Locate `last` by IDENTITY (not value equality). list.index() uses ==, which
+ # would match an earlier assistant message with identical content (rare but
+ # possible after retries or reused prompts).
+ asst_pos = next(
+ (
+ i
+ for i in range(len(context.messages) - 1, -1, -1)
+ if context.messages[i] is last
+ ),
+ -1,
+ )
+ if asst_pos < 0:
+ raise HitlInconsistentState(
+ "could not locate last assistant message by identity"
+ )
+
+ # Idempotency: a previous crashed-mid-execute resume may have already left
+ # ToolResultMessage(s) for some of the unresolved tool_calls after asst_pos.
+ # Skip those — DO NOT re-run side-effecting tool bodies.
+ already_resolved = {
+ m.tool_call_id
+ for m in context.messages[asst_pos + 1 :]
+ if isinstance(m, ToolResultMessage)
+ }
+ remaining = [tc for tc in unresolved if tc.id not in already_resolved]
+
+ await emit_event(emit, AgentStartEvent())
+ await emit_event(emit, TurnStartEvent())
+
+ current_context = context
+ batch_tool_results: list[ToolResultMessage] = []
+ terminated_by_tool = False
+
+ if remaining:
+ # Build a fresh assistant message containing only the remaining
+ # tool_calls so execute_tool_calls processes those exact entries.
+ # We do NOT mutate `last` itself — model_copy gives an independent
+ # AssistantMessage that execute_tool_calls can read from.
+ remaining_ids = {tc.id for tc in remaining}
+ partial_msg = last.model_copy(
+ update={
+ "content": [
+ c
+ for c in last.content
+ if not isinstance(c, ToolCall) or c.id in remaining_ids
+ ],
+ }
+ )
+ batch = await execute_tool_calls(
+ current_context,
+ partial_msg,
+ tool_execution=tool_execution,
+ before_tool_call=before_tool_call,
+ after_tool_call=after_tool_call,
+ signal=(stream_options or StreamOptions()).signal,
+ emit=emit,
+ )
+ batch_tool_results = list(batch.messages)
+ terminated_by_tool = batch.terminate
+
+ for r in batch_tool_results:
+ current_context.messages.append(r)
+ new_messages.append(r)
+
+ # Clear pending_request from checkpointer NOW — after tool_results are
+ # appended (and have been checkpointed by the Agent layer's MessageEndEvent
+ # handler). The pending_request column / row is the cross-process witness;
+ # holding it until here preserves crash-recovery idempotency (see spec §5.2).
+ if checkpointer is not None and thread_id is not None:
+ save_pending = getattr(checkpointer, "save_pending_request", None)
+ if save_pending is not None:
+ await save_pending(thread_id, None)
+
+ # Emit TurnEndEvent with the ACTUAL tool_results so listeners get the
+ # 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(
+ message=last,
+ tool_results=batch_tool_results,
+ context=current_context,
+ new_messages=new_messages,
+ )
+ if await should_stop_after_turn(stop_ctx):
+ await emit_event(emit, AgentEndEvent(messages=new_messages))
+ return new_messages
+
+ # Terminate-by-tool semantics (codex BLOCKING: previous draft ignored).
+ if terminated_by_tool:
+ await emit_event(emit, AgentEndEvent(messages=new_messages))
+ return new_messages
+
+ # Fall through to the normal loop for the next model turn.
+ await _run_loop(
+ current_context=current_context,
+ new_messages=new_messages,
+ provider=provider,
+ model=model,
+ convert_to_llm=convert_to_llm,
+ transform_context=transform_context,
+ transform_system_prompt=transform_system_prompt,
+ after_model_response=after_model_response,
+ before_tool_call=before_tool_call,
+ after_tool_call=after_tool_call,
+ should_stop_after_turn=should_stop_after_turn,
+ get_steering_messages=get_steering_messages,
+ get_follow_up_messages=get_follow_up_messages,
+ stream_options=stream_options,
+ tool_execution=tool_execution,
+ emit=emit,
+ )
+ return new_messages
+
+
async def _run_loop(
*,
current_context: AgentContext,
diff --git a/cubepi/agent/tools.py b/cubepi/agent/tools.py
index b5b5ba4..7f57165 100644
--- a/cubepi/agent/tools.py
+++ b/cubepi/agent/tools.py
@@ -168,26 +168,34 @@ async def _execute_prepared(
signal: asyncio.Event | None,
emit_fn: Callable,
) -> tuple[AgentToolResult, bool]:
+ from cubepi.hitl.channel import _in_custom_tool_var
+
+ is_builtin = getattr(prepared.tool, "_hitl_builtin", False)
+ token = None if is_builtin else _in_custom_tool_var.set(True)
try:
- result = await prepared.tool.execute(
- prepared.tool_call.id,
- prepared.args,
- signal=signal,
- on_update=lambda partial: emit_event(
- emit_fn,
- ToolExecutionUpdateEvent(
- tool_call_id=prepared.tool_call.id,
- tool_name=prepared.tool_call.name,
- args=prepared.tool_call.arguments,
- partial_result=partial,
+ try:
+ result = await prepared.tool.execute(
+ prepared.tool_call.id,
+ prepared.args,
+ signal=signal,
+ on_update=lambda partial: emit_event(
+ emit_fn,
+ ToolExecutionUpdateEvent(
+ tool_call_id=prepared.tool_call.id,
+ tool_name=prepared.tool_call.name,
+ args=prepared.tool_call.arguments,
+ partial_result=partial,
+ ),
),
- ),
- )
- return result, False
- except HitlControlException:
- raise
- except Exception as exc:
- return _error_result(str(exc)), True
+ )
+ return result, False
+ except HitlControlException:
+ raise
+ except Exception as exc:
+ return _error_result(str(exc)), True
+ finally:
+ if token is not None:
+ _in_custom_tool_var.reset(token)
async def _finalize(
diff --git a/cubepi/hitl/__init__.py b/cubepi/hitl/__init__.py
index b7953b2..fbe5c01 100644
--- a/cubepi/hitl/__init__.py
+++ b/cubepi/hitl/__init__.py
@@ -24,7 +24,7 @@ from cubepi.hitl.policy import (
Deny,
)
from cubepi.hitl.ask_user import AskUserParams, ask_user_tool
-from cubepi.hitl.channel import HitlChannel, InMemoryChannel
+from cubepi.hitl.channel import CheckpointedChannel, HitlChannel, InMemoryChannel
from cubepi.hitl.middleware import ApprovalPolicyMiddleware, ConfirmToolCallMiddleware
from cubepi.hitl.types import (
ApproveAnswer,
@@ -69,6 +69,7 @@ __all__ = [
"AskUserParams",
"ask_user_tool",
# channel
+ "CheckpointedChannel",
"HitlChannel",
"InMemoryChannel",
# middleware
diff --git a/cubepi/hitl/ask_user.py b/cubepi/hitl/ask_user.py
index 4d38be6..180ffab 100644
--- a/cubepi/hitl/ask_user.py
+++ b/cubepi/hitl/ask_user.py
@@ -81,10 +81,15 @@ def ask_user_tool(channel: HitlChannel) -> AgentTool:
details={"hitl": {"kind": "ask", "answers": answers}},
)
- return AgentTool(
+ tool = AgentTool(
name="ask_user",
description=_DESCRIPTION,
parameters=AskUserParams,
execute=execute,
execution_mode="sequential",
)
+ # Signal to _execute_prepared that this is a built-in HITL tool so the
+ # ContextVar durability guard is NOT set on entry — only custom tool
+ # bodies trigger CheckpointedChannel's HitlDurabilityNotGuaranteed.
+ tool._hitl_builtin = True
+ return tool
diff --git a/cubepi/hitl/channel.py b/cubepi/hitl/channel.py
index b96c326..f272212 100644
--- a/cubepi/hitl/channel.py
+++ b/cubepi/hitl/channel.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import contextvars
import time
import uuid
from typing import Any, AsyncIterator, Protocol
@@ -21,6 +22,16 @@ from cubepi.hitl.types import (
Question,
)
+# 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
+# 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(
+ "_in_custom_tool_var",
+ default=False,
+)
+
class HitlChannel(Protocol):
# ---- agent side ----
@@ -306,4 +317,62 @@ class InMemoryChannel(_BaseChannel):
"""In-process HITL channel; no persistence."""
-# CheckpointedChannel is implemented in Task 9.
+class CheckpointedChannel(_BaseChannel):
+ """Cross-process HITL channel — persists the pending request via a
+ checkpointer so a separate process can call ``Agent.respond()`` after
+ detach.
+
+ The checkpointer MUST implement ``save_pending_request`` and
+ ``load_pending_request`` (first-party checkpointers do; third-party
+ Protocol-only impls may not).
+ """
+
+ def __init__(
+ self,
+ *,
+ checkpointer: Any,
+ 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 = checkpointer
+ self._allow_inside_custom_tool = allow_inside_custom_tool
+
+ 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
+
+ raise HitlDurabilityNotGuaranteed(
+ "CheckpointedChannel called from inside a custom tool body. "
+ "Use ApprovalPolicyMiddleware or ask_user_tool, or pass "
+ "allow_inside_custom_tool=True to opt in."
+ )
+ await self._checkpointer.save_pending_request(self._thread_id, req)
+ await super()._on_pending_set(req)
+
+ async def _on_pending_cleared(
+ self,
+ req: HitlRequest,
+ *,
+ exc: BaseException | None = None,
+ ) -> None:
+ from cubepi.hitl.exceptions import HitlDetached
+
+ if isinstance(exc, HitlDetached):
+ return
+ await self._checkpointer.save_pending_request(self._thread_id, None)
diff --git a/tests/hitl/test_agent_abort_pending.py b/tests/hitl/test_agent_abort_pending.py
new file mode 100644
index 0000000..091c19e
--- /dev/null
+++ b/tests/hitl/test_agent_abort_pending.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from 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 Model, TextContent
+from cubepi.providers.faux import (
+ FauxProvider,
+ faux_assistant_message,
+ faux_text,
+ faux_tool_call,
+)
+
+
+class _Params(BaseModel):
+ cmd: str
+
+
+def _bash_tool() -> AgentTool:
+ async def execute(call_id, args, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text=f"ran {args.cmd}")])
+
+ return AgentTool(
+ name="bash",
+ description="run a shell command",
+ parameters=_Params,
+ execute=execute,
+ execution_mode="sequential",
+ )
+
+
+async def test_abort_pending_closes_conversation():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")
+ provider = FauxProvider()
+ provider.set_responses(
+ [
+ faux_assistant_message(
+ [faux_text("ok"), faux_tool_call("bash", {"cmd": "ls"}, id="tc-1")],
+ stop_reason="tool_use",
+ ),
+ ]
+ )
+ agent = Agent(
+ provider=provider,
+ model=Model(id="faux", provider="faux"),
+ tools=[_bash_tool()],
+ middleware=[ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())],
+ channel=ch,
+ checkpointer=cp,
+ thread_id="t-1",
+ )
+ task = asyncio.create_task(agent.prompt("hi"))
+ for _ in range(200):
+ if ch.pending is not None:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("agent did not suspend on HITL")
+ await agent.detach()
+ await task
+
+ await agent.abort_pending(reason="user closed tab")
+
+ msgs = agent.state.messages
+ # Should end with a synthetic deny tool_result and a stop_reason=aborted
+ # assistant.
+ assert msgs[-2].is_error is True
+ assert "user closed tab" in msgs[-2].content[0].text
+ assert msgs[-1].stop_reason == "aborted"
+ # pending is cleared
+ assert await cp.load_pending_request("t-1") is None
diff --git a/tests/hitl/test_agent_respond.py b/tests/hitl/test_agent_respond.py
new file mode 100644
index 0000000..464a412
--- /dev/null
+++ b/tests/hitl/test_agent_respond.py
@@ -0,0 +1,143 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from 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,
+ HitlNoPendingRequest,
+ HitlStaleAnswer,
+)
+from cubepi.hitl.channel import CheckpointedChannel
+from cubepi.hitl.middleware import ApprovalPolicyMiddleware
+from cubepi.providers.base import Model, TextContent
+from cubepi.providers.faux import (
+ FauxProvider,
+ faux_assistant_message,
+ faux_text,
+ faux_tool_call,
+)
+
+
+class _Params(BaseModel):
+ cmd: str
+
+
+def _bash_tool() -> AgentTool:
+ async def execute(call_id, args, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text=f"ran {args.cmd}")])
+
+ return AgentTool(
+ name="bash",
+ description="run a shell command",
+ parameters=_Params,
+ execute=execute,
+ execution_mode="sequential",
+ )
+
+
+def _two_turn_bash_responses():
+ """Turn 1 calls bash; turn 2 (post tool-result) ends."""
+ return [
+ faux_assistant_message(
+ [faux_text("ok"), faux_tool_call("bash", {"cmd": "ls"}, id="tc-1")],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+
+
+def _faux_with(responses) -> FauxProvider:
+ p = FauxProvider()
+ p.set_responses(responses)
+ return p
+
+
+async def test_respond_completes_a_suspended_run():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")
+ provider = FauxProvider()
+ provider.set_responses(_two_turn_bash_responses())
+ agent = Agent(
+ provider=provider,
+ model=Model(id="faux", provider="faux"),
+ tools=[_bash_tool()],
+ middleware=[
+ ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser()),
+ ],
+ channel=ch,
+ checkpointer=cp,
+ thread_id="t-1",
+ )
+
+ # Start the agent — it will suspend on channel.approve.
+ async def run():
+ await agent.prompt("hi")
+
+ task = asyncio.create_task(run())
+
+ # Wait until pending appears.
+ for _ in range(200):
+ if ch.pending is not None:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("agent did not suspend on HITL")
+
+ # Detach so the run() returns; respond() will pick up.
+ await agent.detach()
+ await task # run() returns cleanly
+
+ # Now respond with approve.
+ await agent.respond(question_id="tc-1", answer=ApproveAnswer(decision="approve"))
+
+ msgs = agent.state.messages
+ assert msgs[-1].content[0].text == "done"
+
+
+async def test_respond_stale_answer():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")
+ agent = Agent(
+ provider=_faux_with([faux_assistant_message("")]),
+ model=Model(id="faux", provider="faux"),
+ channel=ch,
+ checkpointer=cp,
+ thread_id="t-1",
+ )
+ # Manually persist a pending then try the wrong qid.
+ from cubepi.hitl.types import ApproveRequest, HitlRequest
+
+ await cp.save_pending_request(
+ "t-1",
+ HitlRequest(
+ question_id="tc-real",
+ thread_id="t-1",
+ payload=ApproveRequest(tool_name="bash", tool_call_id="tc-real", args={}),
+ created_at=0.0,
+ ),
+ )
+ with pytest.raises(HitlStaleAnswer):
+ await agent.respond(
+ question_id="tc-wrong", answer=ApproveAnswer(decision="approve")
+ )
+
+
+async def test_respond_no_pending():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")
+ agent = Agent(
+ provider=_faux_with([faux_assistant_message("")]),
+ model=Model(id="faux", provider="faux"),
+ channel=ch,
+ checkpointer=cp,
+ thread_id="t-1",
+ )
+ with pytest.raises(HitlNoPendingRequest):
+ await agent.respond(answer=ApproveAnswer(decision="approve"))
diff --git a/tests/hitl/test_checkpointed_channel.py b/tests/hitl/test_checkpointed_channel.py
new file mode 100644
index 0000000..2532c99
--- /dev/null
+++ b/tests/hitl/test_checkpointed_channel.py
@@ -0,0 +1,103 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from cubepi.checkpointer.memory import MemoryCheckpointer
+from cubepi.hitl import ApproveAnswer, HitlDurabilityNotGuaranteed, HitlError
+from cubepi.hitl.channel import CheckpointedChannel
+
+
+async def test_checkpointed_persists_pending_on_ask():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")
+
+ async def host():
+ while True:
+ if await cp.load_pending_request("t-1") is not None:
+ break
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, ApproveAnswer(decision="approve"))
+
+ asyncio.create_task(host())
+ ans = await ch.approve(tool_name="bash", tool_call_id="tc-1", args={})
+ assert ans.decision == "approve"
+ # On success, pending should be cleared from the checkpointer.
+ assert await cp.load_pending_request("t-1") is None
+
+
+async def test_checkpointed_durability_guard_rejects_inside_custom_tool():
+ from cubepi.hitl.channel import _in_custom_tool_var
+
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")
+ token = _in_custom_tool_var.set(True)
+ try:
+ with pytest.raises(HitlDurabilityNotGuaranteed):
+ await ch.confirm("ok?", timeout=0.05)
+ finally:
+ _in_custom_tool_var.reset(token)
+
+
+async def test_checkpointed_durability_optin_allows():
+ from cubepi.hitl.channel import _in_custom_tool_var
+
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(
+ checkpointer=cp,
+ thread_id="t-1",
+ allow_inside_custom_tool=True,
+ )
+ token = _in_custom_tool_var.set(True)
+
+ async def host():
+ while True:
+ if await cp.load_pending_request("t-1") is not None:
+ break
+ await asyncio.sleep(0)
+ await ch.answer(ch.pending.question_id, True)
+
+ try:
+ asyncio.create_task(host())
+ assert await ch.confirm("ok?") is True
+ finally:
+ _in_custom_tool_var.reset(token)
+
+
+async def test_detach_leaves_pending_persisted():
+ cp = MemoryCheckpointer()
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t-1")
+
+ async def detacher():
+ 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
+
+ ch._future.set_exception(HitlDetached())
+
+ asyncio.create_task(detacher())
+ from cubepi.hitl.exceptions import HitlDetached
+
+ with pytest.raises(HitlDetached):
+ await ch.confirm("ok?")
+ # Persisted state must remain on detach (cross-process suspend).
+ assert await cp.load_pending_request("t-1") is not None
+
+
+def test_checkpointed_channel_public_export():
+ from cubepi.hitl import CheckpointedChannel as Exported
+
+ assert Exported is CheckpointedChannel
+
+
+def test_checkpointed_requires_hitl_methods_on_checkpointer():
+ """CheckpointedChannel.__init__ validates the checkpointer has
+ save_pending_request and load_pending_request methods (codex pass 3)."""
+
+ class _BareCheckpointer:
+ pass
+
+ with pytest.raises(HitlError):
+ CheckpointedChannel(checkpointer=_BareCheckpointer(), thread_id="t-1")
diff --git a/tests/hitl/test_resume_cache_prefix.py b/tests/hitl/test_resume_cache_prefix.py
new file mode 100644
index 0000000..8109d8a
--- /dev/null
+++ b/tests/hitl/test_resume_cache_prefix.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+from 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 Model, TextContent
+from cubepi.providers.faux import (
+ FauxProvider,
+ faux_assistant_message,
+ faux_text,
+ faux_tool_call,
+)
+
+
+class _Params(BaseModel):
+ cmd: str
+
+
+def _bash_tool() -> AgentTool:
+ async def execute(call_id, args, *, signal=None, on_update=None):
+ return AgentToolResult(content=[TextContent(text=f"ran {args.cmd}")])
+
+ return AgentTool(
+ name="bash",
+ description="run a shell command",
+ parameters=_Params,
+ execute=execute,
+ execution_mode="sequential",
+ )
+
+
+def _two_turn_bash_responses():
+ return [
+ faux_assistant_message(
+ [faux_text("ok"), faux_tool_call("bash", {"cmd": "ls"}, id="tc-1")],
+ stop_reason="tool_use",
+ ),
+ faux_assistant_message("done"),
+ ]
+
+
+async def _suspend_resume_and_capture(checkpointer):
+ ch = CheckpointedChannel(checkpointer=checkpointer, thread_id="t-1")
+ provider = FauxProvider()
+ provider.set_responses(_two_turn_bash_responses())
+
+ captured: list[dict] = []
+ provider.subscribe_request(lambda payload, model: captured.append(payload))
+
+ agent = Agent(
+ provider=provider,
+ model=Model(id="faux", provider="faux"),
+ tools=[_bash_tool()],
+ middleware=[ApprovalPolicyMiddleware(ch, policy=lambda c: AskUser())],
+ channel=ch,
+ checkpointer=checkpointer,
+ thread_id="t-1",
+ )
+ task = asyncio.create_task(agent.prompt("hi"))
+ for _ in range(200):
+ if ch.pending is not None:
+ break
+ await asyncio.sleep(0.01)
+ else:
+ pytest.fail("agent did not suspend on HITL")
+
+ # First-turn payload bytes (the one the model already saw before suspend)
+ pre_messages = list(captured[0]["messages"])
+
+ await agent.detach()
+ await task
+
+ await agent.respond(question_id="tc-1", answer=ApproveAnswer(decision="approve"))
+
+ # Second turn = post-resume model call. The first len(pre_messages) entries
+ # must be byte-identical to the first turn for prompt-cache to hit.
+ second_turn_messages = captured[1]["messages"]
+ return pre_messages, second_turn_messages[: len(pre_messages)]
+
+
+async def test_resume_preserves_cache_prefix_memory():
+ pre, post = await _suspend_resume_and_capture(MemoryCheckpointer())
+ assert pre == post
+
+
+async def test_resume_preserves_cache_prefix_sqlite(tmp_path):
+ db = tmp_path / "x.db"
+ async with SQLiteCheckpointer(str(db)) as cp:
+ pre, post = await _suspend_resume_and_capture(cp)
+ assert pre == post