The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/turn_api_error): _is_local_validation_error predicate, _RETRYABLE_CLIENT_REASONS table, _fallback_break helper, verdict passthrough; trim turn_loop_errors/turn_retry_state
Tekniume50afc20bb94
diff --git a/agent/turn_api_error.py b/agent/turn_api_error.pyindex 9c835431370..29bde13c2d9 100644--- a/agent/turn_api_error.py+++ b/agent/turn_api_error.py@@ -1,10 +1,9 @@"""API-call exception handler for the conversation turn's retry loop: pre-/post-classificationrecovery, interpreter-shutdown abandon, classified-error routing, overflow recovery, thenon-retryable client-error exit, max-retries exhaustion (primary transport recovery →-fallback → terminal result) and the interruptible backoff. Extracted from-``run_conversation``'s ``except Exception as api_error`` block; nothing here imports+fallback → terminal result) and the interruptible backoff. Nothing here imports``agent.conversation_loop`` at module level (cycle) — loop-internal helpers resolve lazily so-existing ``patch("agent.conversation_loop.X")`` sites keep intercepting.+``patch("agent.conversation_loop.X")`` sites keep intercepting."""from __future__ import annotations@@ -70,16 +69,14 @@ def handle_api_error(_provider_overflow_recovery_pending=_provider_overflow_recovery_pending, result=result,)- # Stop spinner silently — retry status is buffered and- # only flushed when every retry+fallback is exhausted.+ # Stop spinner silently — retry status is buffered and only flushed when every+ # retry+fallback is exhausted.if thinking_spinner:thinking_spinner.stop("")thinking_spinner = Noneif agent.thinking_callback:agent.thinking_callback("")- # Pre-classification recovery (encoding sanitization, image rejection,- # Bedrock SDK streaming fallback) — see agent/turn_recovery.py._recovered, active_system_prompt = recover_before_classification(agent, api_error, messages=messages, api_messages=api_messages, api_kwargs=api_kwargs,active_system_prompt=active_system_prompt,@@ -90,9 +87,8 @@ def handle_api_error(status_code = getattr(api_error, "status_code", None)error_context = agent._extract_api_error_context(api_error)- # ── Interpreter finalization: abandon immediately ──- # Process is exiting mid-flight: retries/rotation/fallbacks are futile- # and the retry trace spams the shell. One log line; shared predicate.+ # Process is exiting mid-flight: retries/rotation/fallbacks are futile and the+ # retry trace spams the shell. One log line.from tools.interpreter_shutdown import interpreter_shutting_downif interpreter_shutting_down(api_error):@@ -101,21 +97,13 @@ def handle_api_error("during API call #%d (%s)",agent.log_prefix, api_call_count, api_error,)- _shutdown_summary = (- "Turn abandoned: the process was shutting down " "before the model call could complete."- )+ _shutdown_summary = "Turn abandoned: the process was shutting down before the model call could complete."return _verdict("return", {- "final_response": _shutdown_summary,- "messages": messages,- "api_calls": api_call_count,- "completed": False,- "failed": True,- "error": _shutdown_summary,- "failure_reason": "interpreter_shutdown",- "failure_retryable": False,+ "final_response": _shutdown_summary, "messages": messages, "api_calls": api_call_count,+ "completed": False, "failed": True, "error": _shutdown_summary,+ "failure_reason": "interpreter_shutdown", "failure_retryable": False,})- # ── Classify the error for structured recovery decisions ──_compressor = getattr(agent, "context_compressor", None)_ctx_len = getattr(_compressor, "context_length", 200000) if _compressor else 200000classified = classify_api_error(@@ -137,9 +125,6 @@ def handle_api_error(reason=classified.reason.value,)- # One-shot post-classification recovery chain (entitlement refresh, credential- # pool, image/multimodal strips, per-provider 401 refresh, format-recovery- # strips) — see agent/turn_recovery.py._recovered, recovered_with_pool = recover_after_classification(agent, api_error, classified, _retry, status_code=status_code, error_context=error_context,messages=messages, api_messages=api_messages,@@ -149,19 +134,16 @@ def handle_api_error(retry_count += 1elapsed_time = time.time() - api_start_time- agent._touch_activity(- f"API error recovery (attempt {retry_count}/{max_retries})"- )+ agent._touch_activity(f"API error recovery (attempt {retry_count}/{max_retries})")error_type, error_msg, _provider, _base, _model = log_api_error_attempt(agent, api_error, retry_count=retry_count, max_retries=max_retries, status_code=status_code,elapsed_time=elapsed_time, api_messages=api_messages, approx_tokens=approx_tokens,)- # Check for interrupt before deciding to retryif agent._interrupt_requested:- # Preserve a pending redirect: the user is steering, not stopping- # — rebuild the turn from the correction instead of aborting.+ # Preserve a pending redirect: the user is steering, not stopping — rebuild the+ # turn from the correction instead of aborting.if agent.clear_interrupt(preserve_redirect=True):_retry.restart_with_redirected_messages = Truereturn _verdict("break")@@ -171,11 +153,8 @@ def handle_api_error(agent._persist_session(messages, conversation_history)agent.clear_interrupt()return _verdict("return", {- "final_response": _interrupt_text,- "messages": messages,- "api_calls": api_call_count,- "completed": False,- "interrupted": True,+ "final_response": _interrupt_text, "messages": messages, "api_calls": api_call_count,+ "completed": False, "interrupted": True,})_ce = route_classified_error(@@ -199,12 +178,8 @@ def handle_api_error(_is_zai_coding_overload = _ce.is_zai_coding_overloadif _ce.provider_overflow_recovery_pending:_provider_overflow_recovery_pending = True- if _ce.action == "return":- return _verdict("return", _ce.result)- if _ce.action == "break":- return _verdict("break")- if _ce.action == "continue":- return _verdict("continue")+ if _ce.action != "fallthrough":+ return _verdict(_ce.action, _ce.result)_ov = recover_from_overflow(agent, api_error, classified, _retry, status_code=status_code, error_msg=error_msg,@@ -223,12 +198,8 @@ def handle_api_error(is_context_length_error = _ov.is_context_length_errorif _ov.provider_overflow_recovery_pending:_provider_overflow_recovery_pending = True- if _ov.action == "return":- return _verdict("return", _ov.result)- if _ov.action == "break":- return _verdict("break")- if _ov.action == "continue":- return _verdict("continue")+ if _ov.action != "fallthrough":+ return _verdict(_ov.action, _ov.result)_ue = settle_unrecovered_error(agent, api_error=api_error, classified=classified, _retry=_retry, status_code=status_code,@@ -243,9 +214,28 @@ def handle_api_error(active_system_prompt = _ue.active_system_promptretry_count = _ue.retry_countcompression_attempts = _ue.compression_attempts- if _ue.action != "fallthrough":- return _verdict(_ue.action, _ue.result)- return _verdict("fallthrough")+ return _verdict(_ue.action, _ue.result)+++def _is_local_validation_error(api_error: Any) -> bool:+ """ValueError/TypeError are local bugs, except: UnicodeEncodeError (surrogate recovery+ path), json.JSONDecodeError (transient provider/network failure, must retry),+ ssl.SSLError (inherits OSError *and* ValueError — a TLS failure is not a local bug)+ and "NoneType is not iterable" TypeErrors (upstream shape mismatches, e.g. Codex+ response.completed.output=null — retryable so the fallback path runs)."""+ if not isinstance(api_error, (ValueError, TypeError)):+ return False+ if isinstance(api_error, (UnicodeEncodeError, json.JSONDecodeError, ssl.SSLError)):+ return False+ _text = str(api_error).lower()+ return not (isinstance(api_error, TypeError) and "nonetype" in _text and "not iterable" in _text)+++# Non-retryable per the classifier, yet handled by the overflow/backoff paths instead.+_RETRYABLE_CLIENT_REASONS = frozenset({+ FailoverReason.rate_limit, FailoverReason.overloaded, FailoverReason.context_overflow,+ FailoverReason.payload_too_large, FailoverReason.long_context_tier, FailoverReason.thinking_signature,+})@dataclass@@ -283,47 +273,29 @@ def settle_unrecovered_error(compression_attempts=compression_attempts, result=result,)- # Non-retryable: ValueError/TypeError are local bugs, except- # UnicodeEncodeError (surrogate path above) and json.JSONDecodeError, a- # transient provider/network failure that must be retried (#14782).- is_local_validation_error = (- isinstance(api_error, (ValueError, TypeError))- and not isinstance(- api_error, (UnicodeEncodeError, json.JSONDecodeError)- )- # ssl.SSLError inherits from OSError *and* ValueError, so the- # ValueError check would misclassify a TLS failure as a local bug;- # keep it retryable.- and not isinstance(api_error, ssl.SSLError)- # "NoneType is not iterable" TypeErrors are upstream shape- # mismatches (e.g. Codex response.completed.output=null), reachable- # via shims/mocks — retryable so the fallback path runs.- and not (- isinstance(api_error, TypeError)- and "nonetype" in str(api_error).lower()- and "not iterable" in str(api_error).lower()- )- )- # ``FailoverReason.billing`` (402) is deliberately NOT excluded: pool- # rotation and eager fallback already gave up, so retrying only burns- # paid requests on a depleted balance. Mirrors 401/403. (#31273)+ def _fallback_break() -> UnrecoveredErrorVerdict:+ nonlocal active_system_prompt, retry_count, compression_attempts+ active_system_prompt = _arm_fallback_restart(agent, api_messages, active_system_prompt, _retry)+ retry_count = 0+ compression_attempts = 0+ return _verdict("break")++ # ``FailoverReason.billing`` (402) is deliberately NOT excluded: pool rotation and+ # eager fallback already gave up, so retrying only burns paid requests on a depleted+ # balance. Mirrors 401/403.is_client_error = (- is_local_validation_error+ _is_local_validation_error(api_error)or (not classified.retryableand not classified.should_compress- and classified.reason not in {- FailoverReason.rate_limit, FailoverReason.overloaded,- FailoverReason.context_overflow, FailoverReason.payload_too_large,- FailoverReason.long_context_tier, FailoverReason.thinking_signature,- }+ and classified.reason not in _RETRYABLE_CLIENT_REASONS)) and not is_context_length_errorif is_client_error:# Copilot self-heal BEFORE fallback: a stale credential yields a 400- # ``model_not_available_for_integrator`` / ``model_not_supported``,- # not a 401. Fresh token + client rebuild, one retry, SAME provider.+ # ``model_not_available_for_integrator`` / ``model_not_supported``, not a 401.+ # Fresh token + client rebuild, one retry, SAME provider.if (_is_copilot_provider(agent)and not _retry.copilot_stale_cred_retry_attempted@@ -339,9 +311,8 @@ def settle_unrecovered_error()retry_count = 0return _verdict("continue")- # Try fallback before aborting; announce it only when a fallback- # chain exists, else "trying fallback..." lies before a silent abort- # (#35314).+ # Announce the fallback only when a chain exists, else "trying fallback..." lies+ # before a silent abort.if agent._has_pending_fallback():if classified.reason == FailoverReason.content_policy_blocked:agent._buffer_status("⚠️ Provider safety filter blocked this request — trying fallback...")@@ -350,11 +321,7 @@ def settle_unrecovered_error(else:agent._buffer_status(f"⚠️ Non-retryable error (HTTP {status_code}) — trying fallback...")if agent._try_activate_fallback():- active_system_prompt = _arm_fallback_restart(- agent, api_messages, active_system_prompt, _retry)- retry_count = 0- compression_attempts = 0- return _verdict("break")+ return _fallback_break()return _verdict("return", nonretryable_client_error_result(agent, api_error, classified, status_code=status_code, api_kwargs=api_kwargs,api_messages=api_messages, messages=messages, conversation_history=conversation_history,@@ -363,29 +330,23 @@ def settle_unrecovered_error())if retry_count >= max_retries:- # Before fallback, rebuild the primary client once for transient- # transport errors (stale pool, TCP reset). Once per API call block.+ # Before fallback, rebuild the primary client once per API call block for+ # transient transport errors (stale pool, TCP reset).if not _retry.primary_recovery_attempted and agent._try_recover_primary_transport(api_error, retry_count=retry_count, max_retries=max_retries,):_retry.primary_recovery_attempted = Trueretry_count = 0- # Transport recovery starts a fresh attempt cycle: re-open- # fallback state so a follow-on 429 can still activate- # fallback_providers.+ # Fresh attempt cycle: re-open fallback state so a follow-on 429 can still+ # activate fallback_providers._retry.has_retried_429 = Falseagent._fallback_index = 0agent._fallback_activated = Falsereturn _verdict("continue")- # Try fallback before giving up entirelyif agent._has_pending_fallback():agent._buffer_status(f"⚠️ Max retries ({max_retries}) exhausted — trying fallback...")if agent._try_activate_fallback():- active_system_prompt = _arm_fallback_restart(- agent, api_messages, active_system_prompt, _retry)- retry_count = 0- compression_attempts = 0- return _verdict("break")+ return _fallback_break()return _verdict("return", max_retries_exhausted_result(agent, api_error, classified, max_retries=max_retries, is_rate_limited=is_rate_limited,error_msg=error_msg, api_kwargs=api_kwargs, api_messages=api_messages,@@ -399,8 +360,8 @@ def settle_unrecovered_error(is_rate_limited=is_rate_limited, is_zai_coding_overload=_is_zai_coding_overload,base_url=_base, model=_model,)- # Same preserve-redirect rule as the invalid-response wait: a steering- # correction must survive backoff, not die as "Operation interrupted".+ # Same preserve-redirect rule as the invalid-response wait: a steering correction+ # must survive backoff, not die as "Operation interrupted"._interrupted = interruptible_backoff_sleep(agent, wait_time, _retry, messages=messages, conversation_history=conversation_history,api_call_count=api_call_count,@@ -411,7 +372,7 @@ def settle_unrecovered_error(if _interrupted is not None:return _verdict("return", _interrupted)if _retry.restart_with_redirected_messages:- # Leave the retry loop — the check below rebuilds this iteration- # from the correction instead of re-firing the stale request.+ # Leave the retry loop — the caller rebuilds this iteration from the correction+ # instead of re-firing the stale request.return _verdict("break")return _verdict("fallthrough")diff --git a/agent/turn_loop_errors.py b/agent/turn_loop_errors.pyindex c3b97efdb96..32c7b20d419 100644--- a/agent/turn_loop_errors.py+++ b/agent/turn_loop_errors.py@@ -1,10 +1,8 @@-"""Outer-loop exception handler for the conversation turn loop.--Extracted from ``run_conversation``'s trailing ``except Exception`` block: phase-aware-classification (interpreter shutdown, deterministic local post-processing bug vs API-path-failure), unanswered tool_call error results, and the per-turn error cap that stops the-loop from spinning until the budget is gone (#92450). Nothing here imports-``agent.conversation_loop`` at module level (cycle); loop-internal constants resolve lazily.+"""Outer-loop exception handler for the conversation turn loop: phase-aware classification+(interpreter shutdown, deterministic local post-processing bug vs API-path failure),+unanswered tool_call error results, and the per-turn error cap that stops the loop from+spinning until the budget is gone. Nothing here imports ``agent.conversation_loop`` at+module level (cycle); loop-internal constants resolve lazily."""from __future__ import annotations@@ -13,7 +11,7 @@ from dataclasses import dataclassimport loggingimport osimport sys-from typing import Any, Dict, Optional+from typing import Anyfrom agent.message_metadata import append_message@@ -39,72 +37,59 @@ def handle_outer_loop_error() -> OuterErrorVerdict:"""Handle an exception that escaped the response-processing block. Shutdown andlocal-processing errors are deterministic and end the turn; API-path errors retry until- ``min(_MAX_OUTER_LOOP_ERRORS, max_iterations)`` escaped exceptions (#92450). The- assistant message is never appended here: a prefill/interim assistant may already be- the tail; ``finalize_turn`` appends only when safe."""+ ``min(_MAX_OUTER_LOOP_ERRORS, max_iterations)`` escaped exceptions. The assistant+ message is never appended here: a prefill/interim assistant may already be the tail+ (assistant→assistant); ``finalize_turn`` appends only when safe."""from agent.conversation_loop import (_API_CALL_MODULES, _LOCAL_PROCESSING_MODULES, _MAX_OUTER_LOOP_ERRORS,_is_interpreter_shutdown_error, _ra,)- def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> OuterErrorVerdict:+ def _verdict(action: str) -> OuterErrorVerdict:return OuterErrorVerdict(action=action, _outer_error_count=_outer_error_count,_turn_exit_reason=_turn_exit_reason, failed=failed, final_response=final_response,)- # Count every escaped exception before classification so permanent- # failures terminate even with an unlimited turn budget. (#92450)+ # Count every escaped exception before classification so permanent failures+ # terminate even with an unlimited turn budget._outer_error_count += 1- # Phase-aware classification: deterministic local post-processing bugs- # (traceback via local helpers, never API helpers) aren't retried (#66267).- # Interpreter shutdown makes every executor op raise: break. (#93217)+ # Interpreter shutdown makes every executor op raise: break.if sys.is_finalizing() or _is_interpreter_shutdown_error(e):- error_msg = (- f"Interpreter is shutting down — cannot continue " f"(API call #{api_call_count}): {e}"- )+ error_msg = f"Interpreter is shutting down — cannot continue (API call #{api_call_count}): {e}"try:agent._safe_print(f"❌ {error_msg}")except (OSError, ValueError):passlogger.warning(error_msg)- # Best-effort persist — the dying executor may raise the same error;- # don't let it mask the shutdown exit. finalize_turn retries.+ # Best-effort persist — the dying executor may raise the same error; don't let+ # it mask the shutdown exit. finalize_turn retries.try:agent._persist_session(messages, conversation_history)except Exception:pass_turn_exit_reason = "interpreter_shutdown"- final_response = (- "Session is shutting down. Your conversation can be "- "resumed with: hermes --resume <session-id>"- )- # Don't append: a prefill/interim assistant may already be the tail- # (assistant→assistant). finalize_turn appends only when safe.+ final_response = "Session is shutting down. Your conversation can be resumed with: hermes --resume <session-id>"return _verdict("break")+ # Deterministic local post-processing bugs (traceback via local helpers, never API+ # helpers) aren't retried.tb_module_names: set[str] = set()_tb = e.__traceback__while _tb is not None:- _fname = os.path.splitext(os.path.basename(_tb.tb_frame.f_code.co_filename))[0]- tb_module_names.add(_fname)+ tb_module_names.add(os.path.splitext(os.path.basename(_tb.tb_frame.f_code.co_filename))[0])_tb = _tb.tb_next-- _hit_local = bool(tb_module_names & _LOCAL_PROCESSING_MODULES)- _hit_api = bool(tb_module_names & _API_CALL_MODULES)-- _is_local_processing_error = _hit_local and not _hit_api+ _is_local_processing_error = bool(tb_module_names & _LOCAL_PROCESSING_MODULES) and not (+ tb_module_names & _API_CALL_MODULES+ )if _is_local_processing_error:- error_msg = (- f"Error during local message processing after "- f"OpenAI-compatible API call #{api_call_count}: {str(e)}"- )+ error_msg = f"Error during local message processing after OpenAI-compatible API call #{api_call_count}: {str(e)}"else:error_msg = f"Error during OpenAI-compatible API call #{api_call_count}: {str(e)}"- # Honor the _vprint contract: suppress_status_output silences hard- # failures; quiet_mode -q still shows them. Traceback is logged below.+ # Honor the _vprint contract: suppress_status_output silences hard failures;+ # quiet_mode -q still shows them. Traceback is logged below.if getattr(agent, "suppress_status_output", False):logger.error(error_msg)else:@@ -113,12 +98,11 @@ def handle_outer_loop_error(except (OSError, ValueError):logger.error(error_msg)- # ERROR level with traceback so outer-loop failures land in agent.log- # AND errors.log and stay reproducible.+ # ERROR level with traceback so outer-loop failures land in agent.log AND errors.log.logger.exception("Outer loop error in API call #%d", api_call_count)- # An appended assistant tool_calls message needs a role="tool" result- # per tool_call_id; fill in error results for unanswered ones.+ # An appended assistant tool_calls message needs a role="tool" result per+ # tool_call_id; fill in error results for unanswered ones.for idx in range(len(messages) - 1, -1, -1):msg = messages[idx]if not isinstance(msg, dict):@@ -132,22 +116,20 @@ def handle_outer_loop_error(if isinstance(m, dict) and m.get("role") == "tool"}for tc in msg["tool_calls"]:- if not tc or not isinstance(tc, dict): continue- if tc["id"] not in answered_ids:- err_msg = {+ if tc and isinstance(tc, dict) and tc["id"] not in answered_ids:+ append_message(messages, {"role": "tool","name": _ra().AIAgent._get_tool_call_name_static(tc),"tool_call_id": tc["id"],"content": f"Error executing tool: {error_msg}",- }- append_message(messages, err_msg)+ })break- # Non-tool errors are already printed; a synthetic message would pollute- # history and risk breaking role alternation.+ # Non-tool errors are already printed; a synthetic message would pollute history+ # and risk breaking role alternation.- # Local errors are deterministic: stop early instead of retrying until the- # budget is gone; a small per-turn cap prevents infinite spinning (#92450).+ # Local errors are deterministic: stop early instead of retrying until the budget is+ # gone; a small per-turn cap prevents infinite spinning._outer_error_cap = min(_MAX_OUTER_LOOP_ERRORS, max(1, agent.max_iterations))if (_is_local_processing_error@@ -164,7 +146,5 @@ def handle_outer_loop_error(else:_turn_exit_reason = f"error_near_max_iterations({error_msg[:80]})"final_response = f"I apologize, but I encountered repeated errors: {error_msg}"- # Don't append the assistant message: a prefill/interim assistant may be- # the tail. finalize_turn appends only when _tail_role != "assistant".return _verdict("break")return _verdict("fallthrough")diff --git a/agent/turn_retry_state.py b/agent/turn_retry_state.pyindex 42bc2fddad8..70a4272f307 100644--- a/agent/turn_retry_state.py+++ b/agent/turn_retry_state.py@@ -1,12 +1,9 @@"""Per-attempt recovery bookkeeping (``TurnRetryState``) for the conversation turn loop.--Each one-shot recovery branch of the inner retry loop is guarded by a flag here so it-fires at most once per attempt. Loop-control (``retry_count``, ``max_retries``) stays-as plain locals. Dependency-free so it imports without a cycle."""+Dependency-free so it imports without a cycle."""from __future__ import annotations-from dataclasses import dataclass, fields+from dataclasses import dataclass@dataclass@@ -14,21 +11,21 @@ class TurnRetryState:"""One-shot recovery guards + restart signals for a single API-call attempt.A fresh instance is created per ``api_call_count`` iteration; each guard fires at- most once, and ``restart_with_*`` signals tell the loop to rebuild and retry."""+ most once, and ``restart_with_*`` signals tell the loop to rebuild and retry.+ Loop-control (``retry_count``, ``max_retries``) stays as plain loop locals."""- # ── Per-provider OAuth / credential refresh guards ───────────────────+ # Per-provider OAuth / credential refresh guardscodex_auth_retry_attempted: bool = Falseanthropic_auth_retry_attempted: bool = Falsenous_auth_retry_attempted: bool = Falsenous_paid_entitlement_refresh_attempted: bool = Falsecopilot_auth_retry_attempted: bool = False- # Copilot surfaces a stale/degraded credential as a 400- # ``model_not_available_for_integrator`` / ``model_not_supported``, not a 401.- # Single-shot forced re-exchange + rebuild, separate from the 401 guard.+ # Copilot surfaces a stale credential as a 400 ``model_not_available_for_integrator``+ # / ``model_not_supported``, not a 401 — separate guard from the 401 one.copilot_stale_cred_retry_attempted: bool = Falsevertex_auth_retry_attempted: bool = False- # ── Format / payload recovery guards ─────────────────────────────────+ # Format / payload recovery guardsthinking_sig_retry_attempted: bool = Falseinvalid_encrypted_content_retry_attempted: bool = Falsenative_compaction_reject_retry_attempted: bool = False@@ -37,27 +34,18 @@ class TurnRetryState:oauth_1m_beta_retry_attempted: bool = Falsellama_cpp_grammar_retry_attempted: bool = False- # ── Transport / rate-limit recovery ──────────────────────────────────+ # Transport / rate-limit recoveryprimary_recovery_attempted: bool = Falsehas_retried_429: bool = False-- # ── Auth-failure provider failover ───────────────────────────────────- # Set once a persistent 401/403 has been escalated to the fallback chain, so- # we don't loop on the same auth failover within one attempt.+ # Persistent 401/403 already escalated to the fallback chain once this attempt.auth_failover_attempted: bool = False- # ── Restart signals (read by the outer loop after the attempt) ───────+ # Restart signals (read by the outer loop after the attempt)restart_with_compressed_messages: bool = Falserestart_with_length_continuation: bool = False- # Set when a content-filter stream stall (e.g. MiniMax "new_sensitive") was- # escalated to the fallback chain: partial content was rolled back off- # ``messages``; re-issue the call against the new provider (#32421).+ # A fallback activation (incl. content-filter stream stalls) rolled partial content+ # off ``messages``; re-issue the call against the new provider.restart_with_rebuilt_messages: bool = False# A user correction cancelled the in-flight request: append a role-safe checkpoint +# user message, rebuild the payload, and retry the same logical iteration.restart_with_redirected_messages: bool = False-- def __iter__(self):- # Convenience for debugging / tests: iterate (name, value) pairs.- for f in fields(self):- yield f.name, getattr(self, f.name)