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
fix(hitl): derive ask/confirm question_id from prompt content
xf gong3068f1446272
diff --git a/cubepi/hitl/channel.py b/cubepi/hitl/channel.pyindex 2cc6bb2..8b5e5a1 100644--- a/cubepi/hitl/channel.py+++ b/cubepi/hitl/channel.py@@ -2,8 +2,9 @@ from __future__ import annotationsimport asyncioimport contextvars+import hashlib+import jsonimport time-import uuidfrom typing import Any, AsyncIterator, Protocolfrom cubepi.hitl.exceptions import (@@ -320,11 +321,14 @@ class _BaseChannel:timeout: float | None | object = _USE_DEFAULT_TIMEOUT,signal: asyncio.Event | None = None,) -> bool:- # During resume the _resume_slot carries the original question_id;- # reuse it so _await_answer's short-circuit matches. The single-pending- # invariant guarantees this is the right slot (see ask() for details).- qid = (- self._resume_slot[0] if self._resume_slot is not None else uuid.uuid4().hex+ # question_id derives from the prompt content (or tool_call_id, when+ # caller supplies one) — NOT from _resume_slot. If a tool body asked+ # Q_A then Q_B and detached with Q_B pending, respond() pre-loads+ # Q_B's qid+answer; the tool's rerun of confirm(Q_A) derives its own+ # qid and falls through to a fresh await instead of consuming Q_B's+ # slot. See `_derive_question_id` docstring for rationale.+ qid = tool_call_id or _derive_question_id(+ "confirm", {"prompt": prompt, "details": details})return await self._await_answer(ConfirmRequest(prompt=prompt, details=details),@@ -362,16 +366,15 @@ class _BaseChannel:timeout: float | None | object = _USE_DEFAULT_TIMEOUT,signal: asyncio.Event | None = None,) -> dict[str, str | list[str]]:- # Resume short-circuit: when the agent detaches while ask() is pending- # and a host later calls Agent.respond(), attach_resume_answer() stores- # the original question_id in _resume_slot. On resume the tool body- # calls ask() again — if we generate a new random UUID here, the- # _await_answer resume match (line 148) will fail and the agent hangs.- # Instead, reuse the resume slot's question_id when one exists. The- # single-pending invariant guarantees that any unpopped resume slot- # belongs to this specific resumption.- qid = (- self._resume_slot[0] if self._resume_slot is not None else uuid.uuid4().hex+ # question_id derives from the questions content — NOT from+ # _resume_slot. If a tool body asked Q_A then Q_B and detached with+ # Q_B pending, respond() pre-loads Q_B's qid+answer; the tool's+ # rerun of ask(Q_A) derives its own qid and falls through to a+ # fresh await instead of consuming Q_B's slot. See+ # `_derive_question_id` docstring for rationale and limitations.+ qid = _derive_question_id(+ "ask",+ [q.model_dump(mode="json") for q in questions],)return await self._await_answer(AskRequest(questions=questions),@@ -381,6 +384,33 @@ class _BaseChannel:)+def _derive_question_id(kind: str, payload_repr: Any) -> str:+ """Deterministic question_id from prompt content.++ Used by ask()/confirm() so resume after detach matches by payload+ content, not by call order. Two consecutive ask() calls in the same+ tool body that re-runs after a detach will derive different qids,+ so the rerun's *first* call won't incorrectly consume the persisted+ answer that was destined for the *second* call.++ `approve()` doesn't need this — it already uses the tool_call_id+ (deterministic across reruns of the same tool batch).++ Limitation: if a tool body legitimately makes the same call twice+ in a row (identical prompt AND identical details), both calls+ derive the same qid; on resume after the second's detach, the+ first call's rerun *will* consume the persisted answer. Callers+ needing to distinguish should pass distinct `details` (or distinct+ `tool_call_id` for confirm()).+ """+ data = json.dumps(+ {"kind": kind, "payload": payload_repr},+ sort_keys=True,+ default=str,+ )+ return hashlib.sha256(data.encode("utf-8")).hexdigest()[:32]++def _outcome_from_answer(kind: str, ans: Any) -> str:if kind == "approve":return {"approve": "approved", "deny": "denied", "edit": "edited"}.get(diff --git a/tests/hitl/test_in_memory_channel.py b/tests/hitl/test_in_memory_channel.pyindex 3a515b5..26e1f87 100644--- a/tests/hitl/test_in_memory_channel.py+++ b/tests/hitl/test_in_memory_channel.py@@ -230,3 +230,69 @@ async def test_attach_resume_answer_qid_mismatch_keeps_slot():# Slot for the OLD qid is still pre-loaded (the implementation should# NOT pop it just because a different qid came through).assert ch._resume_slot == ("tc-OLD", True)+++async def test_ask_resume_slot_not_consumed_by_different_prompt():+ """Regression: when a tool body asks Q_A then Q_B and detaches with Q_B+ pending, respond() pre-loads Q_B's answer. The tool body re-runs from+ the top — Q_A's ask must NOT consume Q_B's resume slot (otherwise Q_A+ gets Q_B's answer and Q_B is never re-asked).++ Codex PR #127 review feedback (P2 channel.py).+ """+ ch = InMemoryChannel()+ questions_b = [Question(key="color", prompt="What colour for Q_B?")]+ questions_a = [Question(key="shape", prompt="What shape for Q_A?")]++ # Compute what Q_B's persisted qid would be via the public ask()+ # path (run a Q_B request, harvest qid, then drop it from pending).+ async def first_run_to_get_qid_b():+ async def host():+ while ch.pending is None:+ await asyncio.sleep(0)+ qid = ch.pending.question_id+ await ch.answer(qid, {"color": "blue"})+ return qid++ host_task = asyncio.create_task(host())+ await ch.ask(questions_b)+ return await host_task++ qid_b = await first_run_to_get_qid_b()++ # Now simulate Agent.respond(): re-prime the slot with Q_B's answer.+ ch.attach_resume_answer(qid_b, {"color": "blue"})++ # Tool body reruns from top and asks Q_A first — must NOT short-circuit+ # to Q_B's answer. With a tight per-call timeout, ask(Q_A) should time+ # out because no host is answering.+ with pytest.raises(HitlTimedOut):+ await ch.ask(questions_a, timeout=0.05)++ # Q_B's slot must still be there for the eventual ask(Q_B) re-call.+ assert ch._resume_slot == (qid_b, {"color": "blue"})+++async def test_confirm_resume_slot_not_consumed_by_different_prompt():+ """Same regression as test_ask_resume_slot_..., for confirm()."""+ ch = InMemoryChannel()++ async def first_run_to_get_qid_b():+ async def host():+ while ch.pending is None:+ await asyncio.sleep(0)+ qid = ch.pending.question_id+ await ch.answer(qid, True)+ return qid++ host_task = asyncio.create_task(host())+ await ch.confirm("Delete database B?")+ return await host_task++ qid_b = await first_run_to_get_qid_b()+ ch.attach_resume_answer(qid_b, True)++ with pytest.raises(HitlTimedOut):+ await ch.confirm("Format disk A?", timeout=0.05)++ assert ch._resume_slot == (qid_b, True)