File size: 10,572 Bytes
6eb6c4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"""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,
    )