"""Provider-agnostic bounded execution loop. This module owns the Phase 3 control caps without knowing anything about the browser, the model provider, or the tool registry. A caller supplies already- constructed async step callables and receives ordered envelopes plus the reason the loop stopped. """ from __future__ import annotations import asyncio import time from collections.abc import Awaitable, Callable, Iterable from dataclasses import dataclass from typing import Any, Literal from ..config import settings DEFAULT_MAX_STEPS = settings.agent_max_steps DEFAULT_STEP_TIMEOUT_SECONDS = 60.0 DEFAULT_WALL_CLOCK_SECONDS = float(settings.agent_wall_clock_seconds) MAX_ATTEMPTS = 2 StopReason = Literal["max_steps", "wall_clock", "budget_exhausted", "completed", "cancelled"] @dataclass(frozen=True) class LoopResult: """Truth data for one bounded loop run. ``envelopes`` contains one final envelope per step the loop finished. A step cut short by the wall clock was attempted but produced no envelope, so it is not counted in ``completed_steps`` and no result is invented for work that never finished. When a retryable step exhausts its budget, the final failed envelope is retained so callers can report the original failure without replaying earlier work. """ completed_steps: int attempts_per_step: tuple[int, ...] envelopes: tuple[dict[str, Any], ...] stopped_by_cap: bool stop_reason: StopReason def _is_retryable(envelope: dict[str, Any]) -> bool: error = envelope.get("error") return isinstance(error, dict) and error.get("retryable") is True def is_retryable(envelope: dict[str, Any]) -> bool: """True when an envelope explicitly says the step may be retried. Public so every caller applies the SAME retry rule - the live chat loop included. A step is retried only when its own envelope says so; nothing is retried because it "looks transient". """ return _is_retryable(envelope) def _timeout_envelope(timeout_seconds: float) -> dict[str, Any]: return { "ok": False, "error": { "code": "STEP_TIMEOUT", "message": f"step timed out after {timeout_seconds:.2f}s", "retryable": False, "diagnostic_id": "bounded-loop-timeout", }, } def _invalid_envelope_envelope( step: Callable[[], Awaitable[dict[str, Any]]], envelope: object, ) -> dict[str, Any]: """Return a structured failure for a step that produced a non-dict value.""" step_name = getattr(step, "__name__", type(step).__name__) received_type = type(envelope).__name__ return { "ok": False, "error": { "code": "INVALID_ENVELOPE", "message": ( f"step '{step_name}' returned an invalid envelope of type " f"'{received_type}'; expected a dict" ), "retryable": False, "diagnostic_id": "bounded-loop-invalid-envelope", }, } async def _run_with_deadlines( step: Callable[[], Awaitable[dict[str, Any]]], *, step_timeout_seconds: float, deadline: float, ) -> tuple[dict[str, Any] | None, bool]: """Run one attempt, returning ``(envelope, wall_clock_expired)``. A step timeout is converted to a bounded, non-retryable failure envelope. If the overall wall-clock deadline expires first, no envelope is invented: the caller records that the cap stopped the loop. """ remaining = deadline - time.monotonic() if remaining <= 0: return None, True timeout = min(step_timeout_seconds, remaining) # When the wall clock is the tighter deadline, a timeout here is the cap # firing rather than the step's own timeout. Deciding it from the # deadlines (instead of re-reading the clock) keeps the outcome # deterministic when both deadlines land on the same instant. wall_clock_limited = remaining <= step_timeout_seconds try: envelope = await asyncio.wait_for(step(), timeout=timeout) except TimeoutError: if wall_clock_limited or time.monotonic() >= deadline: return None, True return _timeout_envelope(step_timeout_seconds), False return envelope, False async def run_bounded( steps: Iterable[Callable[[], Awaitable[dict[str, Any]]]], *, max_steps: int | None = None, wall_clock_seconds: float | None = None, step_timeout_seconds: float | None = None, ) -> LoopResult: """Run ordered steps under four hard caps. The caps are: ``max_steps``, a per-step timeout, at most two attempts for a step whose envelope explicitly says ``retryable=true``, and one total wall-clock deadline. A failed step is recovered at that step only; the workflow is never restarted. """ effective_max_steps = settings.agent_max_steps if max_steps is None else max_steps effective_wall_clock = ( float(settings.agent_wall_clock_seconds) if wall_clock_seconds is None else wall_clock_seconds ) effective_step_timeout = ( DEFAULT_STEP_TIMEOUT_SECONDS if step_timeout_seconds is None else step_timeout_seconds ) if effective_max_steps < 0: raise ValueError("max_steps must be non-negative") if effective_wall_clock <= 0: raise ValueError("wall_clock_seconds must be positive") if effective_step_timeout <= 0: raise ValueError("step_timeout_seconds must be positive") deadline = time.monotonic() + effective_wall_clock envelopes: list[dict[str, Any]] = [] attempts_per_step: list[int] = [] stop_reason: StopReason = "completed" step_iterator = iter(steps) # One step is materialised ahead of time at most. The lookahead is what # lets the loop tell "the cap stopped us with work left" apart from "the # work finished exactly at the cap" -- only the callable is fetched, it # is never executed outside the cap. lookahead: Callable[[], Awaitable[dict[str, Any]]] | None = None exhausted = False def take_step() -> Callable[[], Awaitable[dict[str, Any]]]: nonlocal lookahead if lookahead is not None: step = lookahead lookahead = None return step return next(step_iterator) def has_more_steps() -> bool: nonlocal lookahead, exhausted if lookahead is not None: return True if exhausted: return False try: lookahead = next(step_iterator) except StopIteration: exhausted = True return False return True attempted_steps = 0 cancelled = False while True: if attempted_steps >= effective_max_steps: # The cap stopped the loop -- but only report that when there was # actually more work to do. A workflow that finished exactly at # the cap completed, and the caller must not be told the budget # ran out. stop_reason = "max_steps" if has_more_steps() else "completed" break if time.monotonic() >= deadline: # The wall clock may pass during the final successful step. In that # case the deadline expired after the work was already finished and # must not be reported as a cap stop. stop_reason = "completed" if not has_more_steps() else "wall_clock" break # ``steps`` is intentionally consumed lazily so max_steps can stop the # loop before it materializes or calls another step. try: step = take_step() except StopIteration: exhausted = True stop_reason = "completed" break attempt = 0 envelope: dict[str, Any] | None = None wall_clock_expired = False try: while attempt < MAX_ATTEMPTS: attempt += 1 envelope, wall_clock_expired = await _run_with_deadlines( step, step_timeout_seconds=effective_step_timeout, deadline=deadline, ) if wall_clock_expired: break if not isinstance(envelope, dict): envelope = _invalid_envelope_envelope(step, envelope) break if envelope.get("ok") is not False or not _is_retryable(envelope): break except asyncio.CancelledError: # A step may signal its OWN cancellation, which is a normal stop # reason. A cancellation of THIS task is different: it means the # caller went away (an HTTP client disconnected, the user pressed # Stop) and it must propagate. Swallowing it would report a # normal result for work that was actually aborted. current = asyncio.current_task() if current is not None and current.cancelling(): raise cancelled = True # This break leaves the OUTER loop, so the stop reason must be # recorded HERE - reaching the `if cancelled:` check below would # never happen, and the run would report itself as "completed". stop_reason = "cancelled" break # The step was entered, so it counts as attempted even when the wall # clock cut it short and no envelope could be retained. attempted_steps += 1 if cancelled: stop_reason = "cancelled" break if wall_clock_expired: stop_reason = "wall_clock" break if not isinstance(envelope, dict): envelope = _invalid_envelope_envelope(step, envelope) envelopes.append(envelope) attempts_per_step.append(attempt) if envelope.get("ok") is False and _is_retryable(envelope) and attempt >= MAX_ATTEMPTS: stop_reason = "budget_exhausted" break return LoopResult( completed_steps=len(envelopes), attempts_per_step=tuple(attempts_per_step), envelopes=tuple(envelopes), stopped_by_cap=stop_reason in {"max_steps", "wall_clock", "budget_exhausted"}, stop_reason=stop_reason, )