Skip to content

The agent that grows with you

fix(anthropic): move every holder of the revoked token on credential refresh

mahdi4b842d3f2596
diff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.py
index 2842dfe0362..1981adb844c 100644
--- a/agent/client_lifecycle.py
+++ b/agent/client_lifecycle.py
@@ -913,7 +913,19 @@ class ClientLifecycleMixin:
except Exception as exc:
logger.warning("Failed to rebuild Anthropic client after credential refresh: %s", exc)
return False
+ old_token = self._anthropic_api_key
self._anthropic_api_key, self._is_anthropic_oauth = new_token, self._anthropic_oauth_flag(new_token)
+ # Claude Code revokes the old token on refresh: every holder of it (agent.api_key, the compressor's
+ # main_runtime, the fallback-restore snapshot) must move too, or compression 401s for the session's life.
+ if self.api_key == old_token:
+ self.api_key = new_token
+ cc = getattr(self, "context_compressor", None)
+ if cc is not None and getattr(cc, "api_key", None) == old_token:
+ cc.api_key = new_token
+ rt = getattr(self, "_primary_runtime", None) or {}
+ for k in ("api_key", "anthropic_api_key", "compressor_api_key"):
+ if rt.get(k) == old_token:
+ rt[k] = new_token
return True
# ------------------------------------------------------------------ route-derived client config
diff --git a/tests/agent/test_anthropic_third_party_oauth_guard.py b/tests/agent/test_anthropic_third_party_oauth_guard.py
index 6a77b1c8548..3e3a57395c0 100644
--- a/tests/agent/test_anthropic_third_party_oauth_guard.py
+++ b/tests/agent/test_anthropic_third_party_oauth_guard.py
@@ -123,6 +123,27 @@ class TestOAuthFlagOnRefresh:
assert result is True
assert agent._anthropic_api_key == new
+ def test_refresh_moves_every_holder_of_the_revoked_token(self, agent):
+ """Claude Code revokes the old token on refresh. The compressor forwards its OWN
+ ``api_key`` as the aux main_runtime, so if only the native client moves, every
+ compression summary 401s ("OAuth access token has been revoked") for the session's life."""
+ old, new = "sk-ant-oat01-old", "sk-ant-oat01-new"
+ agent.api_mode, agent.provider = "anthropic_messages", "anthropic"
+ agent._anthropic_base_url = "https://api.anthropic.com"
+ agent._anthropic_client = MagicMock()
+ agent.api_key = agent._anthropic_api_key = agent.context_compressor.api_key = old
+ agent._primary_runtime = {"api_key": old, "anthropic_api_key": old, "compressor_api_key": old}
+
+ with (
+ patch("agent.anthropic_credentials.resolve_anthropic_token", return_value=new),
+ patch.object(AIAgent, "_build_direct_anthropic_client", return_value=MagicMock()),
+ ):
+ assert agent._try_refresh_anthropic_client_credentials() is True
+
+ assert agent._anthropic_api_key == agent.api_key == agent.context_compressor.api_key == new
+ assert set(agent._primary_runtime.values()) == {new}
+
+
class TestOAuthFlagOnCredentialSwap:
"""Site 4 — _swap_credential (credential pool rotation)."""