The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(copilot): follow-ups for salvaged PR #58743
Teknium1737741730c3
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 0825d714487..63771a366cb 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -194,6 +194,24 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], textagent._stream_needs_break = True+def _is_copilot_provider(agent: Any) -> bool:+ """Delegate to ``AIAgent._is_copilot_provider`` (single owner of the check).++ ``agent.provider`` is not always the normalized ``copilot`` slug —+ ``/model`` and profile configs can leave the alias ``github-copilot`` (or+ ``github``) in place, and a bare ``provider == "copilot"`` gate silently+ skips credential recovery for those spellings.+ """+ try:+ return bool(agent._is_copilot_provider())+ except Exception:+ return (getattr(agent, "provider", "") or "").strip().lower() in {+ "copilot",+ "github-copilot",+ "github",+ }++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.@@ -3889,7 +3907,7 @@ def run_conversation(print(f"{agent.log_prefix} • Verify stored credentials: {_dhh}/auth.json")print(f"{agent.log_prefix} • Switch providers temporarily: /model <model> --provider openrouter")if (- agent.provider == "copilot"+ _is_copilot_provider(agent)and status_code == 401and not _retry.copilot_auth_retry_attempted):@@ -4907,7 +4925,7 @@ def run_conversation(# unavailable model. Copilot-scoped so other providers'# real 400s are untouched.if (- agent.provider == "copilot"+ _is_copilot_provider(agent)and not _retry.copilot_stale_cred_retry_attemptedand _is_stale_copilot_credential_error(status_code, str(getattr(api_error, "message", "") or api_error)diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..83bd3894fbc--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+dstkwlldiff --git a/hermes_cli/copilot_auth.py b/hermes_cli/copilot_auth.pyindex bc257023d29..6cad6d0906c 100644--- a/hermes_cli/copilot_auth.py+++ b/hermes_cli/copilot_auth.py@@ -317,6 +317,27 @@ def _token_fingerprint(raw_token: str) -> str:return hashlib.sha256(raw_token.encode()).hexdigest()[:16]+def _read_jwt_store(path: Path) -> Optional[dict]:+ """Bounded read of the on-disk JWT store → dict, or None if unusable.++ Single chokepoint for every read of the persisted store (load, eviction,+ save-merge). A well-formed store is a few KB; a file over the 1 MiB cap or+ with non-dict content is treated as unusable so a corrupt/oversized file+ can't balloon memory or get rewritten back out.+ """+ try:+ 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+ loaded = json.loads(path.read_text())+ return loaded if isinstance(loaded, dict) else None+ except Exception as exc:+ logger.debug("Failed to read persisted Copilot JWT store: %s", exc)+ return None++def evict_cached_exchanged_token(raw_token: str) -> None:"""Drop any cached exchanged JWT for ``raw_token`` (in-process + on-disk).@@ -335,8 +356,8 @@ def evict_cached_exchanged_token(raw_token: str) -> None:if not path or not path.exists():returntry:- store = json.loads(path.read_text())- if isinstance(store, dict) and fp in store:+ store = _read_jwt_store(path)+ if store is not None and fp in store:del store[fp]tmp = path.with_suffix(path.suffix + ".tmp")tmp.write_text(json.dumps(store))@@ -365,14 +386,10 @@ def _load_jwt_from_disk(fp: str) -> Optional[tuple[str, float, Optional[str]]]:return Nonetry:# 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+ # An oversized/corrupt store is treated as unusable — the caller+ # re-exchanges (bound shared with eviction/save via _read_jwt_store).+ store = _read_jwt_store(path)+ entry = store.get(fp) if store is not None else Noneif not isinstance(entry, dict):return Noneapi_token = entry.get("api_token", "")@@ -395,12 +412,7 @@ def _save_jwt_to_disk(try:store: dict = {}if path.exists():- try:- loaded = json.loads(path.read_text())- if isinstance(loaded, dict):- store = loaded- except Exception:- store = {}+ store = _read_jwt_store(path) or {}now = time.time()store = {k: vdiff --git a/run_agent.py b/run_agent.pyindex d730454c068..e574b28ff23 100644--- a/run_agent.py+++ b/run_agent.py@@ -1485,6 +1485,21 @@ class AIAgent:or "models.github.ai" in self._base_url_lower)+ def _is_copilot_provider(self) -> bool:+ """True when the active provider is GitHub Copilot, however spelled.++ ``self.provider`` is not always the normalized slug: ``/model`` and+ profile configs can leave the alias ``github-copilot`` (or ``github``)+ in place — a single session log can show both ``provider=copilot`` and+ ``provider=github-copilot`` for the same account. A bare+ ``provider == "copilot"`` gate silently skips credential recovery for+ the alias spellings, so this is the single owner of the check; the+ Copilot base URL is accepted as a fallback signal.+ """+ if (self.provider or "").strip().lower() in {"copilot", "github-copilot", "github"}:+ return True+ return self._is_copilot_url()+def _anthropic_prompt_cache_policy(self,*,@@ -5161,7 +5176,7 @@ class AIAgent:then mint a new one) so the retry carries a valid IDE token. Mirrors the400 stale-credential recovery; the caller enforces the single-shot guard."""- if self.provider != "copilot":+ if not self._is_copilot_provider():return Falsetry:@@ -5225,7 +5240,7 @@ class AIAgent:rebuild the shared client. Single-shot (guarded by the caller) so agenuinely unavailable model can't loop."""- if self.provider != "copilot":+ if not self._is_copilot_provider():return Falsetry:diff --git a/tests/agent/test_turn_retry_state.py b/tests/agent/test_turn_retry_state.pyindex 7c52e2eb991..28bdbb45772 100644--- a/tests/agent/test_turn_retry_state.py+++ b/tests/agent/test_turn_retry_state.py@@ -19,6 +19,7 @@ EXPECTED_FIELDS = {"nous_auth_retry_attempted","nous_paid_entitlement_refresh_attempted","copilot_auth_retry_attempted",+ "copilot_stale_cred_retry_attempted","vertex_auth_retry_attempted","thinking_sig_retry_attempted","invalid_encrypted_content_retry_attempted",@@ -56,3 +57,34 @@ def test_guards_are_independently_mutable():# untouched guards stay Falseassert s.has_retried_429 is Falseassert s.anthropic_auth_retry_attempted is False+++def test_copilot_provider_check_accepts_alias_spellings():+ """`/model` and profile configs can leave `github-copilot` / `github` as+ the provider spelling; the recovery gates must not silently skip them."""+ from agent.conversation_loop import _is_copilot_provider+ from run_agent import AIAgent++ class _Agent:+ # Reuse the real single-owner check unbound; only provider/_base_url+ # state is faked.+ _is_copilot_provider = AIAgent._is_copilot_provider+ _is_copilot_url = AIAgent._is_copilot_url++ def __init__(self, provider, base_url=""):+ self.provider = provider+ self._base_url_lower = base_url.lower()++ assert _is_copilot_provider(_Agent("copilot"))+ assert _is_copilot_provider(_Agent("github-copilot"))+ assert _is_copilot_provider(_Agent("GitHub-Copilot"))+ assert _is_copilot_provider(_Agent("github"))+ # URL fallback: unnormalized provider but a Copilot base URL.+ assert _is_copilot_provider(_Agent("custom", "https://api.githubcopilot.com"))+ assert not _is_copilot_provider(_Agent("openrouter", "https://openrouter.ai/api/v1"))++ class _NoMethod:+ provider = "github-copilot"++ # Fallback path when the agent object lacks the method entirely.+ assert _is_copilot_provider(_NoMethod())diff --git a/tests/hermes_cli/test_copilot_token_exchange.py b/tests/hermes_cli/test_copilot_token_exchange.pyindex 10768514a82..5a9b7447b1b 100644--- a/tests/hermes_cli/test_copilot_token_exchange.py+++ b/tests/hermes_cli/test_copilot_token_exchange.py@@ -134,3 +134,56 @@ class TestDeriveBaseUrlFromProxyEp:api_token, _, base_url = exchange_copilot_token("gho_test")assert base_url is None+++class TestJwtDiskStoreBounds:+ """The on-disk JWT store must go through one bounded read everywhere."""++ def _store_path(self, tmp_path, monkeypatch):+ import hermes_cli.copilot_auth as mod+ path = tmp_path / mod._JWT_DISK_FILENAME+ monkeypatch.setattr(mod, "_jwt_disk_path", lambda: path)+ return path++ def test_read_jwt_store_rejects_oversized_file(self, tmp_path, monkeypatch):+ import hermes_cli.copilot_auth as mod++ path = self._store_path(tmp_path, monkeypatch)+ path.write_text("x" * (mod._JWT_DISK_MAX_BYTES + 1))+ assert mod._read_jwt_store(path) is None+ # Load path treats it as unusable → caller re-exchanges.+ assert mod._load_jwt_from_disk("deadbeef") is None++ def test_read_jwt_store_rejects_non_dict_and_malformed(self, tmp_path, monkeypatch):+ import hermes_cli.copilot_auth as mod++ path = self._store_path(tmp_path, monkeypatch)+ path.write_text("[1, 2, 3]")+ assert mod._read_jwt_store(path) is None+ path.write_text("{not json")+ assert mod._read_jwt_store(path) is None++ def test_evict_ignores_oversized_store(self, tmp_path, monkeypatch):+ """Eviction on an oversized store must not parse or rewrite it."""+ import hermes_cli.copilot_auth as mod++ path = self._store_path(tmp_path, monkeypatch)+ blob = "x" * (mod._JWT_DISK_MAX_BYTES + 1)+ path.write_text(blob)+ mod.evict_cached_exchanged_token("gho_whatever")+ # Untouched — bounded read refused it before any rewrite.+ assert path.read_text() == blob++ def test_save_discards_oversized_store_instead_of_merging(self, tmp_path, monkeypatch):+ """Saving over a corrupt/oversized store starts fresh rather than+ re-serializing the oversized content back out."""+ import json as _json+ import time as _time+ import hermes_cli.copilot_auth as mod++ path = self._store_path(tmp_path, monkeypatch)+ path.write_text("x" * (mod._JWT_DISK_MAX_BYTES + 1))+ mod._save_jwt_to_disk("fp1", "tid=fresh", _time.time() + 1800, None)+ store = _json.loads(path.read_text())+ assert set(store) == {"fp1"}+ assert store["fp1"]["api_token"] == "tid=fresh"diff --git a/tests/run_agent/test_run_agent_codex_responses.py b/tests/run_agent/test_run_agent_codex_responses.pyindex 9fdb4b64e12..464537f0b4d 100644--- a/tests/run_agent/test_run_agent_codex_responses.py+++ b/tests/run_agent/test_run_agent_codex_responses.py@@ -928,12 +928,10 @@ def test_try_refresh_codex_client_credentials_skips_xai_oauth_when_singleton_difdef 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+ passclass _RebuiltClient:pass@@ -962,7 +960,8 @@ def test_try_refresh_copilot_client_credentials_rebuilds_client(monkeypatch):ok = agent._try_refresh_copilot_client_credentials()assert ok is True- assert closed["value"] is True+ # The old client is retired by _replace_primary_openai_client (release is+ # deferred to GC on current main — no synchronous .close() contract).# 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"