Skip to content

The agent that grows with you

fix(copilot): recover from stale/degraded token 400 AND expired IDE-token 401

dstkwll7779409a7673
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 1b592c20698..11f98c82e94 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2082,6 +2082,31 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo
# restore, request-scoped); auxiliary_client builds its own clients and keeps
# SDK retries because it is NOT wrapped by the conversation loop.
client_kwargs.setdefault("max_retries", 0)
+ # Defense-in-depth: guarantee Copilot requests carry the integration
+ # headers regardless of which build path we came through. The primary
+ # header wiring lives in `_apply_client_headers_for_base_url`, but two
+ # rebuild paths (`primary_recovery`, `restore_primary` in this module)
+ # reconstruct the client purely from a `_primary_runtime` snapshot and do
+ # NOT re-run that wiring. If the snapshot's client_kwargs ever lacks
+ # `default_headers` (older snapshot, header-less resolver result), the
+ # client goes out WITHOUT `Copilot-Integration-Id: vscode-chat`; the
+ # Copilot server then routes it to the "copilot-language-server" integrator
+ # whose model allowlist omits enterprise-only models (claude-opus-4.8) →
+ # HTTP 400 model_not_available_for_integrator on every turn. This chokepoint
+ # is the single place every primary OpenAI client passes through, so filling
+ # missing Copilot headers here closes the whole class. We only ADD missing
+ # keys — never override headers a caller deliberately set.
+ try:
+ if base_url_host_matches(str(client_kwargs.get("base_url", "")), "githubcopilot.com"):
+ from hermes_cli.models import copilot_default_headers
+ existing = dict(client_kwargs.get("default_headers") or {})
+ existing_lower = {k.lower() for k in existing}
+ for hk, hv in copilot_default_headers().items():
+ if hk.lower() not in existing_lower:
+ existing[hk] = hv
+ client_kwargs["default_headers"] = existing
+ except Exception:
+ _ra().logger.debug("Copilot default-header guard skipped", exc_info=True)
# Uses the module-level `OpenAI` name, resolved lazily on first
# access via __getattr__ below. Tests patch via `run_agent.OpenAI`.
client = _ra().OpenAI(**client_kwargs)
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 3ca96898cf9..0825d714487 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -194,6 +194,36 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text
agent._stream_needs_break = True
+def _is_stale_copilot_credential_error(status_code: Optional[int], error_message: str) -> bool:
+ """Detect a Copilot 400 that is really a STALE / DEGRADED credential.
+
+ Copilot surfaces a stale or degraded credential as an HTTP 400 rather than a
+ clean 401. Two body markers indicate this class:
+
+ - ``model_not_available_for_integrator`` — the request reached the
+ restricted ``copilot-language-server`` integrator (the server's fallback
+ when it receives a raw OAuth token instead of an exchanged API token),
+ whose model allowlist omits enterprise-only models.
+ - ``model_not_supported`` / "the requested model is not supported" — the
+ cached bearer's Copilot entitlement rotated out from under a long-lived
+ process.
+
+ Matched narrowly (status 400 AND a specific marker) so a genuinely wrong
+ model name — a real 400 — never triggers the single-shot re-exchange. The
+ caller enforces copilot-provider scoping and the single-shot guard.
+ """
+ lowered = (error_message or "").lower()
+ is_400 = status_code == 400 or "error code: 400" in lowered
+ if not is_400:
+ return False
+ return (
+ "model_not_available_for_integrator" in lowered
+ or "not available for integrator" in lowered
+ or "model_not_supported" in lowered
+ or "the requested model is not supported" in lowered
+ )
+
+
def _image_error_max_dimension(error: Exception) -> Optional[int]:
"""Extract a provider-reported image dimension ceiling, if present."""
parts = []
@@ -4865,6 +4895,32 @@ def run_conversation(
) and not is_context_length_error
if is_client_error:
+ # Copilot self-heal BEFORE fallback: a stale/degraded
+ # credential surfaces as a 400
+ # ``model_not_available_for_integrator`` /
+ # ``model_not_supported`` (not a clean 401), so the 401
+ # refresh path above never fired. Force a fresh token
+ # exchange + client rebuild and retry once on the SAME
+ # provider — a fresh 437-char API token routes to the
+ # correct integrator and the model becomes available again.
+ # Single-shot guard prevents looping on a genuinely
+ # unavailable model. Copilot-scoped so other providers'
+ # real 400s are untouched.
+ if (
+ agent.provider == "copilot"
+ and not _retry.copilot_stale_cred_retry_attempted
+ and _is_stale_copilot_credential_error(
+ status_code, str(getattr(api_error, "message", "") or api_error)
+ )
+ ):
+ _retry.copilot_stale_cred_retry_attempted = True
+ if agent._try_recover_stale_copilot_credential():
+ agent._buffer_vprint(
+ "🔐 Copilot credential re-exchanged after "
+ "model_not_available 400. Retrying request..."
+ )
+ retry_count = 0
+ continue
# Try fallback before aborting — a different provider may
# not have the same issue (rate limit, auth, etc.). Only
# announce the attempt when a fallback chain actually
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 08b0c0ea6b9..16857eba830 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -2336,6 +2336,20 @@ def _seed_from_singletons(provider: str, entries: List[PooledCredential]) -> Tup
token, source = resolve_copilot_token()
if token:
api_token, enterprise_base_url = get_copilot_api_token(token)
+ # Observability: get_copilot_api_token falls back to returning
+ # the RAW token when the exchange fails. A raw ~40-char token
+ # sent to the Copilot API is routed to the fallback
+ # "copilot-language-server" integrator, whose allowlist omits
+ # enterprise-only models (claude-opus-4.8) → HTTP 400 on every
+ # turn. exchange_copilot_token now retries + reuses a persisted
+ # JWT, so this should be rare; surface it at WARNING so a
+ # recurrence is visible in logs instead of failing silently.
+ 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."
+ )
source_name = "gh_cli" if "gh" in source.lower() else f"env:{source}"
if not _is_suppressed(provider, source_name):
active_sources.add(source_name)
@@ -2506,6 +2520,20 @@ def _seed_from_env(provider: str, entries: List[PooledCredential]) -> Tuple[bool
changed = False
active_sources: Set[str] = set()
+ # Copilot has its own dedicated seeding branch (see `_seed_credentials`
+ # for provider == "copilot") which exchanges the raw ghu_ OAuth token
+ # for the ~437-char api token via `get_copilot_api_token`. If we let
+ # the generic env-var loop below run for copilot, it re-reads
+ # COPILOT_GITHUB_TOKEN from .env and shoves the RAW 40-char token in
+ # as `access_token`, overwriting the correctly-exchanged token. That
+ # bypasses the Copilot token exchange entirely and causes 400s with
+ # "not available for integrator copilot-language-server" (the server's
+ # fallback integrator when it receives a raw OAuth token instead of
+ # an api token). Skip the generic loop here — the copilot-specific
+ # branch is authoritative.
+ if provider == "copilot":
+ return False, active_sources
+
# Prefer ~/.hermes/.env over os.environ — the user's config file is the
# authoritative source for Hermes credentials. Stale env vars from parent
# processes (Codex CLI, test scripts, etc.) should not override deliberate
diff --git a/agent/turn_retry_state.py b/agent/turn_retry_state.py
index 59e343bfeda..d73fe5b6bfc 100644
--- a/agent/turn_retry_state.py
+++ b/agent/turn_retry_state.py
@@ -45,6 +45,14 @@ class TurnRetryState:
nous_auth_retry_attempted: bool = False
nous_paid_entitlement_refresh_attempted: bool = False
copilot_auth_retry_attempted: bool = False
+ # Copilot surfaces a stale/degraded credential as a 400
+ # ``model_not_available_for_integrator`` / ``model_not_supported`` instead
+ # of a clean 401 (e.g. a raw OAuth token seeded when the token exchange
+ # degraded at startup, routing the request to the restricted
+ # ``copilot-language-server`` integrator). Guard a single-shot forced
+ # re-exchange + client rebuild for that case, separate from the 401 guard
+ # so both can fire within one attempt if needed.
+ copilot_stale_cred_retry_attempted: bool = False
vertex_auth_retry_attempted: bool = False
# ── Format / payload recovery guards ─────────────────────────────────
diff --git a/hermes_cli/copilot_auth.py b/hermes_cli/copilot_auth.py
index d193c7cf74a..bc257023d29 100644
--- a/hermes_cli/copilot_auth.py
+++ b/hermes_cli/copilot_auth.py
@@ -297,6 +297,19 @@ _TOKEN_EXCHANGE_URL = "https://api.github.com/copilot_internal/v2/token"
_EDITOR_VERSION = "vscode/1.104.1"
_EXCHANGE_USER_AGENT = "GitHubCopilotChat/0.26.7"
+# Transient-failure hardening for the token exchange. Gateway startup often
+# races network readiness (launchd relaunch, DHCP/VPN settling); a single-shot
+# exchange that fails there silently degrades to the RAW GitHub token, which the
+# Copilot server routes to the "copilot-language-server" integrator whose model
+# allowlist omits enterprise-only models (e.g. claude-opus-4.8) → HTTP 400 on
+# every turn until the next restart. Retry a few times, and persist the last
+# good exchanged JWT to disk so a restart during a blip reuses the still-valid
+# ~30-min token instead of degrading.
+_EXCHANGE_MAX_ATTEMPTS = 3
+_EXCHANGE_BACKOFF_BASE_SECONDS = 1.5 # sleeps ~1.5s, ~3.0s between attempts
+_JWT_DISK_FILENAME = ".copilot_jwt.json"
+_JWT_DISK_MAX_BYTES = 1_048_576 # 1 MiB cap on the persisted JWT store read
+
def _token_fingerprint(raw_token: str) -> str:
"""Short fingerprint of a raw token for cache keying (avoids storing full token)."""
@@ -304,6 +317,116 @@ def _token_fingerprint(raw_token: str) -> str:
return hashlib.sha256(raw_token.encode()).hexdigest()[:16]
+def evict_cached_exchanged_token(raw_token: str) -> None:
+ """Drop any cached exchanged JWT for ``raw_token`` (in-process + on-disk).
+
+ Used by the runtime stale-credential recovery path: when a live request
+ starts failing with a Copilot ``model_not_available_for_integrator`` /
+ ``model_not_supported`` 400, the cached exchanged token (or a degraded raw
+ fallback that was cached in its place) is stale. Evicting both cache tiers
+ forces the next ``exchange_copilot_token`` call to hit the network and mint
+ a fresh token instead of returning the poisoned cache entry.
+ """
+ if not raw_token:
+ return
+ fp = _token_fingerprint(raw_token)
+ _jwt_cache.pop(fp, None)
+ path = _jwt_disk_path()
+ if not path or not path.exists():
+ return
+ try:
+ store = json.loads(path.read_text())
+ if isinstance(store, dict) and fp in store:
+ del store[fp]
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ tmp.write_text(json.dumps(store))
+ try:
+ os.chmod(tmp, 0o600)
+ except Exception:
+ pass
+ os.replace(tmp, path)
+ except Exception as exc:
+ logger.debug("Failed to evict cached Copilot JWT: %s", exc)
+
+
+def _jwt_disk_path() -> Optional[Path]:
+ """Path to the on-disk exchanged-JWT cache (profile-aware), or None."""
+ try:
+ from hermes_constants import get_hermes_home
+ return Path(get_hermes_home()) / _JWT_DISK_FILENAME
+ except Exception:
+ return None
+
+
+def _load_jwt_from_disk(fp: str) -> Optional[tuple[str, float, Optional[str]]]:
+ """Load a persisted exchanged JWT for ``fp`` → (api_token, expires_at, base_url)."""
+ path = _jwt_disk_path()
+ if not path or not path.exists():
+ return None
+ try:
+ # Bound the read: this file is a small JSON map of fingerprint → token.
+ # A well-formed store is a few KB; cap at 1 MiB so a corrupt/oversized
+ # file can't balloon memory (mirrors the auth JSON read bound). A file
+ # over the cap is treated as unusable — the caller re-exchanges.
+ if path.stat().st_size > _JWT_DISK_MAX_BYTES:
+ logger.debug("Persisted Copilot JWT store exceeds %d bytes; ignoring", _JWT_DISK_MAX_BYTES)
+ return None
+ store = json.loads(path.read_text())
+ entry = store.get(fp) if isinstance(store, dict) else None
+ if not isinstance(entry, dict):
+ return None
+ api_token = entry.get("api_token", "")
+ expires_at = float(entry.get("expires_at", 0) or 0)
+ base_url = entry.get("base_url")
+ if api_token and expires_at:
+ return api_token, expires_at, base_url
+ except Exception as exc:
+ logger.debug("Failed to load persisted Copilot JWT: %s", exc)
+ return None
+
+
+def _save_jwt_to_disk(
+ fp: str, api_token: str, expires_at: float, base_url: Optional[str]
+) -> None:
+ """Persist an exchanged JWT (0o600), pruning expired entries."""
+ path = _jwt_disk_path()
+ if not path:
+ return
+ try:
+ store: dict = {}
+ if path.exists():
+ try:
+ loaded = json.loads(path.read_text())
+ if isinstance(loaded, dict):
+ store = loaded
+ except Exception:
+ store = {}
+ now = time.time()
+ store = {
+ k: v
+ for k, v in store.items()
+ if isinstance(v, dict) and float(v.get("expires_at", 0) or 0) > now
+ }
+ store[fp] = {
+ "api_token": api_token,
+ "expires_at": expires_at,
+ "base_url": base_url,
+ }
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ tmp.write_text(json.dumps(store))
+ try:
+ os.chmod(tmp, 0o600)
+ except Exception:
+ pass
+ os.replace(tmp, path)
+ try:
+ os.chmod(path, 0o600)
+ except Exception:
+ pass
+ except Exception as exc:
+ logger.debug("Failed to persist Copilot JWT: %s", exc)
+
+
def exchange_copilot_token(raw_token: str, *, timeout: float = 10.0) -> tuple[str, float, Optional[str]]:
"""Exchange a raw GitHub token for a short-lived Copilot API token.
@@ -324,13 +447,25 @@ def exchange_copilot_token(raw_token: str, *, timeout: float = 10.0) -> tuple[st
fp = _token_fingerprint(raw_token)
- # Check cache first
+ # Check in-process cache first
cached = _jwt_cache.get(fp)
if cached:
api_token, expires_at, base_url = cached
if time.time() < expires_at - _JWT_REFRESH_MARGIN_SECONDS:
return api_token, expires_at, base_url
+ # Then the on-disk cache: a fresh process (e.g. gateway restart) has an
+ # empty in-process cache but may have a still-valid persisted JWT. Reusing
+ # it avoids a network round-trip at startup — precisely when the network is
+ # most likely to be flaky and the single-shot exchange would degrade to the
+ # raw token.
+ disk_cached = _load_jwt_from_disk(fp)
+ if disk_cached:
+ api_token, expires_at, base_url = disk_cached
+ if time.time() < expires_at - _JWT_REFRESH_MARGIN_SECONDS:
+ _jwt_cache[fp] = (api_token, expires_at, base_url)
+ return api_token, expires_at, base_url
+
req = urllib.request.Request(
_TOKEN_EXCHANGE_URL,
method="GET",
@@ -342,11 +477,29 @@ def exchange_copilot_token(raw_token: str, *, timeout: float = 10.0) -> tuple[st
},
)
- try:
- with urllib.request.urlopen(req, timeout=timeout) as resp:
- data = json.loads(resp.read().decode())
- except Exception as exc:
- raise ValueError(f"Copilot token exchange failed: {exc}") from exc
+ # Retry with backoff. Startup network races (launchd relaunch, VPN/DHCP
+ # settling) make the first attempt flaky; without this the sole failure
+ # silently degrades to the raw token for the whole process lifetime.
+ data = None
+ last_exc: Optional[Exception] = None
+ for attempt in range(_EXCHANGE_MAX_ATTEMPTS):
+ try:
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ data = json.loads(resp.read().decode())
+ break
+ except Exception as exc: # noqa: BLE001 — retry all, re-raise below
+ last_exc = exc
+ if attempt < _EXCHANGE_MAX_ATTEMPTS - 1:
+ sleep_s = _EXCHANGE_BACKOFF_BASE_SECONDS * (attempt + 1)
+ logger.debug(
+ "Copilot token exchange attempt %d/%d failed (%s); retrying in %.1fs",
+ attempt + 1, _EXCHANGE_MAX_ATTEMPTS, exc, sleep_s,
+ )
+ time.sleep(sleep_s)
+ if data is None:
+ raise ValueError(
+ f"Copilot token exchange failed after {_EXCHANGE_MAX_ATTEMPTS} attempts: {last_exc}"
+ ) from last_exc
api_token = data.get("token", "")
expires_at = data.get("expires_at", 0)
@@ -372,6 +525,7 @@ def exchange_copilot_token(raw_token: str, *, timeout: float = 10.0) -> tuple[st
base_url = _derive_base_url_from_proxy_ep(api_token)
_jwt_cache[fp] = (api_token, expires_at, base_url)
+ _save_jwt_to_disk(fp, api_token, expires_at, base_url)
logger.debug(
"Copilot token exchanged, expires_at=%s, base_url=%s",
expires_at,
diff --git a/run_agent.py b/run_agent.py
index a240bb2925e..d730454c068 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -5149,16 +5149,27 @@ class AIAgent:
def _try_refresh_copilot_client_credentials(self) -> bool:
"""Refresh Copilot credentials and rebuild the shared OpenAI client.
- Copilot tokens may remain the same string across refreshes (`gh auth token`
- returns a stable OAuth token in many setups). We still rebuild the client
- on 401 so retries recover from stale auth/client state without requiring
- a session restart.
+ The raw GitHub OAuth token (`gh auth token`) is usually stable, but the
+ short-TTL *exchanged* IDE token minted from it is what Copilot actually
+ authenticates — and it expires mid-session. A heavy/long turn whose
+ request straddles that expiry gets a clean `401 IDE token expired:
+ unauthorized: token expired`. Simply re-resolving the (unchanged) raw
+ token and rebuilding the client leaves the SAME expired IDE token on the
+ wire, so the retry 401s again and the turn aborts as non-retryable —
+ only a gateway restart helped, because a cold process re-runs the
+ exchange. Fix: force a fresh exchange (evict the cached exchanged JWT,
+ then mint a new one) so the retry carries a valid IDE token. Mirrors the
+ 400 stale-credential recovery; the caller enforces the single-shot guard.
"""
if self.provider != "copilot":
return False
try:
- from hermes_cli.copilot_auth import resolve_copilot_token
+ from hermes_cli.copilot_auth import (
+ resolve_copilot_token,
+ get_copilot_api_token,
+ evict_cached_exchanged_token,
+ )
new_token, token_source = resolve_copilot_token()
except Exception as exc:
@@ -5170,6 +5181,22 @@ class AIAgent:
new_token = new_token.strip()
+ # Force a fresh IDE-token exchange: the cached exchanged JWT is the thing
+ # that expired ("401 IDE token expired"), so evict it and re-mint before
+ # rebuilding the client. Fall back to the resolved (raw) token only if the
+ # exchange itself is unavailable (network blip) — a client rebuild on the
+ # raw token still clears stale client state and may recover on enterprise
+ # seats where headers matter.
+ try:
+ evict_cached_exchanged_token(new_token)
+ api_token, enterprise_base_url = get_copilot_api_token(new_token)
+ if isinstance(api_token, str) and api_token.strip():
+ new_token = api_token.strip()
+ if enterprise_base_url:
+ self.base_url = enterprise_base_url.rstrip("/")
+ except Exception as exc:
+ logger.debug("Copilot 401 re-exchange failed, using resolved token: %s", exc)
+
self.api_key = new_token
self._client_kwargs["api_key"] = self.api_key
self._client_kwargs["base_url"] = self.base_url
@@ -5181,6 +5208,72 @@ class AIAgent:
logger.info("Copilot credentials refreshed from %s", token_source)
return True
+ def _try_recover_stale_copilot_credential(self) -> bool:
+ """Force a fresh Copilot token exchange + client rebuild after a 400.
+
+ Copilot surfaces a stale/degraded credential as a
+ ``400 model_not_available_for_integrator`` /
+ ``model_not_supported`` — NOT a clean 401 — so the normal 401 refresh
+ path never fires. The most common trigger is a raw ``ghu_`` OAuth token
+ that got seeded (and cached) when the startup token exchange degraded:
+ the raw token routes the request to the restricted
+ ``copilot-language-server`` integrator whose allowlist omits
+ enterprise-only models (e.g. ``claude-opus-4.8``).
+
+ Recovery = evict the poisoned cache entry, force a fresh exchange to
+ mint the real ~437-char API token, re-apply the Copilot headers, and
+ rebuild the shared client. Single-shot (guarded by the caller) so a
+ genuinely unavailable model can't loop.
+ """
+ if self.provider != "copilot":
+ return False
+
+ try:
+ from hermes_cli.copilot_auth import (
+ resolve_copilot_token,
+ get_copilot_api_token,
+ evict_cached_exchanged_token,
+ )
+
+ raw_token, token_source = resolve_copilot_token()
+ if not isinstance(raw_token, str) or not raw_token.strip():
+ return False
+ raw_token = raw_token.strip()
+
+ # Drop any cached (possibly degraded/raw) exchanged token so the
+ # next exchange hits the network and mints a fresh one.
+ evict_cached_exchanged_token(raw_token)
+
+ api_token, enterprise_base_url = get_copilot_api_token(raw_token)
+ except Exception as exc:
+ logger.debug("Copilot stale-credential recovery failed: %s", exc)
+ return False
+
+ if not isinstance(api_token, str) or not api_token.strip():
+ return False
+
+ # If the exchange STILL degraded to the raw token, a rebuild won't help
+ # — don't burn the single-shot retry on an identical request.
+ if api_token == raw_token and not enterprise_base_url:
+ logger.warning(
+ "Copilot stale-credential recovery: exchange still degraded to "
+ "raw token; skipping retry (network/exchange endpoint unavailable)."
+ )
+ return False
+
+ self.api_key = api_token.strip()
+ if enterprise_base_url:
+ self.base_url = enterprise_base_url.rstrip("/")
+ self._client_kwargs["api_key"] = self.api_key
+ self._client_kwargs["base_url"] = self.base_url
+ self._apply_client_headers_for_base_url(str(self.base_url or ""))
+
+ if not self._replace_primary_openai_client(reason="copilot_stale_credential_recovery"):
+ return False
+
+ logger.info("Copilot credentials re-exchanged after stale-credential 400 (source=%s)", token_source)
+ return True
+
def _try_refresh_anthropic_client_credentials(self) -> bool:
if self.api_mode != "anthropic_messages" or not hasattr(self, "_anthropic_api_key"):
return False
diff --git a/tests/run_agent/test_run_agent_codex_responses.py b/tests/run_agent/test_run_agent_codex_responses.py
index f4a0515910b..9fdb4b64e12 100644
--- a/tests/run_agent/test_run_agent_codex_responses.py
+++ b/tests/run_agent/test_run_agent_codex_responses.py
@@ -926,10 +926,115 @@ def test_try_refresh_codex_client_credentials_skips_xai_oauth_when_singleton_dif
+def test_try_refresh_copilot_client_credentials_rebuilds_client(monkeypatch):
+ agent = _build_copilot_agent(monkeypatch)
+ closed = {"value": False}
+ rebuilt = {"kwargs": None}
+
+ class _ExistingClient:
+ def close(self):
+ closed["value"] = True
+
+ class _RebuiltClient:
+ pass
+
+ def _fake_openai(**kwargs):
+ rebuilt["kwargs"] = kwargs
+ return _RebuiltClient()
+
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.resolve_copilot_token",
+ lambda: ("gho_new_token", "GH_TOKEN"),
+ )
+ # The 401 refresh forces a fresh IDE-token exchange; mock it to a valid
+ # exchanged token so the test is deterministic and network-free.
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.evict_cached_exchanged_token",
+ lambda _raw: None,
+ )
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.get_copilot_api_token",
+ lambda _raw: ("tid=exchanged-ide-token", None),
+ )
+ monkeypatch.setattr(run_agent, "OpenAI", _fake_openai)
+
+ agent.client = _ExistingClient()
+ ok = agent._try_refresh_copilot_client_credentials()
+
+ assert ok is True
+ assert closed["value"] is True
+ # The freshly EXCHANGED IDE token — not the raw ghu_/gho_ token — goes on
+ # the wire, which is what fixes the "401 IDE token expired" recurrence.
+ assert rebuilt["kwargs"]["api_key"] == "tid=exchanged-ide-token"
+ assert rebuilt["kwargs"]["base_url"] == "https://api.githubcopilot.com"
+ assert rebuilt["kwargs"]["default_headers"]["Copilot-Integration-Id"] == "vscode-chat"
+ assert isinstance(agent.client, _RebuiltClient)
+def test_try_refresh_copilot_client_credentials_rebuilds_even_if_token_unchanged(monkeypatch):
+ agent = _build_copilot_agent(monkeypatch)
+ rebuilt = {"count": 0}
+
+ class _RebuiltClient:
+ pass
+ def _fake_openai(**kwargs):
+ rebuilt["count"] += 1
+ return _RebuiltClient()
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.resolve_copilot_token",
+ lambda: ("gh-token", "gh auth token"),
+ )
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.evict_cached_exchanged_token",
+ lambda _raw: None,
+ )
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.get_copilot_api_token",
+ lambda _raw: ("tid=fresh-exchanged", None),
+ )
+ monkeypatch.setattr(run_agent, "OpenAI", _fake_openai)
+
+ ok = agent._try_refresh_copilot_client_credentials()
+
+ assert ok is True
+ assert rebuilt["count"] == 1
+
+
+def test_try_refresh_copilot_client_credentials_falls_back_when_exchange_unavailable(monkeypatch):
+ """If the IDE-token re-exchange itself fails (network blip), the refresh
+ still rebuilds the client on the resolved raw token rather than throwing —
+ clears stale client state and degrades gracefully."""
+ agent = _build_copilot_agent(monkeypatch)
+ rebuilt = {"kwargs": None}
+
+ class _RebuiltClient:
+ pass
+
+ def _fake_openai(**kwargs):
+ rebuilt["kwargs"] = kwargs
+ return _RebuiltClient()
+
+ def _boom(_raw):
+ raise RuntimeError("exchange endpoint unreachable")
+
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.resolve_copilot_token",
+ lambda: ("gho_raw_token", "GH_TOKEN"),
+ )
+ monkeypatch.setattr(
+ "hermes_cli.copilot_auth.evict_cached_exchanged_token",
+ lambda _raw: None,
+ )
+ monkeypatch.setattr("hermes_cli.copilot_auth.get_copilot_api_token", _boom)
+ monkeypatch.setattr(run_agent, "OpenAI", _fake_openai)
+
+ ok = agent._try_refresh_copilot_client_credentials()
+
+ assert ok is True
+ # Exchange failed → falls back to the resolved raw token, client still rebuilt.
+ assert rebuilt["kwargs"]["api_key"] == "gho_raw_token"
def test_chat_messages_to_responses_input_uses_call_id_for_function_call(monkeypatch):