Skip to content

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

feat(agent): thread active run_id through loop into appended messages

xf gong244b1044b283
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 69775c7..2ae0059 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -277,6 +277,24 @@ class Agent(Generic[TMessage]):
self._steering_queue.clear()
self._follow_up_queue.clear()
+ def _validate_input_run_ids(
+ self,
+ message: str | Message | list[Message],
+ effective_run_id: str,
+ ) -> None:
+ if isinstance(message, str):
+ return
+ if isinstance(message, list):
+ candidates: list[Message] = message
+ else:
+ candidates = [message]
+ for m in candidates:
+ if getattr(m, "run_id", None) is not None and m.run_id != effective_run_id:
+ raise ValueError(
+ f"message.run_id={m.run_id!r} does not match "
+ f"prompt(run_id={effective_run_id!r})"
+ )
+
async def prompt(
self,
message: str | Message | list[Message],
@@ -294,6 +312,10 @@ class Agent(Generic[TMessage]):
"Use steer() or follow_up() to queue messages."
)
effective_run_id = run_id or uuid.uuid4().hex
+ # Reject mismatched caller-supplied Message.run_id BEFORE any state
+ # mutation so the supplied run_id remains reusable (Task 25 will add
+ # claim_run, which must not be called for a rejected prompt).
+ self._validate_input_run_ids(message, effective_run_id)
self._state.active_run_id = effective_run_id
try:
async with self._run_lock:
@@ -307,7 +329,9 @@ class Agent(Generic[TMessage]):
if isinstance(message, str):
messages: list[Message] = [
UserMessage(
- content=[TextContent(text=message)], timestamp=time.time()
+ content=[TextContent(text=message)],
+ timestamp=time.time(),
+ run_id=effective_run_id,
)
]
elif isinstance(message, list):
@@ -757,10 +781,21 @@ class Agent(Generic[TMessage]):
elif event.type == "message_update":
self._state.streaming_message = event.message
elif event.type == "message_end":
+ msg = event.message
+ active = self._state.active_run_id
+ if active is not None:
+ if msg.run_id is None:
+ msg = msg.model_copy(update={"run_id": active})
+ event = event.model_copy(update={"message": msg})
+ elif msg.run_id != active:
+ raise ValueError(
+ f"message.run_id={msg.run_id!r} does not match "
+ f"active run_id={active!r}"
+ )
self._state.streaming_message = None
- self._state._messages.append(event.message)
+ self._state._messages.append(msg)
if self.checkpointer and self.thread_id:
- await self.checkpointer.append(self.thread_id, [event.message])
+ await self.checkpointer.append(self.thread_id, [msg])
elif event.type == "tool_execution_start":
self._state._pending_tool_calls = self._state._pending_tool_calls | {
event.tool_call_id
diff --git a/tests/agent/test_agent_run_id.py b/tests/agent/test_agent_run_id.py
index 2eb8302..0b65a3c 100644
--- a/tests/agent/test_agent_run_id.py
+++ b/tests/agent/test_agent_run_id.py
@@ -52,3 +52,45 @@ async def test_prompt_leaves_active_run_id_set_on_raise(monkeypatch):
with pytest.raises(RuntimeError, match="boom"):
await a.prompt("hello", run_id="R1")
assert a.state.active_run_id == "R1"
+
+
+async def test_appended_messages_carry_run_id():
+ from cubepi.checkpointer.memory import MemoryCheckpointer
+
+ cp = MemoryCheckpointer()
+ a = Agent(
+ model=_ok_faux().model("faux-model"),
+ checkpointer=cp,
+ thread_id="t",
+ )
+ await a.prompt("hello", run_id="R1")
+ data = await cp.load("t")
+ for m in data.messages:
+ assert m.run_id == "R1"
+
+
+async def test_prompt_rejects_mismatched_run_id_before_claim():
+ """Caller pre-stamps a Message with a different run_id than the
+ one supplied to prompt(). Reject BEFORE claim_run so no row is
+ written and the run_id is still reusable."""
+ from cubepi.checkpointer.memory import MemoryCheckpointer
+ from cubepi.providers.base import TextContent, UserMessage
+
+ cp = MemoryCheckpointer()
+ a = Agent(
+ model=_ok_faux().model("faux-model"),
+ checkpointer=cp,
+ thread_id="t",
+ )
+ bad_msg = UserMessage(content=[TextContent(text="hi")], run_id="WRONG")
+ with pytest.raises(ValueError, match="does not match"):
+ await a.prompt(bad_msg, run_id="R1")
+ # No claim row written — "R1" still freely claimable.
+ # NOTE: As of Task 23 there is no claim_run yet (Task 25 adds it),
+ # so cp._runs should be empty regardless. Once Task 25 lands,
+ # this assertion will guarantee no claim row was written.
+ assert "R1" not in cp._runs.get("t", {})
+ # ... and a second prompt with the same run_id succeeds:
+ await a.prompt("hi", run_id="R1")