Skip to content

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

feat(agent): prompt accepts run_id, returns it, exposes via active_run_id

xf gongace0ce1fe6cb
diff --git a/cubepi/agent/agent.py b/cubepi/agent/agent.py
index 0e52b53..69775c7 100644
--- a/cubepi/agent/agent.py
+++ b/cubepi/agent/agent.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import time
+import uuid
from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import Callable, Generic, TypeVar
@@ -276,7 +277,12 @@ class Agent(Generic[TMessage]):
self._steering_queue.clear()
self._follow_up_queue.clear()
- async def prompt(self, message: str | Message | list[Message]) -> None:
+ async def prompt(
+ self,
+ message: str | Message | list[Message],
+ *,
+ run_id: str | None = None,
+ ) -> str:
# 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
@@ -287,34 +293,43 @@ class Agent(Generic[TMessage]):
"Agent is already processing a prompt. "
"Use steer() or follow_up() to queue messages."
)
- async with self._run_lock:
- # Re-check under the lock in case streaming flipped during acquire.
- if self._state.is_streaming: # pragma: no cover — defensive re-check
- raise RuntimeError(
- "Agent is already processing a prompt. "
- "Use steer() or follow_up() to queue messages."
- )
-
- if isinstance(message, str):
- messages: list[Message] = [
- UserMessage(
- content=[TextContent(text=message)], timestamp=time.time()
+ effective_run_id = run_id or uuid.uuid4().hex
+ self._state.active_run_id = effective_run_id
+ try:
+ async with self._run_lock:
+ # Re-check under the lock in case streaming flipped during acquire.
+ if self._state.is_streaming: # pragma: no cover — defensive re-check
+ raise RuntimeError(
+ "Agent is already processing a prompt. "
+ "Use steer() or follow_up() to queue messages."
)
- ]
- elif isinstance(message, list):
- messages = message
- else:
- messages = [message]
-
- # Restore history and extra from checkpointer if this is first prompt
- if self.checkpointer and self.thread_id and not self._state._messages:
- data = await self.checkpointer.load(self.thread_id)
- if data:
- if data.messages:
- self._state._messages = list(data.messages)
- self._extra = dict(data.extra)
- await self._run_prompt(messages)
+ if isinstance(message, str):
+ messages: list[Message] = [
+ UserMessage(
+ content=[TextContent(text=message)], timestamp=time.time()
+ )
+ ]
+ elif isinstance(message, list):
+ messages = message
+ else:
+ messages = [message]
+
+ # Restore history and extra from checkpointer if this is first prompt
+ if self.checkpointer and self.thread_id and not self._state._messages:
+ data = await self.checkpointer.load(self.thread_id)
+ if data:
+ if data.messages:
+ self._state._messages = list(data.messages)
+ self._extra = dict(data.extra)
+
+ await self._run_prompt(messages)
+ except BaseException:
+ # Spec §3.7: leave active_run_id SET on failure.
+ raise
+ else:
+ self._state.active_run_id = None
+ return effective_run_id
async def resume(self) -> None:
# Same fail-fast pattern as prompt(): lock.locked() is the atomic gate.
diff --git a/tests/agent/test_agent_run_id.py b/tests/agent/test_agent_run_id.py
new file mode 100644
index 0000000..2eb8302
--- /dev/null
+++ b/tests/agent/test_agent_run_id.py
@@ -0,0 +1,54 @@
+import pytest
+
+from cubepi.agent.agent import Agent
+from cubepi.providers.base import AssistantMessage, TextContent
+from cubepi.providers.faux import FauxProvider
+
+
+def _ok_faux() -> FauxProvider:
+ p = FauxProvider()
+ p.set_responses(
+ [AssistantMessage(content=[TextContent(text="ok")], stop_reason="end_turn")]
+ )
+ return p
+
+
+def _agent(**kw):
+ return Agent(model=_ok_faux().model("faux-model"), **kw)
+
+
+async def test_prompt_returns_supplied_run_id():
+ a = _agent()
+ got = await a.prompt("hello", run_id="R1")
+ assert got == "R1"
+
+
+async def test_prompt_generates_run_id_when_none():
+ a = _agent()
+ got = await a.prompt("hello")
+ assert isinstance(got, str) and len(got) >= 8
+
+
+async def test_prompt_sets_then_clears_active_run_id_on_clean_return():
+ a = _agent()
+ assert a.state.active_run_id is None
+ await a.prompt("hello", run_id="R1")
+ assert a.state.active_run_id is None # cleared on clean return
+
+
+async def test_prompt_leaves_active_run_id_set_on_raise(monkeypatch):
+ """Spec §3.7 + Task 22: active_run_id must be LEFT SET on any
+ propagating failure after claim."""
+ a = Agent(model=_ok_faux().model("faux-model"))
+
+ async def _boom(*args, **kwargs):
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(a, "_run_prompt", _boom)
+ with pytest.raises(RuntimeError, match="boom"):
+ await a.prompt("hello", run_id="R1")
+ assert a.state.active_run_id == "R1"