turn_recovery_codex.py 3.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Codex Responses recovery rungs: stale encrypted-reasoning strip and the replay verdict reset."""
  2. from __future__ import annotations
  3. import logging
  4. from typing import Any
  5. from agent.turn_retry_state import TurnRetryState
  6. logger = logging.getLogger(__name__)
  7. def _is_codex_token_expired(agent: Any, api_error: Exception) -> bool:
  8. """401 ``token_expired`` from the Codex backend (#88510). It rejects a stale replayed
  9. ``encrypted_content`` blob with this auth signature, so a persisted session loops on "sign
  10. in again" while a fresh session on the same bearer works. The caller treats it like
  11. ``invalid_encrypted_content`` — but only while cached reasoning items remain to strip."""
  12. if getattr(api_error, "status_code", None) != 401:
  13. return False
  14. reason = agent._extract_api_error_context(api_error).get("reason")
  15. return isinstance(reason, str) and reason.strip().lower() == "token_expired"
  16. def reset_codex_reasoning_replay(agent: Any) -> None:
  17. """The replay verdict belongs to the route that earned it: a ``/model`` switch, fallback
  18. activation or primary restore starts the new route with replay on (#61552)."""
  19. agent._codex_reasoning_replay_enabled = True
  20. agent._codex_reasoning_replay_rejected = False
  21. def _recover_stale_codex_reasoning(
  22. agent: Any, _retry: TurnRetryState, messages: list[dict[str, Any]], api_messages: Any,
  23. ) -> bool:
  24. """Stale ``codex_reasoning_items`` blob rejected by the provider: strip cached items (mutates
  25. persisted ``messages``) and retry once. The first rung drops only the replayed blobs not stamped by
  26. exactly this endpoint+model (it consumes its own precondition, so it cannot loop); a repeat goes on
  27. to strip every item. The first full strip keeps replay on, since blobs the
  28. route mints from now on are sealed with its current key; a repeat rejection means the route
  29. cannot round-trip its own blobs, so replay is disabled for the session."""
  30. if (
  31. _retry.invalid_encrypted_content_retry_attempted
  32. or agent.api_mode != "codex_responses"
  33. or not bool(getattr(agent, "_codex_reasoning_replay_enabled", True))
  34. or not any(
  35. isinstance(_m, dict)
  36. and _m.get("role") == "assistant"
  37. and isinstance(_m.get("codex_reasoning_items"), list)
  38. and _m.get("codex_reasoning_items")
  39. for _m in messages
  40. )
  41. ):
  42. return False
  43. from agent.turn_recovery import _vlines # facade owns the verbose printer; late import breaks the cycle
  44. transport = agent._get_transport()
  45. if transport is not None and (removed := transport.drop_unverified_replay(messages, api_messages)):
  46. _vlines(agent, f"⚠️ Encrypted reasoning replay was rejected — dropped {removed} item(s) minted elsewhere, retrying...")
  47. return True
  48. _retry.invalid_encrypted_content_retry_attempted = True
  49. keep_replay = not getattr(agent, "_codex_reasoning_replay_rejected", False)
  50. agent._codex_reasoning_replay_rejected = True
  51. replay_stats = agent._disable_codex_reasoning_replay(messages, keep_replay=keep_replay)
  52. # The retry is rebuilt from the request copy; with replay kept on it would resend the stale blob.
  53. for _m in api_messages if isinstance(api_messages, list) else []:
  54. if isinstance(_m, dict):
  55. _m.pop("codex_reasoning_items", None)
  56. action = "stripped stale" if keep_replay else "disabled replay for this session and stripped"
  57. _vlines(
  58. agent,
  59. f"⚠️ Encrypted reasoning replay was rejected by the provider — "
  60. f"{action} {replay_stats['items']} item(s) from {replay_stats['messages']} message(s), retrying...",
  61. )
  62. logger.warning(
  63. "%sInvalid encrypted reasoning recovery: %s %d items from %d messages",
  64. agent.log_prefix, action, replay_stats["items"], replay_stats["messages"],
  65. )
  66. return True