Skip to content

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

fix(hitl): codex review pass — resume idempotency, abort scan, fail-fast lock, pending-clear race

xf gong402b242cdd07
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index b89036d..ed2e4ce 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -242,11 +242,12 @@ class Agent(Generic[TMessage]):
self._follow_up_queue.clear()
async def prompt(self, message: str | Message | list[Message]) -> None:
- # Fail-fast streaming guard MUST happen before the lock — otherwise a
- # second concurrent prompt() blocks waiting for the lock instead of
- # raising the expected RuntimeError (regression caught by
- # test_raises_when_prompt_called_while_streaming).
- if self._state.is_streaming:
+ # Fail-fast guard: if the run-lock is already held OR a stream is in
+ # progress, raise immediately instead of queueing on the lock. This
+ # makes two concurrent cold prompt() calls fail-fast deterministically
+ # (lock.locked() is the atomic source of truth — checking is_streaming
+ # alone races against the to-be-set flag inside the lock body).
+ if self._run_lock.locked() or self._state.is_streaming:
raise RuntimeError(
"Agent is already processing a prompt. "
"Use steer() or follow_up() to queue messages."
@@ -281,8 +282,8 @@ class Agent(Generic[TMessage]):
await self._run_prompt(messages)
async def resume(self) -> None:
- # Same fail-fast pattern as prompt(): check BEFORE the lock.
- if self._state.is_streaming:
+ # Same fail-fast pattern as prompt(): lock.locked() is the atomic gate.
+ if self._run_lock.locked() or self._state.is_streaming:
raise RuntimeError(
"Agent is already processing. Wait for completion before continuing."
)
@@ -495,18 +496,40 @@ class Agent(Generic[TMessage]):
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.
+ # Scan BACKWARDS for the most recent AssistantMessage that has
+ # tool_calls still unresolved. We cannot just look at the tail —
+ # an in-flight execute may have partially appended ToolResultMessage(s)
+ # before signal-abort fired, leaving the tail as a ToolResultMessage
+ # but the originating assistant turn still needing synthetic deny
+ # for the OTHER tool_calls in the same batch.
+ asst_pos = -1
+ last_assistant = None
+ for i in range(len(self._state._messages) - 1, -1, -1):
+ msg = self._state._messages[i]
+ if not isinstance(msg, AssistantMessage):
+ continue
+ tcs = [c for c in msg.content if isinstance(c, ToolCall)]
+ if not tcs:
+ continue
+ already = {
+ m.tool_call_id
+ for m in self._state._messages[i + 1 :]
+ if isinstance(m, ToolResultMessage)
+ }
+ if any(tc.id not in already for tc in tcs):
+ asst_pos = i
+ last_assistant = msg
+ break
+
+ if last_assistant is None or asst_pos < 0:
+ # No unresolved assistant turn — conversation already closed
+ # by some other path. Still clear pending + emit 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).
+ last = last_assistant
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 :]
diff --git a/cubepi/agent/loop.py b/cubepi/agent/loop.py
index a62816b..51c6f1d 100644
--- a/cubepi/agent/loop.py
+++ b/cubepi/agent/loop.py
@@ -162,44 +162,101 @@ async def run_agent_loop_resume(
checkpointer: Any = None,
thread_id: str | None = None,
) -> list[Message]:
- from cubepi.hitl.exceptions import HitlInconsistentState
-
new_messages: list[Message] = []
+ try:
+ return await _run_agent_loop_resume_body(
+ context=context,
+ provider=provider,
+ model=model,
+ convert_to_llm=convert_to_llm,
+ emit=emit,
+ 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,
+ system_prompt=system_prompt,
+ checkpointer=checkpointer,
+ thread_id=thread_id,
+ new_messages=new_messages,
+ )
+ except (HitlDetached, HitlAborted):
+ # Same as _run_loop's outer catch: the Agent caller (Agent.detach /
+ # Agent.abort_pending) emitted the corresponding event already.
+ # Loop exits silently — assistant message and pending state remain
+ # intact for the next respond() call. This catch covers the prelude
+ # (execute_tool_calls of the resumed tool batch) AND the fall-through
+ # to _run_loop, so a second HITL pause/abort during respond() also
+ # unwinds cleanly instead of escaping.
+ return new_messages
+
+
+async def _run_agent_loop_resume_body(
+ *,
+ context,
+ provider,
+ model,
+ convert_to_llm,
+ emit,
+ transform_context,
+ transform_system_prompt,
+ after_model_response,
+ before_tool_call,
+ after_tool_call,
+ should_stop_after_turn,
+ get_steering_messages,
+ get_follow_up_messages,
+ stream_options,
+ tool_execution,
+ system_prompt,
+ checkpointer,
+ thread_id,
+ new_messages: list,
+) -> list[Message]:
+ from cubepi.hitl.exceptions import HitlInconsistentState
+
# 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:
+ # Locate the suspended AssistantMessage by scanning backwards for the most
+ # recent assistant turn that still has unresolved tool_calls. We cannot
+ # require the tail to be that assistant message — a previous crashed
+ # resume may have left some ToolResultMessage(s) at the tail before
+ # crashing, and crash-recovery idempotency depends on us picking the
+ # right assistant turn and skipping already-resolved tool_calls.
+ asst_pos = -1
+ last: AssistantMessage | None = None
+ for i in range(len(context.messages) - 1, -1, -1):
+ msg = context.messages[i]
+ if not isinstance(msg, AssistantMessage):
+ continue
+ tcs = [c for c in msg.content if isinstance(c, ToolCall)]
+ if not tcs:
+ continue
+ already = {
+ m.tool_call_id
+ for m in context.messages[i + 1 :]
+ if isinstance(m, ToolResultMessage)
+ }
+ if any(tc.id not in already for tc in tcs):
+ asst_pos = i
+ last = msg
+ break
+
+ if last is None or asst_pos < 0:
raise HitlInconsistentState(
- "could not locate last assistant message by identity"
+ "resume could not locate an AssistantMessage with unresolved tool_calls"
)
- # 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.
+ unresolved = [c for c in last.content if isinstance(c, ToolCall)]
+ # Idempotency: skip tool_calls already resolved by a prior crashed resume.
already_resolved = {
m.tool_call_id
for m in context.messages[asst_pos + 1 :]
diff --git a/cubepi/hitl/channel.py b/cubepi/hitl/channel.py
index 631a8f2..7938853 100644
--- a/cubepi/hitl/channel.py
+++ b/cubepi/hitl/channel.py
@@ -218,9 +218,19 @@ class _BaseChannel:
# Cancel any still-pending signal task to avoid leaks.
if signal_task is not None and not signal_task.done():
signal_task.cancel()
- self._pending = None
- self._future = None
- await self._on_pending_cleared(req, exc=exc_caught)
+ # Keep the local _pending/_future slot occupied WHILE
+ # _on_pending_cleared runs — CheckpointedChannel's hook
+ # may do an `await save_pending_request(thread_id, None)`,
+ # and during that await another caller could otherwise
+ # see _pending == None, persist a new pending, then have
+ # it wiped by this prior request's late clear. Holding
+ # the local slot forces concurrent calls to bounce on
+ # HitlConcurrencyError instead.
+ try:
+ await self._on_pending_cleared(req, exc=exc_caught)
+ finally:
+ self._pending = None
+ self._future = None
except BaseException as exc:
outcome = _outcome_from_exception(exc)
raise