Skip to content

The agent that grows with you

refactor(model-providers): actual reuses base fetch_models + hermes_cli normalizer; commandcode anthropic subclasses chat profile; compact router/openrouter docstrings

Teknium8c83b89dd43b
diff --git a/plugins/model-providers/actual/__init__.py b/plugins/model-providers/actual/__init__.py
index 9cce101ef82..35413121291 100644
--- a/plugins/model-providers/actual/__init__.py
+++ b/plugins/model-providers/actual/__init__.py
@@ -2,35 +2,12 @@
from __future__ import annotations
-import json
-import logging
import os
-from urllib.parse import urlparse
-import urllib.request
from providers import register_provider
-from providers.base import ProviderProfile, _profile_user_agent
-
-logger = logging.getLogger(__name__)
+from providers.base import ProviderProfile
DEFAULT_ACTUAL_BASE_URL = "https://api.actual.inc/v1"
-_LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1", "0.0.0.0"}
-
-
-def _normalize_actual_base_url(base_url: str) -> str:
- """Append /v1 to a bare hosted or local host; pass anything else through."""
- url = str(base_url or "").strip().rstrip("/")
- if not url:
- return DEFAULT_ACTUAL_BASE_URL
- try:
- parsed = urlparse(url)
- host = (parsed.hostname or "").lower().rstrip(".")
- path = parsed.path.rstrip("/")
- except Exception:
- return url
- if (host == "api.actual.inc" or host in _LOCAL_HOSTS) and path in {"", "/"}:
- return url + "/v1"
- return url
class ActualProfile(ProviderProfile):
@@ -40,24 +17,11 @@ class ActualProfile(ProviderProfile):
def fetch_models(
self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0
) -> list[str] | None:
- from hermes_cli.urllib_security import open_credentialed_url
+ """ACTUAL_BASE_URL wins over the caller's base_url; bare hosts get ``/v1`` appended."""
+ from hermes_cli.auth import normalize_actual_base_url
- base_url = _normalize_actual_base_url(
- os.getenv("ACTUAL_BASE_URL", "").strip() or base_url or self.base_url
- )
- req = urllib.request.Request(base_url + "/models")
- if api_key:
- req.add_header("Authorization", f"Bearer {api_key}")
- req.add_header("Accept", "application/json")
- req.add_header("User-Agent", _profile_user_agent())
- try:
- with open_credentialed_url(req, timeout=timeout) as resp:
- data = json.loads(resp.read().decode())
- items = data if isinstance(data, list) else data.get("data", [])
- return [m["id"] for m in items if isinstance(m, dict) and "id" in m]
- except Exception as exc:
- logger.debug("fetch_models(actual): %s", exc)
- return None
+ base_url = normalize_actual_base_url(os.getenv("ACTUAL_BASE_URL", "").strip() or base_url or self.base_url)
+ return super().fetch_models(api_key=api_key, base_url=base_url, timeout=timeout)
actual = ActualProfile(
diff --git a/plugins/model-providers/commandcode/__init__.py b/plugins/model-providers/commandcode/__init__.py
index 7191d9d4f01..960324060df 100644
--- a/plugins/model-providers/commandcode/__init__.py
+++ b/plugins/model-providers/commandcode/__init__.py
@@ -17,50 +17,38 @@ _COMMANDCODE_BASE = "https://api.commandcode.ai/provider/v1"
_COMMANDCODE_MODELS_URL = f"{_COMMANDCODE_BASE}/models"
-def _fetch_commandcode_models(
- timeout: float = 10.0,
- base_url: str | None = None,
-) -> list[str] | None:
- """Fetch model IDs from the public (unauthenticated) /models endpoint.
-
- The picker passes base_url unconditionally, so only a value differing from
- the default counts as a customised endpoint.
- """
- caller_base = (base_url or "").strip().rstrip("/")
- custom = caller_base and caller_base != _COMMANDCODE_BASE
- models_url = caller_base + "/models" if custom else _COMMANDCODE_MODELS_URL
- try:
- req = urllib.request.Request(models_url)
- req.add_header("Accept", "application/json")
- req.add_header("User-Agent", _profile_user_agent())
- with urllib.request.urlopen(req, timeout=timeout) as resp:
- data = json.loads(resp.read().decode())
- return [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m]
- except Exception as exc:
- logger.debug("fetch_models(commandcode): %s", exc)
- return None
-
-
class CommandCodeProfile(ProviderProfile):
"""CommandCode — OpenAI-compatible chat completions endpoint."""
def fetch_models(
self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0
) -> list[str] | None:
- return _fetch_commandcode_models(timeout=timeout, base_url=base_url)
+ """Public (unauthenticated) /models endpoint. The picker passes base_url
+ unconditionally, so only a value differing from the default is a custom endpoint."""
+ caller_base = (base_url or "").strip().rstrip("/")
+ custom = caller_base and caller_base != _COMMANDCODE_BASE
+ models_url = caller_base + "/models" if custom else _COMMANDCODE_MODELS_URL
+ try:
+ req = urllib.request.Request(models_url)
+ req.add_header("Accept", "application/json")
+ req.add_header("User-Agent", _profile_user_agent())
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
+ data = json.loads(resp.read().decode())
+ return [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m]
+ except Exception as exc:
+ logger.debug("fetch_models(commandcode): %s", exc)
+ return None
-class CommandCodeAnthropicProfile(ProviderProfile):
+class CommandCodeAnthropicProfile(CommandCodeProfile):
"""CommandCode — Anthropic Messages API-compatible endpoint."""
def fetch_models(
self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0
) -> list[str] | None:
"""Public /models endpoint, filtered to Anthropic-family models."""
- all_models = _fetch_commandcode_models(timeout=timeout, base_url=base_url)
- if all_models is None:
- return None
- return [m for m in all_models if m.startswith("claude-")]
+ all_models = super().fetch_models(api_key=api_key, base_url=base_url, timeout=timeout)
+ return None if all_models is None else [m for m in all_models if m.startswith("claude-")]
commandcode = CommandCodeProfile(
diff --git a/plugins/model-providers/openrouter/__init__.py b/plugins/model-providers/openrouter/__init__.py
index 20f0597ec17..f25ee79b5e6 100644
--- a/plugins/model-providers/openrouter/__init__.py
+++ b/plugins/model-providers/openrouter/__init__.py
@@ -37,13 +37,9 @@ def _anthropic_reasoning_is_mandatory(model: str | None) -> bool:
def _sticky_key(session_id: str | None) -> str | None:
"""Declared routing scope, then ambient conversation, then explicit session_id.
-
Aux call sites (compression, titles, vision, MoA…) pass no ``session_id``,
- so the ambient lineage ROOT keeps them pinned to their conversation.
- """
- return _cache_scope_from_session_id(
- get_affinity_scope() or get_conversation_context() or session_id
- )
+ so the ambient lineage ROOT keeps them pinned to their conversation."""
+ return _cache_scope_from_session_id(get_affinity_scope() or get_conversation_context() or session_id)
class OpenRouterProfile(ProviderProfile):
@@ -51,11 +47,8 @@ class OpenRouterProfile(ProviderProfile):
@staticmethod
def _clamp_reasoning_to_catalog(cfg: dict[str, Any], model: str | None) -> dict[str, Any]:
- """Clamp ``cfg["effort"]`` to the nearest LOWER catalog-advertised level.
-
- No-op when the catalog is unreachable, the model is unlisted, or no
- supported_efforts list is published (None = all levels accepted).
- """
+ """Clamp ``cfg["effort"]`` to the nearest LOWER catalog-advertised level. No-op when the
+ catalog is unreachable, the model is unlisted, or no supported_efforts list is published."""
effort = cfg.get("effort")
if not effort or cfg.get("enabled") is False:
return cfg
@@ -80,8 +73,8 @@ class OpenRouterProfile(ProviderProfile):
def fetch_models(
self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0
) -> list[str] | None:
- """Fetch from the public OpenRouter catalog (no auth). Tool-call filtering
- happens in hermes_cli/models.py, which the picker reaches first."""
+ """Public OpenRouter catalog (no auth), cached per process. Tool-call
+ filtering happens in hermes_cli/models.py, which the picker reaches first."""
global _CACHE # noqa: PLW0603
if _CACHE is not None:
return _CACHE
@@ -104,7 +97,6 @@ class OpenRouterProfile(ProviderProfile):
prefs = context.get("provider_preferences")
if prefs:
body["provider"] = prefs
-
# Pareto Code router plugin is only meaningful for openrouter/pareto-code.
score = context.get("openrouter_min_coding_score")
if (context.get("model") or "") == "openrouter/pareto-code" and score is not None and score != "":
@@ -143,7 +135,6 @@ class OpenRouterProfile(ProviderProfile):
extra_body["reasoning"] = self._clamp_reasoning_to_catalog(dict(reasoning_config), model)
else:
extra_body["reasoning"] = {"enabled": True, "effort": "medium"}
-
# xAI's prompt cache is pinned per backend server via this header.
grok_conv_id = _sticky_key(session_id)
if grok_conv_id and model and model.startswith(("x-ai/grok-", "xai/grok-")):
diff --git a/plugins/model-providers/router/__init__.py b/plugins/model-providers/router/__init__.py
index ee20972fdbc..9604d354fa2 100644
--- a/plugins/model-providers/router/__init__.py
+++ b/plugins/model-providers/router/__init__.py
@@ -1,18 +1,12 @@
"""Ramp Router (router.com) provider profile: Responses-only LLM gateway.
-Wire notes (verified live against api.router.com):
-* Responses API is the native wire; ``/chat/completions`` is only a thin shim.
- ``api_mode="codex_responses"`` plus the ``api.router.com`` host mandate in
- ``hermes_cli/providers.py`` keep every path on it.
-* The catalog is account-scoped (BYOK accounts see extra IDs), so this profile
- ships no ``fallback_models`` — the picker relies on ``fetch_models()``.
-* Router 400s on ``reasoning.effort`` levels outside a model's published
- vocabulary and on any reasoning field for non-reasoning models. The efforts
- map from ``GET /v1/models`` is cached (memory + disk mirror, background
- warmer; never HTTP on the request hot path) and fed to the codex transport's
- clamp via ``supported_reasoning_efforts``.
-* ``store: false``, ``prompt_cache_key``, encrypted reasoning replay, tools and
- streaming pass through unchanged — no Router-specific request surgery.
+Wire notes (verified live): the Responses API is the native wire (``api_mode=
+"codex_responses"`` + the ``api.router.com`` host mandate in ``hermes_cli/providers.py``);
+the catalog is account-scoped so there are no ``fallback_models`` (picker uses
+``fetch_models()``); Router 400s on ``reasoning.effort`` levels outside a model's
+published vocabulary and on any reasoning field for non-reasoning models, so the
+efforts map from ``GET /v1/models`` is cached (memory + disk mirror, background
+warmer; never HTTP on the request hot path) and fed to the codex transport's clamp.
"""
from __future__ import annotations
@@ -51,8 +45,8 @@ def _base_url() -> str:
def _resolve_api_key() -> str:
- """Resolve the Router key (documented var, then alias), preferring dotenv;
- plain os.environ is the fallback when the dotenv resolver is unavailable or raises."""
+ """Router key (documented var, then alias), preferring dotenv; plain os.environ
+ is the fallback when the dotenv resolver is unavailable or raises."""
resolvers: list = [lambda var: os.environ.get(var, "")]
try:
from hermes_cli.config import get_env_value_prefer_dotenv
@@ -81,10 +75,9 @@ def _dig(obj: Any, *keys: str) -> Any:
def _parse_efforts(items: Any) -> Optional[dict[str, list[str]]]:
"""Parse a ``/v1/models`` ``data`` array into the efforts map (None if unusable).
- Ladder-unknown levels are dropped: clamp_effort ignores them, so an
- all-unknown vocabulary would pass the effort through unclamped to a Router
- 400. ``supported=True`` with no recognized level leaves the model out
- (unknown) so the transport keeps its default clamp behavior.
+ Ladder-unknown levels are dropped: clamp_effort ignores them, so an all-unknown
+ vocabulary would pass the effort through unclamped to a Router 400. ``supported=True``
+ with no recognized level leaves the model out (unknown -> transport default clamp).
"""
if not isinstance(items, list):
return None
@@ -166,9 +159,7 @@ def _seed_efforts(items: Any) -> Optional[dict[str, list[str]]]:
return parsed
-def _fetch_catalog_items(
- *, api_key: str = "", base_url: str = "", timeout: float = 8.0
-) -> Optional[list]:
+def _fetch_catalog_items(*, api_key: str = "", base_url: str = "", timeout: float = 8.0) -> Optional[list]:
"""Fetch the raw ``/v1/models`` ``data`` array. None on any failure."""
import urllib.request
@@ -179,8 +170,7 @@ def _fetch_catalog_items(
if key:
req.add_header("Authorization", f"Bearer {key}")
req.add_header("Accept", "application/json")
- # Router's WAF rejects the default Python-urllib UA.
- req.add_header("User-Agent", _profile_user_agent())
+ req.add_header("User-Agent", _profile_user_agent()) # Router's WAF rejects the default urllib UA
try:
with open_credentialed_url(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode())
@@ -244,7 +234,7 @@ class RouterProfile(ProviderProfile):
def fetch_models(
self, *, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: float = 8.0
) -> Optional[list[str]]:
- """Fetch the live, key-scoped catalog; the same payload seeds the caps cache.
+ """Live, key-scoped catalog; the same payload seeds the caps cache.
Deduped but not sorted: Router's listing order is deliberate presentation."""
items = _fetch_catalog_items(api_key=api_key or "", base_url=base_url or "", timeout=timeout)
if items is None:
@@ -279,8 +269,7 @@ router = RouterProfile(
default_headers={"User-Agent": f"Hermes-Agent/{_HERMES_VERSION}"},
supports_vision=True,
default_aux_model="gpt-5.4-mini",
- # Empty on purpose: model IDs are account-scoped; the picker uses fetch_models().
- fallback_models=(),
+ fallback_models=(), # account-scoped IDs; the picker uses fetch_models()
)
register_provider(router)