Skip to content

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

feat(session): add public execution lifecycle

xfgong8f51e8764ba1
diff --git a/cubeloop/__init__.py b/cubeloop/__init__.py
index 2cc26d2..b60c0e8 100644
--- a/cubeloop/__init__.py
+++ b/cubeloop/__init__.py
@@ -75,6 +75,25 @@ from cubeloop.providers.images import (
SizeSpec,
)
from cubeloop.types import JsonObject, JsonValue, StructuredObject, StructuredValue
+from cubeloop.session import (
+ ContinueExecutionRequest,
+ DeliveryError,
+ ExecutionBusy,
+ ExecutionError,
+ ExecutionEventEnvelope,
+ ExecutionFinished,
+ ExecutionRequest,
+ ExecutionResult,
+ ExecutionSession,
+ InputCommitted,
+ InputEnvelope,
+ InputReceipt,
+ MessageView,
+ PromptExecutionRequest,
+ RespondExecutionRequest,
+ ToolExecutionBinding,
+ TurnExecutionContext,
+)
__all__ = [
"__version__",
@@ -89,9 +108,18 @@ __all__ = [
"BoundModel",
"CapabilityDescriptor",
"ContentFiltered",
+ "ContinueExecutionRequest",
+ "DeliveryError",
"ContextLengthExceeded",
"DEFAULT_TRIGGER_ERRORS",
"FallbackBoundModel",
+ "ExecutionBusy",
+ "ExecutionError",
+ "ExecutionEventEnvelope",
+ "ExecutionFinished",
+ "ExecutionRequest",
+ "ExecutionResult",
+ "ExecutionSession",
"ImagesAborted",
"ImagesCapabilityDescriptor",
"ImagesContext",
@@ -99,14 +127,19 @@ __all__ = [
"ImagesModel",
"ImagesOptions",
"ImagesProvider",
+ "InputCommitted",
+ "InputEnvelope",
+ "InputReceipt",
"JsonObject",
"JsonValue",
"Message",
"MessageStream",
+ "MessageView",
"Middleware",
"Model",
"ModelNotFound",
"Provider",
+ "PromptExecutionRequest",
"ProviderAuthFailed",
"ProviderBadRequest",
"ProviderError",
@@ -117,6 +150,7 @@ __all__ = [
"ReasoningEffort",
"ReasoningMode",
"ReasoningSummary",
+ "RespondExecutionRequest",
"SizeSpec",
"StreamEvent",
"StreamOptions",
@@ -126,7 +160,9 @@ __all__ = [
"TextContent",
"ToolCall",
"ToolDefinition",
+ "ToolExecutionBinding",
"ToolResultMessage",
+ "TurnExecutionContext",
"UserMessage",
"CapabilityWarning",
"PayloadPreview",
diff --git a/cubeloop/agent/agent.py b/cubeloop/agent/agent.py
index 3e941d7..5408ed7 100644
--- a/cubeloop/agent/agent.py
+++ b/cubeloop/agent/agent.py
@@ -312,6 +312,10 @@ class Agent(Generic[TMessage]):
self._active_signal: asyncio.Event | None = None
self._active_done: asyncio.Event | None = None
self._fallback_active_index: int = 0
+ self._checkpoint_loaded = messages is not None
+ from cubeloop.session import ExecutionSession
+
+ self.session = ExecutionSession(self)
@property
def state(self) -> AgentState:
@@ -479,6 +483,27 @@ class Agent(Generic[TMessage]):
message: str | Message | list[Message],
*,
run_id: str | None = None,
+ ) -> str:
+ from cubeloop.session import PromptExecutionRequest
+
+ self._validate_hitl_bindings(run_id, caller="prompt")
+ effective_run_id = run_id or uuid.uuid4().hex
+ result = await self.session.execute(
+ PromptExecutionRequest(
+ run_id=effective_run_id,
+ attempt_id=uuid.uuid4().hex,
+ message=message,
+ )
+ )
+ if result.error is not None and result.error.cause is not None:
+ raise result.error.cause
+ return effective_run_id
+
+ async def _execute_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
@@ -529,13 +554,13 @@ class Agent(Generic[TMessage]):
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:
+ if self.checkpointer and self.thread_id and not self._checkpoint_loaded:
data = await self.checkpointer.load(self.thread_id)
if data:
- if data.messages:
- self._state._messages = list(data.messages)
+ self._state._messages = list(data.messages)
self._extra.clear()
self._extra.update(data.extra)
+ self._checkpoint_loaded = True
await self._run_prompt(messages)
except BaseException:
@@ -695,6 +720,20 @@ class Agent(Generic[TMessage]):
)
async def resume(self, *, run_id: str | None = None) -> str:
+ from cubeloop.session import ContinueExecutionRequest
+
+ effective_run_id = run_id or uuid.uuid4().hex
+ result = await self.session.execute(
+ ContinueExecutionRequest(
+ run_id=effective_run_id,
+ attempt_id=uuid.uuid4().hex,
+ )
+ )
+ if result.error is not None and result.error.cause is not None:
+ raise result.error.cause
+ return effective_run_id
+
+ async def _execute_continue(self, *, run_id: str | None = None) -> str:
# Same fail-fast pattern as prompt(): lock.locked() is the atomic gate.
if self._run_lock.locked() or self._state.is_streaming:
raise RuntimeError(
@@ -844,6 +883,9 @@ class Agent(Generic[TMessage]):
messages=list(self._state._messages),
tools=list(self._state._tools),
extra=self._extra,
+ run_id=self._state.active_run_id,
+ attempt_id=self.session.active_attempt_id,
+ on_turn_context=self.session._capture_turn_context,
)
async def detach(self) -> None:
@@ -875,6 +917,29 @@ class Agent(Generic[TMessage]):
async def respond(
self, *, question_id: str | None = None, answer: StructuredValue
+ ) -> None:
+ from cubeloop.session import RespondExecutionRequest
+
+ recovered_run_id: str | None = None
+ if self.checkpointer is not None and self.thread_id is not None:
+ load_pending = getattr(self.checkpointer, "load_pending", None)
+ if load_pending is not None:
+ loaded = await load_pending(self.thread_id)
+ if loaded is not None:
+ recovered_run_id = loaded[1]
+ result = await self.session.execute(
+ RespondExecutionRequest(
+ run_id=recovered_run_id or uuid.uuid4().hex,
+ attempt_id=uuid.uuid4().hex,
+ question_id=question_id,
+ answer=answer,
+ )
+ )
+ if result.error is not None and result.error.cause is not None:
+ raise result.error.cause
+
+ async def _execute_respond(
+ self, *, question_id: str | None = None, answer: StructuredValue
) -> None:
from cubeloop.hitl.exceptions import (
HitlNoPendingRequest,
@@ -899,12 +964,13 @@ class Agent(Generic[TMessage]):
)
async with self._run_lock:
- if not self._state._messages:
+ if not self._checkpoint_loaded:
data = await self.checkpointer.load(self.thread_id)
if data:
self._state._messages = list(data.messages or [])
self._extra.clear()
self._extra.update(data.extra or {})
+ self._checkpoint_loaded = True
loaded = await load_pending(self.thread_id)
if loaded is None:
@@ -1293,6 +1359,7 @@ class Agent(Generic[TMessage]):
if self.checkpointer and self.thread_id:
await self.checkpointer.save_extra(self.thread_id, self._extra)
+ await self.session._publish_agent_event(event)
await self._emit_to_listeners(event)
async def _emit_to_listeners(self, event: AgentEvent) -> None:
diff --git a/cubeloop/agent/loop.py b/cubeloop/agent/loop.py
index 1a57c05..1af939a 100644
--- a/cubeloop/agent/loop.py
+++ b/cubeloop/agent/loop.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import uuid
from typing import TYPE_CHECKING, Callable
from cubeloop.agent.tools import execute_tool_calls
@@ -63,6 +64,9 @@ async def run_agent_loop(
messages=list(context.messages) + list(prompts),
tools=context.tools,
extra=context.extra,
+ run_id=context.run_id,
+ attempt_id=context.attempt_id,
+ on_turn_context=context.on_turn_context,
)
await emit_event(emit, AgentStartEvent())
@@ -126,6 +130,9 @@ async def run_agent_loop_continue(
messages=list(context.messages),
tools=context.tools,
extra=context.extra,
+ run_id=context.run_id,
+ attempt_id=context.attempt_id,
+ on_turn_context=context.on_turn_context,
)
await emit_event(emit, AgentStartEvent())
@@ -745,6 +752,47 @@ async def _stream_assistant_response(
if transform_system_prompt:
sp = await transform_system_prompt(sp, ctx=context, signal=options.signal)
+ turn_id = uuid.uuid4().hex
+ previous_on_model_attempt = options.on_model_attempt
+
+ async def _capture_model_attempt(model_spec) -> None:
+ from cubeloop.session.turn_execution_context import TurnExecutionContext
+
+ existing = context.turn_execution_context
+ if (
+ existing is None
+ or existing.turn_id != turn_id
+ or existing.model.id != model_spec.id
+ or existing.model.provider_id != model_spec.provider_id
+ ):
+ captured = TurnExecutionContext.capture(
+ turn_id=turn_id,
+ run_id=context.run_id or "",
+ attempt_id=context.attempt_id or "",
+ model=model_spec,
+ reasoning=options.reasoning,
+ system_prompt=sp,
+ messages=llm_messages,
+ tools=context.tools,
+ policy_revision=(
+ str(context.extra["policy_revision"])
+ if "policy_revision" in context.extra
+ else None
+ ),
+ )
+ context.turn_id = turn_id
+ context.turn_execution_context = captured
+ if context.on_turn_context is not None:
+ callback_result = context.on_turn_context(captured)
+ if asyncio.iscoroutine(callback_result):
+ await callback_result
+ if previous_on_model_attempt is not None:
+ callback_result = previous_on_model_attempt(model_spec)
+ if asyncio.iscoroutine(callback_result):
+ await callback_result
+
+ options = options.model_copy(update={"on_model_attempt": _capture_model_attempt})
+
stream = await model.stream(
llm_messages,
system_prompt=sp,
diff --git a/cubeloop/agent/tools.py b/cubeloop/agent/tools.py
index 709b22f..f945310 100644
--- a/cubeloop/agent/tools.py
+++ b/cubeloop/agent/tools.py
@@ -177,6 +177,14 @@ async def _resolve_tool_call(
rewritten = ToolCall(
id=tool_call.id, name=rewritten.name, arguments=rewritten.arguments
)
+ turn_context = context.turn_execution_context
+ if turn_context is not None and turn_context.binding_for(rewritten.name) is None:
+ resolved_tool = next(
+ (tool for tool in context.tools or [] if tool.name == rewritten.name),
+ None,
+ )
+ if resolved_tool is not None:
+ context.turn_execution_context = turn_context.extend(resolved_tool)
return rewritten, True, None
@@ -189,8 +197,12 @@ async def _prepare_tool_call(
*,
resolved: bool = False,
) -> _PreparedToolCall | _ImmediateOutcome:
- tool = None
- if context.tools:
+ turn_context = context.turn_execution_context
+ binding = (
+ turn_context.binding_for(tool_call.name) if turn_context is not None else None
+ )
+ tool = binding.tool if binding is not None else None
+ if tool is None and context.tools:
for t in context.tools:
if t.name == tool_call.name:
tool = t
diff --git a/cubeloop/agent/types.py b/cubeloop/agent/types.py
index efe2c54..b5990d1 100644
--- a/cubeloop/agent/types.py
+++ b/cubeloop/agent/types.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
-from typing import Awaitable, Callable, Generic, Literal, TypeVar
+from typing import Any, Awaitable, Callable, Generic, Literal, TypeVar
from pydantic import BaseModel
@@ -59,6 +59,11 @@ class AgentContext:
messages: list[Message]
tools: list[AgentTool] | None = None
extra: JsonObject = field(default_factory=dict)
+ run_id: str | None = None
+ attempt_id: str | None = None
+ turn_id: str | None = None
+ turn_execution_context: Any = None
+ on_turn_context: Callable[[Any], Any] | None = None
# --- Hook context types ---
diff --git a/cubeloop/providers/base.py b/cubeloop/providers/base.py
index 8da2820..f40a354 100644
--- a/cubeloop/providers/base.py
+++ b/cubeloop/providers/base.py
@@ -634,6 +634,10 @@ def _detach(listeners: list, cb: Callable) -> None:
pass
+OnModelAttemptCallback = Callable[[Model], Awaitable[None] | None]
+"""Called immediately before each concrete provider-model attempt."""
+
+
class StreamOptions(BaseModel):
"""Options bag for Provider.stream(), transparent to the agent loop."""
@@ -643,6 +647,7 @@ class StreamOptions(BaseModel):
signal: asyncio.Event | None = None
on_payload: OnPayloadCallback | None = None
on_response: OnResponseCallback | None = None
+ on_model_attempt: OnModelAttemptCallback | None = None
async def invoke_on_payload(
@@ -883,6 +888,10 @@ class BoundModel:
# the pre-BoundModel loop also called ``provider.stream(model,
# messages, ...)`` positionally. The remaining args sit after
# ``*`` in the protocol so they must stay keyword.
+ if options is not None and options.on_model_attempt is not None:
+ result = options.on_model_attempt(self.spec)
+ if inspect.isawaitable(result):
+ await result
return await self.provider.stream(
self.spec,
messages,
diff --git a/cubeloop/session/__init__.py b/cubeloop/session/__init__.py
new file mode 100644
index 0000000..3f1f142
--- /dev/null
+++ b/cubeloop/session/__init__.py
@@ -0,0 +1,46 @@
+from cubeloop.session.events import (
+ ExecutionEventEnvelope,
+ ExecutionFinished,
+ InputCommitted,
+ SessionEvent,
+)
+from cubeloop.session.input import InputEnvelope, InputReceipt
+from cubeloop.session.session import ExecutionSession
+from cubeloop.session.types import (
+ ContinueExecutionRequest,
+ DeliveryError,
+ ExecutionBusy,
+ ExecutionError,
+ ExecutionOutcome,
+ ExecutionRequest,
+ ExecutionResult,
+ PromptExecutionRequest,
+ RespondExecutionRequest,
+)
+from cubeloop.session.turn_execution_context import (
+ MessageView,
+ ToolExecutionBinding,
+ TurnExecutionContext,
+)
+
+__all__ = [
+ "ContinueExecutionRequest",
+ "DeliveryError",
+ "ExecutionBusy",
+ "ExecutionEventEnvelope",
+ "ExecutionFinished",
+ "ExecutionError",
+ "ExecutionOutcome",
+ "ExecutionRequest",
+ "ExecutionResult",
+ "ExecutionSession",
+ "InputCommitted",
+ "InputEnvelope",
+ "InputReceipt",
+ "MessageView",
+ "PromptExecutionRequest",
+ "RespondExecutionRequest",
+ "SessionEvent",
+ "ToolExecutionBinding",
+ "TurnExecutionContext",
+]
diff --git a/cubeloop/session/events.py b/cubeloop/session/events.py
new file mode 100644
index 0000000..18c6183
--- /dev/null
+++ b/cubeloop/session/events.py
@@ -0,0 +1,32 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal, TypeAlias
+
+from cubeloop.agent.types import AgentEvent
+from cubeloop.session.input import InputDurability
+from cubeloop.session.types import ExecutionResult
+
+
+@dataclass(frozen=True)
+class InputCommitted:
+ input_id: str
+ durability: InputDurability
+ type: Literal["input_committed"] = "input_committed"
+
+
+@dataclass(frozen=True)
+class ExecutionFinished:
+ result: ExecutionResult
+ type: Literal["execution_finished"] = "execution_finished"
+
+
+SessionEvent: TypeAlias = AgentEvent | InputCommitted | ExecutionFinished
+
+
+@dataclass(frozen=True)
+class ExecutionEventEnvelope:
+ run_id: str
+ attempt_id: str
+ seq: int
+ event: SessionEvent
diff --git a/cubeloop/session/input.py b/cubeloop/session/input.py
new file mode 100644
index 0000000..7496f0c
--- /dev/null
+++ b/cubeloop/session/input.py
@@ -0,0 +1,24 @@
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal
+
+from cubeloop.providers.base import Message
+
+InputMode = Literal["steer", "follow_up"]
+InputStatus = Literal["queued", "committed", "cancelled", "closed"]
+InputDurability = Literal["memory", "checkpoint"]
+
+
+@dataclass(frozen=True)
+class InputEnvelope:
+ input_id: str
+ message: Message
+ mode: InputMode
+
+
+@dataclass(frozen=True)
+class InputReceipt:
+ input_id: str
+ status: InputStatus
+ durability: InputDurability | None = None
diff --git a/cubeloop/session/session.py b/cubeloop/session/session.py
new file mode 100644
index 0000000..8e7df36
--- /dev/null
+++ b/cubeloop/session/session.py
@@ -0,0 +1,430 @@
+from __future__ import annotations
+
+import asyncio
+import inspect
+from collections.abc import Callable
+from dataclasses import dataclass, replace
+from typing import TYPE_CHECKING, Any
+
+from cubeloop.agent._tool_cycle import ToolCycleViolation, check_tool_cycle
+from cubeloop.agent.types import MessageEndEvent
+from cubeloop.checkpointer.base import CheckpointData
+from cubeloop.session.events import (
+ ExecutionEventEnvelope,
+ ExecutionFinished,
+ InputCommitted,
+ SessionEvent,
+)
+from cubeloop.session.input import (
+ InputDurability,
+ InputEnvelope,
+ InputReceipt,
+ InputStatus,
+)
+from cubeloop.session.types import (
+ ContinueExecutionRequest,
+ DeliveryError,
+ ExecutionBusy,
+ ExecutionError,
+ ExecutionOutcome,
+ ExecutionRequest,
+ ExecutionResult,
+ PromptExecutionRequest,
+ RespondExecutionRequest,
+)
+from cubeloop.types import JsonObject
+
+if TYPE_CHECKING:
+ from cubeloop.agent.agent import Agent
+ from cubeloop.session.turn_execution_context import TurnExecutionContext
+
+
+@dataclass
+class _Consumer:
+ listener: Callable[[ExecutionEventEnvelope], Any]
+ name: str
+ required: bool
+ capacity: int
+ delivery_timeout: float
+ queue: asyncio.Queue[_DeliveryItem]
+ task: asyncio.Task[None] | None = None
+ closed: bool = False
+
+
+@dataclass
+class _DeliveryItem:
+ envelope: ExecutionEventEnvelope
+ acknowledged: asyncio.Future[None]
+
+
+class _RequiredConsumerError(RuntimeError):
+ pass
+
+
+_INPUT_DEDUP_CAPACITY = 4096
+
+
+class ExecutionSession:
+ """Public lifecycle for sequential execution attempts owned by one Agent."""
+
+ def __init__(self, agent: Agent) -> None:
+ self._agent = agent
+ self._active_attempt_id: str | None = None
+ self._active_run_id: str | None = None
+ self._cancel_requested = False
+ self._seq = 0
+ self._consumers: list[_Consumer] = []
+ self._input_status: dict[str, InputStatus] = {}
+ self._delivery_errors: list[DeliveryError] = []
+ self._turn_contexts: list[TurnExecutionContext] = []
+
+ @property
+ def active_attempt_id(self) -> str | None:
+ return self._active_attempt_id
+
+ @property
+ def turn_contexts(self) -> tuple[TurnExecutionContext, ...]:
+ return tuple(self._turn_contexts)
+
+ def _capture_turn_context(self, context: TurnExecutionContext) -> None:
+ self._turn_contexts.append(context)
+
+ @property
+ def state_context(self) -> JsonObject:
+ """The stable, live mapping persisted as checkpoint extra state."""
+ return self._agent._extra
+
+ async def load_checkpoint(self) -> CheckpointData | None:
+ """Atomically install checkpoint messages and extra while idle."""
+ if self._active_attempt_id is not None or self._agent._run_lock.locked():
+ raise ExecutionBusy("cannot load a checkpoint during execution")
+ if self._agent.checkpointer is None or self._agent.thread_id is None:
+ return None
+
+ async with self._agent._run_lock:
+ data = await self._agent.checkpointer.load(self._agent.thread_id)
+ if data is None:
+ return None
+ messages = list(data.messages)
+ extra = dict(data.extra)
+ self._agent._state._messages = messages
+ self._agent._extra.clear()
+ self._agent._extra.update(extra)
+ self._agent._checkpoint_loaded = True
+ return data
+
+ def request_cancel(self) -> None:
+ self._cancel_requested = True
+ self._agent.abort()
+
+ async def request_detach(self) -> None:
+ if self._agent.channel is None or self._agent.channel.pending is None:
+ raise RuntimeError("execution can detach only at a pending HITL safe point")
+ await self._agent.detach()
+
+ def subscribe(
+ self,
+ listener: Callable[[ExecutionEventEnvelope], Any],
+ *,
+ required: bool = False,
+ name: str | None = None,
+ capacity: int = 256,
+ delivery_timeout: float = 1.0,
+ ) -> Callable[[], None]:
+ if capacity < 1:
+ raise ValueError("consumer capacity must be positive")
+ if delivery_timeout <= 0:
+ raise ValueError("consumer delivery_timeout must be positive")
+ consumer_name = name or getattr(listener, "__name__", "session-consumer")
+ consumer = _Consumer(
+ listener=listener,
+ name=str(consumer_name),
+ required=required,
+ capacity=capacity,
+ delivery_timeout=delivery_timeout,
+ queue=asyncio.Queue(maxsize=capacity),
+ )
+ self._consumers.append(consumer)
+
+ def unsubscribe() -> None:
+ consumer.closed = True
+ if consumer.task is not None:
+ consumer.task.cancel()
+ if consumer in self._consumers:
+ self._consumers.remove(consumer)
+
+ return unsubscribe
+
+ def submit_input(self, envelope: InputEnvelope) -> InputReceipt:
+ existing = self._input_status.get(envelope.input_id)
+ if existing is not None:
+ return InputReceipt(input_id=envelope.input_id, status=existing)
+ if self._active_attempt_id is None:
+ return InputReceipt(input_id=envelope.input_id, status="closed")
+ if len(self._input_status) >= _INPUT_DEDUP_CAPACITY:
+ return InputReceipt(input_id=envelope.input_id, status="closed")
+
+ metadata = dict(envelope.message.metadata)
+ metadata["input_id"] = envelope.input_id
+ metadata["input_mode"] = envelope.mode
+ metadata.setdefault("steer_id", envelope.input_id)
+ message = envelope.message.model_copy(update={"metadata": metadata})
+ if envelope.mode == "steer":
+ self._agent.steer(message)
+ else:
+ self._agent.follow_up(message)
+ self._input_status[envelope.input_id] = "queued"
+ return InputReceipt(input_id=envelope.input_id, status="queued")
+
+ def cancel_input(self, input_id: str) -> InputReceipt:
+ status = self._input_status.get(input_id)
+ if status == "committed":
+ durability: InputDurability = (
+ "checkpoint" if self._has_durable_checkpoint() else "memory"
+ )
+ return InputReceipt(
+ input_id=input_id,
+ status="committed",
+ durability=durability,
+ )
+ if status == "cancelled":
+ return InputReceipt(input_id=input_id, status="cancelled")
+ if status != "queued":
+ return InputReceipt(input_id=input_id, status="closed")
+
+ removed = self._agent._steering_queue.remove(input_id)
+ removed = self._agent._follow_up_queue.remove(input_id) or removed
+ if not removed:
+ return InputReceipt(input_id=input_id, status="closed")
+ self._input_status[input_id] = "cancelled"
+ return InputReceipt(input_id=input_id, status="cancelled")
+
+ async def execute(self, request: ExecutionRequest) -> ExecutionResult:
+ """Execute one attempt and return settled lifecycle facts."""
+ if self._active_attempt_id is not None or self._agent._run_lock.locked():
+ raise ExecutionBusy("execution session is already processing an attempt")
+
+ self._active_attempt_id = request.attempt_id
+ self._active_run_id = request.run_id
+ self._cancel_requested = False
+ self._seq = 0
+ self._delivery_errors = []
+ self._input_status.clear()
+ self._turn_contexts.clear()
+ caught: BaseException | None = None
+ try:
+ if isinstance(request, PromptExecutionRequest):
+ await self._agent._execute_prompt(
+ request.message, run_id=request.run_id
+ )
+ elif isinstance(request, RespondExecutionRequest):
+ await self._agent._execute_respond(
+ question_id=request.question_id,
+ answer=request.answer,
+ )
+ elif isinstance(request, ContinueExecutionRequest):
+ await self._agent._execute_continue(run_id=request.run_id)
+ else: # pragma: no cover - closed typed union
+ raise TypeError(f"unsupported execution request: {type(request)!r}")
+ except asyncio.CancelledError as exc:
+ caught = exc
+ except BaseException as exc:
+ caught = exc
+
+ try:
+ result = await self._settle(request, caught)
+ final_errors = await self._publish(
+ ExecutionFinished(result=result), terminal=True
+ )
+ if final_errors:
+ result = replace(
+ result,
+ delivery_errors=tuple([*result.delivery_errors, *final_errors]),
+ )
+ return result
+ finally:
+ self._active_attempt_id = None
+ self._active_run_id = None
+
+ async def _publish_agent_event(self, event: SessionEvent) -> None:
+ if self._active_attempt_id is None:
+ return
+ await self._publish(event, terminal=False)
+ if not isinstance(event, MessageEndEvent):
+ return
+ message = event.message
+ input_id = message.metadata.get("input_id")
+ if not isinstance(input_id, str):
+ return
+ if self._input_status.get(input_id) != "queued":
+ return
+ self._input_status[input_id] = "committed"
+ durability: InputDurability = (
+ "checkpoint" if self._has_durable_checkpoint() else "memory"
+ )
+ await self._publish(
+ InputCommitted(input_id=input_id, durability=durability),
+ terminal=False,
+ )
+
+ async def _publish(
+ self,
+ event: SessionEvent,
+ *,
+ terminal: bool,
+ ) -> list[DeliveryError]:
+ self._seq += 1
+ envelope = ExecutionEventEnvelope(
+ run_id=self._active_run_id or "",
+ attempt_id=self._active_attempt_id or "",
+ seq=self._seq,
+ event=event,
+ )
+ errors: list[DeliveryError] = []
+ required_failure: DeliveryError | None = None
+ for consumer in tuple(self._consumers):
+ if consumer.closed:
+ continue
+ try:
+ if consumer.task is None:
+ consumer.task = asyncio.create_task(self._consume(consumer))
+ acknowledged = asyncio.get_running_loop().create_future()
+ item = _DeliveryItem(envelope=envelope, acknowledged=acknowledged)
+ await asyncio.wait_for(
+ consumer.queue.put(item),
+ timeout=consumer.delivery_timeout,
+ )
+ await asyncio.wait_for(
+ asyncio.shield(acknowledged),
+ timeout=consumer.delivery_timeout,
+ )
+ except TimeoutError:
+ diagnostic = DeliveryError(
+ consumer=consumer.name,
+ seq=envelope.seq,
+ reason="timeout",
+ message="consumer delivery timed out",
+ )
+ errors.append(diagnostic)
+ self._close_consumer(consumer)
+ if consumer.required and not terminal and required_failure is None:
+ required_failure = diagnostic
+ except Exception as exc:
+ diagnostic = DeliveryError(
+ consumer=consumer.name,
+ seq=envelope.seq,
+ reason="error",
+ message=str(exc),
+ )
+ errors.append(diagnostic)
+ self._close_consumer(consumer)
+ if consumer.required and not terminal and required_failure is None:
+ required_failure = diagnostic
+ self._delivery_errors.extend(errors)
+ if required_failure is not None:
+ raise _RequiredConsumerError(
+ f"required consumer {required_failure.consumer} failed: "
+ f"{required_failure.message}"
+ )
+ return errors
+
+ async def _consume(self, consumer: _Consumer) -> None:
+ while True:
+ item = await consumer.queue.get()
+ try:
+ value = consumer.listener(item.envelope)
+ if inspect.isawaitable(value):
+ await value
+ except asyncio.CancelledError:
+ if not item.acknowledged.done():
+ item.acknowledged.cancel()
+ raise
+ except BaseException as exc:
+ if not item.acknowledged.done():
+ item.acknowledged.set_exception(exc)
+ else:
+ if not item.acknowledged.done():
+ item.acknowledged.set_result(None)
+ finally:
+ consumer.queue.task_done()
+
+ @staticmethod
+ def _close_consumer(consumer: _Consumer) -> None:
+ consumer.closed = True
+ if consumer.task is not None:
+ consumer.task.cancel()
+
+ def _has_durable_checkpoint(self) -> bool:
+ return (
+ self._agent.checkpointer is not None and self._agent.thread_id is not None
+ )
+
+ async def _settle(
+ self,
+ request: ExecutionRequest,
+ caught: BaseException | None,
+ ) -> ExecutionResult:
+ history_consistent = True
+ run_messages = [
+ message
+ for message in self._agent.state.messages
+ if message.run_id == request.run_id
+ ]
+ try:
+ check_tool_cycle(run_messages)
+ except ToolCycleViolation:
+ history_consistent = False
+
+ pending = None
+ if self._agent.checkpointer is not None and self._agent.thread_id is not None:
+ load_pending = getattr(self._agent.checkpointer, "load_pending", None)
+ if load_pending is not None:
+ loaded = await load_pending(self._agent.thread_id)
+ pending = loaded[0] if loaded is not None else None
+
+ private_outcome = self._agent.state.last_outcome
+ error: ExecutionError | None = None
+ if isinstance(caught, asyncio.CancelledError) or (
+ private_outcome == "abandoned" and self._cancel_requested
+ ):
+ outcome: ExecutionOutcome = "cancelled"
+ error = ExecutionError(
+ kind="cancelled",
+ message="execution cancelled",
+ cause=caught,
+ )
+ elif caught is not None:
+ outcome = "failed"
+ error = ExecutionError(
+ kind="finalization",
+ message=str(caught),
+ cause=caught,
+ )
+ elif not history_consistent or private_outcome == "incomplete":
+ outcome = "incomplete"
+ error = ExecutionError(
+ kind="inconsistent",
+ message="execution history has incomplete tool-call results",
+ )
+ elif private_outcome == "suspended":
+ outcome = "suspended"
+ elif private_outcome == "complete" and not self._agent.state.error_message:
+ outcome = "completed"
+ else:
+ outcome = "failed"
+ message = (
+ self._agent.state.error_message or "execution ended without a cause"
+ )
+ error = ExecutionError(kind="execution", message=message)
+
+ checkpoint_committed = outcome in {"completed", "suspended"}
+ return ExecutionResult(
+ run_id=request.run_id,
+ attempt_id=request.attempt_id,
+ outcome=outcome,
+ pending_request=pending,
+ error=error,
+ checkpoint_committed=checkpoint_committed,
+ history_consistent=history_consistent,
+ delivery_errors=tuple(self._delivery_errors),
+ )
diff --git a/cubeloop/session/turn_execution_context.py b/cubeloop/session/turn_execution_context.py
new file mode 100644
index 0000000..4020931
--- /dev/null
+++ b/cubeloop/session/turn_execution_context.py
@@ -0,0 +1,117 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+from types import MappingProxyType
+from typing import Any, Mapping
+
+from cubeloop.agent.types import AgentTool
+from cubeloop.providers.base import Message, Model, ReasoningControl, ToolDefinition
+
+
+def _freeze(value: Any) -> Any:
+ if isinstance(value, dict):
+ return MappingProxyType({key: _freeze(item) for key, item in value.items()})
+ if isinstance(value, list):
+ return tuple(_freeze(item) for item in value)
+ if hasattr(value, "model_dump"):
+ return FrozenObject(_freeze(value.model_dump(mode="python")))
+ return value
+
+
+@dataclass(frozen=True)
+class FrozenObject:
+ _values: Mapping[str, Any]
+
+ def __getattr__(self, name: str) -> Any:
+ try:
+ return self._values[name]
+ except KeyError as exc:
+ raise AttributeError(name) from exc
+
+
+@dataclass(frozen=True)
+class MessageView:
+ role: str
+ content: tuple[FrozenObject, ...]
+ metadata: Mapping[str, Any]
+ run_id: str | None
+
+ @classmethod
+ def capture(cls, message: Message) -> MessageView:
+ return cls(
+ role=message.role,
+ content=tuple(_freeze(item) for item in message.content),
+ metadata=_freeze(message.metadata),
+ run_id=message.run_id,
+ )
+
+
+@dataclass(frozen=True)
+class ToolExecutionBinding:
+ name: str
+ definition: ToolDefinition
+ tool: AgentTool
+
+
+@dataclass(frozen=True)
+class TurnExecutionContext:
+ turn_id: str
+ run_id: str
+ attempt_id: str
+ model: Model
+ reasoning: ReasoningControl
+ system_prompt: str
+ messages: tuple[MessageView, ...]
+ tools: tuple[ToolExecutionBinding, ...]
+ policy_revision: str | None = None
+
+ @classmethod
+ def capture(
+ cls,
+ *,
+ turn_id: str,
+ run_id: str,
+ attempt_id: str,
+ model: Model,
+ reasoning: ReasoningControl,
+ system_prompt: str,
+ messages: list[Message],
+ tools: list[AgentTool] | None,
+ policy_revision: str | None = None,
+ ) -> TurnExecutionContext:
+ return cls(
+ turn_id=turn_id,
+ run_id=run_id,
+ attempt_id=attempt_id,
+ model=model.model_copy(deep=True),
+ reasoning=reasoning.model_copy(deep=True),
+ system_prompt=system_prompt,
+ messages=tuple(MessageView.capture(message) for message in messages),
+ tools=tuple(
+ ToolExecutionBinding(
+ name=tool.name,
+ definition=tool.to_definition().model_copy(deep=True),
+ tool=tool,
+ )
+ for tool in tools or []
+ ),
+ policy_revision=policy_revision,
+ )
+
+ def binding_for(self, name: str) -> ToolExecutionBinding | None:
+ return next((binding for binding in self.tools if binding.name == name), None)
+
+ def extend(self, tool: AgentTool) -> TurnExecutionContext:
+ existing = self.binding_for(tool.name)
+ if existing is not None:
+ if existing.tool is not tool:
+ raise ValueError(
+ f"turn execution context already binds tool {tool.name!r}"
+ )
+ return self
+ binding = ToolExecutionBinding(
+ name=tool.name,
+ definition=tool.to_definition().model_copy(deep=True),
+ tool=tool,
+ )
+ return replace(self, tools=(*self.tools, binding))
diff --git a/cubeloop/session/types.py b/cubeloop/session/types.py
new file mode 100644
index 0000000..5939775
--- /dev/null
+++ b/cubeloop/session/types.py
@@ -0,0 +1,72 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal, TypeAlias
+
+from cubeloop.hitl.types import HitlRequest
+from cubeloop.providers.base import Message
+from cubeloop.types import StructuredValue
+
+ExecutionOutcome: TypeAlias = Literal[
+ "completed", "suspended", "cancelled", "failed", "incomplete"
+]
+
+
+@dataclass(frozen=True)
+class PromptExecutionRequest:
+ run_id: str
+ attempt_id: str
+ message: str | Message | list[Message]
+ kind: Literal["prompt"] = "prompt"
+
+
+@dataclass(frozen=True)
+class RespondExecutionRequest:
+ run_id: str
+ attempt_id: str
+ answer: StructuredValue
+ question_id: str | None = None
+ kind: Literal["respond"] = "respond"
+
+
+@dataclass(frozen=True)
+class ContinueExecutionRequest:
+ run_id: str
+ attempt_id: str
+ kind: Literal["continue"] = "continue"
+
+
+ExecutionRequest: TypeAlias = (
+ PromptExecutionRequest | RespondExecutionRequest | ContinueExecutionRequest
+)
+
+
+@dataclass(frozen=True)
+class ExecutionError:
+ kind: Literal["cancelled", "execution", "finalization", "inconsistent"]
+ message: str
+ cause: BaseException | None = field(default=None, repr=False, compare=False)
+
+
+@dataclass(frozen=True)
+class DeliveryError:
+ consumer: str
+ seq: int
+ reason: Literal["timeout", "closed", "error"]
+ message: str = ""
+
+
+@dataclass(frozen=True)
+class ExecutionResult:
+ run_id: str
+ attempt_id: str
+ outcome: ExecutionOutcome
+ pending_request: HitlRequest | None = None
+ error: ExecutionError | None = None
+ checkpoint_committed: bool = False
+ history_consistent: bool = True
+ delivery_errors: tuple[DeliveryError, ...] = ()
+
+
+class ExecutionBusy(RuntimeError):
+ """Raised when an Agent already has an executing or finalizing attempt."""
diff --git a/tests/agent/test_execution_session.py b/tests/agent/test_execution_session.py
new file mode 100644
index 0000000..53f8b67
--- /dev/null
+++ b/tests/agent/test_execution_session.py
@@ -0,0 +1,160 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from cubeloop import Agent
+from cubeloop.checkpointer.base import CheckpointData
+from cubeloop.checkpointer.memory import MemoryCheckpointer
+from cubeloop.providers.base import AssistantMessage, TextContent, UserMessage
+from cubeloop.providers.faux import FauxProvider
+from cubeloop.session import (
+ ExecutionBusy,
+ PromptExecutionRequest,
+)
+
+
+def _provider(*responses: AssistantMessage) -> FauxProvider:
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(list(responses))
+ return provider
+
+
+def _answer(text: str = "done") -> AssistantMessage:
+ return AssistantMessage(
+ content=[TextContent(text=text)],
+ stop_reason="end_turn",
+ )
+
+
+async def test_execute_returns_explicit_completed_result() -> None:
+ agent = Agent(model=_provider(_answer()).model("faux-model"))
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert result.run_id == "run-1"
+ assert result.attempt_id == "attempt-1"
+ assert result.outcome == "completed"
+ assert result.error is None
+ assert result.history_consistent is True
+
+
+async def test_agent_prompt_and_session_share_one_admission_gate() -> None:
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def slow_response(messages, model):
+ del messages, model
+ entered.set()
+ await release.wait()
+ return _answer()
+
+ provider = _provider()
+ provider.set_responses([slow_response])
+ agent = Agent(model=provider.model("faux-model"))
+ first = asyncio.create_task(agent.prompt("first", run_id="run-1"))
+ await asyncio.wait_for(entered.wait(), timeout=1)
+
+ with pytest.raises(ExecutionBusy):
+ await agent.session.execute(
+ PromptExecutionRequest(
+ run_id="run-2",
+ attempt_id="attempt-2",
+ message="second",
+ )
+ )
+
+ release.set()
+ assert await first == "run-1"
+ assert [m.run_id for m in agent.state.messages] == ["run-1", "run-1"]
+
+
+async def test_load_checkpoint_restores_extra_in_place_even_without_messages() -> None:
+ checkpointer = MemoryCheckpointer()
+ await checkpointer.save_extra("thread-1", {"todo": ["ship"]})
+ agent = Agent(
+ model=_provider(_answer()).model("faux-model"),
+ checkpointer=checkpointer,
+ thread_id="thread-1",
+ )
+ live_context = agent.session.state_context
+
+ loaded = await agent.session.load_checkpoint()
+
+ assert loaded is not None
+ assert loaded.messages == []
+ assert live_context is agent.session.state_context
+ assert live_context == {"todo": ["ship"]}
+ live_context["memory"] = "pinned"
+ await agent.prompt("hi", run_id="run-1")
+ persisted = await checkpointer.load("thread-1")
+ assert persisted is not None
+ assert persisted.extra == {"todo": ["ship"], "memory": "pinned"}
+
+
+async def test_load_checkpoint_failure_does_not_partially_replace_live_state() -> None:
+ class BrokenCheckpointer(MemoryCheckpointer):
+ async def load(self, thread_id: str) -> CheckpointData | None:
+ del thread_id
+ raise RuntimeError("cannot load")
+
+ agent = Agent(
+ model=_provider(_answer()).model("faux-model"),
+ checkpointer=BrokenCheckpointer(),
+ thread_id="thread-1",
+ )
+ agent._state._messages = [UserMessage(content=[TextContent(text="existing")])]
+ agent.session.state_context["existing"] = True
+
+ with pytest.raises(RuntimeError, match="cannot load"):
+ await agent.session.load_checkpoint()
+
+ assert agent.session.state_context == {"existing": True}
+ assert len(agent.state.messages) == 1
+
+
+async def test_cancelled_attempt_returns_cancelled_result() -> None:
+ entered = asyncio.Event()
+
+ async def never_finishes(messages, model):
+ del messages, model
+ entered.set()
+ await asyncio.Future()
+
+ provider = _provider()
+ provider.set_responses([never_finishes])
+ agent = Agent(model=provider.model("faux-model"))
+ task = asyncio.create_task(
+ agent.session.execute(
+ PromptExecutionRequest(
+ run_id="run-1",
+ attempt_id="attempt-1",
+ message="hi",
+ )
+ )
+ )
+ await asyncio.wait_for(entered.wait(), timeout=1)
+
+ agent.session.request_cancel()
+ task.cancel()
+ result = await task
+
+ assert result.outcome == "cancelled"
+ assert result.error is not None
+ assert result.error.kind == "cancelled"
+
+
+async def test_detach_rejects_outside_hitl_safe_point() -> None:
+ agent = Agent(model=_provider(_answer()).model("faux-model"))
+
+ with pytest.raises(RuntimeError, match="HITL safe point"):
+ await agent.session.request_detach()
diff --git a/tests/agent/test_session_events.py b/tests/agent/test_session_events.py
new file mode 100644
index 0000000..a98569b
--- /dev/null
+++ b/tests/agent/test_session_events.py
@@ -0,0 +1,80 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from cubeloop import Agent
+from cubeloop.providers.base import AssistantMessage, TextContent
+from cubeloop.providers.faux import FauxProvider
+from cubeloop.session import PromptExecutionRequest
+
+
+def _agent() -> Agent:
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(
+ [AssistantMessage(content=[TextContent(text="done")], stop_reason="end_turn")]
+ )
+ return Agent(model=provider.model("faux-model"))
+
+
+async def test_attempt_events_have_monotonic_sequence_and_one_finished() -> None:
+ agent = _agent()
+ events = []
+ agent.session.subscribe(lambda event: events.append(event), name="observer")
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert [event.seq for event in events] == list(range(1, len(events) + 1))
+ assert {event.run_id for event in events} == {"run-1"}
+ assert {event.attempt_id for event in events} == {"attempt-1"}
+ finished = [event for event in events if event.event.type == "execution_finished"]
+ assert len(finished) == 1
+ assert finished[0].event.result == result
+
+
+async def test_required_consumer_failure_fails_execution() -> None:
+ agent = _agent()
+
+ async def broken(event):
+ if event.event.type == "message_end":
+ raise RuntimeError("publisher closed")
+
+ agent.session.subscribe(broken, required=True, name="host-publisher")
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert result.outcome == "failed"
+ assert result.error is not None
+ assert "host-publisher" in result.error.message
+
+
+async def test_final_notification_timeout_preserves_settled_result() -> None:
+ agent = _agent()
+
+ async def stalls_on_finished(event):
+ if event.event.type == "execution_finished":
+ await asyncio.Future()
+
+ agent.session.subscribe(
+ stalls_on_finished,
+ required=True,
+ name="stalled-host",
+ delivery_timeout=0.01,
+ )
+
+ result = await agent.session.execute(
+ PromptExecutionRequest(run_id="run-1", attempt_id="attempt-1", message="hi")
+ )
+
+ assert result.outcome == "completed"
+ assert len(result.delivery_errors) == 1
+ assert result.delivery_errors[0].consumer == "stalled-host"
+ assert result.delivery_errors[0].reason == "timeout"
diff --git a/tests/agent/test_session_input.py b/tests/agent/test_session_input.py
new file mode 100644
index 0000000..e42de47
--- /dev/null
+++ b/tests/agent/test_session_input.py
@@ -0,0 +1,132 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from cubeloop import Agent
+from cubeloop.checkpointer.memory import MemoryCheckpointer
+from cubeloop.providers.base import AssistantMessage, TextContent, UserMessage
+from cubeloop.providers.faux import FauxProvider
+from cubeloop.session import InputEnvelope, PromptExecutionRequest
+
+
+async def test_input_committed_only_after_checkpoint_append() -> None:
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def first_response(messages, model):
+ del messages, model
+ entered.set()
+ await release.wait()
+ return AssistantMessage(
+ content=[TextContent(text="first")], stop_reason="end_turn"
+ )
+
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(
+ [
+ first_response,
+ AssistantMessage(
+ content=[TextContent(text="after steer")], stop_reason="end_turn"
+ ),
+ ]
+ )
+ checkpointer = MemoryCheckpointer()
+ agent = Agent(
+ model=provider.model("faux-model"),
+ checkpointer=checkpointer,
+ thread_id="thread-1",
+ )
+ events = []
+ agent.session.subscribe(lambda event: events.append(event), name="test-observer")
+ task = asyncio.create_task(
+ agent.session.execute(
+ PromptExecutionRequest(
+ run_id="run-1", attempt_id="attempt-1", message="start"
+ )
+ )
+ )
+ await asyncio.wait_for(entered.wait(), timeout=1)
+
+ receipt = agent.session.submit_input(
+ InputEnvelope(
+ input_id="steer-1",
+ message=UserMessage(content=[TextContent(text="change course")]),
+ mode="steer",
+ )
+ )
+ assert receipt.status == "queued"
+ assert not [event for event in events if event.event.type == "input_committed"]
+
+ release.set()
+ result = await task
+ assert result.outcome == "completed"
+ committed = [event for event in events if event.event.type == "input_committed"]
+ assert len(committed) == 1
+ assert committed[0].event.input_id == "steer-1"
+ assert committed[0].event.durability == "checkpoint"
+ persisted = await checkpointer.load("thread-1")
+ assert persisted is not None
+ assert any(
+ message.metadata.get("input_id") == "steer-1" for message in persisted.messages
+ )
+
+
+async def test_duplicate_and_cancelled_queued_input_is_not_injected() -> None:
+ entered = asyncio.Event()
+ release = asyncio.Event()
+
+ async def response(messages, model):
+ del messages, model
+ entered.set()
+ await release.wait()
+ return AssistantMessage(
+ content=[TextContent(text="done")], stop_reason="end_turn"
+ )
+
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses([response])
+ agent = Agent(model=provider.model("faux-model"))
+ task = asyncio.create_task(
+ agent.session.execute(
+ PromptExecutionRequest(
+ run_id="run-1", attempt_id="attempt-1", message="start"
+ )
+ )
+ )
+ await asyncio.wait_for(entered.wait(), timeout=1)
+ envelope = InputEnvelope(
+ input_id="steer-1",
+ message=UserMessage(content=[TextContent(text="cancel me")]),
+ mode="steer",
+ )
+
+ assert agent.session.submit_input(envelope).status == "queued"
+ assert agent.session.submit_input(envelope).status == "queued"
+ assert agent.session.cancel_input("steer-1").status == "cancelled"
+
+ release.set()
+ await task
+ assert not any(
+ message.metadata.get("input_id") == "steer-1"
+ for message in agent.state.messages
+ )
+ assert agent.session.cancel_input("steer-1").status == "cancelled"
+
+
+def test_input_to_idle_session_is_closed() -> None:
+ provider = FauxProvider(provider_id="faux")
+ agent = Agent(model=provider.model("faux-model"))
+
+ receipt = agent.session.submit_input(
+ InputEnvelope(
+ input_id="late",
+ message=UserMessage(content=[TextContent(text="too late")]),
+ mode="follow_up",
+ )
+ )
+
+ assert receipt.status == "closed"
diff --git a/tests/agent/test_turn_execution_context.py b/tests/agent/test_turn_execution_context.py
new file mode 100644
index 0000000..084efb8
--- /dev/null
+++ b/tests/agent/test_turn_execution_context.py
@@ -0,0 +1,130 @@
+from __future__ import annotations
+
+import pytest
+from pydantic import BaseModel
+
+from cubeloop import Agent
+from cubeloop.agent.types import AgentTool, AgentToolResult
+from cubeloop.providers.base import (
+ AssistantMessage,
+ TextContent,
+ ToolCall,
+ UserMessage,
+)
+from cubeloop.providers.faux import FauxProvider
+from cubeloop.providers.fallback import FallbackBoundModel
+
+
+class _Args(BaseModel):
+ value: str
+
+
+async def test_context_captures_transformed_request_as_immutable_view() -> None:
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(
+ [AssistantMessage(content=[TextContent(text="done")], stop_reason="end_turn")]
+ )
+
+ async def transform(messages, *, ctx, signal=None):
+ del ctx, signal
+ return [
+ *messages,
+ UserMessage(
+ content=[TextContent(text="snapshot")], metadata={"nested": {"v": 1}}
+ ),
+ ]
+
+ agent = Agent(
+ model=provider.model("faux-model"),
+ system_prompt="stable",
+ transform_context=transform,
+ )
+
+ await agent.prompt("hi", run_id="run-1")
+
+ context = agent.session.turn_contexts[-1]
+ assert context.run_id == "run-1"
+ assert context.attempt_id
+ assert context.model.id == "faux-model"
+ assert context.system_prompt == "stable"
+ assert context.messages[-1].content[0].text == "snapshot"
+ transformed = context.messages[-1]
+ with pytest.raises(TypeError):
+ transformed.metadata["nested"] = {"v": 2} # type: ignore[index]
+ assert agent.state.messages[0].metadata == {}
+
+
+async def test_tool_call_uses_binding_captured_for_the_model_request() -> None:
+ calls: list[str] = []
+
+ async def old_execute(tool_call_id, args, *, signal=None, on_update=None):
+ del tool_call_id, args, signal, on_update
+ calls.append("old")
+ return AgentToolResult(content=[TextContent(text="old")])
+
+ async def new_execute(tool_call_id, args, *, signal=None, on_update=None):
+ del tool_call_id, args, signal, on_update
+ calls.append("new")
+ return AgentToolResult(content=[TextContent(text="new")])
+
+ old_tool = AgentTool(
+ name="work", description="work", parameters=_Args, execute=old_execute
+ )
+ new_tool = AgentTool(
+ name="work", description="work", parameters=_Args, execute=new_execute
+ )
+ provider = FauxProvider(provider_id="faux")
+ provider.set_responses(
+ [
+ AssistantMessage(
+ content=[ToolCall(id="call-1", name="work", arguments={"value": "x"})],
+ stop_reason="tool_use",
+ ),
+ AssistantMessage(
+ content=[TextContent(text="done")], stop_reason="end_turn"
+ ),
+ ]
+ )
+
+ async def replace_after_response(message, context, signal=None):
+ del message, signal
+ context.tools = [new_tool]
+
+ agent = Agent(
+ model=provider.model("faux-model"),
+ tools=[old_tool],
+ after_model_response=replace_after_response,
+ )
+
+ await agent.prompt("hi", run_id="run-1")
+
+ assert calls == ["old"]
+ assert len(agent.session.turn_contexts) == 2
+ assert (
+ agent.session.turn_contexts[0].turn_id != agent.session.turn_contexts[1].turn_id
+ )
+
+
+async def test_retry_reuses_context_and_fallback_captures_new_model_view() -> None:
+ primary = FauxProvider(provider_id="primary").model("primary-model")
+ fallback_provider = FauxProvider(provider_id="fallback")
+ fallback_provider.set_responses(
+ [AssistantMessage(content=[TextContent(text="done")], stop_reason="end_turn")]
+ )
+ model = FallbackBoundModel(
+ chain=(primary, fallback_provider.model("fallback-model")),
+ max_retries_per_model=1,
+ )
+ agent = Agent(model=model)
+
+ await agent.prompt("hi", run_id="run-1")
+
+ contexts = agent.session.turn_contexts
+ assert [(ctx.model.provider_id, ctx.model.id) for ctx in contexts] == [
+ ("primary", "primary-model"),
+ ("fallback", "fallback-model"),
+ ]
+ assert contexts[0].turn_id == contexts[1].turn_id
diff --git a/website/docs/api/index.mdx b/website/docs/api/index.mdx
index 7c47003..68887ae 100644
--- a/website/docs/api/index.mdx
+++ b/website/docs/api/index.mdx
@@ -8,6 +8,7 @@ description: "Reference documentation for the CubeLoop Python API."
Auto-generated from CubeLoop's public modules.
- `cubeloop.agent`
+- `cubeloop.session`
- `cubeloop.providers`
- `cubeloop.checkpointer`
- `cubeloop.middleware`
diff --git a/website/docs/getting-started/core-concepts.md b/website/docs/getting-started/core-concepts.md
index 0c21f26..74ddfa4 100644
--- a/website/docs/getting-started/core-concepts.md
+++ b/website/docs/getting-started/core-concepts.md
@@ -12,7 +12,7 @@ the rest of the docs become a lookup table.
`Agent` is the stateful façade: you construct it with a provider, a
model, optional tools, and optional middleware/checkpointer. You drive
-it through three methods:
+ordinary applications through three methods:
- `await agent.prompt(message)` — start a new turn from a user message.
- `await agent.resume()` — continue from the last persisted message
@@ -32,6 +32,31 @@ unsubscribe()
Subscribers receive every `AgentEvent` the loop emits. They can be
sync or async.
+Hosts that need explicit attempt outcomes use the same engine through
+`agent.session`:
+
+```python
+from cubeloop import PromptExecutionRequest
+
+result = await agent.session.execute(
+ PromptExecutionRequest(
+ run_id="run-42",
+ attempt_id="worker-attempt-1",
+ message="Continue the analysis",
+ )
+)
+
+if result.outcome == "suspended":
+ render_form(result.pending_request)
+elif result.outcome != "completed":
+ record_failure(result.error)
+```
+
+An execution session belongs to one `Agent` and runs attempts sequentially.
+It is not a distributed lock or a durable worker session. `ExecutionBusy`
+rejects overlapping `execute()` calls; applications still own admission,
+authorization, leases, and transport status.
+
## Tool
A tool is an async function the model can call. Decorate it with
@@ -118,6 +143,14 @@ Streams and events are two layers:
Subscribe to agent events for UI; for low-level token routing dig into
`event.stream_event`. See [Streaming Events](../guides/agents/streaming).
+`agent.session.subscribe(...)` adds a host-facing layer. Every event is
+wrapped with `run_id`, `attempt_id`, and an attempt-local sequence number.
+The session also emits `input_committed` after an injected message has been
+appended to the checkpointer, and exactly one `execution_finished` for an
+accepted attempt. Mark a consumer `required=True` only when execution cannot
+continue safely without it; observer failures never change the execution
+outcome.
+
## Middleware
`Middleware` is a class with up to nine typed hooks:
diff --git a/website/docs/guides/agents/multi-turn.md b/website/docs/guides/agents/multi-turn.md
index 2a419d4..cdb01cb 100644
--- a/website/docs/guides/agents/multi-turn.md
+++ b/website/docs/guides/agents/multi-turn.md
@@ -51,6 +51,27 @@ sees it before its next response — it's not lost.
- `"one-at-a-time"` (default) — one queued message per pickup point.
- `"all"` — every queued message is drained at once.
+Service hosts that must correlate a queued message with durable storage can
+use the identified session API:
+
+```python
+from cubeloop import InputEnvelope
+
+receipt = agent.session.submit_input(
+ InputEnvelope(
+ input_id=client_message_id,
+ message=UserMessage(content=[TextContent(text=content)]),
+ mode="steer",
+ )
+)
+```
+
+`queued` means the in-memory queue accepted the message. It is not a durable
+acknowledgement. Subscribe to the session's `input_committed` event; its
+durability is `checkpoint` only after the message append succeeds. Steering
+and follow-up remain separate queues with their existing pickup points and
+batch policies.
+
## Queued follow-ups: `agent.follow_up()`
`follow_up` is for *"after the current run, start a new turn with
@@ -133,16 +154,18 @@ async with SQLiteCheckpointer("conv.db") as cp:
await agent.prompt("continue our chat")
```
-The `_extra` slot (an arbitrary `dict[str, Any]`) is also restored.
-Middleware that wants to persist per-thread state should write into
-`context.extra`; the checkpointer's `save_extra` is called at
-`agent_end`.
+The checkpoint `extra` mapping is also restored. Middleware that wants to
+persist per-thread state should write into `context.extra`; the checkpointer's
+`save_extra` is called at `agent_end`. Hosts should use
+`agent.session.state_context`, which is the stable live mapping, and
+`await agent.session.load_checkpoint()` when they need an explicit idle-time
+restore. Messages and extra are installed together, including checkpoints
+whose message list is empty.
## Common pitfalls
-- **`prompt()` while another `prompt()` is in flight** raises
- `RuntimeError`. Use `steer()` or `follow_up()`, or `wait_for_idle()`
- first.
+- **Starting any execution while another is in flight or finalizing** raises
+ `ExecutionBusy`. Use `steer()` or `follow_up()`, or `wait_for_idle()` first.
- **`resume()` with last message = assistant and no queue** raises
`"Cannot continue from message role: assistant"`. Either queue a
follow-up first or call `prompt()` instead.
diff --git a/website/docs/guides/middleware/hooks.md b/website/docs/guides/middleware/hooks.md
index 62c4799..fd56a73 100644
--- a/website/docs/guides/middleware/hooks.md
+++ b/website/docs/guides/middleware/hooks.md
@@ -90,6 +90,15 @@ Fires **before each model call**, on the system prompt string. Use to:
Composition: chained.
+After `transform_context`, `convert_to_llm`, and
+`transform_system_prompt` finish, CubeLoop captures a read-only
+`TurnExecutionContext`. It records the logical request and the concrete tool
+bindings that produced that turn without adding identifiers to model input.
+Transport retries of the same model reuse the capture; a fallback model gets
+a new capture under the same turn. Tool calls retain the binding from their
+capture, while `before_tool_call` still performs current authorization and
+policy checks at execution time.
+
## `resolve_tool_call`
```python
diff --git a/website/scripts/build_api_reference.py b/website/scripts/build_api_reference.py
index bfe2797..52d7b74 100644
--- a/website/scripts/build_api_reference.py
+++ b/website/scripts/build_api_reference.py
@@ -41,12 +41,13 @@ from griffe import AliasResolutionError
MODULES = [
("cubeloop.agent", "Agents", 1),
- ("cubeloop.providers", "Providers", 2),
- ("cubeloop.checkpointer", "Checkpointing", 3),
- ("cubeloop.middleware", "Middleware", 4),
- ("cubeloop.mcp", "MCP", 5),
- ("cubeloop.tracing", "Tracing", 6),
- ("cubeloop.utils", "Utils", 7),
+ ("cubeloop.session", "Execution", 2),
+ ("cubeloop.providers", "Providers", 3),
+ ("cubeloop.checkpointer", "Checkpointing", 4),
+ ("cubeloop.middleware", "Middleware", 5),
+ ("cubeloop.mcp", "MCP", 6),
+ ("cubeloop.tracing", "Tracing", 7),
+ ("cubeloop.utils", "Utils", 8),
]
REPO_ROOT = Path(__file__).resolve().parents[2]
diff --git a/website/sidebars.ts b/website/sidebars.ts
index 273d7fd..6343f77 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -75,6 +75,7 @@ const sidebars: SidebarsConfig = {
link: { type: 'doc', id: 'api/index' },
items: [
'api/cubeloop-agent',
+ 'api/cubeloop-session',
'api/cubeloop-providers',
'api/cubeloop-checkpointer',
'api/cubeloop-middleware',