Skip to content

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

feat(agent): respond() resumes run_id via load_pending; never reclaims

xf gong8e4b22849ab3
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 57aef91..672b51d 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -558,7 +558,7 @@ class Agent(Generic[TMessage]):
async def respond(
self, *, question_id: str | None = None, answer: StructuredValue
- ) -> None: # pragma: no cover — E2E tested
+ ) -> None:
from cubepi.hitl.exceptions import (
HitlNoPendingRequest,
HitlStaleAnswer,
@@ -569,11 +569,11 @@ class Agent(Generic[TMessage]):
if not (self.thread_id and self.checkpointer):
raise RuntimeError("respond() requires thread_id + checkpointer")
- load_pending = getattr(self.checkpointer, "load_pending_request", None)
+ load_pending = getattr(self.checkpointer, "load_pending", None)
if load_pending is None:
raise HitlError(
"respond() requires a checkpointer that implements "
- "load_pending_request (and save_pending_request)"
+ "load_pending (added in checkpointer v4)"
)
async with self._run_lock:
@@ -583,9 +583,10 @@ class Agent(Generic[TMessage]):
self._state._messages = list(data.messages or [])
self._extra = dict(data.extra or {})
- pending = await load_pending(self.thread_id)
- if pending is None:
+ loaded = await load_pending(self.thread_id)
+ if loaded is None:
raise HitlNoPendingRequest("no pending request on this thread")
+ pending, recovered_run_id = loaded
if question_id is None:
question_id = pending.question_id
if question_id != pending.question_id:
@@ -593,8 +594,27 @@ class Agent(Generic[TMessage]):
f"answer for {question_id}, pending is {pending.question_id}"
)
+ # Thread the recovered run_id into agent state so the resume loop
+ # stamps appended messages and _dispatch_outcome can mark the
+ # run complete. respond() does NOT call claim_run — the original
+ # prompt() already claimed it (single-claim invariant per spec).
+ if recovered_run_id is not None:
+ self._state.active_run_id = recovered_run_id
+ self._state.last_outcome = None
+
self._channel.attach_resume_answer(question_id, answer)
- await self._run_hitl_resume()
+ try:
+ await self._run_hitl_resume()
+ except BaseException:
+ # Spec §3.7: leave active_run_id SET on raise.
+ raise
+ else:
+ # Legacy guard: pending persisted without run_id (older
+ # save_pending_request callers) cannot drive dispatch.
+ if recovered_run_id is not None:
+ outcome: RunOutcome = self._state.last_outcome or "abandoned"
+ await self._dispatch_outcome(outcome, recovered_run_id)
+ self._state.active_run_id = None
async def abort_pending(
self, reason: str = "aborted by host"
@@ -728,6 +748,7 @@ class Agent(Generic[TMessage]):
await self._process_event(AgentAbortedEvent(reason=reason))
async def _run_hitl_resume(self) -> None:
+ sink = self._outcome_sink()
await self._run_with_lifecycle(
lambda signal: run_agent_loop_resume(
context=self._create_context_snapshot(),
@@ -748,6 +769,7 @@ class Agent(Generic[TMessage]):
emit=lambda e: self._process_event(e),
checkpointer=self.checkpointer,
thread_id=self.thread_id,
+ set_outcome=sink,
)
)
diff --git a/tests/agent/test_respond_resume_run_id.py b/tests/agent/test_respond_resume_run_id.py
new file mode 100644
index 0000000..042cecf
--- /dev/null
+++ b/tests/agent/test_respond_resume_run_id.py
@@ -0,0 +1,174 @@
+"""Task 28: respond() resumes run_id via load_pending; never reclaims.
+
+The new respond() body uses the unified ``load_pending`` Protocol method,
+which returns ``(HitlRequest, run_id | None)``. On clean resume it
+propagates the recovered run_id into AgentState.active_run_id, then runs
+the resume loop. After the loop returns successfully it dispatches the
+outcome (mark_run_complete on "complete") and clears active_run_id.
+
+A legacy guard skips dispatch when the recovered run_id is None (pending
+saved by an older save_pending_request call that didn't carry a run_id).
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from cubepi.agent.agent import Agent
+from cubepi.checkpointer.memory import MemoryCheckpointer
+from cubepi.hitl.ask_user import ask_user_tool
+from cubepi.hitl.channel import CheckpointedChannel
+from cubepi.providers.base import (
+ AssistantMessage,
+ TextContent,
+ ToolCall,
+)
+from cubepi.providers.faux import FauxProvider
+
+
+def _pause_then_finish_provider() -> FauxProvider:
+ """Two-turn script: ask_user (pause) → final assistant on resume."""
+ p = FauxProvider()
+ p.set_responses(
+ [
+ AssistantMessage(
+ content=[
+ ToolCall(
+ id="ask-1",
+ name="ask_user",
+ arguments={"questions": [{"key": "ans", "prompt": "?"}]},
+ )
+ ],
+ stop_reason="tool_use",
+ ),
+ AssistantMessage(
+ content=[TextContent(text="done")],
+ stop_reason="end_turn",
+ ),
+ ]
+ )
+ return p
+
+
+async def _drive_pause(
+ cp: MemoryCheckpointer,
+ model_factory,
+) -> None:
+ """Build an Agent, kick a prompt(), wait until pending is persisted."""
+ ch = CheckpointedChannel(checkpointer=cp, thread_id="t", run_id="R1")
+ tool = ask_user_tool(ch)
+ a = Agent(
+ model=model_factory(),
+ tools=[tool],
+ checkpointer=cp,
+ thread_id="t",
+ channel=ch,
+ )
+ task = asyncio.create_task(a.prompt("hi", run_id="R1"))
+ # Wait for pending to be persisted.
+ for _ in range(500):
+ if await cp.load_pending("t") is not None:
+ break
+ await asyncio.sleep(0.01)
+ else: # pragma: no cover — defensive
+ task.cancel()
+ raise AssertionError("pending never appeared")
+ await a.detach()
+ await task
+
+
+async def test_respond_clears_active_run_id_on_clean_resume() -> None:
+ cp = MemoryCheckpointer()
+ p = _pause_then_finish_provider()
+
+ def _model():
+ return p.model("faux-model")
+
+ await _drive_pause(cp, _model)
+
+ # Fresh Agent — emulates a new host process picking up the run.
+ ch2 = CheckpointedChannel(checkpointer=cp, thread_id="t", run_id="R1")
+ tool2 = ask_user_tool(ch2)
+ a2 = Agent(
+ model=_model(),
+ tools=[tool2],
+ checkpointer=cp,
+ thread_id="t",
+ channel=ch2,
+ )
+ loaded = await cp.load_pending("t")
+ assert loaded is not None
+ qid = loaded[0].question_id
+ await a2.respond(question_id=qid, answer="yes")
+
+ assert a2.state.active_run_id is None
+
+
+async def test_respond_resume_writes_marker() -> None:
+ cp = MemoryCheckpointer()
+ p = _pause_then_finish_provider()
+
+ def _model():
+ return p.model("faux-model")
+
+ await _drive_pause(cp, _model)
+
+ # Marker not yet written — prompt() suspended, not completed.
+ assert cp._runs["t"]["R1"].completed_at is None
+
+ ch2 = CheckpointedChannel(checkpointer=cp, thread_id="t", run_id="R1")
+ tool2 = ask_user_tool(ch2)
+ a2 = Agent(
+ model=_model(),
+ tools=[tool2],
+ checkpointer=cp,
+ thread_id="t",
+ channel=ch2,
+ )
+ loaded = await cp.load_pending("t")
+ assert loaded is not None
+ qid = loaded[0].question_id
+ await a2.respond(question_id=qid, answer="yes")
+
+ # Clean resume → outcome "complete" → mark_run_complete fired.
+ assert cp._runs["t"]["R1"].completed_at is not None
+
+
+async def test_respond_resume_with_legacy_pending_does_not_crash() -> None:
+ """Legacy guard: pending persisted without a run_id (run_id=None)
+ must NOT crash respond() and must NOT trigger dispatch."""
+ cp = MemoryCheckpointer()
+ p = _pause_then_finish_provider()
+
+ def _model():
+ return p.model("faux-model")
+
+ await _drive_pause(cp, _model)
+
+ # Forge legacy: re-save the pending request with run_id=None so the
+ # checkpointer "forgets" the run_id binding.
+ loaded = await cp.load_pending("t")
+ assert loaded is not None
+ pending_req, _ = loaded
+ await cp.save_pending_request("t", pending_req, run_id=None)
+
+ ch2 = CheckpointedChannel(checkpointer=cp, thread_id="t", run_id="R1")
+ tool2 = ask_user_tool(ch2)
+ a2 = Agent(
+ model=_model(),
+ tools=[tool2],
+ checkpointer=cp,
+ thread_id="t",
+ channel=ch2,
+ )
+ qid = pending_req.question_id
+ # Must not raise.
+ await a2.respond(question_id=qid, answer="yes")
+
+ # Legacy guard skipped dispatch — marker remains unwritten.
+ assert cp._runs["t"]["R1"].completed_at is None
diff --git a/tests/agent/test_tool_cycle_invariant.py b/tests/agent/test_tool_cycle_invariant.py
index d286f52..e4209dd 100644
--- a/tests/agent/test_tool_cycle_invariant.py
+++ b/tests/agent/test_tool_cycle_invariant.py
@@ -151,10 +151,6 @@ async def test_incomplete_tool_cycle_does_not_mark():
assert cp._runs["t"]["R1"].completed_at is None
- reason="needs Task 28 load_pending recovery for run_id propagation",
- strict=False,
-)
@pytest.mark.asyncio
async def test_tool_cycle_invariant_spans_hitl_resume():
"""Pause mid-tool-use (ask_user). Resume; provider then emits an
diff --git a/tests/hitl/test_edge_cases.py b/tests/hitl/test_edge_cases.py
index 9c53062..4c918dd 100644
--- a/tests/hitl/test_edge_cases.py
+++ b/tests/hitl/test_edge_cases.py
@@ -108,7 +108,7 @@ def test_respond_raises_when_checkpointer_lacks_hitl():
checkpointer=_BareCP(),
thread_id="t-1",
)
- with pytest.raises(HitlError, match="load_pending_request"):
+ with pytest.raises(HitlError, match="load_pending"):
asyncio.get_event_loop().run_until_complete(
agent.respond(answer=ApproveAnswer(decision="approve"))
)