Skip to content

The agent that grows with you

fix(agent): a failing credential-refresh hook falls back instead of escaping

Teknium51e731f57a41
diff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.py
index f18a100727a..e8834058a5f 100644
--- a/agent/client_lifecycle.py
+++ b/agent/client_lifecycle.py
@@ -814,9 +814,10 @@ class ClientLifecycleMixin:
and rebuild the shared client (caller enforces the single-shot guard). ``reason``:
``unauthorized`` (401) or ``stale`` (a non-auth error the profile reads as a stale credential)."""
from agent.conversation_loop import _credential_refresh_profile
+ from agent.provider_route_hooks import ask_on_error_path
profile = _credential_refresh_profile(self)
- refreshed = profile.refresh_runtime_credentials(reason=reason) if profile else None
- if not refreshed:
+ refreshed = ask_on_error_path(profile, "refresh_runtime_credentials", None, reason=reason) if profile else None
+ if not (isinstance(refreshed, (tuple, list)) and len(refreshed) == 2 and refreshed[0]):
return False
token, base_url = refreshed
self.api_key = token
diff --git a/agent/provider_route_hooks.py b/agent/provider_route_hooks.py
index 54df74b69f2..9a92b4a55fe 100644
--- a/agent/provider_route_hooks.py
+++ b/agent/provider_route_hooks.py
@@ -118,6 +118,25 @@ def ask_profile(profile: Any, hook: str, fallback: Any, *args: Any, scope: Any =
return fallback
+def ask_on_error_path(profile: Any, hook: str, fallback: Any, **kwargs: Any) -> Any:
+ """*profile*'s answer to an API-error-path *hook* (credential refresh, stale-credential test, refresh
+ notice), asked every time: a lost plugin host may be back for the next error. A raise answers
+ *fallback* ("not refreshed"), logged with its traceback once per (provider, hook) per process, so the
+ original API error still reaches the fallback walk instead of escaping its handler."""
+ try:
+ return getattr(profile, hook)(**kwargs)
+ except Exception: # health: allow BLE001 -- plugin hook boundary; logged with traceback once below
+ key = (getattr(profile, "name", "?"), hook)
+ if key not in _ERROR_PATH_WARNED:
+ _ERROR_PATH_WARNED.add(key)
+ logger.warning("provider %s: %s hook failed; handling the API error without it", key[0], hook,
+ exc_info=True)
+ return fallback
+
+
+_ERROR_PATH_WARNED: set[tuple] = set()
+
+
def route_answer(hook: str, *, provider: str = "", scope: Any = None, **kwargs: Any) -> Any:
"""First truthy answer of *hook* across ``route_profiles``; None when no profile claims the endpoint.
Failures follow ``ask_profile``'s policy (*scope* = the agent, when there is one)."""
diff --git a/agent/turn_api_error.py b/agent/turn_api_error.py
index 7306b2cab50..d0017152925 100644
--- a/agent/turn_api_error.py
+++ b/agent/turn_api_error.py
@@ -277,6 +277,7 @@ def settle_unrecovered_error(
result), else the interruptible error backoff. ``FailoverReason.billing`` (402) is deliberately
treated as non-retryable (#31273)."""
from agent.conversation_loop import _arm_fallback_restart, _credential_refresh_profile
+ from agent.provider_route_hooks import ask_on_error_path
def _verdict(action: str, result: Optional[dict[str, Any]] = None) -> UnrecoveredErrorVerdict:
return UnrecoveredErrorVerdict(
@@ -325,13 +326,14 @@ def settle_unrecovered_error(
if (
not _retry.provider_stale_refresh_attempted
and (profile := _credential_refresh_profile(agent)) is not None
- and profile.is_stale_credential_error(
- status_code=status_code, message=str(getattr(api_error, "message", "") or api_error)
+ and ask_on_error_path(
+ profile, "is_stale_credential_error", False,
+ status_code=status_code, message=str(getattr(api_error, "message", "") or api_error),
)
):
_retry.provider_stale_refresh_attempted = True
if agent._try_refresh_provider_runtime_credentials(reason="stale"):
- agent._buffer_vprint("πŸ” " + (profile.credential_refresh_notice(reason="stale") or (
+ agent._buffer_vprint("πŸ” " + (ask_on_error_path(profile, "credential_refresh_notice", "", reason="stale") or (
f"{profile.display_name or profile.name} credential renewed after a "
"stale-credential error. Retrying request...")))
retry_count = 0
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index c123314ced0..5be3ad86580 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -436,7 +436,8 @@ def _refresh_credentials_after_401(
if not _retry.provider_auth_refresh_attempted and (profile := _credential_refresh_profile(agent)) is not None:
_retry.provider_auth_refresh_attempted = True
if agent._try_refresh_provider_runtime_credentials(reason="unauthorized"):
- agent._buffer_vprint("πŸ” " + (profile.credential_refresh_notice(reason="unauthorized") or (
+ from agent.provider_route_hooks import ask_on_error_path
+ agent._buffer_vprint("πŸ” " + (ask_on_error_path(profile, "credential_refresh_notice", "", reason="unauthorized") or (
f"{profile.display_name or profile.name} credentials refreshed after 401. Retrying request...")))
return True
if (
diff --git a/tests/agent/test_provider_refresh_hook_failures.py b/tests/agent/test_provider_refresh_hook_failures.py
new file mode 100644
index 00000000000..b445ffa7a11
--- /dev/null
+++ b/tests/agent/test_provider_refresh_hook_failures.py
@@ -0,0 +1,91 @@
+"""A provider's credential-refresh hooks run inside the API-error handler: a raising hook (a plugin bug,
+a plugin host that disconnected or timed out) answers "not refreshed" and the original API error walks
+the fallback chain, instead of escaping the handler outside the retry loop's ``try``."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from agent.client_lifecycle import ClientLifecycleMixin
+from agent.error_classifier import classify_api_error
+from agent.turn_api_error import settle_unrecovered_error
+from providers.base import ProviderProfile
+
+
+class _HostGone(ProviderProfile):
+ """Every refresh hook can lose its plugin host; *broken* names the one that does."""
+
+ broken = ""
+
+ def _maybe_raise(self, hook: str) -> None:
+ if hook == self.broken:
+ raise ConnectionError("plugin host closed the connection")
+
+ def is_stale_credential_error(self, *, status_code, message):
+ self._maybe_raise("is_stale_credential_error")
+ return True
+
+ def refresh_runtime_credentials(self, *, reason):
+ self._maybe_raise("refresh_runtime_credentials")
+ return ("fresh-token", None)
+
+ def credential_refresh_notice(self, *, reason):
+ self._maybe_raise("credential_refresh_notice")
+ return ""
+
+
+class _Err(Exception):
+ status_code = 400
+ response = None
+ body = {"error": {"message": "Unsupported parameter: 'max_tokens'", "type": "invalid_request_error"}}
+
+
+class _Agent:
+ """The real credential-refresh method; the fallback seam records activations; the rest no-ops."""
+ log_prefix = ""
+ verbose = False
+ provider = "acme-hosted"
+ base_url = "https://api.acme-hosted.example/v1"
+ api_key = "stale-token"
+ _fallback_chain = [object()]
+ _fallback_index = 0
+ _credential_pool = None
+ _try_refresh_provider_runtime_credentials = ClientLifecycleMixin._try_refresh_provider_runtime_credentials
+
+ def __init__(self):
+ self.activated = []
+
+ def _has_pending_fallback(self):
+ return True
+
+ def _try_activate_fallback(self, **kwargs):
+ self.activated.append(True)
+ return True
+
+ def _replace_primary_openai_client(self, *, reason):
+ return False # the rebuilt client could not be made: not refreshed either
+
+ def __getattr__(self, name):
+ return lambda *args, **kwargs: None
+
+
[email protected]("broken", ["is_stale_credential_error", "refresh_runtime_credentials"])
+def test_a_raising_refresh_hook_keeps_the_api_error_and_walks_the_fallback_chain(broken):
+ profile = _HostGone(name="acme-hosted")
+ profile.broken = broken
+ agent, err = _Agent(), _Err("Unsupported parameter: 'max_tokens'")
+ retry = SimpleNamespace(provider_stale_refresh_attempted=False, primary_recovery_attempted=False)
+ with patch("agent.conversation_loop._credential_refresh_profile", lambda a: profile):
+ verdict = settle_unrecovered_error(
+ agent, api_error=err, classified=classify_api_error(err, provider=agent.provider), _retry=retry,
+ status_code=400, error_msg=str(err), is_context_length_error=False, is_rate_limited=False,
+ _is_zai_coding_overload=False, _provider=agent.provider, _base=agent.base_url, _model="m",
+ messages=[], api_messages=[], api_kwargs={}, active_system_prompt="", conversation_history=None,
+ approx_tokens=10, retry_count=0, max_retries=3, compression_attempts=0, api_call_count=1,
+ )
+ assert verdict.action == "break"
+ assert agent.activated == [True]
+ assert agent.api_key == "stale-token"