The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): compact models_dev registry/override helpers; inline _fetch_registry
Teknium4cfe4f4857e6
diff --git a/agent/models_dev.py b/agent/models_dev.pyindex edc9543d177..5d4b93038ab 100644--- a/agent/models_dev.py+++ b/agent/models_dev.py@@ -7,6 +7,7 @@ Refreshes use ETag conditional GET when a servable registry is held. Hot pathspass ``allow_network=False`` and never do I/O. A corrupt/empty disk cache isquarantined, never served as ``{}``. ``models_dev.url`` in config.yaml = mirror."""+import contextlibimport jsonimport loggingimport re@@ -75,13 +76,10 @@ class ModelInfo:def format_capabilities(self) -> str:"""Human-readable capabilities, e.g. 'reasoning, tools, vision, PDF'."""flags = (- (self.reasoning, "reasoning"), (self.tool_call, "tools"),- (self.supports_vision(), "vision"), (self.supports_pdf(), "PDF"),- (self.supports_audio_input(), "audio"),- (self.structured_output, "structured output"), (self.open_weights, "open weights"),+ (self.reasoning, "reasoning"), (self.tool_call, "tools"), (self.supports_vision(), "vision"), (self.supports_pdf(), "PDF"),+ (self.supports_audio_input(), "audio"), (self.structured_output, "structured output"), (self.open_weights, "open weights"),)- caps = [label for on, label in flags if on]- return ", ".join(caps) if caps else "basic"+ return ", ".join(label for on, label in flags if on) or "basic"@dataclass@@ -136,10 +134,9 @@ def _models_dev_to_hermes_ids(mdev_id: str) -> List[str]:"""Return the Hermes provider ids that map to *mdev_id* (may be [])."""global _MODELS_DEV_TO_PROVIDERif _MODELS_DEV_TO_PROVIDER is None:- reverse: Dict[str, List[str]] = {}+ _MODELS_DEV_TO_PROVIDER = {}for hermes_id, mapped in PROVIDER_TO_MODELS_DEV.items():- reverse.setdefault(mapped, []).append(hermes_id)- _MODELS_DEV_TO_PROVIDER = reverse+ _MODELS_DEV_TO_PROVIDER.setdefault(mapped, []).append(hermes_id)return _MODELS_DEV_TO_PROVIDER.get(mdev_id, [])@@ -180,10 +177,7 @@ def _quietly(what: str, fn, default=None):def _load_etag() -> str:"""Last-known ETag from disk, or "" if missing."""- def read() -> str:- etag_path = _get_etag_path()- return etag_path.read_text(encoding="utf-8").strip() if etag_path.exists() else ""- return _quietly("load models.dev ETag", read, "")+ return _quietly("load models.dev ETag", lambda: _get_etag_path().read_text(encoding="utf-8").strip() if _get_etag_path().exists() else "", "")def _save_etag(etag: str) -> None:@@ -195,19 +189,16 @@ def _save_etag(etag: str) -> None:def _clear_etag() -> None:- """Delete the ETag sidecar so the next fetch is unconditional: an- If-None-Match without a servable cache invites a 304 that leaves the- process with no data at all."""+ """Delete the ETag sidecar so the next fetch is unconditional: an If-None-Match without a+ servable cache invites a 304 that leaves the process with no data at all."""_quietly("clear models.dev ETag", lambda: _get_etag_path().unlink(missing_ok=True))def _get_models_dev_url() -> str:"""The models.dev API URL, honoring the ``models_dev.url`` config override."""url = _cfg_get("models_dev", "url", default="")- if isinstance(url, str) and url.strip():- return url.strip()# Module global (not a captured constant) so patching MODELS_DEV_URL works.- return MODELS_DEV_URL+ return url.strip() if isinstance(url, str) and url.strip() else MODELS_DEV_URLdef _validate_registry(data: Any) -> bool:@@ -216,8 +207,8 @@ def _validate_registry(data: Any) -> bool:def _load_disk_cache() -> Dict[str, Any]:- """Load the disk cache; a corrupt/empty one is quarantined with a warning- so it never masquerades as ``{}`` and breaks provider/model resolution."""+ """Load the disk cache; a corrupt/empty one is quarantined with a warning so it never+ masquerades as ``{}`` and breaks provider/model resolution."""try:cache_path = _get_cache_path()if cache_path.exists():@@ -229,18 +220,15 @@ def _load_disk_cache() -> Dict[str, Any]:_quarantine_corrupt_cache(cache_path)except Exception as e:logger.warning("Failed to load models.dev disk cache; quarantining: %s", e)- try:+ with contextlib.suppress(Exception):_quarantine_corrupt_cache(_get_cache_path())- except Exception:- passreturn {}def _quarantine_corrupt_cache(cache_path: Path) -> None:- """Rename a rejected cache aside and drop its ETag sidecar. Renaming makes the- rejection a one-time event — otherwise every hot-path call that finds the- in-memory cache empty re-parses and re-warns until a network fetch succeeds.- The sidecar vouches for a registry we no longer hold, so it goes too."""+ """Rename a rejected cache aside and drop its ETag sidecar. Renaming makes the rejection a+ one-time event — otherwise every hot-path call that finds the in-memory cache empty re-parses+ and re-warns until a network fetch succeeds. The sidecar vouches for a registry we no longer hold."""try:cache_path.rename(cache_path.with_suffix(".json.corrupt"))except Exception as e:@@ -249,22 +237,18 @@ def _quarantine_corrupt_cache(cache_path: Path) -> None:def _disk_cache_age_seconds() -> Optional[float]:- """Age of the disk cache file in seconds, or None if missing/unreadable. An- mtime in the future (clock skew) is also None — unknown freshness — so- callers fall through to the network rather than trusting it forever."""+ """Age of the disk cache file in seconds, or None if missing/unreadable. An mtime in the future+ (clock skew) is also None — unknown freshness — so callers fall through to the network."""def stat() -> Optional[float]:cache_path = _get_cache_path()- if not cache_path.exists():- return None- age = time.time() - cache_path.stat().st_mtime+ age = time.time() - cache_path.stat().st_mtime if cache_path.exists() else -1return age if age >= 0 else Nonereturn _quietly("stat models.dev disk cache", stat)def _save_disk_cache(data: Dict[str, Any], etag: str = "") -> None:"""Save the registry atomically, plus the ETag sidecar when non-empty."""- _quietly("save models.dev disk cache", lambda: atomic_json_write(- _get_cache_path(), data, indent=None, separators=(",", ":")))+ _quietly("save models.dev disk cache", lambda: atomic_json_write(_get_cache_path(), data, indent=None, separators=(",", ":")))if etag:_save_etag(etag)@@ -275,16 +259,14 @@ class _NotModified(Exception):def _fetch_models_dev_from_network(*, conditional: bool = False) -> Tuple[Dict[str, Any], str]:- """Fetch the live registry; returns ``(registry, etag)`` (etag "" if none).- Raises on network errors and on an empty/invalid payload. ``conditional``- sends ``If-None-Match`` with the sidecar's ETag and raises ``_NotModified``- on 304 — pass True ONLY while holding ``_models_dev_fetch_lock`` AND a- servable registry, or a 304 leaves the process with no data."""+ """Fetch the live registry; returns ``(registry, etag)`` (etag "" if none). Raises on network+ errors and on an empty/invalid payload. ``conditional`` sends ``If-None-Match`` with the sidecar's+ ETag and raises ``_NotModified`` on 304 — pass True ONLY while holding ``_models_dev_fetch_lock``+ AND a servable registry, or a 304 leaves the process with no data."""headers: Dict[str, str] = {}if conditional and (etag := _load_etag()):headers["If-None-Match"] = etag- # (connect, read): 5 s connect fails fast on blackholed hosts instead of- # stalling the first turn; 10 s read tolerates a slow registry.+ # (connect, read): 5 s connect fails fast on blackholed hosts; 10 s read tolerates a slow registry.response = requests.get(_get_models_dev_url(), headers=headers, timeout=(5, 10))if response.status_code == 304:raise _NotModified()@@ -296,13 +278,10 @@ def _fetch_models_dev_from_network(*, conditional: bool = False) -> Tuple[Dict[sdef _mark_stale_cache_grace() -> None:- """Give stale cache data a 5-minute in-memory grace before retrying refresh.- Only ever moves the timestamp forward, so a background refresh that completed- between the caller's staleness check and this call keeps its fresh stamp."""+ """Give stale cache data a 5-minute in-memory grace before retrying refresh. Only ever moves the+ timestamp forward, so a background refresh that completed meanwhile keeps its fresh stamp."""global _models_dev_cache_time- grace_time = time.time() - _MODELS_DEV_CACHE_TTL + _MODELS_DEV_RETRY_DELAY- if grace_time > _models_dev_cache_time:- _models_dev_cache_time = grace_time+ _models_dev_cache_time = max(_models_dev_cache_time, time.time() - _MODELS_DEV_CACHE_TTL + _MODELS_DEV_RETRY_DELAY)def _serve_stale(msg: str, *args: Any) -> Dict[str, Any]:@@ -314,9 +293,8 @@ def _serve_stale(msg: str, *args: Any) -> Dict[str, Any]:def _commit_registry(data: Dict[str, Any], *, etag: str = "", where: str) -> None:- """Persist a fetched registry: disk + in-mem + clear backoff. Callers hold- ``_models_dev_fetch_lock`` so a failing refresh on one path can never stomp- state a succeeding refresh on the other just committed."""+ """Persist a fetched registry: disk + in-mem + clear backoff. Callers hold ``_models_dev_fetch_lock``+ so a failing refresh on one path can never stomp state a succeeding refresh just committed."""global _models_dev_cache, _models_dev_cache_time, _models_dev_retry_after_save_disk_cache(data, etag)_models_dev_cache = data@@ -329,13 +307,12 @@ def _commit_registry(data: Dict[str, Any], *, etag: str = "", where: str) -> Nondef _confirm_cache_not_modified(*, where: str) -> None:- """After a 304: clear backoff and re-mark the held cache fresh (disk is- untouched — only the freshness marker advances). Caller holds the lock."""+ """After a 304: clear backoff and re-mark the held cache fresh (disk is untouched — only the+ freshness marker advances). Caller holds the lock."""global _models_dev_cache_time, _models_dev_retry_afterif not _models_dev_cache:- # Should be unreachable (conditional GETs require a servable cache) but- # previously caused a permanent empty-registry loop: drop the sidecar- # and arm the normal backoff rather than marking {} "fresh".+ # Should be unreachable (conditional GETs require a servable cache) but previously caused a+ # permanent empty-registry loop: drop the sidecar and arm the backoff rather than marking {} "fresh"._clear_etag()_models_dev_retry_after = time.time() + _MODELS_DEV_RETRY_DELAYlogger.warning("models.dev returned 304 but no cached registry is held (%s); "@@ -354,8 +331,8 @@ def _note_refresh_failure(exc: Exception, *, where: str) -> None:def _refresh_locked(where: str) -> Optional[Dict[str, Any]]:- """One conditional fetch + state update. Caller holds ``_models_dev_fetch_lock``.- Returns the registry to serve, or None when the fetch failed (backoff armed)."""+ """One conditional fetch + state update; caller holds ``_models_dev_fetch_lock``. Returns the+ registry to serve, or None when the fetch failed (backoff armed)."""try:data, etag = _fetch_models_dev_from_network(conditional=bool(_models_dev_cache))_commit_registry(data, etag=etag, where=where)@@ -372,10 +349,9 @@ def _background_refresh_models_dev() -> None:"""Best-effort refresh after serving stale cache data."""global _models_dev_refresh_in_flighttry:- # Fetch INSIDE the lock, symmetric with the foreground path: the- # conditional-GET inputs (memory cache + sidecar) can't be mutated- # mid-fetch by a concurrent force_refresh and the two paths can't- # double-download. Hot-path callers never touch this lock.+ # Fetch INSIDE the lock, symmetric with the foreground path: the conditional-GET inputs (memory+ # cache + sidecar) can't be mutated mid-fetch by a concurrent force_refresh and the two paths+ # can't double-download. Hot-path callers never touch this lock.with _models_dev_fetch_lock:_refresh_locked("background")finally:@@ -384,8 +360,7 @@ def _background_refresh_models_dev() -> None:def _start_background_refresh_models_dev() -> None:- """Start one daemon refresh worker if none is running and the failure- backoff has elapsed."""+ """Start one daemon refresh worker if none is running and the failure backoff has elapsed."""global _models_dev_refresh_in_flightif time.time() < _models_dev_retry_after:return@@ -397,23 +372,19 @@ def _start_background_refresh_models_dev() -> None:try:thread.start()except Exception as e:- # Thread/fd exhaustion: clear the flag so refresh isn't disabled for- # the rest of the process. Callers still get stale data.+ # Thread/fd exhaustion: clear the flag so refresh isn't disabled for the rest of the process.with _models_dev_refresh_lock:_models_dev_refresh_in_flight = Falselogger.debug("Failed to start models.dev refresh thread: %s", e)def fetch_models_dev(force_refresh: bool = False, *, allow_network: bool = True) -> Dict[str, Any]:- """Fetch the models.dev registry (dict keyed by provider ID; {} on failure).- Cache hierarchy: fresh in-memory → stale in-memory (served now, refreshed in- one background daemon thread — stale beats a foreground timeout) → disk of any- age (stale triggers the same background refresh) → singleflight foreground- fetch. A failed refresh suppresses automatic refreshes for 5 minutes.- ``force_refresh=True`` bypasses the cache fast paths and the backoff, falling- back to cached data only if the call fails. ``allow_network=False`` returns- any memory/disk cache regardless of age and never makes a request.- """+ """Fetch the models.dev registry (dict keyed by provider ID; {} on failure). Cache hierarchy:+ fresh in-memory → stale in-memory (served now, refreshed in one background daemon thread — stale+ beats a foreground timeout) → disk of any age (stale triggers the same background refresh) →+ singleflight foreground fetch. A failed refresh suppresses automatic refreshes for 5 minutes.+ ``force_refresh=True`` bypasses the cache fast paths and the backoff, falling back to cached data+ only if the call fails. ``allow_network=False`` returns any memory/disk cache and never makes a request."""global _models_dev_cache, _models_dev_cache_time, _models_dev_retry_afterif not allow_network:if not _models_dev_cache and (disk_data := _load_disk_cache()):@@ -428,38 +399,35 @@ def fetch_models_dev(force_refresh: bool = False, *, allow_network: bool = True)# Stage 2: stale in-memory cache beats blocking on the network.if _models_dev_cache:return _serve_stale("Using stale in-memory models.dev cache; refreshing in background")- # Stage 3: disk cache (cold-start only). A stale disk cache is- # deliberately usable so resolution doesn't hang when models.dev is- # unreachable.+ # Stage 3: disk cache (cold-start only). A stale disk cache is deliberately usable so+ # resolution doesn't hang when models.dev is unreachable.disk_age = _disk_cache_age_seconds()if disk_age is not None and (disk_data := _load_disk_cache()):_models_dev_cache = disk_dataif disk_age >= _MODELS_DEV_CACHE_TTL:return _serve_stale("Using stale models.dev disk cache (age=%.0fs); refreshing in background", disk_age)- # Anchor the in-mem TTL to the file's age so an aging cache isn't- # extended by another full TTL.+ # Anchor the in-mem TTL to the file's age so an aging cache isn't extended by another full TTL._models_dev_cache_time = time.time() - disk_agelogger.debug("Loaded models.dev from fresh disk cache (%d providers, age=%.0fs)", len(disk_data), disk_age)return _models_dev_cache- # Process-wide backoff: don't make every caller retry an unreachable- # endpoint while no usable cache exists.+ # Process-wide backoff: don't make every caller retry an unreachable endpoint while no usable cache exists.if time.time() < _models_dev_retry_after:return _models_dev_cache- # Stage 4: singleflight foreground fetch. Recheck state under the lock —- # another caller may have refreshed or armed the backoff while we waited.+ # Stage 4: singleflight foreground fetch. Recheck state under the lock — another caller may+ # have refreshed or armed the backoff while we waited.with _models_dev_fetch_lock:if not force_refresh and (_models_dev_cache or time.time() < _models_dev_retry_after):return _models_dev_cache- # Cold force_refresh: stages 1-3 were skipped, so hydrate memory from- # disk first so the conditional GET fires and a 304 can re-confirm it.+ # Cold force_refresh: stages 1-3 were skipped, so hydrate memory from disk first so the+ # conditional GET fires and a 304 can re-confirm it.if force_refresh and not _models_dev_cache and (disk := _load_disk_cache()):_models_dev_cache = disk_models_dev_cache_time = 0 # servable but not freshserved = _refresh_locked("foreground")if served is not None:return served- # Stage 5: network failed — serve any stale memory/disk cache. Freshness- # stays expired; the retry-after timestamp gates the next attempt.+ # Stage 5: network failed — serve any stale memory/disk cache. Freshness stays expired;+ # the retry-after timestamp gates the next attempt.if not _models_dev_cache:_models_dev_cache = _load_disk_cache()_models_dev_cache_time = 0@@ -468,15 +436,11 @@ def fetch_models_dev(force_refresh: bool = False, *, allow_network: bool = True)return _models_dev_cache-def _fetch_registry(allow_network: bool) -> Dict[str, Any]:- # Keep the zero-argument call on the allow_network path: dozens of test- # sites monkeypatch fetch_models_dev with zero-arg lambdas.- return fetch_models_dev() if allow_network else fetch_models_dev(allow_network=False)--def _registry_provider(mdev_id: str, allow_network: bool) -> Optional[Dict[str, Any]]:"""The raw models.dev provider entry, or None."""- provider_data = _fetch_registry(allow_network).get(mdev_id)+ # Keep the zero-argument call on the allow_network path: dozens of test sites monkeypatch fetch_models_dev with zero-arg lambdas.+ registry = fetch_models_dev() if allow_network else fetch_models_dev(allow_network=False)+ provider_data = registry.get(mdev_id)return provider_data if isinstance(provider_data, dict) else None@@ -495,18 +459,12 @@ def _get_provider_models(provider: str, *, allow_network: bool = False) -> Optiodef _iter_model_entries(models: Dict[str, Any], model: str, *, suffix_fallback: bool = True):- """Yield ``(model_id, entry)`` candidates: exact, case-insensitive, then- (optionally) ``:cloud``/``-cloud`` suffixed forms.- Suffix fallback: some providers (ollama-cloud) store ``kimi-k2.6:cloud``- while the live API returns the bare name; without it context lookup falls to- stale OpenRouter metadata and trips the 64k minimum-context guard. Every- consumer shares this order so a suffix-keyed catalog model counts as KNOWN- for ``model_overrides`` fill-gap ``_default`` semantics.- """- candidates = [model]- if suffix_fallback:- candidates += [model + suffix for suffix in (":cloud", "-cloud")]- for name in candidates:+ """Yield ``(model_id, entry)`` candidates: exact, case-insensitive, then (optionally)+ ``:cloud``/``-cloud`` suffixed forms. Suffix fallback: some providers (ollama-cloud) store+ ``kimi-k2.6:cloud`` while the live API returns the bare name; without it context lookup falls to+ stale OpenRouter metadata and trips the 64k minimum-context guard. Every consumer shares this+ order so a suffix-keyed catalog model counts as KNOWN for ``model_overrides`` fill-gap ``_default``."""+ for name in ([model] + [model + suffix for suffix in (":cloud", "-cloud")] if suffix_fallback else [model]):entry = models.get(name)if isinstance(entry, dict):yield name, entry@@ -533,48 +491,34 @@ def _extract_context(entry: Dict[str, Any]) -> Optional[int]:def lookup_models_dev_context(provider: str, model: str, *, allow_network: bool = False) -> Optional[int]:- """Context window in tokens for provider+model, or None if not found.- An EXPLICIT ``model_overrides`` entry wins over the catalog; ``_default``- fills the gap only when the catalog has no answer (the self-unblock path for- wrong/missing context in models.dev). Catalog entries with context=0 are- skipped in favour of later candidates. ``allow_network`` defaults to False —- this runs every turn and must never block."""+ """Context window in tokens for provider+model, or None if not found. An EXPLICIT ``model_overrides``+ entry wins over the catalog; ``_default`` fills the gap only when the catalog has no answer (the+ self-unblock path for wrong/missing context in models.dev). Catalog entries with context=0 are+ skipped in favour of later candidates. ``allow_network`` defaults to False — runs every turn."""override_ctx = _override_context_window(provider, model)if override_ctx is not None:return override_ctxmodels = _get_provider_models(provider, allow_network=allow_network)- if models is not None:- for _mid, entry in _iter_model_entries(models, model):- ctx = _extract_context(entry)- if ctx:- return ctx- return _default_override_context(provider)---# Per-model overrides (config.yaml → model_overrides). Canonical schema (the ONLY-# key space consumers accept): context_window, max_output_tokens, supports_tools,-# supports_vision, supports_reasoning, model_family.-# ``<provider>.<model_id>`` is an explicit partial patch that always wins over the-# catalog. ``<provider>._default`` / top-level ``_default`` are FILL-GAP defaults:-# they apply ONLY to models the catalog does not know and never displace catalog-# data. Provider keys accept the Hermes or models.dev id; model ids match exactly,-# then case-insensitively (mirroring catalog lookup).+ catalog_ctx = next((ctx for _mid, entry in _iter_model_entries(models, model) if (ctx := _extract_context(entry))), None) if models is not None else None+ return catalog_ctx if catalog_ctx is not None else _default_override_context(provider)++# Per-model overrides (config.yaml → model_overrides). Canonical schema (the ONLY key space consumers+# accept): context_window, max_output_tokens, supports_tools, supports_vision, supports_reasoning,+# model_family. ``<provider>.<model_id>`` is an explicit partial patch that always wins over the+# catalog. ``<provider>._default`` / top-level ``_default`` are FILL-GAP defaults: they apply ONLY to+# models the catalog does not know and never displace catalog data. Provider keys accept the Hermes+# or models.dev id; model ids match exactly, then case-insensitively (mirroring catalog lookup)._OVERRIDE_WARNED_KEYS: set = set()-# Safe defaults for models absent from the catalog (tools on, vision/reasoning-# off, 200K context); shared by get_model_capabilities and get_model_info so-# the two unknown-model paths agree.-_UNKNOWN_MODEL_BASE: Dict[str, Any] = {- "limit": {"context": 200000, "output": 8192},- "tool_call": True,-}+# Safe defaults for models absent from the catalog (tools on, vision/reasoning off, 200K context);+# shared by get_model_capabilities and get_model_info so the two unknown-model paths agree.+_UNKNOWN_MODEL_BASE: Dict[str, Any] = {"limit": {"context": 200000, "output": 8192}, "tool_call": True}def _load_model_overrides() -> Dict[str, Any]:- """The ``model_overrides`` config section ({} on any failure). Deliberately not- memoized: ``load_config_readonly()`` is already (mtime, size)-cached upstream,- and an ``id(cfg)``-keyed layer can serve stale overrides after a reload when- CPython reuses the dict address."""+ """The ``model_overrides`` config section ({} on any failure). Deliberately not memoized:+ ``load_config_readonly()`` is already (mtime, size)-cached upstream, and an ``id(cfg)``-keyed+ layer can serve stale overrides after a reload when CPython reuses the dict address."""return _dict_or_empty(_cfg_get("model_overrides", default={}))@@ -584,20 +528,13 @@ def _provider_override_section(provider: str) -> Optional[Dict[str, Any]]:provider_key = (provider or "").strip()if not overrides or not provider_key:return None- # Forward (Hermes → models.dev id) and reverse (caller passed a models.dev- # id, config keyed by Hermes id) aliases.- candidates = [provider_key, PROVIDER_TO_MODELS_DEV.get(provider_key)]- candidates += _models_dev_to_hermes_ids(provider_key)- for key in candidates:- section = overrides.get(key) if key else None- if isinstance(section, dict):- return section- return None+ # Forward (Hermes → models.dev id) and reverse (caller passed a models.dev id, config keyed by Hermes id) aliases.+ candidates = [provider_key, PROVIDER_TO_MODELS_DEV.get(provider_key), *_models_dev_to_hermes_ids(provider_key)]+ return next((section for section in (overrides.get(key) if key else None for key in candidates) if isinstance(section, dict)), None)def _explicit_model_override(provider: str, model: str) -> Optional[Dict[str, Any]]:- """Explicit per-provider+model override dict (exact, then case-insensitive- skipping the ``_default`` sentinel), or None."""+ """Explicit per-provider+model override dict (exact, then case-insensitive skipping the ``_default`` sentinel), or None."""model_key = (model or "").strip()section = _provider_override_section(provider) if model_key else Noneif section is None:@@ -606,10 +543,7 @@ def _explicit_model_override(provider: str, model: str) -> Optional[Dict[str, Anif isinstance(entry, dict):return entrymodel_lower = model_key.lower()- for mid, mdata in section.items():- if mid != "_default" and mid.lower() == model_lower and isinstance(mdata, dict):- return mdata- return None+ return next((mdata for mid, mdata in section.items() if mid != "_default" and mid.lower() == model_lower and isinstance(mdata, dict)), None)def _default_model_override(provider: str) -> Optional[Dict[str, Any]]:@@ -624,9 +558,7 @@ def _default_model_override(provider: str) -> Optional[Dict[str, Any]]:def _override_for(provider: str, model: str, *, catalog_hit: bool) -> Optional[Dict[str, Any]]:"""Explicit override if any; else the ``_default`` only on a catalog miss."""explicit = _explicit_model_override(provider, model)- if explicit is not None or catalog_hit:- return explicit- return _default_model_override(provider)+ return explicit if explicit is not None or catalog_hit else _default_model_override(provider)def _override_int(override: Dict[str, Any], key: str) -> Optional[int]:@@ -634,12 +566,10 @@ def _override_int(override: Dict[str, Any], key: str) -> Optional[int]:raw = override.get(key)if raw is None:return None- try:+ with contextlib.suppress(TypeError, ValueError):value = int(raw)if value > 0:return value- except (TypeError, ValueError):- passwarn_key = (key, repr(raw))if warn_key not in _OVERRIDE_WARNED_KEYS:_OVERRIDE_WARNED_KEYS.add(warn_key)@@ -648,10 +578,9 @@ def _override_int(override: Dict[str, Any], key: str) -> Optional[int]:def _override_context_window(provider: str, model: str) -> Optional[int]:- """EXPLICITLY overridden context_window, or None. Explicit-only on purpose:- this runs early in the resolution chain (agent/model_metadata.py, before- custom_providers and live probes) where a ``_default`` must not preempt more- specific sources; fill-gap defaults apply in ``lookup_models_dev_context``."""+ """EXPLICITLY overridden context_window, or None. Explicit-only on purpose: this runs early in the+ resolution chain (agent/model_metadata.py, before custom_providers and live probes) where a+ ``_default`` must not preempt more specific sources; fill-gap defaults apply in ``lookup_models_dev_context``."""ov = _explicit_model_override(provider, model)return _override_int(ov, "context_window") if ov is not None else None@@ -663,13 +592,11 @@ def _default_override_context(provider: str) -> Optional[int]:def _override_to_catalog_shape(override: Dict[str, Any]) -> Tuple[Dict[str, Any], Optional[bool]]:- """Translate canonical override keys into a models.dev-shaped patch.- Returns ``(patch, vision)`` — vision is out-of-band because it maps onto the- ``modalities.input`` list rather than a scalar field."""+ """Translate canonical override keys into a models.dev-shaped patch. Returns ``(patch, vision)`` —+ vision is out-of-band because it maps onto the ``modalities.input`` list rather than a scalar field."""patch: Dict[str, Any] = {}limit = {- catalog_key: value- for catalog_key, override_key in (("context", "context_window"), ("output", "max_output_tokens"))+ catalog_key: value for catalog_key, override_key in (("context", "context_window"), ("output", "max_output_tokens"))if (value := _override_int(override, override_key)) is not None}if limit:@@ -686,9 +613,8 @@ def _override_to_catalog_shape(override: Dict[str, Any]) -> Tuple[Dict[str, Any]def _merge_catalog_entry_with_override(raw: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:- """Patch a catalog entry with a canonical-schema override. Sub-dicts- (``limit``, ``modalities``) are merged, not clobbered — setting only- ``context_window`` must not wipe the catalog's ``limit.output``."""+ """Patch a catalog entry with a canonical-schema override. Sub-dicts (``limit``, ``modalities``) are+ merged, not clobbered — setting only ``context_window`` must not wipe the catalog's ``limit.output``."""shaped, vision_override = _override_to_catalog_shape(override)merged = dict(raw)limit_patch = shaped.pop("limit", None)@@ -709,31 +635,23 @@ def _merge_catalog_entry_with_override(raw: Dict[str, Any], override: Dict[str,def _apply_overrides(provider: str, model: str, entry: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:- """*entry* patched by its override; ``_UNKNOWN_MODEL_BASE`` patched by a- fill-gap override on a catalog miss (selected AFTER lookup: _default only- fills misses); None when neither exists."""+ """*entry* patched by its override; ``_UNKNOWN_MODEL_BASE`` patched by a fill-gap override on a+ catalog miss (selected AFTER lookup: _default only fills misses); None when neither exists."""override = _override_for(provider, model, catalog_hit=entry is not None)- if override is None:- return entry- return _merge_catalog_entry_with_override(entry if entry is not None else _UNKNOWN_MODEL_BASE, override)+ return entry if override is None else _merge_catalog_entry_with_override(entry if entry is not None else _UNKNOWN_MODEL_BASE, override)def _entry_supports_vision(entry: Dict[str, Any]) -> bool:- """Prefer explicit ``modalities.input`` (the older ``attachment`` flag can be- stale or too broad for image routing); fall back to it only when the input- modalities are absent/invalid."""+ """Prefer explicit ``modalities.input`` (the older ``attachment`` flag can be stale or too broad+ for image routing); fall back to it only when the input modalities are absent/invalid."""input_mods = _dict_or_empty(entry.get("modalities", {})).get("input")- if isinstance(input_mods, list):- return "image" in input_mods- return bool(entry.get("attachment", False))+ return "image" in input_mods if isinstance(input_mods, list) else bool(entry.get("attachment", False))def get_model_capabilities(provider: str, model: str, *, allow_network: bool = False) -> Optional[ModelCapabilities]:- """Capability metadata from the models.dev cache, or None if unresolvable.- EXPLICIT ``model_overrides`` patch catalog fields; ``_default`` fills the gap- only for models the catalog does not know. Unspecified fields fall through to- the catalog, or to safe defaults (tools on, vision/reasoning off, 200K/8K).- ``allow_network`` defaults to False — vision/image routing is a hot path."""+ """Capability metadata from the models.dev cache, or None if unresolvable. EXPLICIT ``model_overrides``+ patch catalog fields; ``_default`` fills the gap only for models the catalog does not know. Unspecified+ fields fall through to the catalog, or to safe defaults. ``allow_network`` defaults to False (hot path)."""models = _get_provider_models(provider, allow_network=allow_network)entry = _find_model_entry(models, model) if models is not None else Noneraw = _apply_overrides(provider, model, entry)@@ -750,29 +668,20 @@ def get_model_capabilities(provider: str, model: str, *, allow_network: bool = Fdef list_provider_models(provider: str, *, allow_network: bool = True) -> List[str]:- """All model IDs for a provider ([] if unknown). ``allow_network`` defaults- to True: the model picker is interactive and a fresh catalog is worth a- short wait."""+ """All model IDs for a provider ([] if unknown). ``allow_network`` defaults to True: the model+ picker is interactive and a fresh catalog is worth a short wait."""from hermes_cli.models import normalize_providerprovider = normalize_provider(provider) or providermodels = _get_provider_models(provider, allow_network=allow_network)- if models is None:- return []- return [mid for mid in models if not _should_hide_from_provider_catalog(provider, mid)]+ return [mid for mid in models if not _should_hide_from_provider_catalog(provider, mid)] if models is not None else []-# Non-agentic or noise models (TTS, embedding, dated preview snapshots,-# live/streaming-only, image-only).+# Non-agentic or noise models (TTS, embedding, dated preview snapshots, live/streaming-only, image-only)._NOISE_PATTERNS: re.Pattern = re.compile(- r"-tts\b|embedding|live-|-(preview|exp)-\d{2,4}[-_]|"- r"-image\b|-image-preview\b|-customtools\b",- re.IGNORECASE,-)-# Hidden from the Gemini catalogs surfaced in setup/model selection (capability-# metadata stays available for direct/manual use).+ r"-tts\b|embedding|live-|-(preview|exp)-\d{2,4}[-_]|" r"-image\b|-image-preview\b|-customtools\b", re.IGNORECASE)+# Hidden from the Gemini catalogs surfaced in setup/model selection (capability metadata stays available for direct use)._GOOGLE_HIDDEN_MODELS = frozenset({- # Low-TPM Gemma models that trip Google input-token quota walls under- # agent-style traffic despite advertising large context windows.+ # Low-TPM Gemma models that trip Google input-token quota walls under agent-style traffic."gemma-4-31b-it", "gemma-4-26b-it", "gemma-4-26b-a4b-it","gemma-3-1b", "gemma-3-1b-it", "gemma-3-2b", "gemma-3-2b-it","gemma-3-4b", "gemma-3-4b-it", "gemma-3-12b", "gemma-3-12b-it",@@ -784,24 +693,17 @@ _GOOGLE_HIDDEN_MODELS = frozenset({def _should_hide_from_provider_catalog(provider: str, model_id: str) -> bool:- return ((provider or "").strip().lower() in {"gemini", "google"}- and (model_id or "").strip().lower() in _GOOGLE_HIDDEN_MODELS)+ return (provider or "").strip().lower() in {"gemini", "google"} and (model_id or "").strip().lower() in _GOOGLE_HIDDEN_MODELSdef list_agentic_models(provider: str, *, allow_network: bool = True) -> List[str]:- """Model IDs suitable for agentic use: tool_call=True, minus hidden and- noise models. [] on any failure. ``allow_network`` defaults to True (called- from interactive model selection)."""+ """Model IDs suitable for agentic use: tool_call=True, minus hidden and noise models. [] on any+ failure. ``allow_network`` defaults to True (called from interactive model selection)."""models = _get_provider_models(provider, allow_network=allow_network)- if models is None:- return []return [mid for mid, entry in models.items()- if isinstance(entry, dict)- and not _should_hide_from_provider_catalog(provider, mid)- and entry.get("tool_call", False)- and not _NOISE_PATTERNS.search(mid)- ]+ if isinstance(entry, dict) and not _should_hide_from_provider_catalog(provider, mid) and entry.get("tool_call", False) and not _NOISE_PATTERNS.search(mid)+ ] if models is not None else []def _parse_model_info(model_id: str, raw: Dict[str, Any], provider_id: str) -> ModelInfo:@@ -814,25 +716,14 @@ def _parse_model_info(model_id: str, raw: Dict[str, Any], provider_id: str) -> Mdef _cost(key: str) -> Optional[float]:return float(cost[key]) if cost.get(key) is not None else Nonereturn ModelInfo(- id=model_id,- name=raw.get("name", "") or model_id,- family=raw.get("family", "") or "",- provider_id=provider_id,- **{k: bool(raw.get(k, False)) for k in (- "reasoning", "tool_call", "attachment", "temperature", "structured_output", "open_weights")},- input_modalities=_mods("input"),- output_modalities=_mods("output"),- context_window=_extract_limit(raw, "context") or 0,- max_output=_extract_limit(raw, "output") or 0,- max_input=_extract_limit(raw, "input"),- cost_input=float(cost.get("input", 0) or 0),- cost_output=float(cost.get("output", 0) or 0),- cost_cache_read=_cost("cache_read"),- cost_cache_write=_cost("cache_write"),- knowledge_cutoff=raw.get("knowledge", "") or "",- release_date=raw.get("release_date", "") or "",- status=raw.get("status", "") or "",- interleaved=raw.get("interleaved", False),+ id=model_id, name=raw.get("name", "") or model_id, family=raw.get("family", "") or "", provider_id=provider_id,+ **{k: bool(raw.get(k, False)) for k in ("reasoning", "tool_call", "attachment", "temperature", "structured_output", "open_weights")},+ input_modalities=_mods("input"), output_modalities=_mods("output"),+ context_window=_extract_limit(raw, "context") or 0, max_output=_extract_limit(raw, "output") or 0, max_input=_extract_limit(raw, "input"),+ cost_input=float(cost.get("input", 0) or 0), cost_output=float(cost.get("output", 0) or 0),+ cost_cache_read=_cost("cache_read"), cost_cache_write=_cost("cache_write"),+ knowledge_cutoff=raw.get("knowledge", "") or "", release_date=raw.get("release_date", "") or "",+ status=raw.get("status", "") or "", interleaved=raw.get("interleaved", False),)@@ -841,33 +732,25 @@ def _parse_provider_info(provider_id: str, raw: Dict[str, Any]) -> ProviderInfo:env = raw.get("env") or []models = raw.get("models") or {}return ProviderInfo(- id=provider_id,- name=raw.get("name", "") or provider_id,- env=tuple(env) if isinstance(env, list) else (),- api=raw.get("api", "") or "",- doc=raw.get("doc", "") or "",- model_count=len(models) if isinstance(models, dict) else 0,+ id=provider_id, name=raw.get("name", "") or provider_id, env=tuple(env) if isinstance(env, list) else (),+ api=raw.get("api", "") or "", doc=raw.get("doc", "") or "", model_count=len(models) if isinstance(models, dict) else 0,)def get_provider_info(provider_id: str, *, allow_network: bool = True) -> Optional[ProviderInfo]:- """Provider metadata by Hermes or models.dev ID, or None if not cataloged.- ``allow_network`` defaults to True — primary caller is interactive setup."""+ """Provider metadata by Hermes or models.dev ID, or None if not cataloged. ``allow_network`` defaults to True (interactive setup)."""mdev_id = PROVIDER_TO_MODELS_DEV.get(provider_id, provider_id)raw = _registry_provider(mdev_id, allow_network)return _parse_provider_info(mdev_id, raw) if raw is not None else Nonedef get_model_info(provider_id: str, model_id: str, *, allow_network: bool = False) -> Optional[ModelInfo]:- """Full model metadata by Hermes or models.dev provider ID (exact match,- then case-insensitive), or None if not found. EXPLICIT ``model_overrides``- patch known catalog models; ``_default`` fills the gap only for unknown ones.- ``allow_network`` defaults to False — cost guard and inventory are hot paths."""+ """Full model metadata by Hermes or models.dev provider ID (exact match, then case-insensitive), or+ None if not found. EXPLICIT ``model_overrides`` patch known catalog models; ``_default`` fills the gap+ only for unknown ones. ``allow_network`` defaults to False — cost guard and inventory are hot paths."""mdev_id = PROVIDER_TO_MODELS_DEV.get(provider_id, provider_id)models = _registry_models(mdev_id, allow_network=allow_network)- mid, entry = model_id, None- if models is not None:- mid, entry = next(_iter_model_entries(models, model_id, suffix_fallback=False), (model_id, None))+ mid, entry = next(_iter_model_entries(models, model_id, suffix_fallback=False), (model_id, None)) if models is not None else (model_id, None)# Not in catalog — an override (explicit or _default) may still provide it.raw = _apply_overrides(provider_id, model_id, entry)return _parse_model_info(mid, raw, mdev_id) if raw is not None else None