The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): model_setup_flows — base-url/env helpers, per-provider model-list table, nous/anthropic/copilot phase helpers
Tekniume249887f0257
diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex 695ba3956fe..964b4e6d6a9 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -1,14 +1,11 @@"""Per-provider model-selection wizard flows for ``hermes setup`` / ``hermes model``.-Contract: ``select_provider_and_model`` in main.py re-imports every ``_model_flow_*``-here, so tests patching ``hermes_cli.main._model_flow_*`` keep working. main.py-internal-helpers (``_prompt_api_key``, ``_save_custom_provider``, ...) and config/auth/models-functions are imported lazily inside function bodies: that avoids the main.py import-cycle and lets tests patch ``hermes_cli.config.load_config`` etc. at call time.--The shared skeleton (credential prompt, persist step, OAuth gate, pickers) lives in-:mod:`hermes_cli.model_setup_flows_common`; it is re-exported here so existing imports-and ``patch("hermes_cli.model_setup_flows.<name>")`` keep resolving.+Contract: ``select_provider_and_model`` in main.py re-imports every ``_model_flow_*`` here, so+tests patching ``hermes_cli.main._model_flow_*`` keep working. main.py-internal helpers+(``_prompt_api_key``, ``_save_custom_provider``, ...) and config/auth/models functions are+imported lazily inside function bodies: that avoids the main.py import cycle and lets tests+patch ``hermes_cli.config.load_config`` etc. at call time. The shared skeleton lives in+:mod:`hermes_cli.model_setup_flows_common` and is re-exported here."""from __future__ import annotations@@ -52,6 +49,34 @@ from hermes_cli.model_setup_flows_bedrock import ( # noqa: F401_model_flow_bedrock)+def _env_base_url(base_url_env: str) -> str:+ """Base-URL override from ``.env`` then the process environment ('' when unset)."""+ from hermes_cli.config import get_env_value++ if not base_url_env:+ return ""+ return get_env_value(base_url_env) or os.getenv(base_url_env, "")+++def _prompt_base_url_override(effective_base: str, base_url_env: str) -> str:+ """Optional ``Base URL [...]`` prompt; a valid override is saved to *base_url_env*."""+ from hermes_cli.config import save_env_value++ override = _ask(f"Base URL [{effective_base}]: ", cancel_msg="", on_cancel="")+ if override and base_url_env:+ if not override.startswith(_HTTP):+ print(" Invalid URL — must start with http:// or https://. Keeping current value.")+ else:+ save_env_value(base_url_env, override)+ return override+ return effective_base+++def _report_live_models(model_list, source: str) -> None:+ if model_list:+ print(f" Found {len(model_list)} model(s) from {source}")++def _model_flow_openrouter(config, current_model=""):"""OpenRouter provider: ensure API key, then pick model."""from hermes_constants import OPENROUTER_BASE_URL@@ -76,16 +101,6 @@ def _model_flow_openrouter(config, current_model=""):base_url=OPENROUTER_BASE_URL, api_mode="chat_completions")-def _print_moa_preset(name: str, preset: dict) -> None:- """Print the full reference-models + aggregator breakdown for a preset."""- print(f" Preset: {name}")- print(" Reference models:")- for idx, slot in enumerate(preset.get("reference_models") or [], start=1):- print(f" {idx}. {slot.get('provider')}:{slot.get('model')}")- agg = preset.get("aggregator") or {}- print(f" Aggregator: {agg.get('provider')}:{agg.get('model')}")--def _model_flow_ai_gateway(config, current_model=""):"""Vercel AI Gateway provider: ensure API key, then pick model with pricing."""from hermes_constants import AI_GATEWAY_BASE_URL@@ -115,8 +130,8 @@ def _model_flow_ai_gateway(config, current_model=""):def _model_flow_moa(config, current_model=""):"""Mixture of Agents virtual provider: pick a preset, then persist it.- No credential step — presets reference already-configured providers. The preset- list is always shown (even with one entry), then the full breakdown on selection.+ No credential step — presets reference already-configured providers. The preset list is+ always shown (even with one entry), then the full breakdown on selection."""from hermes_cli.auth import _save_model_choicefrom hermes_cli.moa_config import normalize_moa_config@@ -166,40 +181,39 @@ def _model_flow_moa(config, current_model=""):_commit_model_config(cfg)_save_model_choice(selected_name)- _say("", f"Default model set to: {selected_name} (via Mixture of Agents)")- _print_moa_preset(selected_name, presets[selected_name])+ preset = presets[selected_name]+ _say("", f"Default model set to: {selected_name} (via Mixture of Agents)", f" Preset: {selected_name}", " Reference models:")+ for i, slot in enumerate(preset.get("reference_models") or [], start=1):+ print(f" {i}. {slot.get('provider')}:{slot.get('model')}")+ agg = preset.get("aggregator") or {}+ print(f" Aggregator: {agg.get('provider')}:{agg.get('model')}")def _nous_login_args(args) -> argparse.Namespace:return argparse.Namespace(- portal_url=getattr(args, "portal_url", None),- inference_url=getattr(args, "inference_url", None),- client_id=getattr(args, "client_id", None),- scope=getattr(args, "scope", None),- no_browser=bool(getattr(args, "no_browser", False)),- timeout=getattr(args, "timeout", None) or 15.0,- ca_bundle=getattr(args, "ca_bundle", None),- insecure=bool(getattr(args, "insecure", False)))+ portal_url=getattr(args, "portal_url", None), inference_url=getattr(args, "inference_url", None),+ client_id=getattr(args, "client_id", None), scope=getattr(args, "scope", None),+ no_browser=bool(getattr(args, "no_browser", False)), timeout=getattr(args, "timeout", None) or 15.0,+ ca_bundle=getattr(args, "ca_bundle", None), insecure=bool(getattr(args, "insecure", False)))def _nous_model_catalog(free_tier: bool, portal_url: str, model_ids: list, pricing: dict):"""Free/paid-tier catalog for the Nous picker.- Returns ``(model_ids, pricing, unavailable_models, unavailable_message,- policy_narrowed)`` or None (message already printed) when nothing is selectable.+ Returns ``(model_ids, pricing, unavailable_models, unavailable_message, policy_narrowed)``+ or None (message already printed) when nothing is selectable."""from hermes_cli.models import (nous_policy_allowed_ids, partition_nous_models_by_tier, restrict_to_nous_policy,union_with_portal_free_recommendations, union_with_portal_paid_recommendations)- # Free users: augment with the Portal's freeRecommendedModels (so newly launched- # free models appear before this build's curated list catches up), then partition- # into selectable/unavailable by Portal pricing. Paid users: same idea with- # paidRecommendedModels, no partition.+ # Free users: augment with the Portal's freeRecommendedModels (so newly launched free+ # models appear before this build's curated list catches up), then partition into+ # selectable/unavailable by Portal pricing. Paid users: paidRecommendedModels, no partition.unavailable_models: list[str] = []unavailable_message = ""- # Org policy narrows BEFORE the tier split, so a rescued id still has to pass- # the free/paid predicate instead of going around it.+ # Org policy narrows BEFORE the tier split, so a rescued id still has to pass the+ # free/paid predicate instead of going around it._policy_allowed = nous_policy_allowed_ids()if free_tier:try:@@ -232,13 +246,66 @@ def _nous_model_catalog(free_tier: bool, portal_url: str, model_ids: list, pricireturn model_ids, pricing, unavailable_models, unavailable_message, _policy_narrowed-def _model_flow_nous(config, current_model="", args=None):- """Nous Portal provider: ensure logged in, then pick model."""+def _nous_verified_credentials(creds_or_none=None):+ """Resolve Nous runtime credentials; on failure print the diagnosis (re-login when the+ session expired) and return None."""from hermes_cli.auth import (- get_provider_auth_state, _prompt_model_selection, _save_model_choice, _update_config_for_provider,- resolve_nous_runtime_credentials, AuthError, format_auth_error, _login_nous, PROVIDER_REGISTRY,+ AuthError, PROVIDER_REGISTRY, _login_nous, format_auth_error, resolve_nous_runtime_credentials,)++ try:+ return resolve_nous_runtime_credentials()+ except Exception as exc:+ relogin = isinstance(exc, AuthError) and exc.relogin_required+ msg = format_auth_error(exc) if isinstance(exc, AuthError) else str(exc)+ if relogin:+ _say(f"Session expired: {msg}", "Re-authenticating with Nous Portal...\n")+ try:+ _login_nous(_nous_login_args(None), PROVIDER_REGISTRY["nous"])+ except Exception as login_exc:+ print(f"Re-login failed: {login_exc}")+ return None+ print(f"Could not verify credentials: {msg}")+ return None+++def _nous_persist_selection(selected: str, creds: dict) -> dict:+ """Nous persist step: model choice + provider state, then rewrite ``model`` on a fresh+ config (the caller's may carry stale custom-provider fields) and clear a conflicting+ OPENAI_BASE_URL / OPENAI_API_KEY. Returns the saved config."""+ from hermes_cli.auth import _save_model_choice, _update_config_for_providerfrom hermes_cli.config import get_env_value, load_config, save_config, save_env_value++ _save_model_choice(selected)+ inference_url = creds.get("base_url", "")+ _update_config_for_provider("nous", inference_url)+ config = load_config()+ current_model_cfg = config.get("model")+ if isinstance(current_model_cfg, dict):+ model_cfg = dict(current_model_cfg)+ elif isinstance(current_model_cfg, str) and current_model_cfg.strip():+ model_cfg = {"default": current_model_cfg.strip()}+ else:+ model_cfg = {}+ model_cfg["provider"] = "nous"+ model_cfg["default"] = selected+ if inference_url and inference_url.strip():+ model_cfg["base_url"] = inference_url.rstrip("/")+ else:+ model_cfg.pop("base_url", None)+ clear_model_endpoint_credentials(model_cfg)+ config["model"] = model_cfg+ if get_env_value("OPENAI_BASE_URL"):+ save_env_value("OPENAI_BASE_URL", "")+ save_env_value("OPENAI_API_KEY", "")+ save_config(config)+ return config+++def _model_flow_nous(config, current_model="", args=None):+ """Nous Portal provider: ensure logged in, then pick model."""+ from hermes_cli.auth import get_provider_auth_state, _prompt_model_selection, _login_nous, PROVIDER_REGISTRY+ from hermes_cli.config import load_configfrom hermes_cli.nous_subscription import prompt_enable_tool_gatewaystate = get_provider_auth_state("nous")@@ -257,8 +324,8 @@ def _model_flow_nous(config, current_model="", args=None):_run_login(_login_then_offer_gateway, _nous_login_args(args), PROVIDER_REGISTRY["nous"])return- # Already logged in — the curated list (agentic models users know from- # OpenRouter) instead of the hundreds returned by the live /models endpoint.+ # Already logged in — the curated list (agentic models users know from OpenRouter)+ # instead of the hundreds returned by the live /models endpoint.from hermes_cli.models import check_nous_free_tier, get_curated_nous_model_ids, get_pricing_for_providermodel_ids = get_curated_nous_model_ids()@@ -267,25 +334,16 @@ def _model_flow_nous(config, current_model="", args=None):return# Verify credentials are still valid (catches expired sessions early)- try:- creds = resolve_nous_runtime_credentials()- except Exception as exc:- relogin = isinstance(exc, AuthError) and exc.relogin_required- msg = format_auth_error(exc) if isinstance(exc, AuthError) else str(exc)- if relogin:- _say(f"Session expired: {msg}", "Re-authenticating with Nous Portal...\n")- try:- _login_nous(_nous_login_args(None), PROVIDER_REGISTRY["nous"])- except Exception as login_exc:- print(f"Re-login failed: {login_exc}")- return- print(f"Could not verify credentials: {msg}")+ creds = _nous_verified_credentials()+ if creds is None:returnpricing = get_pricing_for_provider("nous")# Force fresh account data so recent credit purchases are reflected immediately.free_tier = check_nous_free_tier(force_fresh=True)if not free_tier:+ from hermes_cli.auth import resolve_nous_runtime_credentials+try:creds = resolve_nous_runtime_credentials(force_refresh=True) or credsexcept Exception:@@ -320,32 +378,7 @@ def _model_flow_nous(config, current_model="", args=None):if not selected:print("No change.")return- _save_model_choice(selected)- inference_url = creds.get("base_url", "")- _update_config_for_provider("nous", inference_url)- # Reload after the auth helper writes provider state; the incoming config- # object may still contain stale custom-provider fields.- config = load_config()- current_model_cfg = config.get("model")- if isinstance(current_model_cfg, dict):- model_cfg = dict(current_model_cfg)- elif isinstance(current_model_cfg, str) and current_model_cfg.strip():- model_cfg = {"default": current_model_cfg.strip()}- else:- model_cfg = {}- model_cfg["provider"] = "nous"- model_cfg["default"] = selected- if inference_url and inference_url.strip():- model_cfg["base_url"] = inference_url.rstrip("/")- else:- model_cfg.pop("base_url", None)- clear_model_endpoint_credentials(model_cfg)- config["model"] = model_cfg- # Clear any custom endpoint that might conflict- if get_env_value("OPENAI_BASE_URL"):- save_env_value("OPENAI_BASE_URL", "")- save_env_value("OPENAI_API_KEY", "")- save_config(config)+ config = _nous_persist_selection(selected, creds)print(f"Default model set to: {selected} (via Nous Portal)")# Offer Tool Gateway enablement for paid subscribersprompt_enable_tool_gateway(config)@@ -402,9 +435,9 @@ def _model_flow_xai_oauth(_config, current_model="", *, args=None):login_args, PROVIDER_REGISTRY["xai-oauth"], fresh_name="xAI OAuth"):return- # ``resolve_xai_oauth_runtime_credentials`` only reads the auth.json singleton,- # but credentials may live only in the pool (``hermes auth add xai-oauth``) —- # fall back to the default base URL so the picker still completes.+ # ``resolve_xai_oauth_runtime_credentials`` only reads the auth.json singleton, but+ # credentials may live only in the pool (``hermes auth add xai-oauth``) — fall back to+ # the default base URL so the picker still completes.base_url = DEFAULT_XAI_OAUTH_BASE_URLtry:creds = resolve_xai_oauth_runtime_credentials()@@ -460,8 +493,7 @@ def _model_flow_minimax_oauth(config, current_model="", args=None):if not state or not state.get("access_token"):_say("Not logged into MiniMax. Starting OAuth login...", "")mock_args = argparse.Namespace(- region=getattr(args, "region", None) or "global",- no_browser=bool(getattr(args, "no_browser", False)),+ region=getattr(args, "region", None) or "global", no_browser=bool(getattr(args, "no_browser", False)),timeout=getattr(args, "timeout", None) or 15.0)if not _run_login(_login_minimax_oauth, mock_args, PROVIDER_REGISTRY["minimax-oauth"]):return@@ -494,6 +526,20 @@ def _copilot_model_list(live_ids) -> list:return model_list+def _copilot_catalog(api_key: str):+ """``(catalog, catalog_ids, normalize)`` for a GitHub token; *normalize* canonicalizes a+ model id against the catalog (identity when unknown)."""+ from hermes_cli.models import fetch_github_model_catalog, normalize_copilot_model_id++ catalog = fetch_github_model_catalog(api_key)+ ids = [item.get("id", "") for item in catalog if item.get("id")] if catalog else []++ def _normalize(mid):+ return normalize_copilot_model_id(mid, catalog=catalog, api_key=api_key) or mid++ return catalog, ids, _normalize++def _copilot_obtain_token() -> bool:"""No Copilot token yet: offer device-code login or manual entry. False = stop."""from hermes_cli.config import save_env_value@@ -551,9 +597,7 @@ def _model_flow_copilot(config, current_model=""):from hermes_cli.setup import _current_reasoning_effort, _set_reasoning_effortfrom hermes_cli.auth import PROVIDER_REGISTRY, resolve_api_key_provider_credentialsfrom hermes_cli.config import load_config- from hermes_cli.models import (- fetch_api_models, fetch_github_model_catalog, github_model_reasoning_efforts, copilot_model_api_mode,- normalize_copilot_model_id)+ from hermes_cli.models import fetch_api_models, github_model_reasoning_efforts, copilot_model_api_modeprovider_id = "copilot"pconfig = PROVIDER_REGISTRY[provider_id]@@ -577,11 +621,9 @@ def _model_flow_copilot(config, current_model=""):print()effective_base = pconfig.inference_base_url- catalog = fetch_github_model_catalog(api_key)- live_models = [item.get("id", "") for item in catalog if item.get("id")] if catalog else fetch_api_models(api_key, effective_base)-- def _normalize(mid):- return normalize_copilot_model_id(mid, catalog=catalog, api_key=api_key) or mid+ catalog, live_models, _normalize = _copilot_catalog(api_key)+ if not catalog:+ live_models = fetch_api_models(api_key, effective_base)selected = _pick_model_or_prompt(_copilot_model_list(live_models), "Model name: ", current_model=_normalize(current_model),@@ -616,7 +658,6 @@ def _model_flow_copilot_acp(config, current_model=""):from hermes_cli.auth import (PROVIDER_REGISTRY, get_external_process_provider_status, resolve_api_key_provider_credentials,resolve_external_process_provider_credentials)- from hermes_cli.models import fetch_github_model_catalog, normalize_copilot_model_iddel configprovider_id = "copilot-acp"@@ -641,15 +682,10 @@ def _model_flow_copilot_acp(config, current_model=""):catalog_api_key = resolve_api_key_provider_credentials("copilot").get("api_key", "")except Exception:pass- catalog = fetch_github_model_catalog(catalog_api_key)-- def _normalize(mid):- return normalize_copilot_model_id(mid, catalog=catalog, api_key=catalog_api_key) or mid-- model_list = _copilot_model_list([item.get("id", "") for item in catalog if item.get("id")] if catalog else [])+ _catalog, catalog_ids, _normalize = _copilot_catalog(catalog_api_key)selected = _pick_model_or_prompt(- model_list, "Model name: ", current_model=_normalize(current_model), confirm_provider=provider_id,- confirm_base_url=effective_base, confirm_api_key=catalog_api_key)+ _copilot_model_list(catalog_ids), "Model name: ", current_model=_normalize(current_model),+ confirm_provider=provider_id, confirm_base_url=effective_base, confirm_api_key=catalog_api_key)if selected:selected = _normalize(selected)_finish_model(selected, provider_id, f"Default model set to: {selected} (via {pconfig.name})",@@ -657,13 +693,8 @@ def _model_flow_copilot_acp(config, current_model=""):def _model_flow_kimi(config, current_model=""):- """Kimi / Moonshot model selection with automatic endpoint routing.-- - sk-kimi-* keys → api.kimi.com/coding/v1 (Kimi Coding Plan)- - Other keys → api.moonshot.ai/v1 (legacy Moonshot)-- No manual base URL prompt — endpoint is determined by key prefix.- """+ """Kimi / Moonshot model selection; the endpoint is chosen by key prefix (no URL prompt):+ ``sk-kimi-*`` → api.kimi.com/coding/v1 (Kimi Coding Plan), other keys → Moonshot."""from hermes_cli.auth import PROVIDER_REGISTRY, KIMI_CODE_BASE_URLfrom hermes_cli.config import get_env_value, save_env_valuefrom hermes_cli.models import _PROVIDER_MODELS@@ -672,12 +703,10 @@ def _model_flow_kimi(config, current_model=""):pconfig = PROVIDER_REGISTRY[provider_id]base_url_env = pconfig.base_url_env_var or ""- # Step 1: Check / prompt for API key_, existing_key, abort = _ensure_flow_api_key(provider_id, pconfig)if abort:return- # Step 2: Auto-detect endpoint from key prefixis_coding_plan = existing_key.startswith("sk-kimi-")if is_coding_plan:effective_base = KIMI_CODE_BASE_URL@@ -690,7 +719,6 @@ def _model_flow_kimi(config, current_model=""):save_env_value(base_url_env, "")print()- # Step 3: Model selection — show appropriate models for the endpointmodel_list = _PROVIDER_MODELS.get("kimi-coding" if is_coding_plan else "moonshot", [])selected = _pick_model_or_prompt(model_list, "Enter model name: ", current_model=current_model, confirm_provider=provider_id,@@ -704,7 +732,7 @@ def _model_flow_stepfun(config, current_model=""):"""StepFun Step Plan flow with region-specific endpoints."""from hermes_cli.main import _infer_stepfun_region, _prompt_provider_choice, _stepfun_base_url_for_regionfrom hermes_cli.auth import PROVIDER_REGISTRY- from hermes_cli.config import get_env_value, save_env_value+ from hermes_cli.config import save_env_valuefrom hermes_cli.models import _PROVIDER_MODELS, fetch_api_modelsprovider_id = "stepfun"@@ -715,20 +743,16 @@ def _model_flow_stepfun(config, current_model=""):if abort:return- current_base = ""- if base_url_env:- current_base = get_env_value(base_url_env) or os.getenv(base_url_env, "")+ current_base = _env_base_url(base_url_env)if not current_base:model_cfg = config.get("model")if isinstance(model_cfg, dict):current_base = str(model_cfg.get("base_url") or "").strip()current_region = _infer_stepfun_region(current_base or pconfig.inference_base_url)- region_choices = [- ("international", f"International ({_stepfun_base_url_for_region('international')})"),- ("china", f"China ({_stepfun_base_url_for_region('china')})")]ordered_regions = []- for region_key, label in region_choices:+ for region_key, region_name in (("international", "International"), ("china", "China")):+ label = f"{region_name} ({_stepfun_base_url_for_region(region_key)})"if region_key == current_region:ordered_regions.insert(0, (region_key, f"{label} ← currently active"))else:@@ -763,10 +787,9 @@ def _model_flow_stepfun(config, current_model=""):def _model_flow_vertex(config, current_model=""):"""Google Vertex AI provider: Gemini via the OpenAI-compatible endpoint.- Auth is OAuth2 — short-lived tokens minted from a service-account JSON or- Application Default Credentials (ADC). No static API key. The credential- *path* lives in .env (VERTEX_CREDENTIALS_PATH / GOOGLE_APPLICATION_CREDENTIALS);- project ID and region are non-secret and saved to config.yaml under vertex:.+ Auth is OAuth2 (service-account JSON or ADC), no static key. The credential *path* lives+ in .env (VERTEX_CREDENTIALS_PATH / GOOGLE_APPLICATION_CREDENTIALS); project ID and region+ are non-secret and saved to config.yaml under ``vertex:``."""from hermes_cli.auth import _prompt_model_selectionfrom hermes_cli.config import load_config, get_env_value@@ -819,10 +842,9 @@ def _model_flow_vertex(config, current_model=""):def _select_zai_endpoint(current_base: str) -> str:- """Picker for the four official Z.AI endpoints (sourced from ``ZAI_ENDPOINTS``- in ``hermes_cli.auth`` so it stays in sync with the probe list) plus a- custom-proxy option. Returns the selected base URL; *current_base* on cancel/error.- """+ """Picker for the official Z.AI endpoints (``ZAI_ENDPOINTS`` in ``hermes_cli.auth``, kept in+ sync with the probe list) plus a custom-proxy option. Returns the selected base URL;+ *current_base* on cancel/error."""from hermes_cli.main import _prompt_provider_choicefrom hermes_cli.auth import ZAI_ENDPOINTS@@ -838,7 +860,6 @@ def _select_zai_endpoint(current_base: str) -> str:return current_baseif selected != len(options):return options[selected][1].rstrip("/")- # Custom proxy URLoverride = _ask(f"Custom base URL [{current_base}]: ", cancel_msg="")if not override:return current_base@@ -860,33 +881,86 @@ _GEMINI_FREE_TIER_NOTICE = (def _gemini_tier_ok(existing_key: str, pconfig, base_url_env: str) -> bool:- """Gemini free-tier gate: free-tier daily quotas (<= 250 RPD for Flash) are- exhausted in a handful of agent turns, so refuse a free-tier key. The probe- is best-effort; network or auth errors fall through without blocking."""- from hermes_cli.config import get_env_value-+ """Gemini free-tier gate: free-tier daily quotas (<= 250 RPD for Flash) are exhausted in a+ handful of agent turns, so refuse a free-tier key. The probe is best-effort; network or+ auth errors fall through without blocking."""try:from agent.gemini_native_adapter import probe_gemini_tierexcept Exception:return Trueprint(" Checking Gemini API tier...")- probe_base = (get_env_value(base_url_env) if base_url_env else "") or os.getenv(base_url_env or "", "") or pconfig.inference_base_url- tier = probe_gemini_tier(existing_key, probe_base)+ tier = probe_gemini_tier(existing_key, _env_base_url(base_url_env) or pconfig.inference_base_url)if tier == "free":_say(*_GEMINI_FREE_TIER_NOTICE)return False- # "unknown" (network/auth/unexpected response): don't block; the- # runtime 429 handler surfaces free-tier guidance if needed.+ # "unknown" (network/auth/unexpected response): don't block; the runtime 429 handler+ # surfaces free-tier guidance if needed._say(" Tier check: paid ✓" if tier == "paid" else " Tier check: could not verify (proceeding anyway).", "")return True+def _lmstudio_models(pconfig, curated, api_key, base_url):+ """LM Studio: live /api/v1/models probe only."""+ from hermes_cli.auth import AuthError+ from hermes_cli.models import fetch_lmstudio_models++ try:+ model_list = fetch_lmstudio_models(api_key=api_key, base_url=base_url)+ except AuthError as exc:+ _say(f" LM Studio rejected the request: {exc}", " Set LM_API_KEY (or update it) to match the server's bearer token.")+ model_list = []+ _report_live_models(model_list, "LM Studio")+ return model_list+++def _ollama_cloud_models(pconfig, curated, api_key, base_url):+ """Ollama Cloud: forced live refresh so newly released models appear the moment the user+ enters their key, not when the disk cache TTL expires."""+ from hermes_cli.models import fetch_ollama_cloud_models++ model_list = fetch_ollama_cloud_models(api_key=api_key, base_url=base_url, force_refresh=True)+ _report_live_models(model_list, "Ollama Cloud")+ return model_list+++def _opencode_free_models(pconfig, curated, api_key, base_url):+ """Keyless tier: the curated list is synced against anonymous live probes (models.dev's+ cost.input==0 filter lags reality)."""+ if curated:+ print(f' Showing {len(curated)} keyless free models — use "Enter custom model name" for others.')+ return curated+++def _novita_models(pconfig, curated, api_key, base_url):+ """Novita: live first, then models.dev, then curated."""+ from hermes_cli.models import fetch_api_models++ live_models = fetch_api_models(api_key, base_url)+ if live_models:+ _report_live_models(live_models, f"{pconfig.name} API")+ return live_models+ model_list = _models_dev_merged("novita", curated)+ if model_list:+ _report_live_models(model_list, "models.dev registry")+ return model_list+ _show_curated(curated)+ return curated+++# provider id -> (pconfig, curated, api_key_for_probe, effective_base) -> model list+_SPECIAL_MODEL_LISTS = {+ "lmstudio": _lmstudio_models,+ "ollama-cloud": _ollama_cloud_models,+ "opencode-free": _opencode_free_models,+ "novita": _novita_models}++def _api_key_provider_model_list(provider_id: str, pconfig, existing_key: str, key_env: str, effective_base: str) -> list:"""Model list for an API-key provider. Resolution order:1. models.dev registry (cached, filtered for agentic/tool-capable models)2. Curated static fallback list (offline insurance)3. Live /models endpoint probe (small providers without models.dev data)- LM Studio: live /api/v1/models probe only. Ollama Cloud: merged discovery.+ Providers in ``_SPECIAL_MODEL_LISTS`` have their own resolution."""from hermes_cli.config import get_env_valuefrom hermes_cli.models import _PROVIDER_MODELS, fetch_api_models@@ -894,54 +968,14 @@ def _api_key_provider_model_list(provider_id: str, pconfig, existing_key: str, kcurated = _PROVIDER_MODELS.get(provider_id, [])api_key_for_probe = existing_key or (get_env_value(key_env) if key_env else "")- def _mdev():- model_list = _models_dev_merged(provider_id, curated)- if model_list:- print(f" Found {len(model_list)} model(s) from models.dev registry")- return model_list-- if provider_id == "lmstudio":- from hermes_cli.auth import AuthError- from hermes_cli.models import fetch_lmstudio_models-- try:- model_list = fetch_lmstudio_models(api_key=api_key_for_probe, base_url=effective_base)- except AuthError as exc:- _say(f" LM Studio rejected the request: {exc}", " Set LM_API_KEY (or update it) to match the server's bearer token.")- model_list = []- if model_list:- print(f" Found {len(model_list)} model(s) from LM Studio")- return model_list- if provider_id == "ollama-cloud":- from hermes_cli.models import fetch_ollama_cloud_models-- # Force a live refresh so newly released models appear the moment the user- # enters their key, not when the disk cache TTL expires.- model_list = fetch_ollama_cloud_models(api_key=api_key_for_probe, base_url=effective_base, force_refresh=True)- if model_list:- print(f" Found {len(model_list)} model(s) from Ollama Cloud")- return model_list- if provider_id == "opencode-free":- # Keyless tier: the curated list is synced against anonymous live probes- # (models.dev's cost.input==0 filter lags reality).- if curated:- print(f' Showing {len(curated)} keyless free models — use "Enter custom model name" for others.')- return curated- if provider_id == "novita":- # Live first, then models.dev, then curated.- live_models = fetch_api_models(api_key_for_probe, effective_base)- if live_models:- print(f" Found {len(live_models)} model(s) from {pconfig.name} API")- return live_models- model_list = _mdev()- if model_list:- return model_list- _show_curated(curated)- return curated- # models.dev first (tool-capable, noise-filtered), merged with curated so- # newly added models still appear.- model_list = _mdev()+ special = _SPECIAL_MODEL_LISTS.get(provider_id)+ if special is not None:+ return special(pconfig, curated, api_key_for_probe, effective_base)+ # models.dev first (tool-capable, noise-filtered), merged with curated so newly added+ # models still appear.+ model_list = _models_dev_merged(provider_id, curated)if model_list:+ _report_live_models(model_list, "models.dev registry")return model_listif curated and len(curated) >= 8:# Substantial curated list — use it directly, skip live probe@@ -949,7 +983,7 @@ def _api_key_provider_model_list(provider_id: str, pconfig, existing_key: str, kreturn curatedlive_models = fetch_api_models(api_key_for_probe, effective_base)if live_models and len(live_models) >= len(curated):- print(f" Found {len(live_models)} model(s) from {pconfig.name} API")+ _report_live_models(live_models, f"{pconfig.name} API")return live_models_show_curated(curated) # may be empty: falls through to raw inputreturn curated@@ -958,7 +992,7 @@ def _api_key_provider_model_list(provider_id: str, pconfig, existing_key: str, kdef _model_flow_api_key_provider(config, provider_id, current_model=""):"""Generic flow for API-key providers (z.ai, MiniMax, OpenCode, etc.)."""from hermes_cli.auth import PROVIDER_REGISTRY- from hermes_cli.config import get_env_value, save_env_value, load_config+ from hermes_cli.config import save_env_value, load_configfrom hermes_cli.models import opencode_model_api_mode, normalize_opencode_model_idpconfig = PROVIDER_REGISTRY[provider_id]@@ -966,8 +1000,8 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):base_url_env = pconfig.base_url_env_var or ""is_opencode = provider_id in {"opencode-zen", "opencode-go", "opencode-free"}- # OpenCode Free is keyless — the tier is served anonymously and any- # unrecognized bearer 401s, so there is no key to prompt for.+ # OpenCode Free is keyless — the tier is served anonymously and any unrecognized+ # bearer 401s, so there is no key to prompt for.if provider_id == "opencode-free":print(" OpenCode Free is keyless — no API key or account needed.")existing_key = ""@@ -978,12 +1012,10 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):if provider_id == "gemini" and existing_key and not _gemini_tier_ok(existing_key, pconfig, base_url_env):return- # Optional base URL override. Precedence: env var → config.yaml model.base_url →- # registry default; reading config.yaml keeps a saved remote URL from being- # overwritten with localhost when the user just presses Enter.- current_base = ""- if base_url_env:- current_base = get_env_value(base_url_env) or os.getenv(base_url_env, "")+ # Optional base URL override. Precedence: env var → config.yaml model.base_url → registry+ # default; reading config.yaml keeps a saved remote URL from being overwritten with+ # localhost when the user just presses Enter.+ current_base = _env_base_url(base_url_env)if not current_base:try:_m = load_config().get("model") or {}@@ -994,20 +1026,14 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):effective_base = current_base or pconfig.inference_base_urlif provider_id == "zai":- # Four official endpoints with separate billing paths — a picker lets users- # match the endpoint to their key type.+ # Four official endpoints with separate billing paths — a picker lets users match+ # the endpoint to their key type.chosen_base = _select_zai_endpoint(effective_base)if chosen_base and chosen_base != effective_base and base_url_env:save_env_value(base_url_env, chosen_base)effective_base = chosen_baseelse:- override = _ask(f"Base URL [{effective_base}]: ", cancel_msg="", on_cancel="")- if override and base_url_env:- if not override.startswith(_HTTP):- print(" Invalid URL — must start with http:// or https://. Keeping current value.")- else:- save_env_value(base_url_env, override)- effective_base = override+ effective_base = _prompt_base_url_override(effective_base, base_url_env)model_list = _api_key_provider_model_list(provider_id, pconfig, existing_key, key_env, effective_base)if is_opencode:@@ -1015,9 +1041,8 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):current_model = normalize_opencode_model_id(provider_id, current_model)model_list = list(dict.fromkeys(mid for mid in model_list if mid))- # Per-model pricing when the provider supports it; get_pricing_for_provider() is- # memoized and returns {} otherwise — never a blocking fetch beyond the catalog- # lookup that already happened above.+ # Per-model pricing when the provider supports it; get_pricing_for_provider() is memoized+ # and returns {} otherwise — never a blocking fetch beyond the catalog lookup above.pricing: dict = {}if model_list:try:@@ -1038,11 +1063,36 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):drop_api_mode=not is_opencode)+def _anthropic_authenticate() -> bool:+ """Interactive Anthropic auth (OAuth subscription or API key). False = flow must stop."""+ from hermes_cli.main import _run_anthropic_oauth_flow+ from hermes_cli.config import save_env_value, save_anthropic_api_key++ _say("", " Choose authentication method:", "", " 1. Claude Pro/Max subscription (OAuth login)",+ " 2. Anthropic API key (pay-per-token)", " 3. Cancel", "")+ choice = _ask(" Choice [1/2/3]: ", raw=True, cancel_msg="")+ if choice is None:+ return False+ if choice == "1":+ return _run_anthropic_oauth_flow(save_env_value)+ if choice == "2":+ _say("", " Get an API key at: https://platform.claude.com/settings/keys", "")+ api_key = _ask(" API key (sk-ant-...): ", secret=True, cancel_msg="")+ if api_key is None:+ return False+ if not api_key:+ print(" Cancelled.")+ return False+ save_anthropic_api_key(api_key, save_fn=save_env_value)+ print(" ✓ API key saved.")+ return True+ print(" No change.")+ return False++def _model_flow_anthropic(config, current_model=""):"""Flow for Anthropic provider — OAuth subscription, API key, or Claude Code creds."""- from hermes_cli.main import _run_anthropic_oauth_flowfrom hermes_cli.auth import get_anthropic_key- from hermes_cli.config import save_env_value, save_anthropic_api_keyfrom hermes_cli.models import _PROVIDER_MODELS# Check ALL credential sources@@ -1057,8 +1107,8 @@ def _model_flow_anthropic(config, current_model=""):except Exception:pass- # Stale-OAuth guard: an expired OAuth token with no valid cc_creds fallback is- # treated as missing so the re-auth path is offered.+ # Stale-OAuth guard: an expired OAuth token with no valid cc_creds fallback is treated+ # as missing so the re-auth path is offered.existing_is_stale_oauth = bool(existing_key and _is_oauth_token(existing_key) and not cc_available)has_creds = (bool(existing_key) and not existing_is_stale_oauth) or cc_availableneeds_auth = not has_creds@@ -1068,8 +1118,7 @@ def _model_flow_anthropic(config, current_model=""):from hermes_cli.env_loader import format_secret_source_suffixfrom hermes_cli.auth import PROVIDER_REGISTRY- # Surface which env var supplied the key so Bitwarden users see- # "(from Bitwarden)" instead of a key indistinguishable from .env.+ # Surface which env var supplied the key so Bitwarden users see "(from Bitwarden)".source_suffix = ""for var in PROVIDER_REGISTRY["anthropic"].api_key_env_vars:if os.getenv(var, "").strip() == existing_key:@@ -1087,33 +1136,13 @@ def _model_flow_anthropic(config, current_model=""):return# "use" (default): proceed to model selection with existing creds- if needs_auth:- _say("", " Choose authentication method:", "", " 1. Claude Pro/Max subscription (OAuth login)",- " 2. Anthropic API key (pay-per-token)", " 3. Cancel", "")- choice = _ask(" Choice [1/2/3]: ", raw=True, cancel_msg="")- if choice is None:- return- if choice == "1":- if not _run_anthropic_oauth_flow(save_env_value):- return- elif choice == "2":- _say("", " Get an API key at: https://platform.claude.com/settings/keys", "")- api_key = _ask(" API key (sk-ant-...): ", secret=True, cancel_msg="")- if api_key is None:- return- if not api_key:- print(" Cancelled.")- return- save_anthropic_api_key(api_key, save_fn=save_env_value)- print(" ✓ API key saved.")- else:- print(" No change.")- return+ if needs_auth and not _anthropic_authenticate():+ returnprint()selected = _pick_model_or_prompt(_PROVIDER_MODELS.get("anthropic", []), "Model name (e.g., claude-sonnet-4-20250514): ",current_model=current_model, confirm_provider="anthropic")- # Clear base_url: resolve_runtime_provider() always hardcodes Anthropic's URL,- # and a stale value can contaminate other providers on a later switch.+ # Clear base_url: resolve_runtime_provider() always hardcodes Anthropic's URL, and a+ # stale value can contaminate other providers on a later switch._finish_model(selected, "anthropic", f"Default model set to: {selected} (via Anthropic)", drop_base_url=True, drop_api_mode=True)