fix(copilot): follow-ups for salvaged PR #58743

- Bound ALL reads of the on-disk JWT store through one _read_jwt_store()
  helper (load, eviction, save-merge) — the 1 MiB cap previously only
  covered the load path; eviction and save could still parse an
  oversized/corrupt store and rewrite it back out (sweeper finding).
- Fix the class, not the site: the recovery gates checked the literal
  provider == "copilot" while /model and profile configs can leave the
  alias spelling in place (the reporter's own log shows provider=copilot
  AND provider=github-copilot in one session — the aliased turns would
  have silently skipped recovery). Single owner:
  AIAgent._is_copilot_provider() (slug aliases + Copilot base-URL
  fallback), used by both run_agent recovery methods and both
  conversation_loop gates.
- Update the salvaged 401 test to current main's client-retirement
  contract (release deferred to GC — no synchronous .close()).
- Add copilot_stale_cred_retry_attempted to the TurnRetryState field
  contract test; add bounded-store and alias-gate regression tests.
This commit is contained in:
Teknium
2026-07-31 21:59:55 -07:00
parent 7779409a76
commit 1737741730
7 changed files with 154 additions and 24 deletions
+20 -2
View File
@@ -194,6 +194,24 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text
agent._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 == 401
and 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_attempted
and _is_stale_copilot_credential_error(
status_code, str(getattr(api_error, "message", "") or api_error)
@@ -0,0 +1 @@
dstkwll
+28 -16
View File
@@ -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():
return
try:
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 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
# 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 None
if not isinstance(entry, dict):
return None
api_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: v
+17 -2
View File
@@ -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 the
400 stale-credential recovery; the caller enforces the single-shot guard.
"""
if self.provider != "copilot":
if not self._is_copilot_provider():
return False
try:
@@ -5225,7 +5240,7 @@ class AIAgent:
rebuild the shared client. Single-shot (guarded by the caller) so a
genuinely unavailable model can't loop.
"""
if self.provider != "copilot":
if not self._is_copilot_provider():
return False
try:
+32
View File
@@ -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 False
assert s.has_retried_429 is False
assert 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())
@@ -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"
@@ -928,12 +928,10 @@ 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
pass
class _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"