# Structured generation recovery

| Failure | Action |
| --- | --- |
| Structured output cut off by length | Regenerate from the last complete tool boundary. Partial tool arguments are never executed; partial JSON is never concatenated. |
| Stream ends with no terminal event, empty or partial | Same as length truncation. Partial content is never submitted or executed. |
| Invalid JSON or schema value | Repair under the same allowance |
| Repetitive output (`repetitive_output`) | Detected with no token or wall-clock quota. Stops only that response, keeps completed tool rounds, uses the same allowance, exposes its reason. |
| Transient transport | Provider classification and `Retry-After` decide; a separate transport allowance |
| Cancellation, refusal, invalid configuration | No automatic retry |
| Unknown external outcome | Reconcile before any repeated effect |

## Recovery accounting

One `RecoveryState` (`openprogram/models/providers/utils/failures/recovery.py`) per invocation.

| Allowance | Default | Spent by | Bounded |
| --- | --- | --- | --- |
| Failure | 2 extra attempts; `max_retries` 0 or 1 disables | Length, EOF, schema, repetition | Across the invocation |
| Transport | `OPENPROGRAM_PROVIDER_STREAM_RETRIES` (5) minus 1 | A stream that stalls past the idle bound or drops before its final event; the whole request is sent again and the partial reply is void. Never a repair | Per request: a request that succeeds returns its retries |

- A successful tool round spends nothing. Provider dispatch count is diagnostic, not a second allowance. The structured-output call budget (Runtime `max_retries` requests) credits every transport retry back.
- When this state exists it is the only retry authority for `AgentSession`: no hidden local cap, no restart of completed tools. Explicit retry disabling holds. Standalone `AgentSession` callers keep their own retry settings.
- Each retry reports reason and attempt identity through existing structured-output and execution-stream events. A regeneration instruction asks for a complete value and excludes the invalid candidate. Completed tool results stay in context.
- Cancellation, explicit caller deadlines and non-retryable external effects stay authoritative.

| End state | Rule |
| --- | --- |
| Exhausted | Paused before the error reaches Runtime persistence. Keeps the original cause and a terminal recovery phase; marked transport-exhausted so Runtime cannot restart the invocation. |
| Cancelled | Cancelled |
| Normal return | Not evidence of success; canonical execution status decides |
| At model capacity | Decomposition is the workflow's explicit choice, never guessed by the generic runtime |

## Output parameters

- **Workflow token quota**: None by default; explicit user limits hold
- **Context reservation**: A planning estimate, not the provider output cap
- **Default output cap**: Model capacity, constrained by available context
- **Explicit limit**: Validated, never silently reduced
- **Unknown model limit**: Left to the adapter
- **Long reasoning**: Not a timeout by itself

## Persistence

- Actual requests, effective parameters, stop reasons, available usage and retries are distinguishable. Unknown usage stays unknown.
- Error paths keep metadata without requiring reasoning or sensitive partial text. Paused is distinct from actively retrying.
- Durable execution and effect records own restart and side-effect reconciliation; there is no parallel scheduler.
- Report stages keep resolved scope, supplied materials, retrieved evidence and validated drafts. A text-only `resume_task` is a restart request, not a durable continuation.

## Browser workflows

| Failure | Behaviour | Accepted when |
| --- | --- | --- |
| Text imitating a tool call | Rejected as evidence; real observations come through the public tool boundary | No form action follows an unobserved claim |
| Repetitive model output | See the table above | Repeated stream recovers, healthy long output completes, cancellation and exhaustion stay failures |
| Fixed stage deadline | No Workflow-wide limit. Individual browser operations stay bounded; caller cancellation, explicit limits and retry accounting hold. | No hard-coded 300/600 second aggregate deadline |
| Exception turned into successful text | Typed errors propagate. Function DAG persistence and subprocess IPC keep failed `ToolReturn` and `AgentToolResult` values even on a normal Python return. An unknown write outcome is a non-retryable failure that needs observation before another write. | Public function nodes end in error; completed sibling results stay in diagnostics |

