# Retry decisions for model calls

Errors take shape in two places, and both become a message with `stop_reason="error"` and an `error_message` that may be empty: an exception caught in `runtime/agent/loop/driver.py`, or an `error` event from the provider stream.

|  | `AgentSession` | `Runtime.exec` |
| --- | --- | --- |
| Code | `runtime/agent/loop/session.py`, `retry.py` | `runtime/agent/runtime/execution.py`, `shared.py` |
| Sees | The last assistant message | An exception from `_call` |
| Budget | Invocation's `transport_limit` (default 4); `max_retries=3` without a recovery state | `max_retries=3`, `OPENPROGRAM_MAX_RETRIES` |
| Backoff | `2000·2^(attempt-1)` ms | `1.5·2^attempt` s, ±25%; `OPENPROGRAM_RETRY_BACKOFF_BASE` |
| With Retry-After | – | Lower bound, positive jitter only |
| Before a retry | Pops the failed assistant message | – |

## AgentSession: `is_retryable_error`

| Checked in order | Retry |
| --- | --- |
| `stop_reason` is not `error` | No |
| Context overflow | No; compaction handles it |
| `error_transport_exhausted` | No |
| `error_retryable` set by the provider | That verdict |
| Empty `error_message` | Yes |
| Anything else | Yes if it matches `_RETRY_PATTERN` |

Empty counts as retryable because a dropped stream breaks before any error body arrives. `_RETRY_PATTERN`: overloaded, rate limit, too many requests, 429, 500, 502, 503, 504, service unavailable, server error, internal error, connection error, connection refused, other side closed, fetch failed, upstream connect, reset before headers, terminated, retry delay.

## Runtime.exec

| Exception | Action |
| --- | --- |
| `ExecInterrupt`, `TypeError`, `NotImplementedError`, `ImportError`, `StructuredOutputError` | Raised directly |
| `retryable=False`, or a marker in `_PERMANENT_ERROR_MARKERS` | Gives up, "failed permanently" |
| `transport_exhausted`, deadline passed, attempts spent, Retry-After past the cap | Gives up |
| Sleeping would cross the deadline | Gives up as `TIMEOUT` |
| Otherwise | Sleeps and retries |

Markers: not a valid image, invalid image, image data is not, login expired, login failed, re-auth, unauthorized, invalid api key, invalid_api_key.

## The layers together

Transport retries are counted once: `AgentSession` and the provider stream draw on one `RecoveryState`. When it runs out the message is flagged `error_transport_exhausted` and exec does not restart the invocation with a fresh tool context.

## What retry cannot solve

| Failure | Goes to |
| --- | --- |
| Gateway auth invalid (`openai-codex` login expired or failed) | Permanent; sign in before a batch run |
| Context overflow | Compaction |
| `TypeError`, `NotImplementedError` | The code |

## Messages

A caught exception becomes `type_name: text`, or the type alone when the text is empty, with the traceback on stderr. The final error lists each attempt's `type_name: text` and whether it failed permanently or after N attempts.
