# 模型调用的重试决策

错误在两处成形，都变成 `stop_reason="error"`、`error_message` 可能为空的消息：`runtime/agent/loop/driver.py` 捕获的异常，或提供商流发出的 `error` 事件。

|  | `AgentSession` | `Runtime.exec` |
| --- | --- | --- |
| 代码 | `runtime/agent/loop/session.py`、`retry.py` | `runtime/agent/runtime/execution.py`、`shared.py` |
| 看到的 | 最后一条 assistant 消息 | `_call` 抛出的异常 |
| 预算 | 本次调用的 `transport_limit`（默认 4）；没有恢复状态时 `max_retries=3` | `max_retries=3`，`OPENPROGRAM_MAX_RETRIES` |
| 退避 | `2000·2^(attempt-1)` 毫秒 | `1.5·2^attempt` 秒，±25%；`OPENPROGRAM_RETRY_BACKOFF_BASE` |
| 有 Retry-After | – | 作为下限，只加正向抖动 |
| 重试前 | 弹出失败的 assistant 消息 | – |

## AgentSession：`is_retryable_error`

| 依次检查 | 重试 |
| --- | --- |
| `stop_reason` 不是 `error` | 否 |
| 上下文溢出 | 否，交给压缩 |
| `error_transport_exhausted` | 否 |
| 提供商设置了 `error_retryable` | 以它为准 |
| `error_message` 为空 | 是 |
| 其余情况 | 匹配 `_RETRY_PATTERN` 则是 |

空消息算可重试，因为流断开时往往还没收到错误体。`_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

| 异常 | 动作 |
| --- | --- |
| `ExecInterrupt`、`TypeError`、`NotImplementedError`、`ImportError`、`StructuredOutputError` | 直接抛出 |
| `retryable=False`，或命中 `_PERMANENT_ERROR_MARKERS` | 放弃，“failed permanently” |
| `transport_exhausted`、已过期限、次数用尽、Retry-After 超上限 | 放弃 |
| 等待会越过期限 | 按 `TIMEOUT` 放弃 |
| 其他 | 等待后重试 |

标记：not a valid image、invalid image、image data is not、login expired、login failed、re-auth、unauthorized、invalid api key、invalid_api_key。

## 各层合起来

传输重试只算一次：`AgentSession` 和提供商流共用一个 `RecoveryState`。用尽时消息被标记 `error_transport_exhausted`，exec 不会用新的工具上下文重启本次调用。

## 重试解决不了的

| 失败 | 去向 |
| --- | --- |
| 网关认证失效（`openai-codex` 登录过期或失败） | 永久错误；批量运行前先登录 |
| 上下文溢出 | 压缩 |
| `TypeError`、`NotImplementedError` | 改代码 |

## 错误消息

捕获的异常变成 `type_name: text`，文本为空时只留类型，traceback 打到 stderr。最终错误列出每次尝试的 `type_name: text`，以及是永久失败还是 N 次后失败。
