The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(models): cache GitHub Copilot model catalog for 5 minutes
Xue-1997bd56440f4cc1
diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 28cf578fbfa..75597f4602a 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -7,6 +7,7 @@ Add, remove, or reorder entries here — both `hermes setup` andfrom __future__ import annotations+import copyimport jsonimport loggingimport os@@ -3465,10 +3466,37 @@ def _copilot_catalog_item_is_text_model(item: dict[str, Any]) -> bool:return True+# Module-level cache for the GitHub Copilot /models catalog.+# The picker path can ask for it multiple times in one process via:+# list_authenticated_providers -> cached_provider_model_ids -> provider_model_ids -> _fetch_github_models+# and later get_copilot_model_context()/normalize helpers. Cache the raw filtered+# catalog for a short TTL so we don't pay repeated TLS handshakes on every picker open.+# Keyed by the api_key used for the successful fetch so a credential swap+# mid-process never serves the previous account's catalog. Uses a monotonic+# clock so wall-clock adjustments can't extend the TTL. Lock-free like the+# other module caches here — a racing thread at worst duplicates one fetch.+_github_model_catalog_cache: Optional[list[dict[str, Any]]] = None+_github_model_catalog_cache_key: Optional[str] = None+_github_model_catalog_cache_time: float = 0.0+_GITHUB_MODEL_CATALOG_CACHE_TTL = 300 # 5 minutes++def fetch_github_model_catalog(api_key: Optional[str] = None, timeout: float = 5.0) -> Optional[list[dict[str, Any]]]:"""Fetch the live GitHub Copilot model catalog for this account."""+ global _github_model_catalog_cache, _github_model_catalog_cache_key+ global _github_model_catalog_cache_time++ if (+ _github_model_catalog_cache is not None+ and _github_model_catalog_cache_key == api_key+ and (time.monotonic() - _github_model_catalog_cache_time) < _GITHUB_MODEL_CATALOG_CACHE_TTL+ ):+ # Deep copy: catalog items are dicts, and a shallow copy would let+ # callers mutate the cached entries in place.+ return copy.deepcopy(_github_model_catalog_cache)+attempts: list[dict[str, str]] = []if api_key:attempts.append({@@ -3494,6 +3522,9 @@ def fetch_github_model_catalog(seen_ids.add(model_id)models.append(item)if models:+ _github_model_catalog_cache = copy.deepcopy(models)+ _github_model_catalog_cache_key = api_key+ _github_model_catalog_cache_time = time.monotonic()return modelsexcept Exception:continuediff --git a/tests/hermes_cli/test_copilot_context.py b/tests/hermes_cli/test_copilot_context.pyindex d7bf952fcd0..8914537de88 100644--- a/tests/hermes_cli/test_copilot_context.py+++ b/tests/hermes_cli/test_copilot_context.py@@ -81,6 +81,125 @@ class TestGetCopilotModelContext:assert mock_fetch.call_count == 2++ @patch("hermes_cli.models._urlopen_model_catalog_request")+ def test_fetch_github_model_catalog_uses_short_lived_cache(self, mock_urlopen):+ import json as _json+ import hermes_cli.models as mod++ mod._github_model_catalog_cache = None+ mod._github_model_catalog_cache_key = None+ mod._github_model_catalog_cache_time = 0.0++ payload = {+ "data": [+ {+ "id": "gpt-4.1",+ "model_picker_enabled": True,+ "supported_endpoints": ["/chat/completions"],+ }+ ]+ }++ class _Resp:+ def __enter__(self):+ return self+ def __exit__(self, *args):+ return False+ def read(self):+ return _json.dumps(payload).encode()++ mock_urlopen.return_value = _Resp()++ first = mod.fetch_github_model_catalog(api_key="token")+ second = mod.fetch_github_model_catalog(api_key="token")++ assert [item["id"] for item in first] == ["gpt-4.1"]+ assert [item["id"] for item in second] == ["gpt-4.1"]+ assert mock_urlopen.call_count == 1++ # Cached copies are independent — mutating the result must not+ # poison the cache.+ second[0]["id"] = "mutated"+ third = mod.fetch_github_model_catalog(api_key="token")+ assert [item["id"] for item in third] == ["gpt-4.1"]+ assert mock_urlopen.call_count == 1++ @patch("hermes_cli.models._urlopen_model_catalog_request")+ def test_fetch_github_model_catalog_cache_expires_after_ttl(self, mock_urlopen):+ import json as _json+ import time as _time+ import hermes_cli.models as mod++ mod._github_model_catalog_cache = None+ mod._github_model_catalog_cache_key = None+ mod._github_model_catalog_cache_time = 0.0++ payload = {+ "data": [+ {+ "id": "gpt-4.1",+ "model_picker_enabled": True,+ "supported_endpoints": ["/chat/completions"],+ }+ ]+ }++ class _Resp:+ def __enter__(self):+ return self+ def __exit__(self, *args):+ return False+ def read(self):+ return _json.dumps(payload).encode()++ mock_urlopen.return_value = _Resp()++ mod.fetch_github_model_catalog(api_key="token")+ assert mock_urlopen.call_count == 1++ # Age the entry past the TTL (monotonic clock) — next call re-fetches.+ mod._github_model_catalog_cache_time = (+ _time.monotonic() - mod._GITHUB_MODEL_CATALOG_CACHE_TTL - 1+ )+ mod.fetch_github_model_catalog(api_key="token")+ assert mock_urlopen.call_count == 2++ @patch("hermes_cli.models._urlopen_model_catalog_request")+ def test_fetch_github_model_catalog_cache_misses_on_credential_change(self, mock_urlopen):+ import json as _json+ import hermes_cli.models as mod++ mod._github_model_catalog_cache = None+ mod._github_model_catalog_cache_key = None+ mod._github_model_catalog_cache_time = 0.0++ payload = {+ "data": [+ {+ "id": "gpt-4.1",+ "model_picker_enabled": True,+ "supported_endpoints": ["/chat/completions"],+ }+ ]+ }++ class _Resp:+ def __enter__(self):+ return self+ def __exit__(self, *args):+ return False+ def read(self):+ return _json.dumps(payload).encode()++ mock_urlopen.return_value = _Resp()++ mod.fetch_github_model_catalog(api_key="token-a")+ assert mock_urlopen.call_count == 1+ # A different token must not be served the previous account's catalog.+ mod.fetch_github_model_catalog(api_key="token-b")+ assert mock_urlopen.call_count == 2+@patch("hermes_cli.models.fetch_github_model_catalog", return_value=[])def test_returns_none_for_empty_catalog(self, mock_fetch):assert get_copilot_model_context("gpt-4.1") is None