Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 28 additions & 10 deletions hermes_cli/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -86,6 +87,23 @@
_openrouter_catalog_cache: list[tuple[str, str]] | None = None


def _read_model_catalog_json(resp) -> Any:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this bounded reader available to hermes_cli/model_catalog.py too. fetch_openrouter_models() first fetches that remote curated manifest, and _fetch_manifest() still performs an unbounded resp.read() on current main.

"""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]:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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 {}
Expand Down Expand Up @@ -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 {}
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion tests/hermes_cli/test_api_key_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
8 changes: 4 additions & 4 deletions tests/hermes_cli/test_model_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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 = []
Expand All @@ -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:
Expand All @@ -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()):
Expand Down
54 changes: 51 additions & 3 deletions tests/hermes_cli/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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",

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Current main reaches this response through _urlopen_model_catalog_request() (hermes_cli/models.py:33), not raw urllib.request.urlopen; port this mock to that wrapper seam when salvaging the test.

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.

Expand All @@ -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
Expand Down Expand Up @@ -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":['
Expand Down