Skip to content

The agent that grows with you

refactor(hermes_cli): azure flow — current-settings dataclass, transport-detection phase helper; squeeze import blanks

Teknium9f9401cf0548
diff --git a/hermes_cli/main_platform_setup.py b/hermes_cli/main_platform_setup.py
index b0891ebe173..a0d5014508d 100644
--- a/hermes_cli/main_platform_setup.py
+++ b/hermes_cli/main_platform_setup.py
@@ -99,7 +99,6 @@ def _whatsapp_allowed_users(wa_mode: str, get_env_value, save_env_value) -> None
def _whatsapp_install_bridge(bridge_dir) -> bool:
"""Step 4 of ``hermes whatsapp``: ``npm install`` the bridge when needed. False = stop."""
from hermes_constants import find_node_executable, with_hermes_node_path
-
if (bridge_dir / "node_modules").exists():
print("✓ Bridge dependencies already installed")
return True
@@ -131,7 +130,6 @@ def cmd_whatsapp(args):
_require_tty("whatsapp")
from hermes_cli.config import get_env_value, save_env_value
from hermes_constants import find_node_executable, with_hermes_node_path
-
_say("", "⚕ WhatsApp Setup", "=" * 50)
wa_mode = _whatsapp_choose_mode(get_env_value, save_env_value)
@@ -218,7 +216,6 @@ def cmd_whatsapp_cloud(args):
from hermes_cli.main import _require_tty
_require_tty("whatsapp-cloud")
from hermes_cli.setup_whatsapp_cloud import run_whatsapp_cloud_setup
-
return run_whatsapp_cloud_setup()
@@ -277,7 +274,6 @@ def _sync_propose(args, ssc) -> int:
def _sync_toggle(args, sub: str) -> int:
from tools.skill_usage import set_sync, is_curation_eligible
-
skill = args.skill
if not is_curation_eligible(skill):
_err(f"'{skill}' is not sync-eligible (bundled, hub-installed, "
@@ -291,7 +287,6 @@ def _sync_toggle(args, sub: str) -> int:
def _sync_status(ssc) -> int:
import json as _json
-
status = ssc.sync_status()
print(_json.dumps(status, indent=2, ensure_ascii=False))
if status.get("org_available"):
@@ -350,7 +345,6 @@ _SYNC_GATED = {
def cmd_sync(args):
"""Skill Sync — personal sync across devices, plus sharing with your org."""
import json as _json
-
sub = getattr(args, "sync_command", None)
if sub in {None, ""}:
_err(_SYNC_USAGE)
@@ -359,7 +353,6 @@ def cmd_sync(args):
return _sync_toggle(args, sub)
from tools import skills_sync_client as ssc
-
if sub == "device":
return _sync_device(args, ssc)
if sub == "propose":
@@ -409,7 +402,6 @@ def cmd_slack(args):
if sub == "manifest":
from hermes_cli.slack_cli import slack_manifest_command
-
status = slack_manifest_command(args)
if status:
raise SystemExit(status)
diff --git a/hermes_cli/main_provider_setup.py b/hermes_cli/main_provider_setup.py
index a301dc5e337..2637a8dafef 100644
--- a/hermes_cli/main_provider_setup.py
+++ b/hermes_cli/main_provider_setup.py
@@ -44,7 +44,6 @@ def _clear_stale_openai_base_url():
clients (compression, vision, delegation) to the old custom endpoint.
"""
from hermes_cli.config import get_env_value, save_env_value, load_config
-
model_cfg = load_config().get("model", {})
provider = (model_cfg.get("provider") or "").strip().lower() if isinstance(model_cfg, dict) else ""
if provider == "custom" or not provider:
@@ -144,7 +143,6 @@ def _save_aux_choice(task: str, *, provider: str, model: str = "", base_url: str
model config never modified). ``delegation`` writes the top-level section, with "auto"
stored as an empty provider."""
from hermes_cli.config import load_config, save_config
-
cfg = load_config()
if task == _DELEGATION_TASK_KEY:
entry = _ensure_dict_section(cfg, "delegation")
@@ -161,7 +159,6 @@ def _save_aux_choice(task: str, *, provider: str, model: str = "", base_url: str
def _reset_aux_to_auto() -> int:
"""Reset every known aux task (built-in + plugin) back to auto/empty. Returns number reset."""
from hermes_cli.config import load_config, save_config
-
cfg = load_config()
aux = _ensure_dict_section(cfg, "auxiliary")
count = 0
@@ -196,7 +193,6 @@ def _aux_config_menu() -> None:
"""Top-level auxiliary-model picker; loops until the user picks "Back"."""
from hermes_cli.main import _aux_select_for_task, _prompt_provider_choice
from hermes_cli.config import load_config
-
while True:
cfg = load_config()
_say("", " Auxiliary models — side-task routing", "",
@@ -240,7 +236,6 @@ def _aux_select_for_task(task: str) -> None:
from hermes_cli.main import _prompt_provider_choice
from hermes_cli.config import load_config
from hermes_cli.inventory import build_aux_picker_rows, format_aux_picker_entries
-
task_cfg = _aux_task_cfg(load_config(), task)
current_provider = str(task_cfg.get("provider") or "auto").strip() or "auto"
current_model = str(task_cfg.get("model") or "").strip()
@@ -285,7 +280,6 @@ def _aux_flow_provider_model(task: str, provider_slug: str, curated_models: list
"""Prompt for a model under an already-authenticated provider, save to aux."""
from hermes_cli.auth import _prompt_model_selection
from hermes_cli.models import get_pricing_for_provider
-
display_name = _aux_task_display_name(task)
try:
pricing = get_pricing_for_provider(provider_slug) or {}
@@ -370,7 +364,6 @@ def _prompt_provider_choice(choices, *, default=0, title="Select provider:"):
(piped stdin, non-TTY). Returns the selected index, or None if the user cancels."""
try:
from hermes_cli.setup import _curses_prompt_choice
-
idx = _curses_prompt_choice(title, choices, default)
if idx >= 0:
print()
@@ -409,7 +402,6 @@ _CUSTOM_API_MODE_ANSWERS = {answer: value for value, _, _, answers in _CUSTOM_AP
def _prompt_custom_api_mode_selection(base_url: str, current_api_mode: str = "") -> Optional[str]:
"""Prompt for a custom provider API mode: an explicit mode string, or None for auto-detect."""
from hermes_cli.runtime_provider import _detect_api_mode_for_url
-
detected_mode = _detect_api_mode_for_url(base_url)
default_mode = str(current_api_mode or "").strip().lower() or detected_mode or ""
@@ -437,7 +429,6 @@ def _auto_provider_name(base_url: str) -> str:
"""Display name from a custom endpoint URL, e.g. "Local (localhost:11434)" or
"RunPod (xyz.runpod.io)" — the default offered during custom endpoint setup."""
import re
-
name = re.sub(r"/v1/?$", "", _short_url(base_url)).split("/")[0]
if "localhost" in name or "127.0.0.1" in name:
return f"Local ({name})"
@@ -472,7 +463,6 @@ def _save_custom_provider(base_url, api_key="", model="", context_length=None, n
of inlining the secret.
"""
from hermes_cli.config import load_config, save_config
-
cfg = load_config()
providers = cfg.get("custom_providers") or []
if not isinstance(providers, list):
@@ -530,7 +520,6 @@ def _save_custom_provider(base_url, api_key="", model="", context_length=None, n
def _remove_custom_provider(config):
"""Let the user remove a saved custom provider from config.yaml."""
from hermes_cli.config import load_config, save_config
-
cfg = load_config()
providers = cfg.get("custom_providers") or []
if not isinstance(providers, list) or not providers:
@@ -546,7 +535,6 @@ def _remove_custom_provider(config):
try:
from hermes_cli.curses_ui import curses_radiolist
-
idx = curses_radiolist("Select provider to remove:", list(choices), selected=0, cancel_returns=-1)
print()
if idx < 0:
@@ -598,7 +586,6 @@ def _prompt_reasoning_effort_selection(efforts, current_effort=""):
n = len(ordered)
try:
from hermes_cli.curses_ui import curses_radiolist
-
choices = [_label(effort) for effort in ordered] + [disable_label, skip_label]
idx = curses_radiolist("Select reasoning effort:", choices, selected=default_idx, cancel_returns=-1)
if idx < 0:
@@ -626,7 +613,6 @@ def _prompt_api_key(pconfig, existing_key: str, provider_id: str = "", existing_
"""
from hermes_cli.auth import LMSTUDIO_NOAUTH_PLACEHOLDER
from hermes_cli.config import save_env_value
-
key_env = pconfig.api_key_env_vars[0] if pconfig.api_key_env_vars else ""
def _prompt_new_key(*, allow_lmstudio_default: bool) -> str:
@@ -656,7 +642,6 @@ def _prompt_api_key(pconfig, existing_key: str, provider_id: str = "", existing_
# Already configured — offer K / R / C
from hermes_cli.env_loader import format_secret_source_suffix
-
source_suffix = format_secret_source_suffix(key_env) if key_env else ""
print(f" {pconfig.name} API key: {existing_key[:8]}... ✓{source_suffix}")
if not key_env:
@@ -691,7 +676,6 @@ def _infer_stepfun_region(base_url: str) -> str:
def _stepfun_base_url_for_region(region: str) -> str:
from hermes_cli.auth import STEPFUN_STEP_PLAN_CN_BASE_URL, STEPFUN_STEP_PLAN_INTL_BASE_URL
-
return STEPFUN_STEP_PLAN_CN_BASE_URL if region == "china" else STEPFUN_STEP_PLAN_INTL_BASE_URL
@@ -709,7 +693,6 @@ def _run_anthropic_oauth_flow(save_env_value):
use_anthropic_claude_code_credentials(save_fn=save_env_value)
print(" ✓ Claude Code credentials linked.")
from hermes_constants import display_hermes_home as _dhh_fn
-
print(f" Hermes will use Claude's credential store directly instead of copying a setup-token into {_dhh_fn()}/.env.")
return True
return False
@@ -848,7 +831,6 @@ def _build_provider_picker_rows(config: dict, active: str, provider_labels: dict
gateway/TUI pickers.
"""
from hermes_cli.models import CANONICAL_PROVIDERS, _PROVIDER_ALIASES, group_providers, provider_group_for_slug
-
canonical_descs = {p.slug: p.tui_desc for p in CANONICAL_PROVIDERS}
_cli_excluded = {
str(p).strip().lower()
diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.py
index 964b4e6d6a9..82f9109ee15 100644
--- a/hermes_cli/model_setup_flows.py
+++ b/hermes_cli/model_setup_flows.py
@@ -52,7 +52,6 @@ from hermes_cli.model_setup_flows_bedrock import ( # noqa: F401
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, "")
@@ -61,7 +60,6 @@ def _env_base_url(base_url_env: str) -> str:
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):
@@ -90,7 +88,6 @@ def _model_flow_openrouter(config, current_model=""):
return
from hermes_cli.models import model_ids, get_pricing_for_provider
-
openrouter_models = model_ids(force_refresh=True)
# Live pricing is non-blocking — empty dict on failure.
pricing = get_pricing_for_provider("openrouter", force_refresh=True)
@@ -107,7 +104,6 @@ def _model_flow_ai_gateway(config, current_model=""):
from hermes_cli.main import _prompt_api_key
from hermes_cli.auth import PROVIDER_REGISTRY, _prompt_model_selection
from hermes_cli.config import get_env_value
-
pconfig = PROVIDER_REGISTRY["ai-gateway"]
existing_key = get_env_value("AI_GATEWAY_API_KEY") or ""
if not existing_key:
@@ -118,7 +114,6 @@ def _model_flow_ai_gateway(config, current_model=""):
return
from hermes_cli.models import ai_gateway_model_ids, get_pricing_for_provider
-
models_list = ai_gateway_model_ids(force_refresh=True)
pricing = get_pricing_for_provider("ai-gateway", force_refresh=True)
selected = _prompt_model_selection(models_list, current_model=current_model, pricing=pricing)
@@ -135,7 +130,6 @@ def _model_flow_moa(config, current_model=""):
"""
from hermes_cli.auth import _save_model_choice
from hermes_cli.moa_config import normalize_moa_config
-
moa = normalize_moa_config(config.get("moa") if isinstance(config, dict) else {})
presets = moa.get("presets") or {}
if not presets:
@@ -218,7 +212,6 @@ def _nous_model_catalog(free_tier: bool, portal_url: str, model_ids: list, prici
if free_tier:
try:
from hermes_cli.nous_account import format_nous_portal_entitlement_message, get_nous_portal_account_info
-
_account_info = get_nous_portal_account_info(force_fresh=True)
unavailable_message = format_nous_portal_entitlement_message(_account_info, capability="paid Nous models") or ""
except Exception:
@@ -239,7 +232,6 @@ def _nous_model_catalog(free_tier: bool, portal_url: str, model_ids: list, prici
print("No free models currently available.")
if unavailable_models:
from hermes_cli.auth import DEFAULT_NOUS_PORTAL_URL
-
_url = (portal_url or DEFAULT_NOUS_PORTAL_URL).rstrip("/")
print(unavailable_message or f"Upgrade at {_url} to access paid models.")
return None
@@ -275,7 +267,6 @@ def _nous_persist_selection(selected: str, creds: dict) -> dict:
OPENAI_BASE_URL / OPENAI_API_KEY. Returns the saved config."""
from hermes_cli.auth import _save_model_choice, _update_config_for_provider
from 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)
@@ -307,7 +298,6 @@ def _model_flow_nous(config, current_model="", args=None):
from hermes_cli.auth import get_provider_auth_state, _prompt_model_selection, _login_nous, PROVIDER_REGISTRY
from hermes_cli.config import load_config
from hermes_cli.nous_subscription import prompt_enable_tool_gateway
-
state = get_provider_auth_state("nous")
if not state or not state.get("access_token"):
_say("Not logged into Nous Portal. Starting login...", "")
@@ -327,7 +317,6 @@ def _model_flow_nous(config, current_model="", args=None):
# 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_provider
-
model_ids = get_curated_nous_model_ids()
if not model_ids:
print("No curated models available for Nous Portal.")
@@ -343,7 +332,6 @@ def _model_flow_nous(config, current_model="", args=None):
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 creds
except Exception:
@@ -365,7 +353,6 @@ def _model_flow_nous(config, current_model="", args=None):
model_ids, pricing, unavailable_models, unavailable_message, _policy_narrowed = catalog
from hermes_cli.nous_account import nous_policy_notice
-
_policy_notice = nous_policy_notice(removed=_policy_narrowed)
if _policy_notice:
print(_policy_notice)
@@ -390,7 +377,6 @@ def _model_flow_openai_codex(config, current_model=""):
get_codex_auth_status, _prompt_model_selection, _login_openai_codex, PROVIDER_REGISTRY, DEFAULT_CODEX_BASE_URL,
)
from hermes_cli.codex_models import get_codex_model_ids
-
if not _oauth_gate(
bool(get_codex_auth_status().get("logged_in")), "OpenAI Codex", _login_openai_codex, argparse.Namespace(),
PROVIDER_REGISTRY["openai-codex"], recheck=lambda: get_codex_auth_status().get("logged_in"),
@@ -409,7 +395,6 @@ def _model_flow_openai_codex(config, current_model=""):
if not _codex_token:
try:
from hermes_cli.auth import resolve_codex_runtime_credentials
-
_codex_token = resolve_codex_runtime_credentials().get("api_key")
except Exception:
pass
@@ -428,7 +413,6 @@ def _model_flow_xai_oauth(_config, current_model="", *, args=None):
get_xai_oauth_auth_status, _prompt_model_selection, resolve_xai_oauth_runtime_credentials, _login_xai_oauth,
DEFAULT_XAI_OAUTH_BASE_URL, PROVIDER_REGISTRY)
from hermes_cli.models import provider_model_ids
-
login_args = argparse.Namespace(no_browser=bool(getattr(args, "no_browser", False)), timeout=getattr(args, "timeout", None))
if not _oauth_gate(
bool(get_xai_oauth_auth_status().get("logged_in")), "xAI Grok OAuth (SuperGrok / Premium+)", _login_xai_oauth,
@@ -458,7 +442,6 @@ def _model_flow_qwen_oauth(_config, current_model=""):
get_qwen_auth_status, resolve_qwen_runtime_credentials, _prompt_model_selection, DEFAULT_QWEN_BASE_URL,
)
from hermes_cli.models import fetch_api_models
-
status = get_qwen_auth_status()
if not status.get("logged_in"):
_say("Not logged into Qwen CLI OAuth.", "Run: qwen auth qwen-oauth")
@@ -505,7 +488,6 @@ def _model_flow_minimax_oauth(config, current_model="", args=None):
return
from hermes_cli.models import _PROVIDER_MODELS
-
model_ids = _PROVIDER_MODELS.get("minimax-oauth", [])
selected = _prompt_model_selection(model_ids, current_model, confirm_provider="minimax-oauth", confirm_base_url=creds["base_url"])
_activate_provider_model(selected, "minimax-oauth", creds["base_url"], f"\u2713 Using MiniMax model: {selected}", no_change=None)
@@ -514,7 +496,6 @@ def _model_flow_minimax_oauth(config, current_model="", args=None):
def _copilot_model_list(live_ids) -> list:
"""Live GitHub Copilot ids, or the curated fallback with a warning."""
from hermes_cli.models import _PROVIDER_MODELS
-
if live_ids:
model_list = [model_id for model_id in live_ids if model_id]
print(f" Found {len(model_list)} model(s) from GitHub Copilot")
@@ -530,7 +511,6 @@ 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 []
@@ -543,7 +523,6 @@ def _copilot_catalog(api_key: str):
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
-
_say("No GitHub token configured for GitHub Copilot.", "", " Supported token types:",
" → OAuth token (gho_*) via `copilot login` or device code flow",
" → Fine-grained PAT (github_pat_*) with Copilot Requests permission",
@@ -556,7 +535,6 @@ def _copilot_obtain_token() -> bool:
if choice == "1":
try:
from hermes_cli.copilot_auth import copilot_device_code_login
-
token = copilot_device_code_login()
if not token:
print(" Login cancelled or failed.")
@@ -577,7 +555,6 @@ def _copilot_obtain_token() -> bool:
# Validate token type
try:
from hermes_cli.copilot_auth import validate_copilot_token
-
valid, msg = validate_copilot_token(new_key)
if not valid:
print(f" ✗ {msg}")
@@ -598,7 +575,6 @@ def _model_flow_copilot(config, current_model=""):
from hermes_cli.auth import PROVIDER_REGISTRY, resolve_api_key_provider_credentials
from hermes_cli.config import load_config
from hermes_cli.models import fetch_api_models, github_model_reasoning_efforts, copilot_model_api_mode
-
provider_id = "copilot"
pconfig = PROVIDER_REGISTRY[provider_id]
creds = resolve_api_key_provider_credentials(provider_id)
@@ -612,7 +588,6 @@ def _model_flow_copilot(config, current_model=""):
else:
if source in {"GITHUB_TOKEN", "GH_TOKEN"}:
from hermes_cli.env_loader import format_secret_source_suffix
-
print(f" GitHub token: {api_key[:8]}... ✓ ({source}{format_secret_source_suffix(source)})")
elif source == "gh auth token":
print(" GitHub token: ✓ (from `gh auth token`)")
@@ -698,7 +673,6 @@ def _model_flow_kimi(config, current_model=""):
from hermes_cli.auth import PROVIDER_REGISTRY, KIMI_CODE_BASE_URL
from hermes_cli.config import get_env_value, save_env_value
from hermes_cli.models import _PROVIDER_MODELS
-
provider_id = "kimi-coding"
pconfig = PROVIDER_REGISTRY[provider_id]
base_url_env = pconfig.base_url_env_var or ""
@@ -734,7 +708,6 @@ def _model_flow_stepfun(config, current_model=""):
from hermes_cli.auth import PROVIDER_REGISTRY
from hermes_cli.config import save_env_value
from hermes_cli.models import _PROVIDER_MODELS, fetch_api_models
-
provider_id = "stepfun"
pconfig = PROVIDER_REGISTRY[provider_id]
base_url_env = pconfig.base_url_env_var or ""
@@ -847,7 +820,6 @@ def _select_zai_endpoint(current_base: str) -> str:
*current_base* on cancel/error."""
from hermes_cli.main import _prompt_provider_choice
from hermes_cli.auth import ZAI_ENDPOINTS
-
options = [(label, url) for _, url, _, label in ZAI_ENDPOINTS]
normalized_current = (current_base or "").strip().rstrip("/")
@@ -903,7 +875,6 @@ 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:
@@ -917,7 +888,6 @@ 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
@@ -934,7 +904,6 @@ def _opencode_free_models(pconfig, curated, api_key, base_url):
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")
@@ -964,7 +933,6 @@ def _api_key_provider_model_list(provider_id: str, pconfig, existing_key: str, k
"""
from hermes_cli.config import get_env_value
from hermes_cli.models import _PROVIDER_MODELS, fetch_api_models
-
curated = _PROVIDER_MODELS.get(provider_id, [])
api_key_for_probe = existing_key or (get_env_value(key_env) if key_env else "")
@@ -994,7 +962,6 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):
from hermes_cli.auth import PROVIDER_REGISTRY
from hermes_cli.config import save_env_value, load_config
from hermes_cli.models import opencode_model_api_mode, normalize_opencode_model_id
-
pconfig = PROVIDER_REGISTRY[provider_id]
key_env = pconfig.api_key_env_vars[0] if pconfig.api_key_env_vars else ""
base_url_env = pconfig.base_url_env_var or ""
@@ -1047,7 +1014,6 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):
if model_list:
try:
from hermes_cli.models import get_pricing_for_provider
-
pricing = get_pricing_for_provider(provider_id) or {}
except Exception:
pricing = {}
@@ -1067,7 +1033,6 @@ 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="")
@@ -1100,7 +1065,6 @@ def _model_flow_anthropic(config, current_model=""):
cc_available = False
try:
from agent.anthropic_adapter import read_claude_code_credentials, is_claude_code_token_valid, _is_oauth_token
-
cc_creds = read_claude_code_credentials()
if cc_creds and is_claude_code_token_valid(cc_creds):
cc_available = True
diff --git a/hermes_cli/model_setup_flows_azure.py b/hermes_cli/model_setup_flows_azure.py
index f988be9806d..beaa6893199 100644
--- a/hermes_cli/model_setup_flows_azure.py
+++ b/hermes_cli/model_setup_flows_azure.py
@@ -6,6 +6,8 @@ Prompt strings and config write order are behavior.
from __future__ import annotations
+from dataclasses import dataclass, field
+
from hermes_cli.config import clear_model_endpoint_credentials
from hermes_cli.model_setup_flows_common import _HTTP, _ask, _commit_model_config, _load_config_model_section, _say
@@ -14,14 +16,38 @@ def _azure_mode_label(mode: str) -> str:
return "OpenAI-style" if mode == "chat_completions" else "Anthropic-style"
+@dataclass
+class _AzureCurrent:
+ """The active Azure Foundry settings shown as prompt defaults."""
+ base_url: str = ""
+ api_mode: str = ""
+ auth_mode: str = "api_key"
+ entra: dict = field(default_factory=dict)
+ api_key: str = ""
+
+
+def _azure_current(config) -> _AzureCurrent:
+ from hermes_cli.config import get_env_value
+
+ cur = _AzureCurrent(api_key=get_env_value("AZURE_FOUNDRY_API_KEY") or "")
+ model_cfg = config.get("model", {})
+ if isinstance(model_cfg, dict) and model_cfg.get("provider") == "azure-foundry":
+ cur.base_url = str(model_cfg.get("base_url", "") or "")
+ cur.api_mode = str(model_cfg.get("api_mode", "") or "")
+ cur.auth_mode = str(model_cfg.get("auth_mode") or "api_key").strip().lower() or "api_key"
+ _cur_entra = model_cfg.get("entra") or {}
+ cur.entra = _cur_entra if isinstance(_cur_entra, dict) else {}
+ return cur
+
+
def _azure_entra_preflight(current_entra: dict):
- """Entra ID credential preflight for the Azure flow. Returns
- ``(token_provider, entra_overrides)``; ``None`` when the user cancelled;
- ``False`` when the adapter is missing (caller falls back to API-key auth)."""
+ """Entra ID credential preflight. Returns ``(token_provider, entra_overrides)``; ``None``
+ when the user cancelled; ``False`` when the adapter is missing (fall back to API key)."""
try:
from agent.azure_identity_adapter import (
EntraIdentityConfig, SCOPE_AI_AZURE_DEFAULT, build_token_provider, describe_active_credential,
- has_azure_identity_installed)
+ has_azure_identity_installed,
+ )
except ImportError as exc:
_say("", f"⚠ Could not import azure-identity adapter: {exc}", " Falling back to API key auth.")
return False
@@ -60,8 +86,8 @@ def _azure_entra_preflight(current_entra: dict):
print("Cancelled.")
return None
- # Best-effort token provider for the detection probe; on failure the probe
- # falls back to manual entry.
+ # Best-effort token provider for the detection probe; on failure the probe falls back
+ # to manual entry.
try:
token_provider = build_token_provider(config=_config)
except Exception as exc:
@@ -91,58 +117,72 @@ def _azure_pick_model(discovered_models: list, current_model: str):
return pick
+def _azure_detect_transport(effective_url: str, effective_key: str, token_provider, current_api_mode: str):
+ """Probe the endpoint; returns ``(api_mode, discovered_models)`` (manual pick of the API
+ format when detection is incomplete) or None when cancelled."""
+ from hermes_cli import azure_detect
+
+ _say("", "◐ Probing endpoint to auto-detect transport and models...")
+ detection = azure_detect.detect(effective_url, api_key=effective_key, token_provider=token_provider)
+ discovered_models: list[str] = list(detection.models)
+ api_mode: str = detection.api_mode or ""
+ if api_mode:
+ print(f"✓ Detected API transport: {_azure_mode_label(api_mode)}")
+ if detection.reason:
+ print(f" ({detection.reason})")
+ if discovered_models:
+ print(f"✓ Found {len(discovered_models)} deployed model(s) on this endpoint")
+ return api_mode, discovered_models
+ _say(f"⚠ Auto-detection incomplete: {detection.reason}", "",
+ "Select the API format your Azure Foundry endpoint uses:",
+ " 1. OpenAI-style (POST /v1/chat/completions)",
+ " For: GPT models, Llama, Mistral, and most open models",
+ " 2. Anthropic-style (POST /v1/messages)",
+ " For: Claude models deployed via Anthropic API format")
+ default_choice = "2" if current_api_mode == "anthropic_messages" else "1"
+ mode_choice = _ask(f"API format [1/2] ({default_choice}): ", raw=True)
+ if mode_choice is None:
+ return None
+ return ("anthropic_messages" if (mode_choice or default_choice) == "2" else "chat_completions"), discovered_models
+
+
def _model_flow_azure_foundry(config, current_model=""):
"""Azure Foundry provider: configure endpoint, auth mode, API mode, and model.
- Two transports (OpenAI-style ``/v1/chat/completions``, Anthropic-style
- ``/v1/messages``) and two auth modes: **API key** (``AZURE_FOUNDRY_API_KEY``) or
- **Microsoft Entra ID** (keyless RBAC via ``azure-identity``; the same ``Azure AI
- User`` role covers both transports — OpenAI SDK takes a callable ``api_key``,
- Anthropic gets a bearer-injecting ``httpx.Client`` from
- :func:`agent.azure_identity_adapter.build_bearer_http_client`).
-
- Detection order: ``/anthropic`` URL suffix → Anthropic; ``GET <base>/models``
- success → OpenAI-style + model picker; Anthropic Messages probe; manual entry.
- Context length resolves via :func:`agent.model_metadata.get_model_context_length`.
+ Two transports (OpenAI-style ``/v1/chat/completions``, Anthropic-style ``/v1/messages``)
+ and two auth modes: **API key** (``AZURE_FOUNDRY_API_KEY``) or **Microsoft Entra ID**
+ (keyless RBAC via ``azure-identity``; the same ``Azure AI User`` role covers both
+ transports). Detection order: ``/anthropic`` URL suffix → Anthropic; ``GET <base>/models``
+ success → OpenAI-style + model picker; Anthropic Messages probe; manual entry. Context
+ length resolves via :func:`agent.model_metadata.get_model_context_length`.
"""
from hermes_cli.config import get_env_value, save_env_value
from hermes_cli import azure_detect
- # ── Load current Azure Foundry configuration ─────────────────────
- model_cfg = config.get("model", {})
- current_base_url = current_api_mode = ""
- current_auth_mode, current_entra = "api_key", {}
- if isinstance(model_cfg, dict) and model_cfg.get("provider") == "azure-foundry":
- current_base_url = str(model_cfg.get("base_url", "") or "")
- current_api_mode = str(model_cfg.get("api_mode", "") or "")
- current_auth_mode = str(model_cfg.get("auth_mode") or "api_key").strip().lower() or "api_key"
- _cur_entra = model_cfg.get("entra") or {}
- current_entra = _cur_entra if isinstance(_cur_entra, dict) else {}
- current_api_key = get_env_value("AZURE_FOUNDRY_API_KEY") or ""
-
+ cur = _azure_current(config)
_say("", "Azure Foundry Configuration", "=" * 50, "",
"Azure Foundry can host models with either OpenAI-style or",
"Anthropic-style API endpoints. Hermes will probe your",
"endpoint to auto-detect the transport and the deployed",
"models when possible.", "")
- if current_base_url:
- print(f" Current endpoint: {current_base_url}")
- if current_api_mode:
- print(f" Current API mode: {_azure_mode_label(current_api_mode)}")
- if current_auth_mode == "entra_id":
+ if cur.base_url:
+ print(f" Current endpoint: {cur.base_url}")
+ if cur.api_mode:
+ print(f" Current API mode: {_azure_mode_label(cur.api_mode)}")
+ if cur.auth_mode == "entra_id":
print(" Current auth mode: Microsoft Entra ID (keyless)")
- elif current_api_key:
- print(f" Current auth mode: API key ({current_api_key[:8]}...)")
+ elif cur.api_key:
+ print(f" Current auth mode: API key ({cur.api_key[:8]}...)")
print()
- # ── Step 1: endpoint URL ─────────────────────────────────────────
- _placeholder = current_base_url or (
+ # Step 1: endpoint URL
+ _placeholder = cur.base_url or (
"e.g. https://<resource>.openai.azure.com/openai/v1 or https://<resource>.services.ai.azure.com/anthropic"
)
base_url = _ask(f"API endpoint URL [{_placeholder}]: ")
if base_url is None:
return
- effective_url = (base_url or current_base_url).rstrip("/")
+ effective_url = (base_url or cur.base_url).rstrip("/")
if not effective_url:
print("No endpoint URL provided. Cancelled.")
return
@@ -150,23 +190,23 @@ def _model_flow_azure_foundry(config, current_model=""):
print(f"Invalid URL: {effective_url} (must start with http:// or https://)")
return
- # ── Step 2: authentication mode ──────────────────────────────────
+ # Step 2: authentication mode
_say("", "Authentication:", " 1. API key (AZURE_FOUNDRY_API_KEY in .env)",
" 2. Microsoft Entra ID (managed identity / workload identity / az login)",
" Recommended by Microsoft. Works for both OpenAI-style and Anthropic-style endpoints.",
" Requires the 'Azure AI User' role on the Foundry resource.")
- _auth_default = "2" if current_auth_mode == "entra_id" else "1"
+ _auth_default = "2" if cur.auth_mode == "entra_id" else "1"
auth_choice = _ask(f"Authentication mode [1/2] ({_auth_default}): ", raw=True)
if auth_choice is None:
return
use_entra = (auth_choice or _auth_default) == "2"
- # ── Step 3: credentials (key OR Entra preflight) ─────────────────
+ # Step 3: credentials (key OR Entra preflight)
effective_key: str = ""
entra_overrides: dict = {}
token_provider = None # callable when entra
if use_entra:
- preflight = _azure_entra_preflight(current_entra)
+ preflight = _azure_entra_preflight(cur.entra)
if preflight is None:
return
if preflight is False:
@@ -175,39 +215,21 @@ def _model_flow_azure_foundry(config, current_model=""):
token_provider, entra_overrides = preflight
if not use_entra:
print()
- api_key = _ask(f"API key [{current_api_key[:8] + '...' if current_api_key else 'required'}]: ", secret=True)
+ api_key = _ask(f"API key [{cur.api_key[:8] + '...' if cur.api_key else 'required'}]: ", secret=True)
if api_key is None:
return
- effective_key = api_key or current_api_key
+ effective_key = api_key or cur.api_key
if not effective_key:
print("No API key provided. Cancelled.")
return
- # ── Step 4: auto-detect transport + models ───────────────────────
- _say("", "◐ Probing endpoint to auto-detect transport and models...")
- detection = azure_detect.detect(effective_url, api_key=effective_key, token_provider=token_provider)
- discovered_models: list[str] = list(detection.models)
- api_mode: str = detection.api_mode or ""
- if api_mode:
- print(f"✓ Detected API transport: {_azure_mode_label(api_mode)}")
- if detection.reason:
- print(f" ({detection.reason})")
- if discovered_models:
- print(f"✓ Found {len(discovered_models)} deployed model(s) on this endpoint")
- else:
- _say(f"⚠ Auto-detection incomplete: {detection.reason}", "",
- "Select the API format your Azure Foundry endpoint uses:",
- " 1. OpenAI-style (POST /v1/chat/completions)",
- " For: GPT models, Llama, Mistral, and most open models",
- " 2. Anthropic-style (POST /v1/messages)",
- " For: Claude models deployed via Anthropic API format")
- default_choice = "2" if current_api_mode == "anthropic_messages" else "1"
- mode_choice = _ask(f"API format [1/2] ({default_choice}): ", raw=True)
- if mode_choice is None:
- return
- api_mode = "anthropic_messages" if (mode_choice or default_choice) == "2" else "chat_completions"
+ # Step 4: auto-detect transport + models
+ detected = _azure_detect_transport(effective_url, effective_key, token_provider, cur.api_mode)
+ if detected is None:
+ return
+ api_mode, discovered_models = detected
- # ── Step 5: model name ───────────────────────────────────────────
+ # Step 5: model name
print()
effective_model = _azure_pick_model(discovered_models, current_model)
if effective_model is None:
@@ -216,10 +238,10 @@ def _model_flow_azure_foundry(config, current_model=""):
print("No model name provided. Cancelled.")
return
- # ── Step 6: context-length lookup ────────────────────────────────
+ # Step 6: context-length lookup
ctx_len = azure_detect.lookup_context_length(effective_model, effective_url, api_key=effective_key, token_provider=token_provider)
- # ── Step 7: persist ──────────────────────────────────────────────
+ # Step 7: persist
if not use_entra:
save_env_value("AZURE_FOUNDRY_API_KEY", effective_key)
cfg, model = _load_config_model_section()
@@ -240,8 +262,7 @@ def _model_flow_azure_foundry(config, current_model=""):
_commit_model_config(cfg)
config["model"] = dict(model)
- # Clear conflicting env vars so auxiliary clients don't pick up a stale
- # OpenAI base URL / key.
+ # Clear conflicting env vars so auxiliary clients don't pick up a stale OpenAI base URL / key.
for var in ("OPENAI_BASE_URL", "OPENAI_API_KEY"):
if get_env_value(var):
save_env_value(var, "")
diff --git a/hermes_cli/model_setup_flows_bedrock.py b/hermes_cli/model_setup_flows_bedrock.py
index b7d2a031557..3b0f5705ee5 100644
--- a/hermes_cli/model_setup_flows_bedrock.py
+++ b/hermes_cli/model_setup_flows_bedrock.py
@@ -56,7 +56,6 @@ def _model_flow_bedrock_api_key(config, region, current_model=""):
from hermes_cli.auth import _resolve_api_key_provider_secret, ProviderConfig
from hermes_cli.config import save_env_value
from hermes_cli.models import _PROVIDER_MODELS
-
mantle_base_url = f"https://bedrock-mantle.{region}.api.aws/v1"
# Check env var and credential pool (keys added via `hermes auth`)
@@ -64,7 +63,6 @@ def _model_flow_bedrock_api_key(config, region, current_model=""):
existing_key, existing_source = _resolve_api_key_provider_secret("bedrock", bedrock_pconfig)
if existing_key:
from hermes_cli.env_loader import format_secret_source_suffix
-
source_suffix = format_secret_source_suffix(existing_source or "AWS_BEARER_TOKEN_BEDROCK")
print(f" Bedrock API Key: {existing_key[:12]}... ✓{source_suffix}")
else:
diff --git a/hermes_cli/model_setup_flows_common.py b/hermes_cli/model_setup_flows_common.py
index fc6ff897316..c58f0a46c28 100644
--- a/hermes_cli/model_setup_flows_common.py
+++ b/hermes_cli/model_setup_flows_common.py
@@ -42,7 +42,6 @@ def _ask(prompt: str, *, secret: bool = False, raw: bool = False, cancel_msg: st
def _existing_api_key_for_model_flow(provider_id: str, pconfig) -> tuple[str, str]:
"""Resolve an existing wizard credential without changing its storage."""
from hermes_cli.auth import _resolve_api_key_provider_secret
-
return _resolve_api_key_provider_secret(provider_id, pconfig)
@@ -53,7 +52,6 @@ def _ensure_flow_api_key(provider_id: str, pconfig, *, missing_hint=()) -> tuple
Returns ``(existing_key, resolved_key, abort)``.
"""
from hermes_cli.main import _prompt_api_key
-
existing_key, existing_source = _existing_api_key_for_model_flow(provider_id, pconfig)
if not existing_key:
for line in missing_hint:
@@ -65,7 +63,6 @@ def _ensure_flow_api_key(provider_id: str, pconfig, *, missing_hint=()) -> tuple
def _load_config_model_section() -> tuple[dict, dict]:
"""Return ``(cfg, cfg["model"])`` with the model section coerced to a dict."""
from hermes_cli.config import load_config
-
cfg = load_config()
model = cfg.get("model")
if not isinstance(model, dict):
@@ -78,7 +75,6 @@ def _begin_model_config(selected: str, provider: str) -> tuple[dict, dict]:
"""Record *selected* as the model choice and open the config model section
with ``provider`` set; callers set endpoint fields then ``_commit_model_config``."""
from hermes_cli.auth import _save_model_choice
-
_save_model_choice(selected)
cfg, model = _load_config_model_section()
model["provider"] = provider
@@ -89,7 +85,6 @@ def _commit_model_config(cfg: dict) -> None:
"""Persist *cfg* and deactivate any OAuth provider."""
from hermes_cli.auth import deactivate_provider
from hermes_cli.config import save_config
-
save_config(cfg)
deactivate_provider()
@@ -134,7 +129,6 @@ def _activate_provider_model(selected, provider_id: str, base_url: str, done: st
"""OAuth-provider persist: model choice + ``_update_config_for_provider`` (which owns
the auth-state bookkeeping), then *done*; *no_change* (``None`` = silent) otherwise."""
from hermes_cli.auth import _save_model_choice, _update_config_for_provider
-
if not selected:
if no_change is not None:
print(no_change)
@@ -157,7 +151,6 @@ def _pick_model_or_prompt(model_list, prompt: str, **kwargs):
"""Radio picker when *model_list* is non-empty, else a free-text ``line_input``
(None on Ctrl-C/EOF)."""
from hermes_cli.auth import _prompt_model_selection
-
if model_list:
return _prompt_model_selection(model_list, **kwargs)
return _ask(prompt, cancel_msg=None)
@@ -204,7 +197,6 @@ def _models_dev_merged(provider_id: str, curated) -> list:
mdev_models: list = []
try:
from agent.models_dev import list_agentic_models
-
mdev_models = list_agentic_models(provider_id)
except Exception:
pass
@@ -269,7 +261,6 @@ def _curses_choice(title: str, rows: list, default_idx: int):
non-TTY) so the caller can fall back to a numbered prompt."""
try:
from hermes_cli.setup import _curses_prompt_choice
-
return _curses_prompt_choice(title, rows, default_idx)
except Exception:
return None
diff --git a/hermes_cli/model_setup_flows_custom.py b/hermes_cli/model_setup_flows_custom.py
index b4096b3fc34..98fc979082c 100644
--- a/hermes_cli/model_setup_flows_custom.py
+++ b/hermes_cli/model_setup_flows_custom.py
@@ -34,7 +34,6 @@ def _probe_custom_endpoint(effective_key: str, effective_url: str) -> tuple[dict
"""Verify a custom endpoint via ``probe_api_models`` and report; returns
``(probe, effective_url)`` where the URL may be the working fallback base."""
from hermes_cli.models import probe_api_models
-
probe = probe_api_models(effective_key, effective_url)
if probe.get("used_fallback") and probe.get("resolved_base_url"):
print(f"Warning: endpoint verification worked at {probe['resolved_base_url']}/models, "
@@ -82,7 +81,6 @@ def _model_flow_custom(config):
from hermes_cli.auth import _save_model_choice, deactivate_provider
from hermes_cli.config import custom_endpoint_key_env, get_env_value, save_env_value
from hermes_cli.secret_prompt import masked_secret_prompt
-
current_url = get_env_value("OPENAI_BASE_URL") or ""
current_key = get_env_value("OPENAI_API_KEY") or ""
@@ -256,7 +254,6 @@ def _discover_named_custom_models(provider_info: dict, api_key: str, configured_
if live_models:
try:
from hermes_cli.model_switch import _save_discovered_models_to_config
-
_save_discovered_models_to_config(base_url, live_models, api_mode=api_mode, headers=extra_headers or None)
except Exception:
pass
@@ -269,7 +266,6 @@ def _pick_named_custom_model(name: str, models: list, saved_model: str):
print(f"Found {len(models)} model(s):\n")
try:
from hermes_cli.curses_ui import curses_radiolist
-
menu_items = [f"{m} (current)" if m == saved_model else m for m in models] + ["Cancel"]
idx = curses_radiolist(f"Select model from {name}:", menu_items, selected=default_idx, cancel_returns=-1, searchable=True)
print()
@@ -303,7 +299,6 @@ def _model_flow_named_custom(config, provider_info):
from hermes_cli.auth import _save_model_choice
from hermes_cli.config import load_config, save_config
from hermes_cli.model_switch import _entry_models_discovered, _models_config_is_allowlist
-
name = provider_info["name"]
base_url = provider_info["base_url"]
api_mode = provider_info.get("api_mode", "")