**Browser tool contract and Desktop registration**

- Stages expose only `computer_use`, and accept only its `type="browser"` target without `device` or `app`; prompts describe `list_tabs`, `get_state`, `create_tab` and the four actions a stage may take. Missing tools, login and permission failures stay explicit and never authorize another transport or a write.
- With an origin window and no bound Page, the `list_tabs` listing keeps that origin. With no authorized origin, inventory does not fall back to all desktop windows.
- In a subprocess, inventory goes through the parent webtab bridge, which accepts only the originating window and bindings authorized for that execution. The child's own registry mints and consumes its Page tokens; tokens do not cross registries.
- Opening a URL through `computer_use` and page recovery creates a background Page through Resources, with no foreground chat route, mounted Browser pane or existing page needed. Window registration and native Page target availability are separate failure stages.
- The direct MCP entry keeps a failed browser result as `ToolReturn(is_error=True)`; HTTP dispatch success is not browser success.
- The Desktop bridge registers its exact window identifier on startup and reconnection, before awaiting retained-view or resource restoration, and may repeat that idempotently afterward. Pending restoration does not block a first page. Registration never selects another window or broadens ownership.
- `desktop_unavailable`: the worker cannot use a registered Desktop WebTab at that moment. It differs from a model imitating a tool call and from page network or content errors.
- Report writes need a real observed save or submit and a matching post-action observation with positive success evidence. Explicit failure or missing confirmation is an unknown, non-retryable outcome.
- Out of scope: a second scheduler, durable checkpoints inferred from strings, browser-permission bypass, a new durable report state machine.

## Model routing and group reports

- A subscription provider keeps an explicit model id in the request body and the routing header. The Grok proxy routes by `x-grok-model-override`; `grok-build` is only the fallback for an empty id, and an alias stays an alias.
- Native function calls run only from provider function-call events, never parsed from prose.
- The `read` tool treats a null `offset` or `limit` as omitted, because strict schemas make optional fields required and nullable. Text defaults: line 1, 2000 lines. PDF defaults: page 1, 20 pages. No global null removal.
- Group-report parsing may use prompt-based schema validation when the provider cannot express the schema. Runtime errors are execution errors, not successful `BLOCKED` strings. Missing member attribution asks for clarification and never invents authors. A local draft authorizes no messaging or submission.

**Acceptance**

| Area | Covered by |
| --- | --- |
| Reproduce | Truncation through `agent_loop` and Runtime public calls, sync and async |
| Scenarios | Truncation then success, exhaustion, mixed failure counts, empty and partial EOF, disabled recovery, cancellation, completed-tool non-replay, partial-tool rejection, returned provider errors, explicit output cap, default capacity, context legality, restart, unknown effect reconciliation, combined transport and format repair |
| Files | `runtime/context/compaction/request.py`, `runtime/agent/loop/`, `models/providers/structured_output.py`, `runtime/agent/runtime/providers.py` and `execution.py`, provider retry utilities, stream persistence |
| Test paths | `tests/unit/agent/execution`, `tests/component/programs/tools`, `tests/component/context`, `tests/component/providers`, `tests/contracts`; expand for any other production boundary touched |
| Browser, live | From an empty inventory, open and observe a URL with no manual Browser creation. The installed service passes only when a `computer_use` browser call lists the tabs and reads one, returning its title and element refs, without submitting or saving anything. |
| Group report, live | Real-provider routing comparison, native read-only tool call, the original material parse in its actual prompt-validated mode, a local draft from explicitly attributed test data |

Fake-provider tests do not prove a real report; passing deterministic checks does not prove a live external write.

## Implementation status

Implemented: shared accounting, output-cap separation, length and EOF regeneration, paused and cancelled states, browser origin forwarding, immediate Desktop registration, repetitive-response recovery, receipt retention, truthful error propagation. Quota removal and parse checkpoints live in the separately versioned `weekly_report` and `personal_weekly_report` packages. Open: removal of the compatibility request counter; real end-to-end report submission.
