Skip to content

The agent that grows with you

fix(auth): prevent repeated copilot raw token exchange warnings (#114740)

Mohamad Kansobd2b8124f432
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 12b16b164bb..7000f342612 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -2150,6 +2150,15 @@ def _resolve_api_key_provider() -> Tuple[Optional[OpenAI], Optional[str]]:
if not is_provider_explicitly_configured("anthropic"):
continue
return _try_anthropic()
+ if provider_id == "copilot":
+ # Explicit-config gate: ambient gh-CLI credentials must not silently become aux fallback (#114740).
+ with contextlib.suppress(ImportError):
+ from hermes_cli.auth import is_provider_explicitly_configured
+ if not is_provider_explicitly_configured("copilot"):
+ continue
+ model = _get_aux_model_for_provider(provider_id) or None
+ if model is None:
+ continue # skip provider if we don't know a valid aux model
pool_present, entry = _select_pool_entry(provider_id)
if pool_present:
api_key = _pool_runtime_api_key(entry)
@@ -2172,9 +2181,6 @@ def _resolve_api_key_provider() -> Tuple[Optional[OpenAI], Optional[str]]:
if isinstance(runtime.get("api_key"), str) and runtime["api_key"]:
api_key = runtime["api_key"]
via = " (session endpoint)"
- model = _get_aux_model_for_provider(provider_id) or None
- if model is None:
- continue # skip provider if we don't know a valid aux model
logger.debug("Auxiliary text client: %s (%s)%s", pconfig.name, model, via)
# Native Gemini, else OpenAI-wire + Anthropic rewrap.
base_url = _to_openai_base_url(raw_base_url)
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 124f22c5940..6d47010633d 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -2400,6 +2400,28 @@ def _seed_nous_singleton(seed: _Seeder, auth_store: Dict[str, Any]) -> None:
})
+# Warn once per token per process when Copilot exchange degrades to raw token (#114740).
+_COPILOT_RAW_DEGRADATION_WARNED: Set[str] = set()
+
+
+def _warn_copilot_raw_degradation_once(token: str) -> None:
+ """WARN once per token per process when Copilot exchange degrades to raw token (#114740)."""
+ fingerprint = fingerprint_secret_value(token) or "unknown"
+ if fingerprint in _COPILOT_RAW_DEGRADATION_WARNED:
+ return
+ _COPILOT_RAW_DEGRADATION_WARNED.add(fingerprint)
+ logger.warning(
+ "Copilot token exchange degraded to RAW token (exchange "
+ "unavailable); enterprise-only models may 400 with "
+ "model_not_available_for_integrator until exchange recovers."
+ )
+
+
+def _reset_copilot_raw_degradation_warned() -> None:
+ """Clear the degradation warning cache (for test isolation)."""
+ _COPILOT_RAW_DEGRADATION_WARNED.clear()
+
+
def _seed_copilot_singleton(seed: _Seeder) -> None:
# Copilot tokens are resolved dynamically via `gh auth token` or env vars
# (COPILOT_GITHUB_TOKEN / GH_TOKEN); they don't live in the auth store.
@@ -2429,13 +2451,9 @@ def _seed_copilot_singleton(seed: _Seeder) -> None:
# get_copilot_api_token falls back to the RAW token when the exchange
# fails; the Copilot API then routes it to the fallback
# "copilot-language-server" integrator whose allowlist omits
- # enterprise-only models -> HTTP 400 on every turn. Surface it.
+ # enterprise-only models -> HTTP 400 on every turn. Surface it once.
if api_token == token and not enterprise_base_url:
- logger.warning(
- "Copilot token exchange degraded to RAW token (exchange "
- "unavailable); enterprise-only models may 400 with "
- "model_not_available_for_integrator until exchange recovers."
- )
+ _warn_copilot_raw_degradation_once(token)
pconfig = PROVIDER_REGISTRY.get(seed.provider)
seed.upsert(source_name, {
"auth_type": AUTH_TYPE_API_KEY,
diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py
index 6a73a74bd41..d39ba535cd0 100644
--- a/tests/agent/test_auxiliary_client.py
+++ b/tests/agent/test_auxiliary_client.py
@@ -2094,6 +2094,78 @@ def test_resolve_api_key_provider_skips_unconfigured_anthropic(monkeypatch):
"_try_anthropic() should not be called when anthropic is not explicitly configured"
+def test_resolve_api_key_provider_skips_unconfigured_copilot(monkeypatch):
+ """_resolve_api_key_provider must skip copilot when user never configured it (#114740)."""
+ from collections import OrderedDict
+ from hermes_cli.auth import ProviderConfig
+
+ fake_registry = OrderedDict({
+ "copilot": ProviderConfig(
+ id="copilot",
+ name="Copilot",
+ auth_type="api_key",
+ inference_base_url="https://api.githubcopilot.com",
+ api_key_env_vars=("GITHUB_COPILOT_TOKEN", "GH_TOKEN"),
+ ),
+ })
+
+ pool_selected = []
+
+ def mock_select_pool_entry(provider_id):
+ pool_selected.append(provider_id)
+ return False, None
+
+ monkeypatch.setattr("agent.auxiliary_client._select_pool_entry", mock_select_pool_entry)
+ monkeypatch.setattr("hermes_cli.auth.PROVIDER_REGISTRY", fake_registry)
+ monkeypatch.setattr(
+ "hermes_cli.auth.is_provider_explicitly_configured",
+ lambda pid: False,
+ )
+
+ from agent.auxiliary_client import _resolve_api_key_provider
+ client, model = _resolve_api_key_provider()
+
+ assert client is None
+ assert model is None
+ assert "copilot" not in pool_selected, \
+ "_select_pool_entry() should not be called for unconfigured copilot"
+
+
+def test_resolve_api_key_provider_skips_provider_without_aux_model(monkeypatch):
+ """_resolve_api_key_provider must not load pool or credentials for providers without an aux model (#114740)."""
+ from collections import OrderedDict
+ from hermes_cli.auth import ProviderConfig
+
+ fake_registry = OrderedDict({
+ "some-provider": ProviderConfig(
+ id="some-provider",
+ name="Some Provider",
+ auth_type="api_key",
+ inference_base_url="https://api.example.com",
+ api_key_env_vars=("SOME_API_KEY",),
+ ),
+ })
+
+ pool_selected = []
+
+ def mock_select_pool_entry(provider_id):
+ pool_selected.append(provider_id)
+ return False, None
+
+ monkeypatch.setattr("agent.auxiliary_client._select_pool_entry", mock_select_pool_entry)
+ monkeypatch.setattr("hermes_cli.auth.PROVIDER_REGISTRY", fake_registry)
+ monkeypatch.setattr("agent.auxiliary_client._get_aux_model_for_provider", lambda pid: "")
+
+ from agent.auxiliary_client import _resolve_api_key_provider
+ client, model = _resolve_api_key_provider()
+
+ assert client is None
+ assert model is None
+ assert len(pool_selected) == 0, \
+ "_select_pool_entry() should not be called when provider has no aux model"
+
+
+
# ---------------------------------------------------------------------------
# model="default" elimination (#7512)
# ---------------------------------------------------------------------------
diff --git a/tests/agent/test_credential_pool.py b/tests/agent/test_credential_pool.py
index faa3e4e36f5..e866e7b3491 100644
--- a/tests/agent/test_credential_pool.py
+++ b/tests/agent/test_credential_pool.py
@@ -1552,6 +1552,47 @@ def test_load_pool_skips_resolve_when_all_copilot_sources_suppressed(tmp_path, m
assert pool.entries() == []
+def test_load_pool_copilot_raw_degradation_warns_once(tmp_path, monkeypatch, caplog):
+ """Copilot token exchange degraded to RAW token warning is emitted once per token (#114740)."""
+ import logging
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hermes"))
+ _write_auth_store(tmp_path, {"version": 1, "credential_pool": {}})
+
+ from agent.credential_pool import _reset_copilot_raw_degradation_warned, load_pool
+ _reset_copilot_raw_degradation_warned()
+
+ current_token = ["gho_raw_initial"]
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.resolve_copilot_token",
+ lambda: (current_token[0], "gh auth token"),
+ )
+ # Exchange degrades to raw token (no enterprise url, returns raw token)
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.get_copilot_api_token",
+ lambda token: (token, None),
+ )
+
+ with caplog.at_level(logging.WARNING, logger="agent.credential_pool"):
+ # First pool load emits warning
+ load_pool("copilot")
+ warnings = [r.message for r in caplog.records if "Copilot token exchange degraded to RAW token" in r.message]
+ assert len(warnings) == 1
+
+ # Subsequent pool load with same token must not emit duplicate warning
+ caplog.clear()
+ load_pool("copilot")
+ warnings = [r.message for r in caplog.records if "Copilot token exchange degraded to RAW token" in r.message]
+ assert len(warnings) == 0
+
+ # Changing the token produces a warning for the new token
+ current_token[0] = "gho_raw_different_token"
+ caplog.clear()
+ load_pool("copilot")
+ warnings = [r.message for r in caplog.records if "Copilot token exchange degraded to RAW token" in r.message]
+ assert len(warnings) == 1
+
+
+
def test_load_pool_seeds_qwen_oauth_via_cli_tokens(tmp_path, monkeypatch):