From 44a5531fa9ef2fa91f92d3639532761e93a4edab Mon Sep 17 00:00:00 2001 From: luyifan Date: Mon, 29 Jun 2026 18:54:48 +0800 Subject: [PATCH] Bound model catalog response reads --- hermes_cli/models.py | 38 +++++++++++---- tests/hermes_cli/test_api_key_providers.py | 2 +- tests/hermes_cli/test_model_validation.py | 8 ++-- tests/hermes_cli/test_models.py | 54 ++++++++++++++++++++-- 4 files changed, 84 insertions(+), 18 deletions(-) diff --git a/hermes_cli/models.py b/hermes_cli/models.py index cf3eb40edaaf8..18013edab5898 100644 --- a/hermes_cli/models.py +++ b/hermes_cli/models.py @@ -28,6 +28,7 @@ COPILOT_EDITOR_VERSION = "vscode/1.104.1" COPILOT_REASONING_EFFORTS_GPT5 = ["minimal", "low", "medium", "high"] COPILOT_REASONING_EFFORTS_O_SERIES = ["low", "medium", "high"] +_MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES = 16 * 1024 * 1024 # Fallback OpenRouter snapshot used when the live catalog is unavailable. @@ -86,6 +87,23 @@ _openrouter_catalog_cache: list[tuple[str, str]] | None = None +def _read_model_catalog_json(resp) -> Any: + """Read a bounded model-catalog JSON response.""" + raw = resp.read(_MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES + 1) + if len(raw) > _MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES: + raise ValueError( + "model catalog response exceeded " + f"{_MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES} bytes" + ) + return json.loads(raw.decode("utf-8")) + + +def _read_model_catalog_text(resp) -> str: + """Read a bounded model-catalog text response.""" + raw = resp.read(_MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES + 1) + if len(raw) > _MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES: + raw = raw[:_MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES] + return raw.decode("utf-8", errors="ignore") def _codex_curated_models() -> list[str]: @@ -892,7 +910,7 @@ def fetch_nous_recommended_models( headers={"Accept": "application/json"}, ) with urllib.request.urlopen(req, timeout=timeout) as resp: - data = json.loads(resp.read().decode()) + data = _read_model_catalog_json(resp) if not isinstance(data, dict): data = {} except Exception: @@ -1364,7 +1382,7 @@ def fetch_openrouter_models( headers={"Accept": "application/json"}, ) with urllib.request.urlopen(req, timeout=timeout) as resp: - payload = json.loads(resp.read().decode()) + payload = _read_model_catalog_json(resp) except Exception: return list(_openrouter_catalog_cache or fallback) @@ -1485,7 +1503,7 @@ def fetch_models_with_pricing( try: req = urllib.request.Request(url, headers=headers) with urllib.request.urlopen(req, timeout=timeout) as resp: - payload = json.loads(resp.read().decode()) + payload = _read_model_catalog_json(resp) except Exception: _pricing_cache[cache_key] = {} return {} @@ -1599,7 +1617,7 @@ def _fetch_novita_pricing( try: req = urllib.request.Request(url, headers=headers) with urllib.request.urlopen(req, timeout=timeout) as resp: - payload = json.loads(resp.read().decode()) + payload = _read_model_catalog_json(resp) except Exception: _pricing_cache[cache_key] = {} return {} @@ -2713,7 +2731,7 @@ def _do_request(h: dict[str, str]): headers=h, ) with urllib.request.urlopen(req, timeout=timeout) as resp: - return json.loads(resp.read().decode()) + return _read_model_catalog_json(resp) try: try: @@ -2728,7 +2746,7 @@ def _do_request(h: dict[str, str]): and http_err.code == 400 ): try: - body_text = http_err.read().decode(errors="ignore").lower() + body_text = _read_model_catalog_text(http_err).lower() except Exception: body_text = "" if "long context beta" in body_text and "not yet available" in body_text: @@ -2828,7 +2846,7 @@ def fetch_github_model_catalog( req = urllib.request.Request(COPILOT_MODELS_URL, headers=headers) try: with urllib.request.urlopen(req, timeout=timeout) as resp: - data = json.loads(resp.read().decode()) + data = _read_model_catalog_json(resp) items = _payload_items(data) models: list[dict[str, Any]] = [] seen_ids: set[str] = set() @@ -2945,7 +2963,7 @@ def _lmstudio_fetch_raw_models( request = urllib.request.Request(server_root + "/api/v1/models", headers=headers) try: with urllib.request.urlopen(request, timeout=timeout) as resp: - payload = json.loads(resp.read().decode()) + payload = _read_model_catalog_json(resp) except urllib.error.HTTPError as exc: if exc.code in {401, 403}: from hermes_cli.auth import AuthError @@ -3090,7 +3108,7 @@ def ensure_lmstudio_model_loaded( ), timeout=timeout, ) as resp: - resp.read() + _read_model_catalog_text(resp) except Exception: return None return target_context_length @@ -3496,7 +3514,7 @@ def probe_api_models( req = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(req, timeout=timeout) as resp: - data = json.loads(resp.read().decode()) + data = _read_model_catalog_json(resp) return { "models": [m.get("id", "") for m in data.get("data", [])], "probed_url": url, diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.py index ad864f8cd9de1..92c278b1eda16 100644 --- a/tests/hermes_cli/test_api_key_providers.py +++ b/tests/hermes_cli/test_api_key_providers.py @@ -1206,7 +1206,7 @@ def __enter__(self): def __exit__(self, *args): return False - def read(self): + def read(self, size=-1): import json as _json return _json.dumps(fake_payload).encode() diff --git a/tests/hermes_cli/test_model_validation.py b/tests/hermes_cli/test_model_validation.py index ca621f915d019..8ccfd36fc7d2e 100644 --- a/tests/hermes_cli/test_model_validation.py +++ b/tests/hermes_cli/test_model_validation.py @@ -223,7 +223,7 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - def read(self): + def read(self, size=-1): return b'{"data": [{"id": "enterprise-claude"}]}' with patch( @@ -286,7 +286,7 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - def read(self): + def read(self, size=-1): return b'{"data": [{"id": "local-model"}]}' calls = [] @@ -313,7 +313,7 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - def read(self): + def read(self, size=-1): return b'{"data": [{"id": "gpt-5.4", "model_picker_enabled": true, "supported_endpoints": ["/responses"], "capabilities": {"type": "chat", "supports": {"reasoning_effort": ["low", "medium", "high"]}}}, {"id": "claude-sonnet-4.6", "model_picker_enabled": true, "supported_endpoints": ["/chat/completions"], "capabilities": {"type": "chat", "supports": {"reasoning_effort": ["low", "medium", "high"]}}}, {"id": "text-embedding-3-small", "model_picker_enabled": true, "capabilities": {"type": "embedding"}}]}' with patch("hermes_cli.models.urllib.request.urlopen", return_value=_Resp()) as mock_urlopen: @@ -332,7 +332,7 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - def read(self): + def read(self, size=-1): return b'{"data": [{"id": "gpt-5.4", "model_picker_enabled": true, "supported_endpoints": ["/responses"], "capabilities": {"type": "chat", "supports": {"reasoning_effort": ["low", "medium", "high"]}}}, {"id": "text-embedding-3-small", "model_picker_enabled": true, "capabilities": {"type": "embedding"}}]}' with patch("hermes_cli.models.urllib.request.urlopen", return_value=_Resp()): diff --git a/tests/hermes_cli/test_models.py b/tests/hermes_cli/test_models.py index 2f087635662dd..d4a983d669566 100644 --- a/tests/hermes_cli/test_models.py +++ b/tests/hermes_cli/test_models.py @@ -66,7 +66,7 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - def read(self): + def read(self, size=-1): return b'{"data":[{"id":"anthropic/claude-opus-4.8","pricing":{"prompt":"0.000015","completion":"0.000075"}},{"id":"qwen/qwen3.7-max","pricing":{"prompt":"0.000000325","completion":"0.00000195"}},{"id":"nvidia/nemotron-3-super-120b-a12b:free","pricing":{"prompt":"0","completion":"0"}}]}' monkeypatch.setattr(_models_mod, "_openrouter_catalog_cache", None) @@ -86,6 +86,54 @@ def test_falls_back_to_static_snapshot_on_fetch_failure(self, monkeypatch): assert models == OPENROUTER_MODELS + def test_live_fetch_bounds_response_read(self, monkeypatch): + reads: list[int] = [] + + class _Resp: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + def read(self, size=-1): + reads.append(size) + return b'{"data":[]}' + + monkeypatch.setattr(_models_mod, "_openrouter_catalog_cache", None) + with patch( + "hermes_cli.model_catalog.get_curated_openrouter_models", + return_value=None, + ), patch("hermes_cli.models.urllib.request.urlopen", return_value=_Resp()): + fetch_openrouter_models(force_refresh=True) + + assert reads == [_models_mod._MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES + 1] + + def test_live_fetch_falls_back_on_oversized_response(self, monkeypatch): + reads: list[int] = [] + + class _Resp: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + def read(self, size=-1): + reads.append(size) + return b"x" * size + + monkeypatch.setattr(_models_mod, "_MODEL_CATALOG_RESPONSE_BODY_MAX_BYTES", 8) + monkeypatch.setattr(_models_mod, "_openrouter_catalog_cache", None) + with patch( + "hermes_cli.model_catalog.get_curated_openrouter_models", + return_value=None, + ), patch("hermes_cli.models.urllib.request.urlopen", return_value=_Resp()): + models = fetch_openrouter_models(force_refresh=True) + + assert reads == [9] + assert models == OPENROUTER_MODELS + def test_filters_out_models_without_tool_support(self, monkeypatch): """Models whose supported_parameters omits 'tools' must not appear in the picker. @@ -100,7 +148,7 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - def read(self): + def read(self, size=-1): # opus-4.6 advertises tools → kept # nano-image has explicit supported_parameters that OMITS tools → dropped # qwen3.7-max advertises tools → kept @@ -150,7 +198,7 @@ def __enter__(self): def __exit__(self, exc_type, exc, tb): return False - def read(self): + def read(self, size=-1): # No supported_parameters field at all on either entry. return ( b'{"data":['