Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/bermudalocals_hermes-agent-lite.json

1 line
183 KiB
JSON
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{"repo": "bermudalocals/hermes-agent-lite", "files": {"hermes_cli/auth.py": {"160ae748d243940671329e425cc67a3f82c2a2a0": {"t": 1785595312.5518577, "n": 166839, "h": "596f619153f60470", "c": "\"\"\"\nMulti-provider authentication system for Hermes Agent.\n\nSupports OAuth device code flows (Nous Portal, future: OpenAI Codex) and\ntraditional API key providers (OpenRouter, custom endpoints). Auth state\nis persisted in ~/.hermes/auth.json with cross-process file locking.\n\nArchitecture:\n- ProviderConfig registry defines known OAuth providers\n- Auth store (auth.json) holds per-provider credential state\n- resolve_provider() picks the active provider via priority chain\n- resolve_*_runtime_credentials() handles token refresh and key minting\n- logout_command() is the CLI entry point for clearing auth\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport logging\nimport os\nimport shutil\nimport shlex\nimport ssl\nimport stat\nimport sys\nimport base64\nimport hashlib\nimport subprocess\nimport threading\nimport time\nimport uuid\nimport webbrowser\nfrom contextlib import contextmanager\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timezone\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional\nfrom urllib.parse import parse_qs, urlencode, urlparse\n\nimport httpx\nimport yaml\n\nfrom hermes_cli.config import get_hermes_home, get_config_path, read_raw_config\nfrom hermes_constants import OPENROUTER_BASE_URL\n\nlogger = logging.getLogger(__name__)\n\ntry:\n import fcntl\nexcept Exception:\n fcntl = None\ntry:\n import msvcrt\nexcept Exception:\n msvcrt = None\n\n# =============================================================================\n# Constants\n# =============================================================================\n\nAUTH_STORE_VERSION = 1\nAUTH_LOCK_TIMEOUT_SECONDS = 15.0\n\n# Nous Portal defaults\nDEFAULT_NOUS_PORTAL_URL = \"https://portal.nousresearch.com\"\nDEFAULT_NOUS_INFERENCE_URL = \"https://inference-api.nousresearch.com/v1\"\nDEFAULT_NOUS_CLIENT_ID = \"hermes-cli\"\nDEFAULT_NOUS_SCOPE = \"inference:mint_agent_key\"\nDEFAULT_AGENT_KEY_MIN_TTL_SECONDS = 30 * 60 # 30 minutes\nACCESS_TOKEN_REFRESH_SKEW_SECONDS = 120 # refresh 2 min before expiry\nDEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS = 1 # poll at most every 1s\nDEFAULT_CODEX_BASE_URL = \"https://chatgpt.com/backend-api/codex\"\nDEFAULT_QWEN_BASE_URL = \"https://portal.qwen.ai/v1\"\nDEFAULT_GITHUB_MODELS_BASE_URL = \"https://api.githubcopilot.com\"\nDEFAULT_COPILOT_ACP_BASE_URL = \"acp://copilot\"\nDEFAULT_OLLAMA_CLOUD_BASE_URL = \"https://ollama.com/v1\"\nSTEPFUN_STEP_PLAN_INTL_BASE_URL = \"https://api.stepfun.ai/step_plan/v1\"\nSTEPFUN_STEP_PLAN_CN_BASE_URL = \"https://api.stepfun.com/step_plan/v1\"\nCODEX_OAUTH_CLIENT_ID = \"app_EMoamEEZ73f0CkXaXp7hrann\"\nCODEX_OAUTH_TOKEN_URL = \"https://auth.openai.com/oauth/token\"\nCODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 120\nQWEN_OAUTH_CLIENT_ID = \"f0304373b74a44d2b584a3fb70ca9e56\"\nQWEN_OAUTH_TOKEN_URL = \"https://chat.qwen.ai/api/v1/oauth2/token\"\nQWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 120\nDEFAULT_SPOTIFY_ACCOUNTS_BASE_URL = \"https://accounts.spotify.com\"\nDEFAULT_SPOTIFY_API_BASE_URL = \"https://api.spotify.com/v1\"\nDEFAULT_SPOTIFY_REDIRECT_URI = \"http://127.0.0.1:43827/spotify/callback\"\nSPOTIFY_DOCS_URL = \"https://hermes-agent.nousresearch.com/docs/user-guide/features/spotify\"\nSPOTIFY_DASHBOARD_URL = \"https://developer.spotify.com/dashboard\"\nSPOTIFY_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 120\nDEFAULT_SPOTIFY_SCOPE = \" \".join((\n \"user-modify-playback-state\",\n \"user-read-playback-state\",\n \"user-read-currently-playing\",\n \"user-read-recently-played\",\n \"playlist-read-private\",\n \"playlist-read-collaborative\",\n \"playlist-modify-public\",\n \"playlist-modify-private\",\n \"user-library-read\",\n \"user-library-modify\",\n))\nSERVICE_PROVIDER_NAMES: Dict[str, str] = {\n \"spotify\": \"Spotify\",\n}\n\n# Google Gemini OAuth (google-gemini-cli provider, Cloud Code Assist backend)\nDEFAULT_GEMINI_CLOUDCODE_BASE_URL = \"cloudcode-pa://google\"\nGEMINI_OAUTH_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 60 # refresh 60s before expiry\n\n\n# =============================================================================\n# Provider Registry\n# =============================================================================\n\n@dataclass\nclass ProviderConfig:\n \"\"\"Describes a known inference provider.\"\"\"\n id: str\n name: str\n auth_type: str # \"oauth_device_code\", \"oauth_external\", or \"api_key\"\n portal_base_url: str = \"\"\n inference_base_url: str = \"\"\n client_id: str = \"\"\n scope: str = \"\"\n extra: Dict[str, Any] = field(default_factory=dict)\n # For API-key providers: env vars to check (in priority order)\n api_key_env_vars: tuple = ()\n # Optional env var for base URL override\n base_url_env_var: str = \"\"\n\n\nPROVIDER_REGISTRY: Dict[str, ProviderConfig] = {\n \"nous\": ProviderConfig(\n id=\"nous\",\n name=\"Nous Portal\",\n auth_type=\"oauth_device_code\",\n portal_base_url=DEFAULT_NOUS_PORTAL_URL,\n inference_base_url=DEFAULT_NOUS_INFERENCE_URL,\n client_id=DEFAULT_NOUS_CLIENT_ID,\n scope=DEFAULT_NOUS_SCOPE,\n ),\n \"openai-codex\": ProviderConfig(\n id=\"openai-codex\",\n name=\"OpenAI Codex\",\n auth_type=\"oauth_external\",\n inference_base_url=DEFAULT_CODEX_BASE_URL,\n ),\n \"qwen-oauth\": ProviderConfig(\n id=\"qwen-oauth\",\n name=\"Qwen OAuth\",\n auth_type=\"oauth_external\",\n inference_base_url=DEFAULT_QWEN_BASE_URL,\n ),\n \"google-gemini-cli\": ProviderConfig(\n id=\"google-gemini-cli\",\n name=\"Google Gemini (OAuth)\",\n auth_type=\"oauth_external\",\n inference_base_url=DEFAULT_GEMINI_CLOUDCODE_BASE_URL,\n ),\n \"copilot\": ProviderConfig(\n id=\"copilot\",\n name=\"GitHub Copilot\",\n auth_type=\"api_key\",\n inference_base_url=DEFAULT_GITHUB_MODELS_BASE_URL,\n api_key_env_vars=(\"COPILOT_GITHUB_TOKEN\", \"GH_TOKEN\", \"GITHUB_TOKEN\"),\n base_url_env_var=\"COPILOT_API_BASE_URL\",\n ),\n \"copilot-acp\": ProviderConfig(\n id=\"copilot-acp\",\n name=\"GitHub Copilot ACP\",\n auth_type=\"external_process\",\n inference_base_url=DEFAULT_COPILOT_ACP_BASE_URL,\n base_url_env_var=\"COPILOT_ACP_BASE_URL\",\n ),\n \"gemini\": ProviderConfig(\n id=\"gemini\",\n name=\"Google AI Studio\",\n auth_type=\"api_key\",\n inference_base_url=\"https://generativelanguage.googleapis.com/v1beta\",\n api_key_env_vars=(\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\"),\n base_url_env_var=\"GEMINI_BASE_URL\",\n ),\n \"zai\": ProviderConfig(\n id=\"zai\",\n name=\"Z.AI / GLM\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.z.ai/api/paas/v4\",\n api_key_env_vars=(\"GLM_API_KEY\", \"ZAI_API_KEY\", \"Z_AI_API_KEY\"),\n base_url_env_var=\"GLM_BASE_URL\",\n ),\n \"kimi-coding\": ProviderConfig(\n id=\"kimi-coding\",\n name=\"Kimi / Moonshot\",\n auth_type=\"api_key\",\n # Legacy platform.moonshot.ai keys use this endpoint (OpenAI-compat).\n # sk-kimi- (Kimi Code) keys are auto-redirected to api.kimi.com/coding\n # by _resolve_kimi_base_url() below.\n inference_base_url=\"https://api.moonshot.ai/v1\",\n api_key_env_vars=(\"KIMI_API_KEY\", \"KIMI_CODING_API_KEY\"),\n base_url_env_var=\"KIMI_BASE_URL\",\n ),\n \"kimi-coding-cn\": ProviderConfig(\n id=\"kimi-coding-cn\",\n name=\"Kimi / Moonshot (China)\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.moonshot.cn/v1\",\n api_key_env_vars=(\"KIMI_CN_API_KEY\",),\n ),\n \"stepfun\": ProviderConfig(\n id=\"stepfun\",\n name=\"StepFun Step Plan\",\n auth_type=\"api_key\",\n inference_base_url=STEPFUN_STEP_PLAN_INTL_BASE_URL,\n api_key_env_vars=(\"STEPFUN_API_KEY\",),\n base_url_env_var=\"STEPFUN_BASE_URL\",\n ),\n \"arcee\": ProviderConfig(\n id=\"arcee\",\n name=\"Arcee AI\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.arcee.ai/api/v1\",\n api_key_env_vars=(\"ARCEEAI_API_KEY\",),\n base_url_env_var=\"ARCEE_BASE_URL\",\n ),\n \"minimax\": ProviderConfig(\n id=\"minimax\",\n name=\"MiniMax\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.minimax.io/anthropic\",\n api_key_env_vars=(\"MINIMAX_API_KEY\",),\n base_url_env_var=\"MINIMAX_BASE_URL\",\n ),\n \"anthropic\": ProviderConfig(\n id=\"anthropic\",\n name=\"Anthropic\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.anthropic.com\",\n api_key_env_vars=(\"ANTHROPIC_API_KEY\", \"ANTHROPIC_TOKEN\", \"CLAUDE_CODE_OAUTH_TOKEN\"),\n base_url_env_var=\"ANTHROPIC_BASE_URL\",\n ),\n \"alibaba\": ProviderConfig(\n id=\"alibaba\",\n name=\"Alibaba Cloud (DashScope)\",\n auth_type=\"api_key\",\n inference_base_url=\"https://dashscope-intl.aliyuncs.com/compatible-mode/v1\",\n api_key_env_vars=(\"DASHSCOPE_API_KEY\",),\n base_url_env_var=\"DASHSCOPE_BASE_URL\",\n ),\n \"alibaba-coding-plan\": ProviderConfig(\n id=\"alibaba-coding-plan\",\n name=\"Alibaba Cloud (Coding Plan)\",\n auth_type=\"api_key\",\n inference_base_url=\"https://coding-intl.dashscope.aliyuncs.com/v1\",\n api_key_env_vars=(\"ALIBABA_CODING_PLAN_API_KEY\", \"DASHSCOPE_API_KEY\"),\n base_url_env_var=\"ALIBABA_CODING_PLAN_BASE_URL\",\n ),\n \"minimax-cn\": ProviderConfig(\n id=\"minimax-cn\",\n name=\"MiniMax (China)\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.minimaxi.com/anthropic\",\n api_key_env_vars=(\"MINIMAX_CN_API_KEY\",),\n base_url_env_var=\"MINIMAX_CN_BASE_URL\",\n ),\n \"deepseek\": ProviderConfig(\n id=\"deepseek\",\n name=\"DeepSeek\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.deepseek.com/v1\",\n api_key_env_vars=(\"DEEPSEEK_API_KEY\",),\n base_url_env_var=\"DEEPSEEK_BASE_URL\",\n ),\n \"xai\": ProviderConfig(\n id=\"xai\",\n name=\"xAI\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.x.ai/v1\",\n api_key_env_vars=(\"XAI_API_KEY\",),\n base_url_env_var=\"XAI_BASE_URL\",\n ),\n \"nvidia\": ProviderConfig(\n id=\"nvidia\",\n name=\"NVIDIA NIM\",\n auth_type=\"api_key\",\n inference_base_url=\"https://integrate.api.nvidia.com/v1\",\n api_key_env_vars=(\"NVIDIA_API_KEY\",),\n base_url_env_var=\"NVIDIA_BASE_URL\",\n ),\n \"ai-gateway\": ProviderConfig(\n id=\"ai-gateway\",\n name=\"Vercel AI Gateway\",\n auth_type=\"api_key\",\n inference_base_url=\"https://ai-gateway.vercel.sh/v1\",\n api_key_env_vars=(\"AI_GATEWAY_API_KEY\",),\n base_url_env_var=\"AI_GATEWAY_BASE_URL\",\n ),\n \"opencode-zen\": ProviderConfig(\n id=\"opencode-zen\",\n name=\"OpenCode Zen\",\n auth_type=\"api_key\",\n inference_base_url=\"https://opencode.ai/zen/v1\",\n api_key_env_vars=(\"OPENCODE_ZEN_API_KEY\",),\n base_url_env_var=\"OPENCODE_ZEN_BASE_URL\",\n ),\n \"opencode-go\": ProviderConfig(\n id=\"opencode-go\",\n name=\"OpenCode Go\",\n auth_type=\"api_key\",\n # OpenCode Go mixes API surfaces by model:\n # - GLM / Kimi use OpenAI-compatible chat completions under /v1\n # - MiniMax models use Anthropic Messages under /v1/messages\n # Keep the provider base at /v1 and select api_mode per-model.\n inference_base_url=\"https://opencode.ai/zen/go/v1\",\n api_key_env_vars=(\"OPENCODE_GO_API_KEY\",),\n base_url_env_var=\"OPENCODE_GO_BASE_URL\",\n ),\n \"kilocode\": ProviderConfig(\n id=\"kilocode\",\n name=\"Kilo Code\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.kilo.ai/api/gateway\",\n api_key_env_vars=(\"KILOCODE_API_KEY\",),\n base_url_env_var=\"KILOCODE_BASE_URL\",\n ),\n \"huggingface\": ProviderConfig(\n id=\"huggingface\",\n name=\"Hugging Face\",\n auth_type=\"api_key\",\n inference_base_url=\"https://router.huggingface.co/v1\",\n api_key_env_vars=(\"HF_TOKEN\",),\n base_url_env_var=\"HF_BASE_URL\",\n ),\n \"xiaomi\": ProviderConfig(\n id=\"xiaomi\",\n name=\"Xiaomi MiMo\",\n auth_type=\"api_key\",\n inference_base_url=\"https://api.xiaomimimo.com/v1\",\n api_key_env_vars=(\"XIAOMI_API_KEY\",),\n base_url_env_var=\"XIAOMI_BASE_URL\",\n ),\n \"ollama-cloud\": ProviderConfig(\n id=\"ollama-cloud\",\n name=\"Ollama Cloud\",\n auth_type=\"api_key\",\n inference_base_url=DEFAULT_OLLAMA_CLOUD_BASE_URL,\n api_key_env_vars=(\"OLLAMA_API_KEY\",),\n base_url_env_var=\"OLLAMA_BASE_URL\",\n ),\n \"bedrock\": ProviderConfig(\n id=\"bedrock\",\n name=\"AWS Bedrock\",\n auth_type=\"aws_sdk\",\n inference_base_url=\"https://bedrock-runtime.us-east-1.amazonaws.com\",\n api_key_env_vars=(),\n base_url_env_var=\"BEDROCK_BASE_URL\",\n ),\n}\n\n\n# =============================================================================\n# Anthropic Key Helper\n# =============================================================================\n\ndef get_anthropic_key() -> str:\n \"\"\"Return the first usable Anthropic credential, or ``\"\"``.\n\n Checks both the ``.env`` file (via ``get_env_value``) and the process\n environment (``os.getenv``). The fallback order mirrors the\n ``PROVIDER_REGISTRY[\"anthropic\"].api_key_env_vars`` tuple:\n\n ANTHROPIC_API_KEY -> ANTHROPIC_TOKEN -> CLAUDE_CODE_OAUTH_TOKEN\n \"\"\"\n from hermes_cli.config import get_env_value\n\n for var in PROVIDER_REGISTRY[\"anthropic\"].api_key_env_vars:\n value = get_env_value(var) or os.getenv(var, \"\")\n if value:\n return value\n return \"\"\n\n\n# =============================================================================\n# Kimi Code Endpoint Detection\n# =============================================================================\n\n# Kimi Code (kimi.com/code) issues keys prefixed \"sk-kimi-\" that only work\n# on api.kimi.com/coding. Legacy keys from platform.moonshot.ai work on\n# api.moonshot.ai/v1 (the old default). Auto-detect when user hasn't set\n# KIMI_BASE_URL explicitly.\n#\n# Note: the base URL intentionally has NO /v1 suffix. The /coding endpoint\n# speaks the Anthropic Messages protocol, and the anthropic SDK appends\n# \"/v1/messages\" internally — so \"/coding\" + SDK suffix → \"/coding/v1/messages\"\n# (the correct target). Using \"/coding/v1\" here would produce\n# \"/coding/v1/v1/messages\" (a 404).\nKIMI_CODE_BASE_URL = \"https://api.kimi.com/coding\"\n\n\ndef _resolve_kimi_base_url(api_key: str, default_url: str, env_override: str) -> str:\n \"\"\"Return the correct Kimi base URL based on the API key prefix.\n\n If the user has explicitly set KIMI_BASE_URL, that always wins.\n Otherwise, sk-kimi- prefixed keys route to api.kimi.com/coding/v1.\n \"\"\"\n if env_override:\n return env_override\n # No key → nothing to infer from. Return default without inspecting.\n if not api_key:\n return default_url\n if api_key.startswith(\"sk-kimi-\"):\n return KIMI_CODE_BASE_URL\n return default_url\n\n\n\n_PLACEHOLDER_SECRET_VALUES = {\n \"*\",\n \"**\",\n \"***\",\n \"changeme\",\n \"your_api_key\",\n \"your-api-key\",\n \"placeholder\",\n \"example\",\n \"dummy\",\n \"null\",\n \"none\",\n}\n\n\ndef has_usable_secret(value: Any, *, min_length: int = 4) -> bool:\n \"\"\"Return True when a configured secret looks usable, not empty/placeholder.\"\"\"\n if not isinstance(value, str):\n return False\n cleaned = value.strip()\n if len(cleaned) < min_length:\n return False\n if cleaned.lower() in _PLACEHOLDER_SECRET_VALUES:\n return False\n return True\n\n\ndef _resolve_api_key_provider_secret(\n provider_id: str, pconfig: ProviderConfig\n) -> tuple[str, str]:\n \"\"\"Resolve an API-key provider's token and indicate where it came from.\"\"\"\n if provider_id == \"copilot\":\n # Use the dedicated copilot auth module for proper token validation\n try:\n from hermes_cli.copilot_auth import resolve_copilot_token, get_copilot_api_token\n token, source = resolve_copilot_token()\n if token:\n return get_copilot_api_token(token), source\n except ValueError as exc:\n logger.warning(\"Copilot token validation failed: %s\", exc)\n except Exception:\n pass\n return \"\", \"\"\n\n for env_var in pconfig.api_key_env_vars:\n val = os.getenv(env_var, \"\").strip()\n if has_usable_secret(val):\n return val, env_var\n\n return \"\", \"\"\n\n\n# =============================================================================\n# Z.AI Endpoint Detection\n# =============================================================================\n\n# Z.AI has separate billing for general vs coding plans, and global vs China\n# endpoints. A key that works on one may return \"Insufficient balance\" on\n# another. We probe at setup time and store the working endpoint.\n# Each entry lists candidate models to try in order — newer coding plan accounts\n# may only have access to recent models (glm-5.1, glm-5v-turbo) while older\n# ones still use glm-4.7.\n\nZAI_ENDPOINTS = [\n # (id, base_url, probe_models, label)\n (\"global\", \"https://api.z.ai/api/paas/v4\", [\"glm-5\"], \"Global\"),\n (\"cn\", \"https://open.bigmodel.cn/api/paas/v4\", [\"glm-5\"], \"China\"),\n (\"coding-global\", \"https://api.z.ai/api/coding/paas/v4\", [\"glm-5.1\", \"glm-5v-turbo\", \"glm-4.7\"], \"Global (Coding Plan)\"),\n (\"coding-cn\", \"https://open.bigmodel.cn/api/coding/paas/v4\", [\"glm-5.1\", \"glm-5v-turbo\", \"glm-4.7\"], \"China (Coding Plan)\"),\n]\n\n\ndef detect_zai_endpoint(api_key: str, timeout: float = 8.0) -> Optional[Dict[str, str]]:\n \"\"\"Probe z.ai endpoints to find one that accepts this API key.\n\n Returns {\"id\": ..., \"base_url\": ..., \"model\": ..., \"label\": ...} for the\n first working endpoint, or None if all fail. For endpoints with multiple\n candidate models, tries each in order and returns the first that succeeds.\n \"\"\"\n for ep_id, base_url, probe_models, label in ZAI_ENDPOINTS:\n for model in probe_models:\n try:\n resp = httpx.post(\n f\"{base_url}/chat/completions\",\n headers={\n \"Authorization\": f\"Bearer {api_key}\",\n \"Content-Type\": \"application/json\",\n },\n json={\n \"model\": model,\n \"stream\": False,\n \"max_tokens\": 1,\n \"messages\": [{\"role\": \"user\", \"content\": \"ping\"}],\n },\n timeout=timeout,\n )\n if resp.status_code == 200:\n logger.debug(\"Z.AI endpoint probe: %s (%s) model=%s OK\", ep_id, base_url, model)\n return {\n \"id\": ep_id,\n \"base_url\": base_url,\n \"model\": model,\n \"label\": label,\n }\n logger.debug(\"Z.AI endpoint probe: %s model=%s returned %s\", ep_id, model, resp.status_code)\n except Exception as exc:\n logger.debug(\"Z.AI endpoint probe: %s model=%s failed: %s\", ep_id, model, exc)\n return None\n\n\ndef _resolve_zai_base_url(api_key: str, default_url: str, env_override: str) -> str:\n \"\"\"Return the correct Z.AI base URL by probing endpoints.\n\n If the user has explicitly set GLM_BASE_URL, that always wins.\n Otherwise, probe the candidate endpoints to find one that accepts the\n key. The detected endpoint is cached in provider state (auth.json) keyed\n on a hash of the API key so subsequent starts skip the probe.\n \"\"\"\n if env_override:\n return env_override\n\n # No API key set → don't probe (would fire N×M HTTPS requests with an\n # empty Bearer token, all returning 401). This path is hit during\n # auxiliary-client auto-detection when the user has no Z.AI credentials\n # at all — the caller discards the result immediately, so the probe is\n # pure latency for every AIAgent construction.\n if not api_key:\n return default_url\n\n # Check provider-state cache for a previously-detected endpoint.\n auth_store = _load_auth_store()\n state = _load_provider_state(auth_store, \"zai\") or {}\n cached = state.get(\"detected_endpoint\")\n if isinstance(cached, dict) and cached.get(\"base_url\"):\n key_hash = cached.get(\"key_hash\", \"\")\n if key_hash == hashlib.sha256(api_key.encode()).hexdigest()[:16]:\n logger.debug(\"Z.AI: using cached endpoint %s\", cached[\"base_url\"])\n return cached[\"base_url\"]\n\n # Probe — may take up to ~8s per endpoint.\n detected = detect_zai_endpoint(api_key)\n if detected and detected.get(\"base_url\"):\n # Persist the detection result keyed on the API key hash.\n key_hash = hashlib.sha256(api_key.encode()).hexdigest()[:16]\n state[\"detected_endpoint\"] = {\n \"base_url\": detected[\"base_url\"],\n \"endpoint_id\": detected.get(\"id\", \"\"),\n \"model\": detected.get(\"model\", \"\"),\n \"label\": detected.get(\"label\", \"\"),\n \"key_hash\": key_hash,\n }\n _save_provider_state(auth_store, \"zai\", state)\n logger.info(\"Z.AI: auto-detected endpoint %s (%s)\", detected[\"label\"], detected[\"base_url\"])\n return detected[\"base_url\"]\n\n logger.debug(\"Z.AI: probe failed, falling back to default %s\", default_url)\n return default_url\n\n\n# =============================================================================\n# Error Types\n# =============================================================================\n\nclass AuthError(RuntimeError):\n \"\"\"Structured auth error with UX mapping hints.\"\"\"\n\n def __init__(\n self,\n message: str,\n *,\n provider: str = \"\",\n code: Optional[str] = None,\n relogin_required: bool = False,\n ) -> None:\n super().__init__(message)\n self.provider = provider\n self.code = code\n self.relogin_required = relogin_required\n\n\ndef format_auth_error(error: Exception) -> str:\n \"\"\"Map auth failures to concise user-facing guidance.\"\"\"\n if not isinstance(error, AuthError):\n return str(error)\n\n if error.relogin_required:\n return f\"{error} Run `hermes model` to re-authenticate.\"\n\n if error.code == \"subscription_required\":\n return (\n \"No active paid subscription found on Nous Portal. \"\n \"Please purchase/activate a subscription, then retry.\"\n )\n\n if error.code == \"insufficient_credits\":\n return (\n \"Subscription credits are exhausted. \"\n \"Top up/renew credits in Nous Portal, then retry.\"\n )\n\n if error.code == \"temporarily_unavailable\":\n return f\"{error} Please retry in a few seconds.\"\n\n return str(error)\n\n\ndef _token_fingerprint(token: Any) -> Optional[str]:\n \"\"\"Return a short hash fingerprint for telemetry without leaking token bytes.\"\"\"\n if not isinstance(token, str):\n return None\n cleaned = token.strip()\n if not cleaned:\n return None\n return hashlib.sha256(cleaned.encode(\"utf-8\")).hexdigest()[:12]\n\n\ndef _oauth_trace_enabled() -> bool:\n raw = os.getenv(\"HERMES_OAUTH_TRACE\", \"\").strip().lower()\n return raw in {\"1\", \"true\", \"yes\", \"on\"}\n\n\ndef _oauth_trace(event: str, *, sequence_id: Optional[str] = None, **fields: Any) -> None:\n if not _oauth_trace_enabled():\n return\n payload: Dict[str, Any] = {\"event\": event}\n if sequence_id:\n payload[\"sequence_id\"] = sequence_id\n payload.update(fields)\n logger.info(\"oauth_trace %s\", json.dumps(payload, sort_keys=True, ensure_ascii=False))\n\n\n# =============================================================================\n# Auth Store — persistence layer for ~/.hermes/auth.json\n# =============================================================================\n\ndef _auth_file_path() -> Path:\n path = get_hermes_home() / \"auth.json\"\n # Seat belt: if pytest is running and HERMES_HOME resolves to the real\n # user's auth store, refuse rather than silently corrupt it. This catches\n # tests that forgot to monkeypatch HERMES_HOME, tests invoked without the\n # hermetic conftest, or sandbox escapes via threads/subprocesses. In\n # production (no PYTEST_CURRENT_TEST) this is a single dict lookup.\n if os.environ.get(\"PYTEST_CURRENT_TEST\"):\n real_home_auth = (Path.home() / \".hermes\" / \"auth.json\").resolve(strict=False)\n try:\n resolved = path.resolve(strict=False)\n except Exception:\n resolved = path\n if resolved == real_home_auth:\n raise RuntimeError(\n f\"Refusing to touch real user auth store during test run: {path}. \"\n \"Set HERMES_HOME to a tmp_path in your test fixture, or run \"\n \"via scripts/run_tests.sh for hermetic CI-parity env.\"\n )\n return path\n\n\ndef _auth_lock_path() -> Path:\n return _auth_file_path().with_suffix(\".lock\")\n\n\n_auth_lock_holder = threading.local()\n\n@contextmanager\ndef _auth_store_lock(timeout_seconds: float = AUTH_LOCK_TIMEOUT_SECONDS):\n \"\"\"Cross-process advisory lock for auth.json reads+writes. Reentrant.\"\"\"\n # Reentrant: if this thread already holds the lock, just yield.\n if getattr(_auth_lock_holder, \"depth\", 0) > 0:\n _auth_lock_holder.depth += 1\n try:\n yield\n finally:\n _auth_lock_holder.depth -= 1\n return\n\n lock_path = _auth_lock_path()\n lock_path.parent.mkdir(parents=True, exist_ok=True)\n\n if fcntl is None and msvcrt is None:\n _auth_lock_holder.depth = 1\n try:\n yield\n finally:\n _auth_lock_holder.depth = 0\n return\n\n # On Windows, msvcrt.locking needs the file to have content and the\n # file pointer at position 0. Ensure the lock file has at least 1 byte.\n if msvcrt and (not lock_path.exists() or lock_path.stat().st_size == 0):\n lock_path.write_text(\" \", encoding=\"utf-8\")\n\n with lock_path.open(\"r+\" if msvcrt else \"a+\") as lock_file:\n deadline = time.time() + max(1.0, timeout_seconds)\n while True:\n try:\n if fcntl:\n fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)\n else:\n lock_file.seek(0)\n msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK, 1)\n break\n except (BlockingIOError, OSError, PermissionError):\n if time.time() >= deadline:\n raise TimeoutError(\"Timed out waiting for auth store lock\")\n time.sleep(0.05)\n\n _auth_lock_holder.depth = 1\n try:\n yield\n finally:\n _auth_lock_holder.depth = 0\n if fcntl:\n fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)\n elif msvcrt:\n try:\n lock_file.seek(0)\n msvcrt.locking(lock_file.fileno(), msvcrt.LK_UNLCK, 1)\n except (OSError, IOError):\n pass\n\n\ndef _load_auth_store(auth_file: Optional[Path] = None) -> Dict[str, Any]:\n auth_file = auth_file or _auth_file_path()\n if not auth_file.exists():\n return {\"version\": AUTH_STORE_VERSION, \"providers\": {}}\n\n try:\n raw = json.loads(auth_file.read_text())\n except Exception as exc:\n corrupt_path = auth_file.with_suffix(\".json.corrupt\")\n try:\n import shutil\n shutil.copy2(auth_file, corrupt_path)\n except Exception:\n pass\n logger.warning(\n \"auth: failed to parse %s (%s) — starting with empty store. \"\n \"Corrupt file preserved at %s\",\n auth_file, exc, corrupt_path,\n )\n return {\"version\": AUTH_STORE_VERSION, \"providers\": {}}\n\n if isinstance(raw, dict) and (\n isinstance(raw.get(\"providers\"), dict)\n or isinstance(raw.get(\"credential_pool\"), dict)\n ):\n raw.setdefault(\"providers\", {})\n return raw\n\n # Migrate from PR's \"systems\" format if present\n if isinstance(raw, dict) and isinstance(raw.get(\"systems\"), dict):\n systems = raw[\"systems\"]\n providers = {}\n if \"nous_portal\" in systems:\n providers[\"nous\"] = systems[\"nous_portal\"]\n return {\"version\": AUTH_STORE_VERSION, \"providers\": providers,\n \"active_provider\": \"nous\" if providers else None}\n\n return {\"version\": AUTH_STORE_VERSION, \"providers\": {}}\n\n\ndef _save_auth_store(auth_store: Dict[str, Any]) -> Path:\n auth_file = _auth_file_path()\n auth_file.parent.mkdir(parents=True, exist_ok=True)\n auth_store[\"version\"] = AUTH_STORE_VERSION\n auth_store[\"updated_at\"] = datetime.now(timezone.utc).isoformat()\n payload = json.dumps(auth_store, indent=2) + \"\\n\"\n tmp_path = auth_file.with_name(f\"{auth_file.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}\")\n try:\n with tmp_path.open(\"w\", encoding=\"utf-8\") as handle:\n handle.write(payload)\n handle.flush()\n os.fsync(handle.fileno())\n os.replace(tmp_path, auth_file)\n try:\n dir_fd = os.open(str(auth_file.parent), os.O_RDONLY)\n except OSError:\n dir_fd = None\n if dir_fd is not None:\n try:\n os.fsync(dir_fd)\n finally:\n os.close(dir_fd)\n finally:\n try:\n if tmp_path.exists():\n tmp_path.unlink()\n except OSError:\n pass\n # Restrict file permissions to owner only\n try:\n auth_file.chmod(stat.S_IRUSR | stat.S_IWUSR)\n except OSError:\n pass\n return auth_file\n\n\ndef _load_provider_state(auth_store: Dict[str, Any], provider_id: str) -> Optional[Dict[str, Any]]:\n providers = auth_store.get(\"providers\")\n if not isinstance(providers, dict):\n return None\n state = providers.get(provider_id)\n return dict(state) if isinstance(state, dict) else None\n\n\ndef _save_provider_state(auth_store: Dict[str, Any], provider_id: str, state: Dict[str, Any]) -> None:\n providers = auth_store.setdefault(\"providers\", {})\n if not isinstance(providers, dict):\n auth_store[\"providers\"] = {}\n providers = auth_store[\"providers\"]\n providers[provider_id] = state\n auth_store[\"active_provider\"] = provider_id\n\n\ndef _store_provider_state(\n auth_store: Dict[str, Any],\n provider_id: str,\n state: Dict[str, Any],\n *,\n set_active: bool = True,\n) -> None:\n providers = auth_store.setdefault(\"providers\", {})\n if not isinstance(providers, dict):\n auth_store[\"providers\"] = {}\n providers = auth_store[\"providers\"]\n providers[provider_id] = state\n if set_active:\n auth_store[\"active_provider\"] = provider_id\n\n\ndef is_known_auth_provider(provider_id: str) -> bool:\n normalized = (provider_id or \"\").strip().lower()\n return normalized in PROVIDER_REGISTRY or normalized in SERVICE_PROVIDER_NAMES\n\n\ndef get_auth_provider_display_name(provider_id: str) -> str:\n normalized = (provider_id or \"\").strip().lower()\n if normalized in PROVIDER_REGISTRY:\n return PROVIDER_REGISTRY[normalized].name\n return SERVICE_PROVIDER_NAMES.get(normalized, provider_id)\n\n\ndef read_credential_pool(provider_id: Optional[str] = None) -> Dict[str, Any]:\n \"\"\"Return the persisted credential pool, or one provider slice.\"\"\"\n auth_store = _load_auth_store()\n pool = auth_store.get(\"credential_pool\")\n if not isinstance(pool, dict):\n pool = {}\n if provider_id is None:\n return dict(pool)\n provider_entries = pool.get(provider_id)\n return list(provider_entries) if isinstance(provider_entries, list) else []\n\n\ndef write_credential_pool(provider_id: str, entries: List[Dict[str, Any]]) -> Path:\n \"\"\"Persist one provider's credential pool under auth.json.\"\"\"\n with _auth_store_lock():\n auth_store = _load_auth_store()\n pool = auth_store.get(\"credential_pool\")\n if not isinstance(pool, dict):\n pool = {}\n auth_store[\"credential_pool\"] = pool\n pool[provider_id] = list(entries)\n return _save_auth_store(auth_store)\n\n\ndef suppress_credential_source(provider_id: str, source: str) -> None:\n \"\"\"Mark a credential source as suppressed so it won't be re-seeded.\"\"\"\n with _auth_store_lock():\n auth_store = _load_auth_store()\n suppressed = auth_store.setdefault(\"suppressed_sources\", {})\n provider_list = suppressed.setdefault(provider_id, [])\n if source not in provider_list:\n provider_list.append(source)\n _save_auth_store(auth_store)\n\n\ndef is_source_suppressed(provider_id: str, source: str) -> bool:\n \"\"\"Check if a credential source has been suppressed by the user.\"\"\"\n try:\n auth_store = _load_auth_store()\n suppressed = auth_store.get(\"suppressed_sources\", {})\n return source in suppressed.get(provider_id, [])\n except Exception:\n return False\n\n\ndef unsuppress_credential_source(provider_id: str, source: str) -> bool:\n \"\"\"Clear a suppression marker so the source will be re-seeded on the next load.\n\n Returns True if a marker was cleared, False if no marker existed.\n \"\"\"\n with _auth_store_lock():\n auth_store = _load_auth_store()\n suppressed = auth_store.get(\"suppressed_sources\")\n if not isinstance(suppressed, dict):\n return False\n provider_list = suppressed.get(provider_id)\n if not isinstance(provider_list, list) or source not in provider_list:\n return False\n provider_list.remove(source)\n if not provider_list:\n suppressed.pop(provider_id, None)\n if not suppressed:\n auth_store.pop(\"suppressed_sources\", None)\n _save_auth_store(auth_store)\n return True\n\n\ndef get_provider_auth_state(provider_id: str) -> Optional[Dict[str, Any]]:\n \"\"\"Return persisted auth state for a provider, or None.\"\"\"\n auth_store = _load_auth_store()\n return _load_provider_state(auth_store, provider_id)\n\n\ndef get_active_provider() -> Optional[str]:\n \"\"\"Return the currently active provider ID from auth store.\"\"\"\n auth_store = _load_auth_store()\n return auth_store.get(\"active_provider\")\n\n\ndef is_provider_explicitly_configured(provider_id: str) -> bool:\n \"\"\"Return True only if the user has explicitly configured this provider.\n\n Checks:\n 1. active_provider in auth.json matches\n 2. model.provider in config.yaml matches\n 3. Provider-specific env vars are set (e.g. ANTHROPIC_API_KEY)\n\n This is used to gate auto-discovery of external credentials (e.g.\n Claude Code's ~/.claude/.credentials.json) so they are never used\n without the user's explicit choice. See PR #4210 for the same\n pattern applied to the setup wizard gate.\n \"\"\"\n normalized = (provider_id or \"\").strip().lower()\n\n # 1. Check auth.json active_provider\n try:\n auth_store = _load_auth_store()\n active = (auth_store.get(\"active_provider\") or \"\").strip().lower()\n if active and active == normalized:\n return True\n except Exception:\n pass\n\n # 2. Check config.yaml model.provider\n try:\n from hermes_cli.config import load_config\n cfg = load_config()\n model_cfg = cfg.get(\"model\")\n if isinstance(model_cfg, dict):\n cfg_provider = (model_cfg.get(\"provider\") or \"\").strip().lower()\n if cfg_provider == normalized:\n return True\n except Exception:\n pass\n\n # 3. Check provider-specific env vars\n # Exclude CLAUDE_CODE_OAUTH_TOKEN — it's set by Claude Code itself,\n # not by the user explicitly configuring anthropic in Hermes.\n _IMPLICIT_ENV_VARS = {\"CLAUDE_CODE_OAUTH_TOKEN\"}\n pconfig = PROVIDER_REGISTRY.get(normalized)\n if pconfig and pconfig.auth_type == \"api_key\":\n for env_var in pconfig.api_key_env_vars:\n if env_var in _IMPLICIT_ENV_VARS:\n continue\n if has_usable_secret(os.getenv(env_var, \"\")):\n return True\n\n return False\n\n\ndef clear_provider_auth(provider_id: Optional[str] = None) -> bool:\n \"\"\"\n Clear auth state for a provider. Used by `hermes logout`.\n If provider_id is None, clears the active provider.\n Returns True if something was cleared.\n \"\"\"\n with _auth_store_lock():\n auth_store = _load_auth_store()\n target = provider_id or auth_store.get(\"active_provider\")\n if not target:\n return False\n\n providers = auth_store.get(\"providers\", {})\n if not isinstance(providers, dict):\n providers = {}\n auth_store[\"providers\"] = providers\n\n pool = auth_store.get(\"credential_pool\")\n if not isinstance(pool, dict):\n pool = {}\n auth_store[\"credential_pool\"] = pool\n\n cleared = False\n if target in providers:\n del providers[target]\n cleared = True\n if target in pool:\n del pool[target]\n cleared = True\n\n if auth_store.get(\"active_provider\") == target:\n auth_store[\"active_provider\"] = None\n cleared = True\n\n if not cleared:\n return False\n _save_auth_store(auth_store)\n return True\n\n\ndef deactivate_provider() -> None:\n \"\"\"\n Clear active_provider in auth.json without deleting credentials.\n Used when the user switches to a non-OAuth provider (OpenRouter, custom)\n so auto-resolution doesn't keep picking the OAuth provider.\n \"\"\"\n with _auth_store_lock():\n auth_store = _load_auth_store()\n auth_store[\"active_provider\"] = None\n _save_auth_store(auth_store)\n\n\n# =============================================================================\n# Provider Resolution — picks which provider to use\n# =============================================================================\n\n\ndef _get_config_hint_for_unknown_provider(provider_name: str) -> str:\n \"\"\"Return a helpful hint string when provider resolution fails.\n\n Checks for common config.yaml mistakes (malformed custom_providers, etc.)\n and returns a human-readable diagnostic, or empty string if nothing found.\n \"\"\"\n try:\n from hermes_cli.config import validate_config_structure\n issues = validate_config_structure()\n if not issues:\n return \"\"\n\n lines = [\"Config issue detected — run 'hermes doctor' for full diagnostics:\"]\n for ci in issues:\n prefix = \"ERROR\" if ci.severity == \"error\" else \"WARNING\"\n lines.append(f\" [{prefix}] {ci.message}\")\n # Show first line of hint\n first_hint = ci.hint.splitlines()[0] if ci.hint else \"\"\n if first_hint:\n lines.append(f\" → {first_hint}\")\n return \"\\n\".join(lines)\n except Exception:\n return \"\"\n\n\ndef resolve_provider(\n requested: Optional[str] = None,\n *,\n explicit_api_key: Optional[str] = None,\n explicit_base_url: Optional[str] = None,\n) -> str:\n \"\"\"\n Determine which inference provider to use.\n\n Priority (when requested=\"auto\" or None):\n 1. active_provider in auth.json with valid credentials\n 2. Explicit CLI api_key/base_url -> \"openrouter\"\n 3. OPENAI_API_KEY or OPENROUTER_API_KEY env vars -> \"openrouter\"\n 4. Provider-specific API keys (GLM, Kimi, MiniMax) -> that provider\n 5. Fallback: \"openrouter\"\n \"\"\"\n normalized = (requested or \"auto\").strip().lower()\n\n # Normalize provider aliases\n _PROVIDER_ALIASES = {\n \"glm\": \"zai\", \"z-ai\": \"zai\", \"z.ai\": \"zai\", \"zhipu\": \"zai\",\n \"google\": \"gemini\", \"google-gemini\": \"gemini\", \"google-ai-studio\": \"gemini\",\n \"x-ai\": \"xai\", \"x.ai\": \"xai\", \"grok\": \"xai\",\n \"kimi\": \"kimi-coding\", \"kimi-for-coding\": \"kimi-coding\", \"moonshot\": \"kimi-coding\",\n \"kimi-cn\": \"kimi-coding-cn\", \"moonshot-cn\": \"kimi-coding-cn\",\n \"step\": \"stepfun\", \"stepfun-coding-plan\": \"stepfun\",\n \"arcee-ai\": \"arcee\", \"arceeai\": \"arcee\",\n \"minimax-china\": \"minimax-cn\", \"minimax_cn\": \"minimax-cn\",\n \"alibaba_coding\": \"alibaba-coding-plan\", \"alibaba-coding\": \"alibaba-coding-plan\",\n \"alibaba_coding_plan\": \"alibaba-coding-plan\",\n \"claude\": \"anthropic\", \"claude-code\": \"anthropic\",\n \"github\": \"copilot\", \"github-copilot\": \"copilot\",\n \"github-models\": \"copilot\", \"github-model\": \"copilot\",\n \"github-copilot-acp\": \"copilot-acp\", \"copilot-acp-agent\": \"copilot-acp\",\n \"aigateway\": \"ai-gateway\", \"vercel\": \"ai-gateway\", \"vercel-ai-gateway\": \"ai-gateway\",\n \"opencode\": \"opencode-zen\", \"zen\": \"opencode-zen\",\n \"qwen-portal\": \"qwen-oauth\", \"qwen-cli\": \"qwen-oauth\", \"qwen-oauth\": \"qwen-oauth\", \"google-gemini-cli\": \"google-gemini-cli\", \"gemini-cli\": \"google-gemini-cli\", \"gemini-oauth\": \"google-gemini-cli\",\n \"hf\": \"huggingface\", \"hugging-face\": \"huggingface\", \"huggingface-hub\": \"huggingface\",\n \"mimo\": \"xiaomi\", \"xiaomi-mimo\": \"xiaomi\",\n \"aws\": \"bedrock\", \"aws-bedrock\": \"bedrock\", \"amazon-bedrock\": \"bedrock\", \"amazon\": \"bedrock\",\n \"go\": \"opencode-go\", \"opencode-go-sub\": \"opencode-go\",\n \"kilo\": \"kilocode\", \"kilo-code\": \"kilocode\", \"kilo-gateway\": \"kilocode\",\n # Local server aliases — route through the generic custom provider\n \"lmstudio\": \"custom\", \"lm-studio\": \"custom\", \"lm_studio\": \"custom\",\n \"ollama\": \"custom\", \"ollama_cloud\": \"ollama-cloud\",\n \"vllm\": \"custom\", \"llamacpp\": \"custom\",\n \"llama.cpp\": \"custom\", \"llama-cpp\": \"custom\",\n }\n normalized = _PROVIDER_ALIASES.get(normalized, normalized)\n\n if normalized == \"openrouter\":\n return \"openrouter\"\n if normalized == \"custom\":\n return \"custom\"\n if normalized in PROVIDER_REGISTRY:\n return normalized\n if normalized != \"auto\":\n # Check for common config.yaml issues that cause this error\n _config_hint = _get_config_hint_for_unknown_provider(normalized)\n msg = f\"Unknown provider '{normalized}'.\"\n if _config_hint:\n msg += f\"\\n\\n{_config_hint}\"\n else:\n msg += \" Check 'hermes model' for available providers, or run 'hermes doctor' to diagnose config issues.\"\n raise AuthError(msg, code=\"invalid_provider\")\n\n # Explicit one-off CLI creds always mean openrouter/custom\n if explicit_api_key or explicit_base_url:\n return \"openrouter\"\n\n # Check auth store for an active OAuth provider\n try:\n auth_store = _load_auth_store()\n active = auth_store.get(\"active_provider\")\n if active and active in PROVIDER_REGISTRY:\n status = get_auth_status(active)\n if status.get(\"logged_in\"):\n return active\n except Exception as e:\n logger.debug(\"Could not detect active auth provider: %s\", e)\n\n if has_usable_secret(os.getenv(\"OPENAI_API_KEY\")) or has_usable_secret(os.getenv(\"OPENROUTER_API_KEY\")):\n return \"openrouter\"\n\n # Auto-detect API-key providers by checking their env vars\n for pid, pconfig in PROVIDER_REGISTRY.items():\n if pconfig.auth_type != \"api_key\":\n continue\n # GitHub tokens are commonly present for repo/tool access but should not\n # hijack inference auto-selection unless the user explicitly chooses\n # Copilot/GitHub Models as the provider.\n if pid == \"copilot\":\n continue\n for env_var in pconfig.api_key_env_vars:\n if has_usable_secret(os.getenv(env_var, \"\")):\n return pid\n\n # AWS Bedrock — detect via boto3 credential chain (IAM roles, SSO, env vars).\n # This runs after API-key providers so explicit keys always win.\n try:\n from agent.bedrock_adapter import has_aws_credentials\n if has_aws_credentials():\n return \"bedrock\"\n except ImportError:\n pass # boto3 not installed — skip Bedrock auto-detection\n\n raise AuthError(\n \"No inference provider configured. Run 'hermes model' to choose a \"\n \"provider and model, or set an API key (OPENROUTER_API_KEY, \"\n \"OPENAI_API_KEY, etc.) in ~/.hermes/.env.\",\n code=\"no_provider_configured\",\n )\n\n\n# =============================================================================\n# Timestamp / TTL helpers\n# =============================================================================\n\ndef _parse_iso_timestamp(value: Any) -> Optional[float]:\n if not isinstance(value, str) or not value:\n return None\n text = value.strip()\n if not text:\n return None\n if text.endswith(\"Z\"):\n text = text[:-1] + \"+00:00\"\n try:\n parsed = datetime.fromisoformat(text)\n except Exception:\n return None\n if parsed.tzinfo is None:\n parsed = parsed.replace(tzinfo=timezone.utc)\n return parsed.timestamp()\n\n\ndef _is_expiring(expires_at_iso: Any, skew_seconds: int) -> bool:\n expires_epoch = _parse_iso_timestamp(expires_at_iso)\n if expires_epoch is None:\n return True\n return expires_epoch <= (time.time() + skew_seconds)\n\n\ndef _coerce_ttl_seconds(expires_in: Any) -> int:\n try:\n ttl = int(expires_in)\n except Exception:\n ttl = 0\n return max(0, ttl)\n\n\ndef _optional_base_url(value: Any) -> Optional[str]:\n if not isinstance(value, str):\n return None\n cleaned = value.strip().rstrip(\"/\")\n return cleaned if cleaned else None\n\n\ndef _decode_jwt_claims(token: Any) -> Dict[str, Any]:\n if not isinstance(token, str) or token.count(\".\") != 2:\n return {}\n payload = token.split(\".\")[1]\n payload += \"=\" * ((4 - len(payload) % 4) % 4)\n try:\n raw = base64.urlsafe_b64decode(payload.encode(\"utf-8\"))\n claims = json.loads(raw.decode(\"utf-8\"))\n except Exception:\n return {}\n return claims if isinstance(claims, dict) else {}\n\n\ndef _codex_access_token_is_expiring(access_token: Any, skew_seconds: int) -> bool:\n claims = _decode_jwt_claims(access_token)\n exp = claims.get(\"exp\")\n if not isinstance(exp, (int, float)):\n return False\n return float(exp) <= (time.time() + max(0, int(skew_seconds)))\n\n\ndef _qwen_cli_auth_path() -> Path:\n return Path.home() / \".qwen\" / \"oauth_creds.json\"\n\n\ndef _read_qwen_cli_tokens() -> Dict[str, Any]:\n auth_path = _qwen_cli_auth_path()\n if not auth_path.exists():\n raise AuthError(\n \"Qwen CLI credentials not found. Run 'qwen auth qwen-oauth' first.\",\n provider=\"qwen-oauth\",\n code=\"qwen_auth_missing\",\n )\n try:\n data = json.loads(auth_path.read_text(encoding=\"utf-8\"))\n except Exception as exc:\n raise AuthError(\n f\"Failed to read Qwen CLI credentials from {auth_path}: {exc}\",\n provider=\"qwen-oauth\",\n code=\"qwen_auth_read_failed\",\n ) from exc\n if not isinstance(data, dict):\n raise AuthError(\n f\"Invalid Qwen CLI credentials in {auth_path}.\",\n provider=\"qwen-oauth\",\n code=\"qwen_auth_invalid\",\n )\n return data\n\n\ndef _save_qwen_cli_tokens(tokens: Dict[str, Any]) -> Path:\n auth_path = _qwen_cli_auth_path()\n auth_path.parent.mkdir(parents=True, exist_ok=True)\n tmp_path = auth_path.with_suffix(\".tmp\")\n tmp_path.write_text(json.dumps(tokens, indent=2, sort_keys=True) + \"\\n\", encoding=\"utf-8\")\n os.chmod(tmp_path, stat.S_IRUSR | stat.S_IWUSR)\n tmp_path.replace(auth_path)\n return auth_path\n\n\ndef _qwen_access_token_is_expiring(expiry_date_ms: Any, skew_seconds: int = QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS) -> bool:\n try:\n expiry_ms = int(expiry_date_ms)\n except Exception:\n return True\n return (time.time() + max(0, int(skew_seconds))) * 1000 >= expiry_ms\n\n\ndef _refresh_qwen_cli_tokens(tokens: Dict[str, Any], timeout_seconds: float = 20.0) -> Dict[str, Any]:\n refresh_token = str(tokens.get(\"refresh_token\", \"\") or \"\").strip()\n if not refresh_token:\n raise AuthError(\n \"Qwen OAuth refresh token missing. Re-run 'qwen auth qwen-oauth'.\",\n provider=\"qwen-oauth\",\n code=\"qwen_refresh_token_missing\",\n )\n\n try:\n response = httpx.post(\n QWEN_OAUTH_TOKEN_URL,\n headers={\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept\": \"application/json\",\n },\n data={\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": refresh_token,\n \"client_id\": QWEN_OAUTH_CLIENT_ID,\n },\n timeout=timeout_seconds,\n )\n except Exception as exc:\n raise AuthError(\n f\"Qwen OAuth refresh failed: {exc}\",\n provider=\"qwen-oauth\",\n code=\"qwen_refresh_failed\",\n ) from exc\n\n if response.status_code >= 400:\n body = response.text.strip()\n raise AuthError(\n \"Qwen OAuth refresh failed. Re-run 'qwen auth qwen-oauth'.\"\n + (f\" Response: {body}\" if body else \"\"),\n provider=\"qwen-oauth\",\n code=\"qwen_refresh_failed\",\n )\n\n try:\n payload = response.json()\n except Exception as exc:\n raise AuthError(\n f\"Qwen OAuth refresh returned invalid JSON: {exc}\",\n provider=\"qwen-oauth\",\n code=\"qwen_refresh_invalid_json\",\n ) from exc\n\n if not isinstance(payload, dict) or not str(payload.get(\"access_token\", \"\") or \"\").strip():\n raise AuthError(\n \"Qwen OAuth refresh response missing access_token.\",\n provider=\"qwen-oauth\",\n code=\"qwen_refresh_invalid_response\",\n )\n\n expires_in = payload.get(\"expires_in\")\n try:\n expires_in_seconds = int(expires_in)\n except Exception:\n expires_in_seconds = 6 * 60 * 60\n\n refreshed = {\n \"access_token\": str(payload.get(\"access_token\", \"\") or \"\").strip(),\n \"refresh_token\": str(payload.get(\"refresh_token\", refresh_token) or refresh_token).strip(),\n \"token_type\": str(payload.get(\"token_type\", tokens.get(\"token_type\", \"Bearer\")) or \"Bearer\").strip() or \"Bearer\",\n \"resource_url\": str(payload.get(\"resource_url\", tokens.get(\"resource_url\", \"portal.qwen.ai\")) or \"portal.qwen.ai\").strip(),\n \"expiry_date\": int(time.time() * 1000) + max(1, expires_in_seconds) * 1000,\n }\n _save_qwen_cli_tokens(refreshed)\n return refreshed\n\n\ndef resolve_qwen_runtime_credentials(\n *,\n force_refresh: bool = False,\n refresh_if_expiring: bool = True,\n refresh_skew_seconds: int = QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,\n) -> Dict[str, Any]:\n tokens = _read_qwen_cli_tokens()\n access_token = str(tokens.get(\"access_token\", \"\") or \"\").strip()\n should_refresh = bool(force_refresh)\n if not should_refresh and refresh_if_expiring:\n should_refresh = _qwen_access_token_is_expiring(tokens.get(\"expiry_date\"), refresh_skew_seconds)\n if should_refresh:\n tokens = _refresh_qwen_cli_tokens(tokens)\n access_token = str(tokens.get(\"access_token\", \"\") or \"\").strip()\n if not access_token:\n raise AuthError(\n \"Qwen OAuth access token missing. Re-run 'qwen auth qwen-oauth'.\",\n provider=\"qwen-oauth\",\n code=\"qwen_access_token_missing\",\n )\n\n base_url = os.getenv(\"HERMES_QWEN_BASE_URL\", \"\").strip().rstrip(\"/\") or DEFAULT_QWEN_BASE_URL\n return {\n \"provider\": \"qwen-oauth\",\n \"base_url\": base_url,\n \"api_key\": access_token,\n \"source\": \"qwen-cli\",\n \"expires_at_ms\": tokens.get(\"expiry_date\"),\n \"auth_file\": str(_qwen_cli_auth_path()),\n }\n\n\ndef get_qwen_auth_status() -> Dict[str, Any]:\n auth_path = _qwen_cli_auth_path()\n try:\n creds = resolve_qwen_runtime_credentials(refresh_if_expiring=False)\n return {\n \"logged_in\": True,\n \"auth_file\": str(auth_path),\n \"source\": creds.get(\"source\"),\n \"api_key\": creds.get(\"api_key\"),\n \"expires_at_ms\": creds.get(\"expires_at_ms\"),\n }\n except AuthError as exc:\n return {\n \"logged_in\": False,\n \"auth_file\": str(auth_path),\n \"error\": str(exc),\n }\n\n\n# =============================================================================\n# Google Gemini OAuth (google-gemini-cli) — PKCE flow + Cloud Code Assist.\n#\n# Tokens live in ~/.hermes/auth/google_oauth.json (managed by agent.google_oauth).\n# The `base_url` here is the marker \"cloudcode-pa://google\" that run_agent.py\n# uses to construct a GeminiCloudCodeClient instead of the default OpenAI SDK.\n# Actual HTTP traffic goes to https://cloudcode-pa.googleapis.com/v1internal:*.\n# =============================================================================\n\ndef resolve_gemini_oauth_runtime_credentials(\n *,\n force_refresh: bool = False,\n) -> Dict[str, Any]:\n \"\"\"Resolve runtime OAuth creds for google-gemini-cli.\"\"\"\n try:\n from agent.google_oauth import (\n GoogleOAuthError,\n _credentials_path,\n get_valid_access_token,\n load_credentials,\n )\n except ImportError as exc:\n raise AuthError(\n f\"agent.google_oauth is not importable: {exc}\",\n provider=\"google-gemini-cli\",\n code=\"google_oauth_module_missing\",\n ) from exc\n\n try:\n access_token = get_valid_access_token(force_refresh=force_refresh)\n except GoogleOAuthError as exc:\n raise AuthError(\n str(exc),\n provider=\"google-gemini-cli\",\n code=exc.code,\n ) from exc\n\n creds = load_credentials()\n base_url = DEFAULT_GEMINI_CLOUDCODE_BASE_URL\n return {\n \"provider\": \"google-gemini-cli\",\n \"base_url\": base_url,\n \"api_key\": access_token,\n \"source\": \"google-oauth\",\n \"expires_at_ms\": (creds.expires_ms if creds else None),\n \"auth_file\": str(_credentials_path()),\n \"email\": (creds.email if creds else \"\") or \"\",\n \"project_id\": (creds.project_id if creds else \"\") or \"\",\n }\n\n\ndef get_gemini_oauth_auth_status() -> Dict[str, Any]:\n \"\"\"Return a status dict for `hermes auth list` / `hermes status`.\"\"\"\n try:\n from agent.google_oauth import _credentials_path, load_credentials\n except ImportError:\n return {\"logged_in\": False, \"error\": \"agent.google_oauth unavailable\"}\n auth_path = _credentials_path()\n creds = load_credentials()\n if creds is None or not creds.access_token:\n return {\n \"logged_in\": False,\n \"auth_file\": str(auth_path),\n \"error\": \"not logged in\",\n }\n return {\n \"logged_in\": True,\n \"auth_file\": str(auth_path),\n \"source\": \"google-oauth\",\n \"api_key\": creds.access_token,\n \"expires_at_ms\": creds.expires_ms,\n \"email\": creds.email,\n \"project_id\": creds.project_id,\n }\n# Spotify auth — PKCE tokens stored in ~/.hermes/auth.json\n# =============================================================================\n\n\ndef _spotify_scope_list(raw_scope: Optional[str] = None) -> List[str]:\n scope_text = (raw_scope or DEFAULT_SPOTIFY_SCOPE).strip()\n scopes = [part for part in scope_text.split() if part]\n seen: set[str] = set()\n ordered: List[str] = []\n for scope in scopes:\n if scope not in seen:\n seen.add(scope)\n ordered.append(scope)\n return ordered\n\n\ndef _spotify_scope_string(raw_scope: Optional[str] = None) -> str:\n return \" \".join(_spotify_scope_list(raw_scope))\n\n\ndef _spotify_client_id(\n explicit: Optional[str] = None,\n state: Optional[Dict[str, Any]] = None,\n) -> str:\n from hermes_cli.config import get_env_value\n\n candidates = (\n explicit,\n get_env_value(\"HERMES_SPOTIFY_CLIENT_ID\"),\n get_env_value(\"SPOTIFY_CLIENT_ID\"),\n state.get(\"client_id\") if isinstance(state, dict) else None,\n )\n for candidate in candidates:\n cleaned = str(candidate or \"\").strip()\n if cleaned:\n return cleaned\n raise AuthError(\n \"Spotify client_id is required. Set HERMES_SPOTIFY_CLIENT_ID or pass --client-id.\",\n provider=\"spotify\",\n code=\"spotify_client_id_missing\",\n )\n\n\ndef _spotify_redirect_uri(\n explicit: Optional[str] = None,\n state: Optional[Dict[str, Any]] = None,\n) -> str:\n from hermes_cli.config import get_env_value\n\n candidates = (\n explicit,\n get_env_value(\"HERMES_SPOTIFY_REDIRECT_URI\"),\n get_env_value(\"SPOTIFY_REDIRECT_URI\"),\n state.get(\"redirect_uri\") if isinstance(state, dict) else None,\n DEFAULT_SPOTIFY_REDIRECT_URI,\n )\n for candidate in candidates:\n cleaned = str(candidate or \"\").strip()\n if cleaned:\n return cleaned\n return DEFAULT_SPOTIFY_REDIRECT_URI\n\n\ndef _spotify_api_base_url(state: Optional[Dict[str, Any]] = None) -> str:\n from hermes_cli.config import get_env_value\n\n candidates = (\n get_env_value(\"HERMES_SPOTIFY_API_BASE_URL\"),\n state.get(\"api_base_url\") if isinstance(state, dict) else None,\n DEFAULT_SPOTIFY_API_BASE_URL,\n )\n for candidate in candidates:\n cleaned = str(candidate or \"\").strip().rstrip(\"/\")\n if cleaned:\n return cleaned\n return DEFAULT_SPOTIFY_API_BASE_URL\n\n\ndef _spotify_accounts_base_url(state: Optional[Dict[str, Any]] = None) -> str:\n from hermes_cli.config import get_env_value\n\n candidates = (\n get_env_value(\"HERMES_SPOTIFY_ACCOUNTS_BASE_URL\"),\n state.get(\"accounts_base_url\") if isinstance(state, dict) else None,\n DEFAULT_SPOTIFY_ACCOUNTS_BASE_URL,\n )\n for candidate in candidates:\n cleaned = str(candidate or \"\").strip().rstrip(\"/\")\n if cleaned:\n return cleaned\n return DEFAULT_SPOTIFY_ACCOUNTS_BASE_URL\n\n\ndef _spotify_code_verifier(length: int = 64) -> str:\n raw = base64.urlsafe_b64encode(os.urandom(length)).decode(\"ascii\")\n return raw.rstrip(\"=\")[:128]\n\n\ndef _spotify_code_challenge(code_verifier: str) -> str:\n digest = hashlib.sha256(code_verifier.encode(\"utf-8\")).digest()\n return base64.urlsafe_b64encode(digest).decode(\"ascii\").rstrip(\"=\")\n\n\ndef _spotify_build_authorize_url(\n *,\n client_id: str,\n redirect_uri: str,\n scope: str,\n state: str,\n code_challenge: str,\n accounts_base_url: str,\n) -> str:\n query = urlencode({\n \"client_id\": client_id,\n \"response_type\": \"code\",\n \"redirect_uri\": redirect_uri,\n \"scope\": scope,\n \"state\": state,\n \"code_challenge_method\": \"S256\",\n \"code_challenge\": code_challenge,\n })\n return f\"{accounts_base_url}/authorize?{query}\"\n\n\ndef _spotify_validate_redirect_uri(redirect_uri: str) -> tuple[str, int, str]:\n parsed = urlparse(redirect_uri)\n if parsed.scheme != \"http\":\n raise AuthError(\n \"Spotify PKCE redirect_uri must use http://localhost or http://127.0.0.1.\",\n provider=\"spotify\",\n code=\"spotify_redirect_invalid\",\n )\n host = parsed.hostname or \"\"\n if host not in {\"127.0.0.1\", \"localhost\"}:\n raise AuthError(\n \"Spotify PKCE redirect_uri must point to localhost or 127.0.0.1.\",\n provider=\"spotify\",\n code=\"spotify_redirect_invalid\",\n )\n if not parsed.port:\n raise AuthError(\n \"Spotify PKCE redirect_uri must include an explicit localhost port.\",\n provider=\"spotify\",\n code=\"spotify_redirect_invalid\",\n )\n return host, parsed.port, parsed.path or \"/\"\n\n\ndef _make_spotify_callback_handler(expected_path: str) -> tuple[type[BaseHTTPRequestHandler], dict[str, Any]]:\n result: dict[str, Any] = {\n \"code\": None,\n \"state\": None,\n \"error\": None,\n \"error_description\": None,\n }\n\n class _SpotifyCallbackHandler(BaseHTTPRequestHandler):\n def do_GET(self) -> None: # noqa: N802\n parsed = urlparse(self.path)\n if parsed.path != expected_path:\n self.send_response(404)\n self.end_headers()\n self.wfile.write(b\"Not found.\")\n return\n\n params = parse_qs(parsed.query)\n result[\"code\"] = params.get(\"code\", [None])[0]\n result[\"state\"] = params.get(\"state\", [None])[0]\n result[\"error\"] = params.get(\"error\", [None])[0]\n result[\"error_description\"] = params.get(\"error_description\", [None])[0]\n\n self.send_response(200)\n self.send_header(\"Content-Type\", \"text/html; charset=utf-8\")\n self.end_headers()\n if result[\"error\"]:\n body = \"<html><body><h1>Spotify authorization failed.</h1>You can close this tab.</body></html>\"\n else:\n body = \"<html><body><h1>Spotify authorization received.</h1>You can close this tab.</body></html>\"\n self.wfile.write(body.encode(\"utf-8\"))\n\n def log_message(self, format: str, *args: Any) -> None: # noqa: A003\n return\n\n return _SpotifyCallbackHandler, result\n\n\ndef _spotify_wait_for_callback(\n redirect_uri: str,\n *,\n timeout_seconds: float = 180.0,\n) -> dict[str, Any]:\n host, port, path = _spotify_validate_redirect_uri(redirect_uri)\n handler_cls, result = _make_spotify_callback_handler(path)\n\n class _ReuseHTTPServer(HTTPServer):\n allow_reuse_address = True\n\n try:\n server = _ReuseHTTPServer((host, port), handler_cls)\n except OSError as exc:\n raise AuthError(\n f\"Could not bind Spotify callback server on {host}:{port}: {exc}\",\n provider=\"spotify\",\n code=\"spotify_callback_bind_failed\",\n ) from exc\n\n thread = threading.Thread(target=server.serve_forever, kwargs={\"poll_interval\": 0.1}, daemon=True)\n thread.start()\n deadline = time.time() + max(5.0, timeout_seconds)\n try:\n while time.time() < deadline:\n if result[\"code\"] or result[\"error\"]:\n return result\n time.sleep(0.1)\n finally:\n server.shutdown()\n server.server_close()\n thread.join(timeout=1.0)\n raise AuthError(\n \"Spotify authorization timed out waiting for the local callback.\",\n provider=\"spotify\",\n code=\"spotify_callback_timeout\",\n )\n\n\ndef _spotify_token_payload_to_state(\n token_payload: Dict[str, Any],\n *,\n client_id: str,\n redirect_uri: str,\n requested_scope: str,\n accounts_base_url: str,\n api_base_url: str,\n previous_state: Optional[Dict[str, Any]] = None,\n) -> Dict[str, Any]:\n now = datetime.now(timezone.utc)\n expires_in = _coerce_ttl_seconds(token_payload.get(\"expires_in\", 0))\n expires_at = datetime.fromtimestamp(now.timestamp() + expires_in, tz=timezone.utc)\n state = dict(previous_state or {})\n state.update({\n \"client_id\": client_id,\n \"redirect_uri\": redirect_uri,\n \"accounts_base_url\": accounts_base_url,\n \"api_base_url\": api_base_url,\n \"scope\": requested_scope,\n \"granted_scope\": str(token_payload.get(\"scope\") or requested_scope).strip(),\n \"token_type\": str(token_payload.get(\"token_type\", \"Bearer\") or \"Bearer\").strip() or \"Bearer\",\n \"access_token\": str(token_payload.get(\"access_token\", \"\") or \"\").strip(),\n \"refresh_token\": str(\n token_payload.get(\"refresh_token\")\n or state.get(\"refresh_token\")\n or \"\"\n ).strip(),\n \"obtained_at\": now.isoformat(),\n \"expires_at\": expires_at.isoformat(),\n \"expires_in\": expires_in,\n \"auth_type\": \"oauth_pkce\",\n })\n return state\n\n\ndef _spotify_exchange_code_for_tokens(\n *,\n client_id: str,\n code: str,\n redirect_uri: str,\n code_verifier: str,\n accounts_base_url: str,\n timeout_seconds: float = 20.0,\n) -> Dict[str, Any]:\n try:\n response = httpx.post(\n f\"{accounts_base_url}/api/token\",\n headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n data={\n \"client_id\": client_id,\n \"grant_type\": \"authorization_code\",\n \"code\": code,\n \"redirect_uri\": redirect_uri,\n \"code_verifier\": code_verifier,\n },\n timeout=timeout_seconds,\n )\n except Exception as exc:\n raise AuthError(\n f\"Spotify token exchange failed: {exc}\",\n provider=\"spotify\",\n code=\"spotify_token_exchange_failed\",\n ) from exc\n\n if response.status_code >= 400:\n detail = response.text.strip()\n raise AuthError(\n \"Spotify token exchange failed.\"\n + (f\" Response: {detail}\" if detail else \"\"),\n provider=\"spotify\",\n code=\"spotify_token_exchange_failed\",\n )\n payload = response.json()\n if not isinstance(payload, dict) or not str(payload.get(\"access_token\", \"\") or \"\").strip():\n raise AuthError(\n \"Spotify token response did not include an access_token.\",\n provider=\"spotify\",\n code=\"spotify_token_exchange_invalid\",\n )\n return payload\n\n\ndef _refresh_spotify_oauth_state(\n state: Dict[str, Any],\n *,\n timeout_seconds: float = 20.0,\n) -> Dict[str, Any]:\n refresh_token = str(state.get(\"refresh_token\", \"\") or \"\").strip()\n if not refresh_token:\n raise AuthError(\n \"Spotify refresh token missing. Run `hermes auth spotify` again.\",\n provider=\"spotify\",\n code=\"spotify_refresh_token_missing\",\n relogin_required=True,\n )\n\n client_id = _spotify_client_id(state=state)\n accounts_base_url = _spotify_accounts_base_url(state)\n try:\n response = httpx.post(\n f\"{accounts_base_url}/api/token\",\n headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n data={\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": refresh_token,\n \"client_id\": client_id,\n },\n timeout=timeout_seconds,\n )\n except Exception as exc:\n raise AuthError(\n f\"Spotify token refresh failed: {exc}\",\n provider=\"spotify\",\n code=\"spotify_refresh_failed\",\n ) from exc\n\n if response.status_code >= 400:\n detail = response.text.strip()\n raise AuthError(\n \"Spotify token refresh failed. Run `hermes auth spotify` again.\"\n + (f\" Response: {detail}\" if detail else \"\"),\n provider=\"spotify\",\n code=\"spotify_refresh_failed\",\n relogin_required=True,\n )\n\n payload = response.json()\n if not isinstance(payload, dict) or not str(payload.get(\"access_token\", \"\") or \"\").strip():\n raise AuthError(\n \"Spotify refresh response did not include an access_token.\",\n provider=\"spotify\",\n code=\"spotify_refresh_invalid\",\n relogin_required=True,\n )\n\n return _spotify_token_payload_to_state(\n payload,\n client_id=client_id,\n redirect_uri=_spotify_redirect_uri(state=state),\n requested_scope=str(state.get(\"scope\") or DEFAULT_SPOTIFY_SCOPE),\n accounts_base_url=accounts_base_url,\n api_base_url=_spotify_api_base_url(state),\n previous_state=state,\n )\n\n\ndef resolve_spotify_runtime_credentials(\n *,\n force_refresh: bool = False,\n refresh_if_expiring: bool = True,\n refresh_skew_seconds: int = SPOTIFY_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,\n) -> Dict[str, Any]:\n with _auth_store_lock():\n auth_store = _load_auth_store()\n state = _load_provider_state(auth_store, \"spotify\")\n if not state:\n raise AuthError(\n \"Spotify is not authenticated. Run `hermes auth spotify` first.\",\n provider=\"spotify\",\n code=\"spotify_auth_missing\",\n relogin_required=True,\n )\n\n should_refresh = bool(force_refresh)\n if not should_refresh and refresh_if_expiring:\n should_refresh = _is_expiring(state.get(\"expires_at\"), refresh_skew_seconds)\n if should_refresh:\n state = _refresh_spotify_oauth_state(state)\n _store_provider_state(auth_store, \"spotify\", state, set_active=False)\n _save_auth_store(auth_store)\n\n access_token = str(state.get(\"access_token\", \"\") or \"\").strip()\n if not access_token:\n raise AuthError(\n \"Spotify access token missing. Run `hermes auth spotify` again.\",\n provider=\"spotify\",\n code=\"spotify_access_token_missing\",\n relogin_required=True,\n )\n\n return {\n \"provider\": \"spotify\",\n \"access_token\": access_token,\n \"api_key\": access_token,\n \"token_type\": str(state.get(\"token_type\", \"Bearer\") or \"Bearer\"),\n \"base_url\": _spotify_api_base_url(state),\n \"scope\": str(state.get(\"granted_scope\") or state.get(\"scope\") or \"\").strip(),\n \"client_id\": _spotify_client_id(state=state),\n \"redirect_uri\": _spotify_redirect_uri(state=state),\n \"expires_at\": state.get(\"expires_at\"),\n \"refresh_token\": str(state.get(\"refresh_token\", \"\") or \"\").strip(),\n }\n\n\ndef get_spotify_auth_status() -> Dict[str, Any]:\n state = get_provider_auth_state(\"spotify\")\n if not state:\n return {\"logged_in\": False}\n\n expires_at = state.get(\"expires_at\")\n refresh_token = str(state.get(\"refresh_token\", \"\") or \"\").strip()\n return {\n \"logged_in\": bool(refresh_token or not _is_expiring(expires_at, 0)),\n \"auth_type\": state.get(\"auth_type\", \"oauth_pkce\"),\n \"client_id\": state.get(\"client_id\"),\n \"redirect_uri\": state.get(\"redirect_uri\"),\n \"scope\": state.get(\"granted_scope\") or state.get(\"scope\"),\n \"expires_at\": expires_at,\n \"api_base_url\": state.get(\"api_base_url\"),\n \"has_refresh_token\": bool(refresh_token),\n }\n\n\ndef _spotify_interactive_setup(redirect_uri_hint: str) -> str:\n \"\"\"Walk the user through creating a Spotify developer app, persist the\n resulting client_id to ~/.hermes/.env, and return it.\n\n Raises SystemExit if the user aborts or submits an empty value.\n \"\"\"\n from hermes_cli.config import save_env_value\n\n print()\n print(\"=\" * 70)\n print(\"Spotify first-time setup\")\n print(\"=\" * 70)\n print()\n print(\"Spotify requires every user to register their own lightweight\")\n print(\"developer app. This takes about two minutes and only has to be\")\n print(\"done once per machine.\")\n print()\n print(f\"Full guide: {SPOTIFY_DOCS_URL}\")\n print()\n print(\"Steps:\")\n print(f\" 1. Opening {SPOTIFY_DASHBOARD_URL} in your browser...\")\n print(\" 2. Click 'Create app' and fill in:\")\n print(\" App name: anything (e.g. hermes-agent)\")\n print(\" Description: anything\")\n print(f\" Redirect URI: {redirect_uri_hint}\")\n print(\" API/SDK: Web API\")\n print(\" 3. Agree to the terms, click Save.\")\n print(\" 4. Open the app's Settings page and copy the Client ID.\")\n print(\" 5. Paste it below.\")\n print()\n\n if not _is_remote_session():\n try:\n webbrowser.open(SPOTIFY_DASHBOARD_URL)\n except Exception:\n pass\n\n try:\n raw = input(\"Spotify Client ID: \").strip()\n except (EOFError, KeyboardInterrupt):\n print()\n raise SystemExit(\"Spotify setup cancelled.\")\n\n if not raw:\n print()\n print(f\"No Client ID entered. See {SPOTIFY_DOCS_URL} for the full guide.\")\n raise SystemExit(\"Spotify setup cancelled: empty Client ID.\")\n\n # Persist so subsequent `hermes auth spotify` runs skip the wizard.\n save_env_value(\"HERMES_SPOTIFY_CLIENT_ID\", raw)\n # Only persist the redirect URI if it's non-default, to avoid pinning\n # users to a value the default might later change to.\n if redirect_uri_hint and redirect_uri_hint != DEFAULT_SPOTIFY_REDIRECT_URI:\n save_env_value(\"HERMES_SPOTIFY_REDIRECT_URI\", redirect_uri_hint)\n\n print()\n print(\"Saved HERMES_SPOTIFY_CLIENT_ID to ~/.hermes/.env\")\n print()\n return raw\n\n\ndef login_spotify_command(args) -> None:\n existing_state = get_provider_auth_state(\"spotify\") or {}\n\n # Interactive wizard: if no client_id is configured anywhere, walk the\n # user through creating the Spotify developer app instead of crashing\n # with \"HERMES_SPOTIFY_CLIENT_ID is required\".\n explicit_client_id = getattr(args, \"client_id\", None)\n try:\n client_id = _spotify_client_id(explicit_client_id, existing_state)\n except AuthError as exc:\n if getattr(exc, \"code\", \"\") != \"spotify_client_id_missing\":\n raise\n client_id = _spotify_interactive_setup(\n redirect_uri_hint=getattr(args, \"redirect_uri\", None) or DEFAULT_SPOTIFY_REDIRECT_URI,\n )\n\n redirect_uri = _spotify_redirect_uri(getattr(args, \"redirect_uri\", None), existing_state)\n scope = _spotify_scope_string(getattr(args, \"scope\", None) or existing_state.get(\"scope\"))\n accounts_base_url = _spotify_accounts_base_url(existing_state)\n api_base_url = _spotify_api_base_url(existing_state)\n open_browser = not getattr(args, \"no_browser\", False)\n\n code_verifier = _spotify_code_verifier()\n code_challenge = _spotify_code_challenge(code_verifier)\n state_nonce = uuid.uuid4().hex\n authorize_url = _spotify_build_authorize_url(\n client_id=client_id,\n redirect_uri=redirect_uri,\n scope=scope,\n state=state_nonce,\n code_challenge=code_challenge,\n accounts_base_url=accounts_base_url,\n )\n\n print(\"Starting Spotify PKCE login...\")\n print(f\"Client ID: {client_id}\")\n print(f\"Redirect URI: {redirect_uri}\")\n print(\"Make sure this redirect URI is allow-listed in your Spotify app settings.\")\n print()\n print(\"Open this URL to authorize Hermes:\")\n print(authorize_url)\n print()\n print(f\"Full setup guide: {SPOTIFY_DOCS_URL}\")\n print()\n\n if open_browser and not _is_remote_session():\n try:\n opened = webbrowser.open(authorize_url)\n except Exception:\n opened = False\n if opened:\n print(\"Browser opened for Spotify authorization.\")\n else:\n print(\"Could not open the browser automatically; use the URL above.\")\n\n callback = _spotify_wait_for_callback(\n redirect_uri,\n timeout_seconds=float(getattr(args, \"timeout\", None) or 180.0),\n )\n if callback.get(\"error\"):\n detail = callback.get(\"error_description\") or callback[\"error\"]\n raise SystemExit(f\"Spotify authorization failed: {detail}\")\n if callback.get(\"state\") != state_nonce:\n raise SystemExit(\"Spotify authorization failed: state mismatch.\")\n\n token_payload = _spotify_exchange_code_for_tokens(\n client_id=client_id,\n code=str(callback.get(\"code\") or \"\"),\n redirect_uri=redirect_uri,\n code_verifier=code_verifier,\n accounts_base_url=accounts_base_url,\n timeout_seconds=float(getattr(args, \"timeout\", None) or 20.0),\n )\n spotify_state = _spotify_token_payload_to_state(\n token_payload,\n client_id=client_id,\n redirect_uri=redirect_uri,\n requested_scope=scope,\n accounts_base_url=accounts_base_url,\n api_base_url=api_base_url,\n )\n\n with _auth_store_lock():\n auth_store = _load_auth_store()\n _store_provider_state(auth_store, \"spotify\", spotify_state, set_active=False)\n saved_to = _save_auth_store(auth_store)\n\n print(\"Spotify login successful!\")\n print(f\" Auth state: {saved_to}\")\n print(\" Provider state saved under providers.spotify\")\n print(f\" Docs: {SPOTIFY_DOCS_URL}\")\n\n# =============================================================================\n# SSH / remote session detection\n# =============================================================================\n\ndef _is_remote_session() -> bool:\n \"\"\"Detect if running in an SSH session where webbrowser.open() won't work.\"\"\"\n return bool(os.getenv(\"SSH_CLIENT\") or os.getenv(\"SSH_TTY\"))\n\n\n# =============================================================================\n# OpenAI Codex auth — tokens stored in ~/.hermes/auth.json (not ~/.codex/)\n#\n# Hermes maintains its own Codex OAuth session separate from the Codex CLI\n# and VS Code extension. This prevents refresh token rotation conflicts\n# where one app's refresh invalidates the other's session.\n# =============================================================================\n\ndef _read_codex_tokens(*, _lock: bool = True) -> Dict[str, Any]:\n \"\"\"Read Codex OAuth tokens from Hermes auth store (~/.hermes/auth.json).\n \n Returns dict with 'tokens' (access_token, refresh_token) and 'last_refresh'.\n Raises AuthError if no Codex tokens are stored.\n \"\"\"\n if _lock:\n with _auth_store_lock():\n auth_store = _load_auth_store()\n else:\n auth_store = _load_auth_store()\n state = _load_provider_state(auth_store, \"openai-codex\")\n if not state:\n raise AuthError(\n \"No Codex credentials stored. Run `hermes auth` to authenticate.\",\n provider=\"openai-codex\",\n code=\"codex_auth_missing\",\n relogin_required=True,\n )\n tokens = state.get(\"tokens\")\n if not isinstance(tokens, dict):\n raise AuthError(\n \"Codex auth state is missing tokens. Run `hermes auth` to re-authenticate.\",\n provider=\"openai-codex\",\n code=\"codex_auth_invalid_shape\",\n relogin_required=True,\n )\n access_token = tokens.get(\"access_token\")\n refresh_token = tokens.get(\"refresh_token\")\n if not isinstance(access_token, str) or not access_token.strip():\n raise AuthError(\n \"Codex auth is missing access_token. Run `hermes auth` to re-authenticate.\",\n provider=\"openai-codex\",\n code=\"codex_auth_missing_access_token\",\n relogin_required=True,\n )\n if not isinstance(refresh_token, str) or not refresh_token.strip():\n raise AuthError(\n \"Codex auth is missing refresh_token. Run `hermes auth` to re-authenticate.\",\n provider=\"openai-codex\",\n code=\"codex_auth_missing_refresh_token\",\n relogin_required=True,\n )\n return {\n \"tokens\": tokens,\n \"last_refresh\": state.get(\"last_refresh\"),\n }\n\n\ndef _save_codex_tokens(tokens: Dict[str, str], last_refresh: str = None) -> None:\n \"\"\"Save Codex OAuth tokens to Hermes auth store (~/.hermes/auth.json).\"\"\"\n if last_refresh is None:\n last_refresh = datetime.now(timezone.utc).isoformat().replace(\"+00:00\", \"Z\")\n with _auth_store_lock():\n auth_store = _load_auth_store()\n state = _load_provider_state(auth_store, \"openai-codex\") or {}\n state[\"tokens\"] = tokens\n state[\"last_refresh\"] = last_refresh\n state[\"auth_mode\"] = \"chatgpt\"\n _save_provider_state(auth_store, \"openai-codex\", state)\n _save_auth_store(auth_store)\n\n\ndef refresh_codex_oauth_pure(\n access_token: str,\n refresh_token: str,\n *,\n timeout_seconds: float = 20.0,\n) -> Dict[str, Any]:\n \"\"\"Refresh Codex OAuth tokens without mutating Hermes auth state.\"\"\"\n del access_token # Access token is only used by callers to decide whether to refresh.\n if not isinstance(refresh_token, str) or not refresh_token.strip():\n raise AuthError(\n \"Codex auth is missing refresh_token. Run `hermes auth` to re-authenticate.\",\n provider=\"openai-codex\",\n code=\"codex_auth_missing_refresh_token\",\n relogin_required=True,\n )\n\n timeout = httpx.Timeout(max(5.0, float(timeout_seconds)))\n with httpx.Client(timeout=timeout, headers={\"Accept\": \"application/json\"}) as client:\n response = client.post(\n CODEX_OAUTH_TOKEN_URL,\n headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n data={\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": refresh_token,\n \"client_id\": CODEX_OAUTH_CLIENT_ID,\n },\n )\n\n if response.status_code != 200:\n code = \"codex_refresh_failed\"\n message = f\"Codex token refresh failed with status {response.status_code}.\"\n relogin_required = False\n try:\n err = response.json()\n if isinstance(err, dict):\n err_obj = err.get(\"error\")\n # OpenAI shape: {\"error\": {\"code\": \"...\", \"message\": \"...\", \"type\": \"...\"}}\n if isinstance(err_obj, dict):\n nested_code = err_obj.get(\"code\") or err_obj.get(\"type\")\n if isinstance(nested_code, str) and nested_code.strip():\n code = nested_code.strip()\n nested_msg = err_obj.get(\"message\")\n if isinstance(nested_msg, str) and nested_msg.strip():\n message = f\"Codex token refresh failed: {nested_msg.strip()}\"\n # OAuth spec shape: {\"error\": \"code_str\", \"error_description\": \"...\"}\n elif isinstance(err_obj, str) and err_obj.strip():\n code = err_obj.strip()\n err_desc = err.get(\"error_description\") or err.get(\"message\")\n if isinstance(err_desc, str) and err_desc.strip():\n message = f\"Codex token refresh failed: {err_desc.strip()}\"\n except Exception:\n pass\n if code in {\"invalid_grant\", \"invalid_token\", \"invalid_request\"}:\n relogin_required = True\n if code == \"refresh_token_reused\":\n message = (\n \"Codex refresh token was already consumed by another client \"\n \"(e.g. Codex CLI or VS Code extension). \"\n \"Run `codex` in your terminal to generate fresh tokens, \"\n \"then run `hermes auth` to re-authenticate.\"\n )\n relogin_required = True\n # A 401/403 from the token endpoint always means the refresh token\n # is invalid/expired — force relogin even if the body error code\n # wasn't one of the known strings above.\n if response.status_code in (401, 403) and not relogin_required:\n relogin_required = True\n raise AuthError(\n message,\n provider=\"openai-codex\",\n code=code,\n relogin_required=relogin_required,\n )\n\n try:\n refresh_payload = response.json()\n except Exception as exc:\n raise AuthError(\n \"Codex token refresh returned invalid JSON.\",\n provider=\"openai-codex\",\n code=\"codex_refresh_invalid_json\",\n relogin_required=True,\n ) from exc\n\n refreshed_access = refresh_payload.get(\"access_token\")\n if not isinstance(refreshed_access, str) or not refreshed_access.strip():\n raise AuthError(\n \"Codex token refresh response was missing access_token.\",\n provider=\"openai-codex\",\n code=\"codex_refresh_missing_access_token\",\n relogin_required=True,\n )\n\n updated = {\n \"access_token\": refreshed_access.strip(),\n \"refresh_token\": refresh_token.strip(),\n \"last_refresh\": datetime.now(timezone.utc).isoformat().replace(\"+00:00\", \"Z\"),\n }\n next_refresh = refresh_payload.get(\"refresh_token\")\n if isinstance(next_refresh, str) and next_refresh.strip():\n updated[\"refresh_token\"] = next_refresh.strip()\n return updated\n\n\ndef _refresh_codex_auth_tokens(\n tokens: Dict[str, str],\n timeout_seconds: float,\n) -> Dict[str, str]:\n \"\"\"Refresh Codex access token using the refresh token.\n \n Saves the new tokens to Hermes auth store automatically.\n \"\"\"\n refreshed = refresh_codex_oauth_pure(\n str(tokens.get(\"access_token\", \"\") or \"\"),\n str(tokens.get(\"refresh_token\", \"\") or \"\"),\n timeout_seconds=timeout_seconds,\n )\n updated_tokens = dict(tokens)\n updated_tokens[\"access_token\"] = refreshed[\"access_token\"]\n updated_tokens[\"refresh_token\"] = refreshed[\"refresh_token\"]\n\n _save_codex_tokens(updated_tokens)\n return updated_tokens\n\n\ndef _import_codex_cli_tokens() -> Optional[Dict[str, str]]:\n \"\"\"Try to read tokens from ~/.codex/auth.json (Codex CLI shared file).\n \n Returns tokens dict if valid and not expired, None otherwise.\n Does NOT write to the shared file.\n \"\"\"\n codex_home = os.getenv(\"CODEX_HOME\", \"\").strip()\n if not codex_home:\n codex_home = str(Path.home() / \".codex\")\n auth_path = Path(codex_home).expanduser() / \"auth.json\"\n if not auth_path.is_file():\n return None\n try:\n payload = json.loads(auth_path.read_text())\n tokens = payload.get(\"tokens\")\n if not isinstance(tokens, dict):\n return None\n access_token = tokens.get(\"access_token\")\n refresh_token = tokens.get(\"refresh_token\")\n if not access_token or not refresh_token:\n return None\n # Reject expired tokens — importing stale tokens from ~/.codex/\n # that can't be refreshed leaves the user stuck with \"Login successful!\"\n # but no working credentials.\n if _codex_access_token_is_expiring(access_token, 0):\n logger.debug(\n \"Codex CLI tokens at %s are expired — skipping import.\", auth_path,\n )\n return None\n return dict(tokens)\n except Exception:\n return None\n\n\ndef resolve_codex_runtime_credentials(\n *,\n force_refresh: bool = False,\n refresh_if_expiring: bool = True,\n refresh_skew_seconds: int = CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,\n) -> Dict[str, Any]:\n \"\"\"Resolve runtime credentials from Hermes's own Codex token store.\"\"\"\n data = _read_codex_tokens()\n tokens = dict(data[\"tokens\"])\n access_token = str(tokens.get(\"access_token\", \"\") or \"\").strip()\n refresh_timeout_seconds = float(os.getenv(\"HERMES_CODEX_REFRESH_TIMEOUT_SECONDS\", \"20\"))\n\n should_refresh = bool(force_refresh)\n if (not should_refresh) and refresh_if_expiring:\n should_refresh = _codex_access_token_is_expiring(access_token, refresh_skew_seconds)\n if should_refresh:\n # Re-read under lock to avoid racing with other Hermes processes\n with _auth_store_lock(timeout_seconds=max(float(AUTH_LOCK_TIMEOUT_SECONDS), refresh_timeout_seconds + 5.0)):\n data = _read_codex_tokens(_lock=False)\n tokens = dict(data[\"tokens\"])\n access_token = str(tokens.get(\"access_token\", \"\") or \"\").strip()\n\n should_refresh = bool(force_refresh)\n if (not should_refresh) and refresh_if_expiring:\n should_refresh = _codex_access_token_is_expiring(access_token, refresh_skew_seconds)\n\n if should_refresh:\n tokens = _refresh_codex_auth_tokens(tokens, refresh_timeout_seconds)\n access_token = str(tokens.get(\"access_token\", \"\") or \"\").strip()\n\n base_url = (\n os.getenv(\"HERMES_CODEX_BASE_URL\", \"\").strip().rstrip(\"/\")\n or DEFAULT_CODEX_BASE_URL\n )\n\n return {\n \"provider\": \"openai-codex\",\n \"base_url\": base_url,\n \"api_key\": access_token,\n \"source\": \"hermes-auth-store\",\n \"last_refresh\": data.get(\"last_refresh\"),\n \"auth_mode\": \"chatgpt\",\n }\n\n\n# =============================================================================\n# TLS verification helper\n# =============================================================================\n\ndef _default_verify() -> bool | ssl.SSLContext:\n \"\"\"Platform-aware default SSL verify for httpx clients.\n\n On macOS with Homebrew Python, the system OpenSSL cannot locate the\n system trust store and valid public certs fail verification. When\n certifi is importable we pin its bundle explicitly; elsewhere we\n defer to httpx's built-in default (certifi via its own dependency).\n Mirrors the weixin fix in 3a0ec1d93.\n \"\"\"\n if sys.platform == \"darwin\":\n try:\n import certifi\n return ssl.create_default_context(cafile=certifi.where())\n except ImportError:\n pass\n return True\n\n\ndef _resolve_verify(\n *,\n insecure: Optional[bool] = None,\n ca_bundle: Optional[str] = None,\n auth_state: Optional[Dict[str, Any]] = None,\n) -> bool | ssl.SSLContext:\n tls_state = auth_state.get(\"tls\") if isinstance(auth_state, dict) else {}\n tls_state = tls_state if isinstance(tls_state, dict) else {}\n\n effective_insecure = (\n bool(insecure) if insecure is not None\n else bool(tls_state.get(\"insecure\", False))\n )\n effective_ca = (\n ca_bundle\n or tls_state.get(\"ca_bundle\")\n or os.getenv(\"HERMES_CA_BUNDLE\")\n or os.getenv(\"SSL_CERT_FILE\")\n or os.getenv(\"REQUESTS_CA_BUNDLE\")\n )\n\n if effective_insecure:\n return False\n if effective_ca:\n ca_path = str(effective_ca)\n if not os.path.isfile(ca_path):\n logger.warning(\n \"CA bundle path does not exist: %s — falling back to default certificates\",\n ca_path,\n )\n return _default_verify()\n return ssl.create_default_context(cafile=ca_path)\n return _default_verify()\n\n\n# =============================================================================\n# OAuth Device Code Flow — generic, parameterized by provider\n# =============================================================================\n\ndef _request_device_code(\n client: httpx.Client,\n portal_base_url: str,\n client_id: str,\n scope: Optional[str],\n) -> Dict[str, Any]:\n \"\"\"POST to the device code endpoint. Returns device_code, user_code, etc.\"\"\"\n response = client.post(\n f\"{portal_base_url}/api/oauth/device/code\",\n data={\n \"client_id\": client_id,\n **({\"scope\": scope} if scope else {}),\n },\n )\n response.raise_for_status()\n data = response.json()\n\n required_fields = [\n \"device_code\", \"user_code\", \"verification_uri\",\n \"verification_uri_complete\", \"expires_in\", \"interval\",\n ]\n missing = [f for f in required_fields if f not in data]\n if missing:\n raise ValueError(f\"Device code response missing fields: {', '.join(missing)}\")\n return data\n\n\ndef _poll_for_token(\n client: httpx.Client,\n portal_base_url: str,\n client_id: str,\n device_code: str,\n expires_in: int,\n poll_interval: int,\n) -> Dict[str, Any]:\n \"\"\"Poll the token endpoint until the user approves or the code expires.\"\"\"\n deadline = time.time() + max(1, expires_in)\n current_interval = max(1, min(poll_interval, DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS))\n\n while time.time() < deadline:\n response = client.post(\n f\"{portal_base_url}/api/oauth/token\",\n data={\n \"grant_type\": \"urn:ietf:params:oauth:grant-type:device_code\",\n \"client_id\": client_id,\n \"device_code\": device_code,\n },\n )\n\n if response.status_code == 200:\n payload = response.json()\n if \"access_token\" not in payload:\n raise ValueError(\"Token response did not include access_token\")\n return payload\n\n try:\n error_payload = response.json()\n except Exception:\n response.raise_for_status()\n raise RuntimeError(\"Token endpoint returned a non-JSON error response\")\n\n error_code = error_payload.get(\"error\", \"\")\n if error_code == \"authorization_pending\":\n time.sleep(current_interval)\n continue\n if error_code == \"slow_down\":\n current_interval = min(current_interval + 1, 30)\n time.sleep(current_interval)\n continue\n\n description = error_payload.get(\"error_description\") or \"Unknown authentication error\"\n raise RuntimeError(f\"{error_code}: {description}\")\n\n raise TimeoutError(\"Timed out waiting for device authorization\")\n\n\n# =============================================================================\n# Nous Portal — token refresh, agent key minting, model discovery\n# =============================================================================\n\ndef _refresh_access_token(\n *,\n client: httpx.Client,\n portal_base_url: str,\n client_id: str,\n refresh_token: str,\n) -> Dict[str, Any]:\n response = client.post(\n f\"{portal_base_url}/api/oauth/token\",\n data={\n \"grant_type\": \"refresh_token\",\n \"client_id\": client_id,\n \"refresh_token\": refresh_token,\n },\n )\n\n if response.status_code == 200:\n payload = response.json()\n if \"access_token\" not in payload:\n raise AuthError(\"Refresh response missing access_token\",\n provider=\"nous\", code=\"invalid_token\", relogin_required=True)\n return payload\n\n try:\n error_payload = response.json()\n except Exception as exc:\n raise AuthError(\"Refresh token exchange failed\",\n provider=\"nous\", relogin_required=True) from exc\n\n code = str(error_payload.get(\"error\", \"invalid_grant\"))\n description = str(error_payload.get(\"error_description\") or \"Refresh token exchange failed\")\n relogin = code in {\"invalid_grant\", \"invalid_token\"}\n\n # Detect the OAuth 2.1 \"refresh token reuse\" signal from the Nous portal\n # server and surface an actionable message. This fires when an external\n # process (health-check script, monitoring tool, custom self-heal hook)\n # called POST /api/oauth/token with Hermes's refresh_token without\n # persisting the rotated token back to auth.json — the server then\n # retires the original RT, Hermes's next refresh uses it, and the whole\n # session chain gets revoked as a token-theft signal (#15099).\n lowered = description.lower()\n if \"reuse\" in lowered or \"reuse detected\" in lowered:\n description = (\n \"Nous Portal detected refresh-token reuse and revoked this session.\\n\"\n \"This usually means an external process (monitoring script, \"\n \"custom self-heal hook, or another Hermes install sharing \"\n \"~/.hermes/auth.json) called POST /api/oauth/token with Hermes's \"\n \"refresh token without persisting the rotated token back.\\n\"\n \"Nous refresh tokens are single-use — only Hermes may call the \"\n \"refresh endpoint. For health checks, use `hermes auth status` \"\n \"instead.\\n\"\n \"Re-authenticate with: hermes auth add nous\"\n )\n\n raise AuthError(description, provider=\"nous\", code=code, relogin_required=relogin)\n\n\ndef _mint_agent_key(\n *,\n client: httpx.Client,\n portal_base_url: str,\n access_token: str,\n min_ttl_seconds: int,\n) -> Dict[str, Any]:\n \"\"\"Mint (or reuse) a short-lived inference API key.\"\"\"\n response = client.post(\n f\"{portal_base_url}/api/oauth/agent-key\",\n headers={\"Authorization\": f\"Bearer {access_token}\"},\n json={\"min_ttl_seconds\": max(60, int(min_ttl_seconds))},\n )\n\n if response.status_code == 200:\n payload = response.json()\n if \"api_key\" not in payload:\n raise AuthError(\"Mint response missing api_key\",\n provider=\"nous\", code=\"server_error\")\n return payload\n\n try:\n error_payload = response.json()\n except Exception as exc:\n raise AuthError(\"Agent key mint request failed\",\n provider=\"nous\", code=\"server_error\") from exc\n\n code = str(error_payload.get(\"error\", \"server_error\"))\n description = str(error_payload.get(\"error_description\") or \"Agent key mint request failed\")\n relogin = code in {\"invalid_token\", \"invalid_grant\"}\n raise AuthError(description, provider=\"nous\", code=code, relogin_required=relogin)\n\n\ndef fetch_nous_models(\n *,\n inference_base_url: str,\n api_key: str,\n timeout_seconds: float = 15.0,\n verify: bool | str = True,\n) -> List[str]:\n \"\"\"Fetch available model IDs from the Nous inference API.\"\"\"\n timeout = httpx.Timeout(timeout_seconds)\n with httpx.Client(timeout=timeout, headers={\"Accept\": \"application/json\"}, verify=verify) as client:\n response = client.get(\n f\"{inference_base_url.rstrip('/')}/models\",\n headers={\"Authorization\": f\"Bearer {api_key}\"},\n )\n\n if response.status_code != 200:\n description = f\"/models request failed with status {response.status_code}\"\n try:\n err = response.json()\n description = str(err.get(\"error_description\") or err.get(\"error\") or description)\n except Exception as e:\n logger.debug(\"Could not parse error response JSON: %s\", e)\n raise AuthError(description, provider=\"nous\", code=\"models_fetch_failed\")\n\n payload = response.json()\n data = payload.get(\"data\")\n if not isinstance(data, list):\n return []\n\n model_ids: List[str] = []\n for item in data:\n if not isinstance(item, dict):\n continue\n model_id = item.get(\"id\")\n if isinstance(model_id, str) and model_id.strip():\n mid = model_id.strip()\n # Skip Hermes models — they're not reliable for agentic tool-calling\n if \"hermes\" in mid.lower():\n continue\n model_ids.append(mid)\n\n # Sort: prefer opus > pro > haiku/flash > sonnet (sonnet is cheap/fast,\n # users who want the best model should see opus first).\n def _model_priority(mid: str) -> tuple:\n low = mid.lower()\n if \"opus\" in low:\n return (0, mid)\n if \"pro\" in low and \"sonnet\" not in low:\n return (1, mid)\n if \"sonnet\" in low:\n return (3, mid)\n return (2, mid)\n\n model_ids.sort(key=_model_priority)\n return list(dict.fromkeys(model_ids))\n\n\ndef _agent_key_is_usable(state: Dict[str, Any], min_ttl_seconds: int) -> bool:\n key = state.get(\"agent_key\")\n if not isinstance(key, str) or not key.strip():\n return False\n return not _is_expiring(state.get(\"agent_key_expires_at\"), min_ttl_seconds)\n\n\ndef resolve_nous_access_token(\n *,\n timeout_seconds: float = 15.0,\n insecure: Optional[bool] = None,\n ca_bundle: Optional[str] = None,\n refresh_skew_seconds: int = ACCESS_TOKEN_REFRESH_SKEW_SECONDS,\n) -> str:\n \"\"\"Resolve a refresh-aware Nous Portal access token for managed tool gateways.\"\"\"\n with _auth_store_lock():\n auth_store = _load_auth_store()\n state = _load_provider_state(auth_store, \"nous\")\n\n if not state:\n raise AuthError(\n \"Hermes is not logged into Nous Portal.\",\n provider=\"nous\",\n relogin_required=True,\n )\n\n portal_base_url = (\n _optional_base_url(state.get(\"portal_base_url\"))\n or os.getenv(\"HERMES_PORTAL_BASE_URL\")\n or os.getenv(\"NOUS_PORTAL_BASE_URL\")\n or DEFAULT_NOUS_PORTAL_URL\n ).rstrip(\"/\")\n client_id = str(state.get(\"client_id\") or DEFAULT_NOUS_CLIENT_ID)\n verify = _resolve_verify(insecure=insecure, ca_bundle=ca_bundle, auth_state=state)\n\n access_token = state.get(\"access_token\")\n refresh_token = state.get(\"refresh_token\")\n if not isinstance(access_token, str) or not access_token:\n raise AuthError(\n \"No access token found for Nous Portal login.\",\n provider=\"nous\",\n relogin_required=True,\n )\n\n if not _is_expiring(state.get(\"expires_at\"), refresh_skew_seconds):\n return access_token\n\n if not isinstance(refresh_token, str) or not refresh_token:\n raise AuthError(\n \"Session expired and no refresh token is available.\",\n provider=\"nous\",\n relogin_required=True,\n )\n\n timeout = httpx.Timeout(timeout_seconds if timeout_seconds else 15.0)\n with httpx.Client(\n timeout=timeout,\n headers={\"Accept\": \"application/json\"},\n verify=verify,\n ) as client:\n refreshed = _refresh_access_token(\n client=client,\n portal_base_url=portal_base_url,\n client_id=client_id,\n refresh_token=refresh_token,\n )\n\n now = datetime.now(timezone.utc)\n access_ttl = _coerce_ttl_seconds(refreshed.get(\"expires_in\"))\n state[\"access_token\"] = refreshed[\"access_token\"]\n state[\"refresh_token\"] = refreshed.get(\"refresh_token\") or refresh_token\n state[\"token_type\"] = refreshed.get(\"token_type\") or state.get(\"token_type\") or \"Bearer\"\n state[\"scope\"] = refreshed.get(\"scope\") or state.get(\"scope\")\n state[\"obtained_at\"] = now.isoformat()\n state[\"expires_in\"] = access_ttl\n state[\"expires_at\"] = datetime.fromtimestamp(\n now.timestamp() + access_ttl,\n tz=timezone.utc,\n ).isoformat()\n state[\"portal_base_url\"] = portal_base_url\n state[\"client_id\"] = client_id\n state[\"tls\"] = {\n \"insecure\": verify is False,\n \"ca_bundle\": verify if isinstance(verify, str) else None,\n }\n _save_provider_state(auth_store, \"nous\", state)\n _save_auth_store(auth_store)\n return state[\"access_token\"]\n\n\ndef refresh_nous_oauth_pure(\n access_token: str,\n refresh_token: str,\n client_id: str,\n portal_base_url: str,\n inference_base_url: str,\n *,\n token_type: str = \"Bearer\",\n scope: str = DEFAULT_NOUS_SCOPE,\n obtained_at: Optional[str] = None,\n expires_at: Optional[str] = None,\n agent_key: Optional[str] = None,\n agent_key_expires_at: Optional[str] = None,\n min_key_ttl_seconds: int = DEFAULT_AGENT_KEY_MIN_TTL_SECONDS,\n timeout_seconds: float = 15.0,\n insecure: Optional[bool] = None,\n ca_bundle: Optional[str] = None,\n force_refresh: bool = False,\n force_mint: bool = False,\n) -> Dict[str, Any]:\n \"\"\"Refresh Nous OAuth state without mutating auth.json.\"\"\"\n state: Dict[str, Any] = {\n \"access_token\": access_token,\n \"refresh_token\": refresh_token,\n \"client_id\": client_id or DEFAULT_NOUS_CLIENT_ID,\n \"portal_base_url\": (portal_base_url or DEFAULT_NOUS_PORTAL_URL).rstrip(\"/\"),\n \"inference_base_url\": (inference_base_url or DEFAULT_NOUS_INFERENCE_URL).rstrip(\"/\"),\n \"token_type\": token_type or \"Bearer\",\n \"scope\": scope or DEFAULT_NOUS_SCOPE,\n \"obtained_at\": obtained_at,\n \"expires_at\": expires_at,\n \"agent_key\": agent_key,\n \"agent_key_expires_at\": agent_key_expires_at,\n \"tls\": {\n \"insecure\": bool(insecure),\n \"ca_bundle\": ca_bundle,\n },\n }\n verify = _resolve_verify(insecure=insecure, ca_bundle=ca_bundle, auth_state=state)\n timeout = httpx.Timeout(timeout_seconds if timeout_seconds else 15.0)\n\n with httpx.Client(timeout=timeout, headers={\"Accept\": \"application/json\"}, verify=verify) as client:\n if force_refresh or _is_expiring(state.get(\"expires_at\"), ACCESS_TOKEN_REFRESH_SKEW_SECONDS):\n refreshed = _refresh_access_token(\n client=client,\n portal_base_url=state[\"portal_base_url\"],\n client_id=state[\"client_id\"],\n refresh_token=state[\"refresh_token\"],\n )\n now = datetime.now(timezone.utc)\n access_ttl = _coerce_ttl_seconds(refreshed.get(\"expires_in\"))\n state[\"access_token\"] = refreshed[\"access_token\"]\n state[\"refresh_token\"] = refreshed.get(\"refresh_token\") or state[\"refresh_token\"]\n state[\"token_type\"] = refreshed.get(\"token_type\") or state.get(\"token_type\") or \"Bearer\"\n state[\"scope\"] = refreshed.get(\"scope\") or state.get(\"scope\")\n refreshed_url = _optional_base_url(refreshed.get(\"inference_base_url\"))\n if refreshed_url:\n state[\"inference_base_url\"] = refreshed_url\n state[\"obtained_at\"] = now.isoformat()\n state[\"expires_in\"] = access_ttl\n state[\"expires_at\"] = datetime.fromtimestamp(\n now.timestamp() + access_ttl, tz=timezone.utc\n ).isoformat()\n\n if force_mint or not _agent_key_is_usable(state, max(60, int(min_key_ttl_seconds))):\n mint_payload = _mint_agent_key(\n client=client,\n portal_base_url=state[\"portal_base_url\"],\n access_token=state[\"access_token\"],\n min_ttl_seconds=min_key_ttl_seconds,\n )\n now = datetime.now(timezone.utc)\n state[\"agent_key\"] = mint_payload.get(\"api_key\")\n state[\"agent_key_id\"] = mint_payload.get(\"key_id\")\n state[\"agent_key_expires_at\"] = mint_payload.get(\"expires_at\")\n state[\"agent_key_expires_in\"] = mint_payload.get(\"expires_in\")\n state[\"agent_key_reused\"] = bool(mint_payload.get(\"reused\", False))\n state[\"agent_key_obtained_at\"] = now.isoformat()\n minted_url = _optional_base_url(mint_payload.get(\"inference_base_url\"))\n if minted_url:\n state[\"inference_base_url\"] = minted_url\n\n return state\n\n\ndef refresh_nous_oauth_from_state(\n state: Dict[str, Any],\n *,\n min_key_ttl_seconds: int = DEFAULT_AGENT_KEY_MIN_TTL_SECONDS,\n timeout_seconds: float = 15.0,\n force_refresh: bool = False,\n force_mint: bool = False,\n) -> Dict[str, Any]:\n \"\"\"Refresh Nous OAuth from a state dict. Thin wrapper around refresh_nous_oauth_pure.\"\"\"\n tls = state.get(\"tls\") or {}\n return refresh_nous_oauth_pure(\n state.get(\"access_token\", \"\"),\n state.get(\"refresh_token\", \"\"),\n state.get(\"client_id\", \"hermes-cli\"),\n state.get(\"portal_base_url\", DEFAULT_NOUS_PORTAL_URL),\n state.get(\"inference_base_url\", DEFAULT_NOUS_INFERENCE_URL),\n token_type=state.get(\"token_type\", \"Bearer\"),\n scope=state.get(\"scope\", DEFAULT_NOUS_SCOPE),\n obtained_at=state.get(\"obtained_at\"),\n expires_at=state.get(\"expires_at\"),\n agent_key=state.get(\"agent_key\"),\n agent_key_expires_at=state.get(\"agent_key_expires_at\"),\n min_key_ttl_seconds=min_key_ttl_seconds,\n timeout_seconds=timeout_seconds,\n insecure=tls.get(\"insecure\"),\n ca_bundle=tls.get(\"ca_bundle\"),\n force_refresh=force_refresh,\n force_mint=force_mint,\n )\n\n\nNOUS_DEVICE_CODE_SOURCE = \"device_code\"\n\n\ndef persist_nous_credentials(\n creds: Dict[str, Any],\n *,\n label: Optional[str] = None,\n):\n \"\"\"Persist minted Nous OAuth credentials as the singleton provider state\n and ensure the credential pool is in sync.\n\n Nous credentials are read at runtime from two independent locations:\n\n - ``providers.nous``: singleton state read by\n ``resolve_nous_runtime_credentials()`` during 401 recovery and by\n ``_seed_from_singletons()`` during pool load.\n - ``credential_pool.nous``: used by the runtime ``pool.select()`` path.\n\n Historically ``hermes auth add nous`` wrote a ``manual:device_code`` pool\n entry only, skipping ``providers.nous``. When the 24h agent_key TTL\n expired, the recovery path read the empty singleton state and raised\n ``AuthError`` silently (``logger.debug`` at INFO level).\n\n This helper writes ``providers.nous`` then calls ``load_pool(\"nous\")`` so\n ``_seed_from_singletons`` materialises the canonical ``device_code`` pool\n entry from the singleton. Re-running login upserts the same entry in\n place; the pool never accumulates duplicate device_code rows.\n\n ``label`` is an optional user-chosen display name (from\n ``hermes auth add nous --label <name>``). It gets embedded in the\n singleton state so that ``_seed_from_singletons`` uses it as the pool\n entry's label on every subsequent ``load_pool(\"nous\")`` instead of the\n auto-derived token fingerprint. When ``None``, the auto-derived label\n via ``label_from_token`` is used (unchanged default behaviour).\n\n Returns the upserted :class:`PooledCredential` entry (or ``None`` if\n seeding somehow produced no match — shouldn't happen).\n \"\"\"\n from agent.credential_pool import load_pool\n\n state = dict(creds)\n if label and str(label).strip():\n state[\"label\"] = str(label).strip()\n\n with _auth_store_lock():\n auth_store = _load_auth_store()\n _save_provider_state(auth_store, \"nous\", state)\n _save_auth_store(auth_store)\n\n pool = load_pool(\"nous\")\n return next(\n (e for e in pool.entries() if e.source == NOUS_DEVICE_CODE_SOURCE),\n None,\n )\n\n\ndef resolve_nous_runtime_credentials(\n *,\n min_key_ttl_seconds: int = DEFAULT_AGENT_KEY_MIN_TTL_SECONDS,\n timeout_seconds: float = 15.0,\n insecure: Optional[bool] = None,\n ca_bundle: Optional[str] = None,\n force_mint: bool = False,\n) -> Dict[str, Any]:\n \"\"\"\n Resolve Nous inference credentials for runtime use.\n\n Ensures access_token is valid (refreshes if needed) and a short-lived\n inference key is present with minimum TTL (mints/reuses as needed).\n Concurrent processes coordinate through the auth store file lock.\n\n Returns dict with: provider, base_url, api_key, key_id, expires_at,\n expires_in, source (\"cache\" or \"portal\").\n \"\"\"\n min_key_ttl_seconds = max(60, int(min_key_ttl_seconds))\n sequence_id = uuid.uuid4().hex[:12]\n\n with _auth_store_lock():\n auth_store = _load_auth_store()\n state = _load_provider_state(auth_store, \"nous\")\n\n if not state:\n raise AuthError(\"Hermes is not logged into Nous Portal.\",\n provider=\"nous\", relogin_required=True)\n\n portal_base_url = (\n _optional_base_url(state.get(\"portal_base_url\"))\n or os.getenv(\"HERMES_PORTAL_BASE_URL\")\n or os.getenv(\"NOUS_PORTAL_BASE_URL\")\n or DEFAULT_NOUS_PORTAL_URL\n ).rstrip(\"/\")\n inference_base_url = (\n _optional_base_url(state.get(\"inference_base_url\"))\n or os.getenv(\"NOUS_INFERENCE_BASE_URL\")\n or DEFAULT_NOUS_INFERENCE_URL\n ).rstrip(\"/\")\n client_id = str(state.get(\"client_id\") or DEFAULT_NOUS_CLIENT_ID)\n\n def _persist_state(reason: str) -> None:\n try:\n _save_provider_state(auth_store, \"nous\", state)\n _save_auth_store(auth_store)\n except Exception as exc:\n _oauth_trace(\n \"nous_state_persist_failed\",\n sequence_id=sequence_id,\n reason=reason,\n error_type=type(exc).__name__,\n )\n raise\n _oauth_trace(\n \"nous_state_persisted\",\n sequence_id=sequence_id,\n reason=reason,\n refresh_token_fp=_token_fingerprint(state.get(\"refresh_token\")),\n access_token_fp=_token_fingerprint(state.get(\"access_token\")),\n )\n\n verify = _resolve_verify(insecure=insecure, ca_bundle=ca_bundle, auth_state=state)\n timeout = httpx.Timeout(timeout_seconds if timeout_seconds else 15.0)\n _oauth_trace(\n \"nous_runtime_credentials_start\",\n sequence_id=sequence_id,\n force_mint=bool(force_mint),\n min_key_ttl_seconds=min_key_ttl_seconds,\n refresh_token_fp=_token_fingerprint(state.get(\"refresh_token\")),\n )\n\n with httpx.Client(timeout=timeout, headers={\"Accept\": \"application/json\"}, verify=verify) as client:\n access_token = state.get(\"access_token\")\n refresh_token = state.get(\"refresh_token\")\n\n if not isinstance(access_token, str) or not access_token:\n raise AuthError(\"No access token found for Nous Portal login.\",\n provider=\"nous\", relogin_required=True)\n\n # Step 1: refresh access token if expiring\n if _is_expiring(state.get(\"expires_at\"), ACCESS_TOKEN_REFRESH_SKEW_SECONDS):\n if not isinstance(refresh_token, str) or not refresh_token:\n raise AuthError(\"Session expired and no refresh token is available.\",\n provider=\"nous\", relogin_required=True)\n\n _oauth_trace(\n \"refresh_start\",\n sequence_id=sequence_id,\n reason=\"access_expiring\",\n refresh_token_fp=_token_fingerprint(refresh_token),\n )\n refreshed = _refresh_access_token(\n client=client, portal_base_url=portal_base_url,\n client_id=client_id, refresh_token=refresh_token,\n )\n now = datetime.now(timezone.utc)\n access_ttl = _coerce_ttl_seconds(refreshed.get(\"expires_in\"))\n previous_refresh_token = refresh_token\n state[\"access_token\"] = refreshed[\"access_token\"]\n state[\"refresh_token\"] = refreshed.get(\"refresh_token\") or refresh_token\n state[\"token_type\"] = refreshed.get(\"token_type\") or state.get(\"token_type\") or \"Bearer\"\n state[\"scope\"] = refreshed.get(\"scope\") or state.get(\"scope\")\n refreshed_url = _optional_base_url(refreshed.get(\"inference_base_url\"))\n if refreshed_url:\n inference_base_url = refreshed_url\n state[\"obtained_at\"] = now.isoformat()\n state[\"expires_in\"] = access_ttl\n state[\"expires_at\"] = datetime.fromtimestamp(\n now.timestamp() + access_ttl, tz=timezone.utc\n ).isoformat()\n access_token = state[\"access_token\"]\n refresh_token = state[\"refresh_token\"]\n _oauth_trace(\n \"refresh_success\",\n sequence_id=sequence_id,\n reason=\"access_expiring\",\n previous_refresh_token_fp=_token_fingerprint(previous_refresh_token),\n new_refresh_token_fp=_token_fingerprint(refresh_token),\n )\n # Persist immediately so downstream mint failures cannot drop rotated refresh tokens.\n _persist_state(\"post_refresh_access_expiring\")\n\n # Step 2: mint agent key if missing/expiring\n used_cached_key = False\n mint_payload: Optional[Dict[str, Any]] = None\n\n if not force_mint and _agent_key_is_usable(state, min_key_ttl_seconds):\n used_cached_key = True\n _oauth_trace(\"agent_key_reuse\", sequence_id=sequence_id)\n else:\n try:\n _oauth_trace(\n \"mint_start\",\n sequence_id=sequence_id,\n access_token_fp=_token_fingerprint(access_token),\n )\n mint_payload = _mint_agent_key(\n client=client, portal_base_url=portal_base_url,\n access_token=access_token, min_ttl_seconds=min_key_ttl_seconds,\n )\n except AuthError as exc:\n _oauth_trace(\n \"mint_error\",\n sequence_id=sequence_id,\n code=exc.code,\n )\n # Retry path: access token may be stale server-side despite local checks\n latest_refresh_token = state.get(\"refresh_token\")\n if (\n exc.code in {\"invalid_token\", \"invalid_grant\"}\n and isinstance(latest_refresh_token, str)\n and latest_refresh_token\n ):\n _oauth_trace(\n \"refresh_start\",\n sequence_id=sequence_id,\n reason=\"mint_retry_after_invalid_token\",\n refresh_token_fp=_token_fingerprint(latest_refresh_token),\n )\n refreshed = _refresh_access_token(\n client=client, portal_base_url=portal_base_url,\n client_id=client_id, refresh_token=latest_refresh_token,\n )\n now = datetime.now(timezone.utc)\n access_ttl = _coerce_ttl_seconds(refreshed.get(\"expires_in\"))\n state[\"access_token\"] = refreshed[\"access_token\"]\n state[\"refresh_token\"] = refreshed.get(\"refresh_token\") or latest_refresh_token\n state[\"token_type\"] = refreshed.get(\"token_type\") or state.get(\"token_type\") or \"Bearer\"\n state[\"scope\"] = refreshed.get(\"scope\") or state.get(\"scope\")\n refreshed_url = _optional_base_url(refreshed.get(\"inference_base_url\"))\n if refreshed_url:\n inference_base_url = refreshed_url\n state[\"obtained_at\"] = now.isoformat()\n state[\"expires_in\"] = access_ttl\n state[\"expires_at\"] = datetime.fromtimestamp(\n now.timestamp() + access_ttl, tz=timezone.utc\n ).isoformat()\n access_token = state[\"access_token\"]\n refresh_token = state[\"refresh_token\"]\n _oauth_trace(\n \"refresh_success\",\n sequence_id=sequence_id,\n reason=\"mint_retry_after_invalid_token\",\n previous_refresh_token_fp=_token_fingerprint(latest_refresh_token),\n new_refresh_token_fp=_token_fingerprint(refresh_token),\n )\n # Persist retry refresh immediately for crash safety and cross-process visibility.\n _persist_state(\"post_refresh_mint_retry\")\n\n mint_payload = _mint_agent_key(\n client=client, portal_base_url=portal_base_url,\n access_token=access_token, min_ttl_seconds=min_key_ttl_seconds,\n )\n else:\n raise\n\n if mint_payload is not None:\n now = datetime.now(timezone.utc)\n state[\"agent_key\"] = mint_payload.get(\"api_key\")\n state[\"agent_key_id\"] = mint_payload.get(\"key_id\")\n state[\"agent_key_expires_at\"] = mint_payload.get(\"expires_at\")\n state[\"agent_key_expires_in\"] = mint_payload.get(\"expires_in\")\n state[\"agent_key_reused\"] = bool(mint_payload.get(\"reused\", False))\n state[\"agent_key_obtained_at\"] = now.isoformat()\n minted_url = _optional_base_url(mint_payload.get(\"inference_base_url\"))\n if minted_url:\n inference_base_url = minted_url\n _oauth_trace(\n \"mint_success\",\n sequence_id=sequence_id,\n reused=bool(mint_payload.get(\"reused\", False)),\n )\n\n # Persist routing and TLS metadata for non-interactive refresh/mint\n state[\"portal_base_url\"] = portal_base_url\n state[\"inference_base_url\"] = inference_base_url\n state[\"client_id\"] = client_id\n state[\"tls\"] = {\n \"insecure\": verify is False,\n \"ca_bundle\": verify if isinstance(verify, str) else None,\n }\n\n _persist_state(\"resolve_nous_runtime_credentials_final\")\n\n api_key = state.get(\"agent_key\")\n if not isinstance(api_key, str) or not api_key:\n raise AuthError(\"Failed to resolve a Nous inference API key\",\n provider=\"nous\", code=\"server_error\")\n\n expires_at = state.get(\"agent_key_expires_at\")\n expires_epoch = _parse_iso_timestamp(expires_at)\n expires_in = (\n max(0, int(expires_epoch - time.time()))\n if expires_epoch is not None\n else _coerce_ttl_seconds(state.get(\"agent_key_expires_in\"))\n )\n\n return {\n \"provider\": \"nous\",\n \"base_url\": inference_base_url,\n \"api_key\": api_key,\n \"key_id\": state.get(\"agent_key_id\"),\n \"expires_at\": expires_at,\n \"expires_in\": expires_in,\n \"source\": \"cache\" if used_cached_key else \"portal\",\n }\n\n\n# =============================================================================\n# Status helpers\n# =============================================================================\n\ndef _empty_nous_auth_status() -> Dict[str, Any]:\n return {\n \"logged_in\": False,\n \"portal_base_url\": None,\n \"inference_base_url\": None,\n \"access_expires_at\": None,\n \"agent_key_expires_at\": None,\n \"has_refresh_token\": False,\n }\n\n\ndef _snapshot_nous_pool_status() -> Dict[str, Any]:\n \"\"\"Best-effort status from the credential pool.\n\n This is a fallback only. The auth-store provider state is the runtime source\n of truth because it is what ``resolve_nous_runtime_credentials()`` refreshes\n and mints against.\n \"\"\"\n try:\n from agent.credential_pool import load_pool\n\n pool = load_pool(\"nous\")\n if not pool or not pool.has_credentials():\n return _empty_nous_auth_status()\n\n entries = list(pool.entries())\n if not entries:\n return _empty_nous_auth_status()\n\n def _entry_sort_key(entry: Any) -> tuple[float, float, int]:\n agent_exp = _parse_iso_timestamp(getattr(entry, \"agent_key_expires_at\", None)) or 0.0\n access_exp = _parse_iso_timestamp(getattr(entry, \"expires_at\", None)) or 0.0\n priority = int(getattr(entry, \"priority\", 0) or 0)\n return (agent_exp, access_exp, -priority)\n\n entry = max(entries, key=_entry_sort_key)\n access_token = (\n getattr(entry, \"access_token\", None)\n or getattr(entry, \"runtime_api_key\", \"\")\n )\n if not access_token:\n return _empty_nous_auth_status()\n\n return {\n \"logged_in\": True,\n \"portal_base_url\": getattr(entry, \"portal_base_url\", None)\n or getattr(entry, \"base_url\", None),\n \"inference_base_url\": getattr(entry, \"inference_base_url\", None)\n or getattr(entry, \"base_url\", None),\n \"access_token\": access_token,\n \"access_expires_at\": getattr(entry, \"expires_at\", None),\n \"agent_key_expires_at\": getattr(entry, \"agent_key_expires_at\", None),\n \"has_refresh_token\": bool(getattr(entry, \"refresh_token\", None)),\n \"source\": f\"pool:{getattr(entry, 'label', 'unknown')}\",\n }\n except Exception:\n return _empty_nous_auth_status()\n\n\ndef get_nous_auth_status() -> Dict[str, Any]:\n \"\"\"Status snapshot for Nous auth.\n\n Prefer the auth-store provider state, because that is the live source of\n truth for refresh + mint operations. When provider state exists, validate it\n by resolving runtime credentials so revoked refresh sessions do not show up\n as a healthy login. If provider state is absent, fall back to the credential\n pool for the just-logged-in / not-yet-promoted case.\n \"\"\"\n state = get_provider_auth_state(\"nous\")\n if state:\n base_status = {\n \"logged_in\": bool(state.get(\"access_token\")),\n \"portal_base_url\": state.get(\"portal_base_url\"),\n \"inference_base_url\": state.get(\"inference_base_url\"),\n \"access_expires_at\": state.get(\"expires_at\"),\n \"agent_key_expires_at\": state.get(\"agent_key_expires_at\"),\n \"has_refresh_token\": bool(state.get(\"refresh_token\")),\n \"access_token\": state.get(\"access_token\"),\n \"source\": \"auth_store\",\n }\n try:\n creds = resolve_nous_runtime_credentials(min_key_ttl_seconds=60)\n refreshed_state = get_provider_auth_state(\"nous\") or state\n base_status.update(\n {\n \"logged_in\": True,\n \"portal_base_url\": refreshed_state.get(\"portal_base_url\") or base_status.get(\"portal_base_url\"),\n \"inference_base_url\": creds.get(\"base_url\")\n or refreshed_state.get(\"inference_base_url\")\n or base_status.get(\"inference_base_url\"),\n \"access_expires_at\": refreshed_state.get(\"expires_at\") or base_status.get(\"access_expires_at\"),\n \"agent_key_expires_at\": creds.get(\"expires_at\")\n or refreshed_state.get(\"agent_key_expires_at\")\n or base_status.get(\"agent_key_expires_at\"),\n \"has_refresh_token\": bool(refreshed_state.get(\"refresh_token\")),\n \"source\": f\"runtime:{creds.get('source', 'portal')}\",\n \"key_id\": creds.get(\"key_id\"),\n }\n )\n return base_status\n except AuthError as exc:\n base_status.update({\n \"logged_in\": False,\n \"error\": str(exc),\n \"relogin_required\": bool(getattr(exc, \"relogin_required\", False)),\n \"error_code\": getattr(exc, \"code\", None),\n })\n return base_status\n\n return _snapshot_nous_pool_status()\n\n\ndef get_codex_auth_status() -> Dict[str, Any]:\n \"\"\"Status snapshot for Codex auth.\n \n Checks the credential pool first (where `hermes auth` stores credentials),\n then falls back to the legacy provider state.\n \"\"\"\n # Check credential pool first — this is where `hermes auth` and\n # `hermes model` store device_code tokens.\n try:\n from agent.credential_pool import load_pool\n pool = load_pool(\"openai-codex\")\n if pool and pool.has_credentials():\n entry = pool.select()\n if entry is not None:\n api_key = (\n getattr(entry, \"runtime_api_key\", None)\n or getattr(entry, \"access_token\", \"\")\n )\n if api_key and not _codex_access_token_is_expiring(api_key, 0):\n return {\n \"logged_in\": True,\n \"auth_store\": str(_auth_file_path()),\n \"last_refresh\": getattr(entry, \"last_refresh\", None),\n \"auth_mode\": \"chatgpt\",\n \"source\": f\"pool:{getattr(entry, 'label', 'unknown')}\",\n \"api_key\": api_key,\n }\n except Exception:\n pass\n\n # Fall back to legacy provider state\n try:\n creds = resolve_codex_runtime_credentials()\n return {\n \"logged_in\": True,\n \"auth_store\": str(_auth_file_path()),\n \"last_refresh\": creds.get(\"last_refresh\"),\n \"auth_mode\": creds.get(\"auth_mode\"),\n \"source\": creds.get(\"source\"),\n \"api_key\": creds.get(\"api_key\"),\n }\n except AuthError as exc:\n return {\n \"logged_in\": False,\n \"auth_store\": str(_auth_file_path()),\n \"error\": str(exc),\n }\n\n\ndef get_api_key_provider_status(provider_id: str) -> Dict[str, Any]:\n \"\"\"Status snapshot for API-key providers (z.ai, Kimi, MiniMax).\"\"\"\n pconfig = PROVIDER_REGISTRY.get(provider_id)\n if not pconfig or pconfig.auth_type != \"api_key\":\n return {\"configured\": False}\n\n api_key = \"\"\n key_source = \"\"\n api_key, key_source = _resolve_api_key_provider_secret(provider_id, pconfig)\n\n env_url = \"\"\n if pconfig.base_url_env_var:\n env_url = os.getenv(pconfig.base_url_env_var, \"\").strip()\n\n if provider_id in (\"kimi-coding\", \"kimi-coding-cn\"):\n base_url = _resolve_kimi_base_url(api_key, pconfig.inference_base_url, env_url)\n elif env_url:\n base_url = env_url\n else:\n base_url = pconfig.inference_base_url\n\n return {\n \"configured\": bool(api_key),\n \"provider\": provider_id,\n \"name\": pconfig.name,\n \"key_source\": key_source,\n \"base_url\": base_url,\n \"logged_in\": bool(api_key), # compat with OAuth status shape\n }\n\n\ndef get_external_process_provider_status(provider_id: str) -> Dict[str, Any]:\n \"\"\"Status snapshot for providers that run a local subprocess.\"\"\"\n pconfig = PROVIDER_REGISTRY.get(provider_id)\n if not pconfig or pconfig.auth_type != \"external_process\":\n return {\"configured\": False}\n\n command = (\n os.getenv(\"HERMES_COPILOT_ACP_COMMAND\", \"\").strip()\n or os.getenv(\"COPILOT_CLI_PATH\", \"\").strip()\n or \"copilot\"\n )\n raw_args = os.getenv(\"HERMES_COPILOT_ACP_ARGS\", \"\").strip()\n args = shlex.split(raw_args) if raw_args else [\"--acp\", \"--stdio\"]\n base_url = os.getenv(pconfig.base_url_env_var, \"\").strip() if pconfig.base_url_env_var else \"\"\n if not base_url:\n base_url = pconfig.inference_base_url\n\n resolved_command = shutil.which(command) if command else None\n return {\n \"configured\": bool(resolved_command or base_url.startswith(\"acp+tcp://\")),\n \"provider\": provider_id,\n \"name\": pconfig.name,\n \"command\": command,\n \"args\": args,\n \"resolved_command\": resolved_command,\n \"base_url\": base_url,\n \"logged_in\": bool(resolved_command or base_url.startswith(\"acp+tcp://\")),\n }\n\n\ndef get_auth_status(provider_id: Optional[str] = None) -> Dict[str, Any]:\n \"\"\"Generic auth status dispatcher.\"\"\"\n target = provider_id or get_active_provider()\n if target == \"spotify\":\n return get_spotify_auth_status()\n if target == \"nous\":\n return get_nous_auth_status()\n if target == \"openai-codex\":\n return get_codex_auth_status()\n if target == \"qwen-oauth\":\n return get_qwen_auth_status()\n if target == \"google-gemini-cli\":\n return get_gemini_oauth_auth_status()\n if target == \"copilot-acp\":\n return get_external_process_provider_status(target)\n # API-key providers\n pconfig = PROVIDER_REGISTRY.get(target)\n if pconfig and pconfig.auth_type == \"api_key\":\n return get_api_key_provider_status(target)\n # AWS SDK providers (Bedrock) — check via boto3 credential chain\n if pconfig and pconfig.auth_type == \"aws_sdk\":\n try:\n from agent.bedrock_adapter import has_aws_credentials\n return {\"logged_in\": has_aws_credentials(), \"provider\": target}\n except ImportError:\n return {\"logged_in\": False, \"provider\": target, \"error\": \"boto3 not installed\"}\n return {\"logged_in\": False}\n\n\ndef resolve_api_key_provider_credentials(provider_id: str) -> Dict[str, Any]:\n \"\"\"Resolve API key and base URL for an API-key provider.\n\n Returns dict with: provider, api_key, base_url, source.\n \"\"\"\n pconfig = PROVIDER_REGISTRY.get(provider_id)\n if not pconfig or pconfig.auth_type != \"api_key\":\n raise AuthError(\n f\"Provider '{provider_id}' is not an API-key provider.\",\n provider=provider_id,\n code=\"invalid_provider\",\n )\n\n api_key = \"\"\n key_source = \"\"\n api_key, key_source = _resolve_api_key_provider_secret(provider_id, pconfig)\n\n env_url = \"\"\n if pconfig.base_url_env_var:\n env_url = os.getenv(pconfig.base_url_env_var, \"\").strip()\n\n if provider_id in (\"kimi-coding\", \"kimi-coding-cn\"):\n base_url = _resolve_kimi_base_url(api_key, pconfig.inference_base_url, env_url)\n elif provider_id == \"zai\":\n base_url = _resolve_zai_base_url(api_key, pconfig.inference_base_url, env_url)\n elif env_url:\n base_url = env_url.rstrip(\"/\")\n else:\n base_url = pconfig.inference_base_url\n\n return {\n \"provider\": provider_id,\n \"api_key\": api_key,\n \"base_url\": base_url.rstrip(\"/\"),\n \"source\": key_source or \"default\",\n }\n\n\ndef resolve_external_process_provider_credentials(provider_id: str) -> Dict[str, Any]:\n \"\"\"Resolve runtime details for local subprocess-backed providers.\"\"\"\n pconfig = PROVIDER_REGISTRY.get(provider_id)\n if not pconfig or pconfig.auth_type != \"external_process\":\n raise AuthError(\n f\"Provider '{provider_id}' is not an external-process provider.\",\n provider=provider_id,\n code=\"invalid_provider\",\n )\n\n base_url = os.getenv(pconfig.base_url_env_var, \"\").strip() if pconfig.base_url_env_var else \"\"\n if not base_url:\n base_url = pconfig.inference_base_url\n\n command = (\n os.getenv(\"HERMES_COPILOT_ACP_COMMAND\", \"\").strip()\n or os.getenv(\"COPILOT_CLI_PATH\", \"\").strip()\n or \"copilot\"\n )\n raw_args = os.getenv(\"HERMES_COPILOT_ACP_ARGS\", \"\").strip()\n args = shlex.split(raw_args) if raw_args else [\"--acp\", \"--stdio\"]\n resolved_command = shutil.which(command) if command else None\n if not resolved_command and not base_url.startswith(\"acp+tcp://\"):\n raise AuthError(\n f\"Could not find the Copilot CLI command '{command}'. \"\n \"Install GitHub Copilot CLI or set HERMES_COPILOT_ACP_COMMAND/COPILOT_CLI_PATH.\",\n provider=provider_id,\n code=\"missing_copilot_cli\",\n )\n\n return {\n \"provider\": provider_id,\n \"api_key\": \"copilot-acp\",\n \"base_url\": base_url.rstrip(\"/\"),\n \"command\": resolved_command or command,\n \"args\": args,\n \"source\": \"process\",\n }\n\n\n# =============================================================================\n# CLI Commands — login / logout\n# =============================================================================\n\ndef _update_config_for_provider(\n provider_id: str,\n inference_base_url: str,\n default_model: Optional[str] = None,\n) -> Path:\n \"\"\"Update config.yaml and auth.json to reflect the active provider.\n\n When *default_model* is provided the function also writes it as the\n ``model.default`` value. This prevents a race condition where the\n gateway (which re-reads config per-message) picks up the new provider\n before the caller has finished model selection, resulting in a\n mismatched model/provider (e.g. ``anthropic/claude-opus-4.6`` sent to\n MiniMax's API).\n \"\"\"\n # Set active_provider in auth.json so auto-resolution picks this provider\n with _auth_store_lock():\n auth_store = _load_auth_store()\n auth_store[\"active_provider\"] = provider_id\n _save_auth_store(auth_store)\n\n # Update config.yaml model section\n config_path = get_config_path()\n config_path.parent.mkdir(parents=True, exist_ok=True)\n\n config = read_raw_config()\n\n current_model = config.get(\"model\")\n if isinstance(current_model, dict):\n model_cfg = dict(current_model)\n elif isinstance(current_model, str) and current_model.strip():\n model_cfg = {\"default\": current_model.strip()}\n else:\n model_cfg = {}\n\n model_cfg[\"provider\"] = provider_id\n if inference_base_url and inference_base_url.strip():\n model_cfg[\"base_url\"] = inference_base_url.rstrip(\"/\")\n else:\n # Clear stale base_url to prevent contamination when switching providers\n model_cfg.pop(\"base_url\", None)\n\n # Clear stale api_key/api_mode left over from a previous custom provider.\n # When the user switches from e.g. a MiniMax custom endpoint\n # (api_mode=anthropic_messages, api_key=mxp-...) to a built-in provider\n # (e.g. OpenRouter), the stale api_key/api_mode would override the new\n # provider's credentials and transport choice. Built-in providers that\n # need a specific api_mode (copilot, xai) set it at request-resolution\n # time via `_copilot_runtime_api_mode` / `_detect_api_mode_for_url`, so\n # removing the persisted value here is safe.\n model_cfg.pop(\"api_key\", None)\n model_cfg.pop(\"api_mode\", None)\n\n # When switching to a non-OpenRouter provider, ensure model.default is\n # valid for the new provider. An OpenRouter-formatted name like\n # \"anthropic/claude-opus-4.6\" will fail on direct-API providers.\n if default_model:\n cur_default = model_cfg.get(\"default\", \"\")\n if not cur_default or \"/\" in cur_default:\n model_cfg[\"default\"] = default_model\n\n config[\"model\"] = model_cfg\n\n config_path.write_text(yaml.safe_dump(config, sort_keys=False))\n return config_path\n\n\ndef _get_config_provider() -> Optional[str]:\n \"\"\"Return model.provider from config.yaml, normalized, if present.\"\"\"\n try:\n config = read_raw_config()\n except Exception:\n return None\n if not config:\n return None\n model = config.get(\"model\")\n if not isinstance(model, dict):\n return None\n provider = model.get(\"provider\")\n if not isinstance(provider, str):\n return None\n provider = provider.strip().lower()\n return provider or None\n\n\ndef _config_provider_matches(provider_id: Optional[str]) -> bool:\n \"\"\"Return True when config.yaml currently selects *provider_id*.\"\"\"\n if not provider_id:\n return False\n return _get_config_provider() == provider_id.strip().lower()\n\n\ndef _logout_default_provider_from_config() -> Optional[str]:\n \"\"\"Fallback logout target when auth.json has no active provider.\n\n `hermes logout` historically keyed off auth.json.active_provider only.\n That left users stuck when auth state had already been cleared but\n config.yaml still selected an OAuth provider such as openai-codex for the\n agent model: there was no active auth provider to target, so logout printed\n \"No provider is currently logged in\" and never reset model.provider.\n \"\"\"\n provider = _get_config_provider()\n if provider in {\"nous\", \"openai-codex\"}:\n return provider\n return None\n\n\ndef _reset_config_provider() -> Path:\n \"\"\"Reset config.yaml provider back to auto after logout.\"\"\"\n config_path = get_config_path()\n if not config_path.exists():\n return config_path\n\n config = read_raw_config()\n if not config:\n return config_path\n\n model = config.get(\"model\")\n if isinstance(model, dict):\n model[\"provider\"] = \"auto\"\n if \"base_url\" in model:\n model[\"base_url\"] = OPENROUTER_BASE_URL\n config_path.write_text(yaml.safe_dump(config, sort_keys=False))\n return config_path\n\n\ndef _prompt_model_selection(\n model_ids: List[str],\n current_model: str = \"\",\n pricing: Optional[Dict[str, Dict[str, str]]] = None,\n unavailable_models: Optional[List[str]] = None,\n portal_url: str = \"\",\n) -> Optional[str]:\n \"\"\"Interactive model selection. Puts current_model first with a marker. Returns chosen model ID or None.\n\n If *pricing* is provided (``{model_id: {prompt, completion}}``), a compact\n price indicator is shown next to each model in aligned columns.\n\n If *unavailable_models* is provided, those models are shown grayed out\n and unselectable, with an upgrade link to *portal_url*.\n \"\"\"\n from hermes_cli.models import _format_price_per_mtok\n\n _unavailable = unavailable_models or []\n\n # Reorder: current model first, then the rest (deduplicated)\n ordered = []\n if current_model and current_model in model_ids:\n ordered.append(current_model)\n for mid in model_ids:\n if mid not in ordered:\n ordered.append(mid)\n\n # All models for column-width computation (selectable + unavailable)\n all_models = list(ordered) + list(_unavailable)\n\n # Column-aligned labels when pricing is available\n has_pricing = bool(pricing and any(pricing.get(m) for m in all_models))\n name_col = max((len(m) for m in all_models), default=0) + 2 if has_pricing else 0\n\n # Pre-compute formatted prices and dynamic column widths\n _price_cache: dict[str, tuple[str, str, str]] = {}\n price_col = 3 # minimum width\n cache_col = 0 # only set if any model has cache pricing\n has_cache = False\n if has_pricing:\n for mid in all_models:\n p = pricing.get(mid) # type: ignore[union-attr]\n if p:\n inp = _format_price_per_mtok(p.get(\"prompt\", \"\"))\n out = _format_price_per_mtok(p.get(\"completion\", \"\"))\n cache_read = p.get(\"input_cache_read\", \"\")\n cache = _format_price_per_mtok(cache_read) if cache_read else \"\"\n if cache:\n has_cache = True\n else:\n inp, out, cache = \"\", \"\", \"\"\n _price_cache[mid] = (inp, out, cache)\n price_col = max(price_col, len(inp), len(out))\n cache_col = max(cache_col, len(cache))\n if has_cache:\n cache_col = max(cache_col, 5) # minimum: \"Cache\" header\n\n def _label(mid):\n if has_pricing:\n inp, out, cache = _price_cache.get(mid, (\"\", \"\", \"\"))\n price_part = f\" {inp:>{price_col}} {out:>{price_col}}\"\n if has_cache:\n price_part += f\" {cache:>{cache_col}}\"\n base = f\"{mid:<{name_col}}{price_part}\"\n else:\n base = mid\n if mid == current_model:\n base += \" ← currently in use\"\n return base\n\n # Default cursor on the current model (index 0 if it was reordered to top)\n default_idx = 0\n\n # Build a pricing header hint for the menu title\n menu_title = \"Select default model:\"\n if has_pricing:\n # Align the header with the model column.\n # Each choice is \" {label}\" (2 spaces) and simple_term_menu prepends\n # a 3-char cursor region (\"-> \" or \" \"), so content starts at col 5.\n pad = \" \" * 5\n header = f\"\\n{pad}{'':>{name_col}} {'In':>{price_col}} {'Out':>{price_col}}\"\n if has_cache:\n header += f\" {'Cache':>{cache_col}}\"\n menu_title += header + \" /Mtok\"\n\n # ANSI escape for dim text\n _DIM = \"\\033[2m\"\n _RESET = \"\\033[0m\"\n\n # Try arrow-key menu first, fall back to number input\n try:\n from simple_term_menu import TerminalMenu\n\n choices = [f\" {_label(mid)}\" for mid in ordered]\n choices.append(\" Enter custom model name\")\n choices.append(\" Skip (keep current)\")\n\n # Print the unavailable block BEFORE the menu via regular print().\n # simple_term_menu pads title lines to terminal width (causes wrapping),\n # so we keep the title minimal and use stdout for the static block.\n # clear_screen=False means our printed output stays visible above.\n _upgrade_url = (portal_url or DEFAULT_NOUS_PORTAL_URL).rstrip(\"/\")\n if _unavailable:\n print(menu_title)\n print()\n for mid in _unavailable:\n print(f\"{_DIM} {_label(mid)}{_RESET}\")\n print()\n print(f\"{_DIM} ── Upgrade at {_upgrade_url} for paid models ──{_RESET}\")\n print()\n effective_title = \"Available free models:\"\n else:\n effective_title = menu_title\n\n menu = TerminalMenu(\n choices,\n cursor_index=default_idx,\n menu_cursor=\"-> \",\n menu_cursor_style=(\"fg_green\", \"bold\"),\n menu_highlight_style=(\"fg_green\",),\n cycle_cursor=True,\n clear_screen=False,\n title=effective_title,\n )\n idx = menu.show()\n from hermes_cli.curses_ui import flush_stdin\n flush_stdin()\n if idx is None:\n return None\n print()\n if idx < len(ordered):\n return ordered[idx]\n elif idx == len(ordered):\n custom = input(\"Enter model name: \").strip()\n return custom if custom else None\n return None\n except (ImportError, NotImplementedError, OSError, subprocess.SubprocessError):\n pass\n\n # Fallback: numbered list\n print(menu_title)\n num_width = len(str(len(ordered) + 2))\n for i, mid in enumerate(ordered, 1):\n print(f\" {i:>{num_width}}. {_label(mid)}\")\n n = len(ordered)\n print(f\" {n + 1:>{num_width}}. Enter custom model name\")\n print(f\" {n + 2:>{num_width}}. Skip (keep current)\")\n\n if _unavailable:\n _upgrade_url = (portal_url or DEFAULT_NOUS_PORTAL_URL).rstrip(\"/\")\n print()\n print(f\" {_DIM}── Unavailable models (requires paid tier — upgrade at {_upgrade_url}) ──{_RESET}\")\n for mid in _unavailable:\n print(f\" {'':>{num_width}} {_DIM}{_label(mid)}{_RESET}\")\n print()\n\n while True:\n try:\n choice = input(f\"Choice [1-{n + 2}] (default: skip): \").strip()\n if not choice:\n return None\n idx = int(choice)\n if 1 <= idx <= n:\n return ordered[idx - 1]\n elif idx == n + 1:\n custom = input(\"Enter model name: \").strip()\n return custom if custom else None\n elif idx == n + 2:\n return None\n print(f\"Please enter 1-{n + 2}\")\n except ValueError:\n print(\"Please enter a number\")\n except (KeyboardInterrupt, EOFError):\n return None\n\n\ndef _save_model_choice(model_id: str) -> None:\n \"\"\"Save the selected model to config.yaml (single source of truth).\n\n The model is stored in config.yaml only — NOT in .env. This avoids\n conflicts in multi-agent setups where env vars would stomp each other.\n \"\"\"\n from hermes_cli.config import save_config, load_config\n\n config = load_config()\n # Always use dict format so provider/base_url can be stored alongside\n if isinstance(config.get(\"model\"), dict):\n config[\"model\"][\"default\"] = model_id\n else:\n config[\"model\"] = {\"default\": model_id}\n save_config(config)\n\n\ndef login_command(args) -> None:\n \"\"\"Deprecated: use 'hermes model' or 'hermes setup' instead.\"\"\"\n print(\"The 'hermes login' command has been removed.\")\n print(\"Use 'hermes auth' to manage credentials,\")\n print(\"'hermes model' to select a provider, or 'hermes setup' for full setup.\")\n raise SystemExit(0)\n\n\ndef _login_openai_codex(\n args,\n pconfig: ProviderConfig,\n *,\n force_new_login: bool = False,\n) -> None:\n \"\"\"OpenAI Codex login via device code flow. Tokens stored in ~/.hermes/auth.json.\"\"\"\n\n del args, pconfig # kept for parity with other provider login helpers\n\n # Check for existing Hermes-owned credentials\n if not force_new_login:\n try:\n existing = resolve_codex_runtime_credentials()\n # Verify the resolved token is actually usable (not expired).\n # resolve_codex_runtime_credentials attempts refresh, so if we get\n # here the token should be valid — but double-check before telling\n # the user \"Login successful!\".\n _resolved_key = existing.get(\"api_key\", \"\")\n if isinstance(_resolved_key, str) and _resolved_key and not _codex_access_token_is_expiring(_resolved_key, 60):\n print(\"Existing Codex credentials found in Hermes auth store.\")\n try:\n reuse = input(\"Use existing credentials? [Y/n]: \").strip().lower()\n except (EOFError, KeyboardInterrupt):\n reuse = \"y\"\n if reuse in (\"\", \"y\", \"yes\"):\n config_path = _update_config_for_provider(\"openai-codex\", existing.get(\"base_url\", DEFAULT_CODEX_BASE_URL))\n print()\n print(\"Login successful!\")\n print(f\" Config updated: {config_path} (model.provider=openai-codex)\")\n return\n else:\n print(\"Existing Codex credentials are expired. Starting fresh login...\")\n except AuthError:\n pass\n\n # Check for existing Codex CLI tokens we can import\n if not force_new_login:\n cli_tokens = _import_codex_cli_tokens()\n if cli_tokens:\n print(\"Found existing Codex CLI credentials at ~/.codex/auth.json\")\n print(\"Hermes will create its own session to avoid conflicts with Codex CLI / VS Code.\")\n try:\n do_import = input(\"Import these credentials? (a separate login is recommended) [y/N]: \").strip().lower()\n except (EOFError, KeyboardInterrupt):\n do_import = \"n\"\n if do_import in (\"y\", \"yes\"):\n _save_codex_tokens(cli_tokens)\n base_url = os.getenv(\"HERMES_CODEX_BASE_URL\", \"\").strip().rstrip(\"/\") or DEFAULT_CODEX_BASE_URL\n config_path = _update_config_for_provider(\"openai-codex\", base_url)\n print()\n print(\"Credentials imported. Note: if Codex CLI refreshes its token,\")\n print(\"Hermes will keep working independently with its own session.\")\n print(f\" Config updated: {config_path} (model.provider=openai-codex)\")\n return\n\n # Run a fresh device code flow — Hermes gets its own OAuth session\n print()\n print(\"Signing in to OpenAI Codex...\")\n print(\"(Hermes creates its own session — won't affect Codex CLI or VS Code)\")\n print()\n\n creds = _codex_device_code_login()\n\n # Save tokens to Hermes auth store\n _save_codex_tokens(creds[\"tokens\"], creds.get(\"last_refresh\"))\n config_path = _update_config_for_provider(\"openai-codex\", creds.get(\"base_url\", DEFAULT_CODEX_BASE_URL))\n print()\n print(\"Login successful!\")\n from hermes_constants import display_hermes_home as _dhh\n print(f\" Auth state: {_dhh()}/auth.json\")\n print(f\" Config updated: {config_path} (model.provider=openai-codex)\")\n\n\ndef _codex_device_code_login() -> Dict[str, Any]:\n \"\"\"Run the OpenAI device code login flow and return credentials dict.\"\"\"\n import time as _time\n\n issuer = \"https://auth.openai.com\"\n client_id = CODEX_OAUTH_CLIENT_ID\n\n # Step 1: Request device code\n try:\n with httpx.Client(timeout=httpx.Timeout(15.0)) as client:\n resp = client.post(\n f\"{issuer}/api/accounts/deviceauth/usercode\",\n json={\"client_id\": client_id},\n headers={\"Content-Type\": \"application/json\"},\n )\n except Exception as exc:\n raise AuthError(\n f\"Failed to request device code: {exc}\",\n provider=\"openai-codex\", code=\"device_code_request_failed\",\n )\n\n if resp.status_code != 200:\n raise AuthError(\n f\"Device code request returned status {resp.status_code}.\",\n provider=\"openai-codex\", code=\"device_code_request_error\",\n )\n\n device_data = resp.json()\n user_code = device_data.get(\"user_code\", \"\")\n device_auth_id = device_data.get(\"device_auth_id\", \"\")\n poll_interval = max(3, int(device_data.get(\"interval\", \"5\")))\n\n if not user_code or not device_auth_id:\n raise AuthError(\n \"Device code response missing required fields.\",\n provider=\"openai-codex\", code=\"device_code_incomplete\",\n )\n\n # Step 2: Show user the code\n print(\"To continue, follow these steps:\\n\")\n print(\" 1. Open this URL in your browser:\")\n print(f\" \\033[94m{issuer}/codex/device\\033[0m\\n\")\n print(\" 2. Enter this code:\")\n print(f\" \\033[94m{user_code}\\033[0m\\n\")\n print(\"Waiting for sign-in... (press Ctrl+C to cancel)\")\n\n # Step 3: Poll for authorization code\n max_wait = 15 * 60 # 15 minutes\n start = _time.monotonic()\n code_resp = None\n\n try:\n with httpx.Client(timeout=httpx.Timeout(15.0)) as client:\n while _time.monotonic() - start < max_wait:\n _time.sleep(poll_interval)\n poll_resp = client.post(\n f\"{issuer}/api/accounts/deviceauth/token\",\n json={\"device_auth_id\": device_auth_id, \"user_code\": user_code},\n headers={\"Content-Type\": \"application/json\"},\n )\n\n if poll_resp.status_code == 200:\n code_resp = poll_resp.json()\n break\n elif poll_resp.status_code in (403, 404):\n continue # User hasn't completed login yet\n else:\n raise AuthError(\n f\"Device auth polling returned status {poll_resp.status_code}.\",\n provider=\"openai-codex\", code=\"device_code_poll_error\",\n )\n except KeyboardInterrupt:\n print(\"\\nLogin cancelled.\")\n raise SystemExit(130)\n\n if code_resp is None:\n raise AuthError(\n \"Login timed out after 15 minutes.\",\n provider=\"openai-codex\", code=\"device_code_timeout\",\n )\n\n # Step 4: Exchange authorization code for tokens\n authorization_code = code_resp.get(\"authorization_code\", \"\")\n code_verifier = code_resp.get(\"code_verifier\", \"\")\n redirect_uri = f\"{issuer}/deviceauth/callback\"\n\n if not authorization_code or not code_verifier:\n raise AuthError(\n \"Device auth response missing authorization_code or code_verifier.\",\n provider=\"openai-codex\", code=\"device_code_incomplete_exchange\",\n )\n\n try:\n with httpx.Client(timeout=httpx.Timeout(15.0)) as client:\n token_resp = client.post(\n CODEX_OAUTH_TOKEN_URL,\n data={\n \"grant_type\": \"authorization_code\",\n \"code\": authorization_code,\n \"redirect_uri\": redirect_uri,\n \"client_id\": client_id,\n \"code_verifier\": code_verifier,\n },\n headers={\"Content-Type\": \"application/x-www-form-urlencoded\"},\n )\n except Exception as exc:\n raise AuthError(\n f\"Token exchange failed: {exc}\",\n provider=\"openai-codex\", code=\"token_exchange_failed\",\n )\n\n if token_resp.status_code != 200:\n raise AuthError(\n f\"Token exchange returned status {token_resp.status_code}.\",\n provider=\"openai-codex\", code=\"token_exchange_error\",\n )\n\n tokens = token_resp.json()\n access_token = tokens.get(\"access_token\", \"\")\n refresh_token = tokens.get(\"refresh_token\", \"\")\n\n if not access_token:\n raise AuthError(\n \"Token exchange did not return an access_token.\",\n provider=\"openai-codex\", code=\"token_exchange_no_access_token\",\n )\n\n # Return tokens for the caller to persist (no longer writes to ~/.codex/)\n base_url = (\n os.getenv(\"HERMES_CODEX_BASE_URL\", \"\").strip().rstrip(\"/\")\n or DEFAULT_CODEX_BASE_URL\n )\n\n return {\n \"tokens\": {\n \"access_token\": access_token,\n \"refresh_token\": refresh_token,\n },\n \"base_url\": base_url,\n \"last_refresh\": datetime.now(timezone.utc).isoformat().replace(\"+00:00\", \"Z\"),\n \"auth_mode\": \"chatgpt\",\n \"source\": \"device-code\",\n }\n\n\ndef _nous_device_code_login(\n *,\n portal_base_url: Optional[str] = None,\n inference_base_url: Optional[str] = None,\n client_id: Optional[str] = None,\n scope: Optional[str] = None,\n open_browser: bool = True,\n timeout_seconds: float = 15.0,\n insecure: bool = False,\n ca_bundle: Optional[str] = None,\n min_key_ttl_seconds: int = 5 * 60,\n) -> Dict[str, Any]:\n \"\"\"Run the Nous device-code flow and return full OAuth state without persisting.\"\"\"\n pconfig = PROVIDER_REGISTRY[\"nous\"]\n portal_base_url = (\n portal_base_url\n or os.getenv(\"HERMES_PORTAL_BASE_URL\")\n or os.getenv(\"NOUS_PORTAL_BASE_URL\")\n or pconfig.portal_base_url\n ).rstrip(\"/\")\n requested_inference_url = (\n inference_base_url\n or os.getenv(\"NOUS_INFERENCE_BASE_URL\")\n or pconfig.inference_base_url\n ).rstrip(\"/\")\n client_id = client_id or pconfig.client_id\n scope = scope or pconfig.scope\n timeout = httpx.Timeout(timeout_seconds)\n verify: bool | str = False if insecure else (ca_bundle if ca_bundle else True)\n\n if _is_remote_session():\n open_browser = False\n\n print(f\"Starting Hermes login via {pconfig.name}...\")\n print(f\"Portal: {portal_base_url}\")\n if insecure:\n print(\"TLS verification: disabled (--insecure)\")\n elif ca_bundle:\n print(f\"TLS verification: custom CA bundle ({ca_bundle})\")\n\n with httpx.Client(timeout=timeout, headers={\"Accept\": \"application/json\"}, verify=verify) as client:\n device_data = _request_device_code(\n client=client,\n portal_base_url=portal_base_url,\n client_id=client_id,\n scope=scope,\n )\n\n verification_url = str(device_data[\"verification_uri_complete\"])\n user_code = str(device_data[\"user_code\"])\n expires_in = int(device_data[\"expires_in\"])\n interval = int(device_data[\"interval\"])\n\n print()\n print(\"To continue:\")\n print(f\" 1. Open: {verification_url}\")\n print(f\" 2. If prompted, enter code: {user_code}\")\n\n if open_browser:\n opened = webbrowser.open(verification_url)\n if opened:\n print(\" (Opened browser for verification)\")\n else:\n print(\" Could not open browser automatically — use the URL above.\")\n\n effective_interval = max(1, min(interval, DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS))\n print(f\"Waiting for approval (polling every {effective_interval}s)...\")\n\n token_data = _poll_for_token(\n client=client,\n portal_base_url=portal_base_url,\n client_id=client_id,\n device_code=str(device_data[\"device_code\"]),\n expires_in=expires_in,\n poll_interval=interval,\n )\n\n now = datetime.now(timezone.utc)\n token_expires_in = _coerce_ttl_seconds(token_data.get(\"expires_in\", 0))\n expires_at = now.timestamp() + token_expires_in\n resolved_inference_url = (\n _optional_base_url(token_data.get(\"inference_base_url\"))\n or requested_inference_url\n )\n if resolved_inference_url != requested_inference_url:\n print(f\"Using portal-provided inference URL: {resolved_inference_url}\")\n\n auth_state = {\n \"portal_base_url\": portal_base_url,\n \"inference_base_url\": resolved_inference_url,\n \"client_id\": client_id,\n \"scope\": token_data.get(\"scope\") or scope,\n \"token_type\": token_data.get(\"token_type\", \"Bearer\"),\n \"access_token\": token_data[\"access_token\"],\n \"refresh_token\": token_data.get(\"refresh_token\"),\n \"obtained_at\": now.isoformat(),\n \"expires_at\": datetime.fromtimestamp(expires_at, tz=timezone.utc).isoformat(),\n \"expires_in\": token_expires_in,\n \"tls\": {\n \"insecure\": verify is False,\n \"ca_bundle\": verify if isinstance(verify, str) else None,\n },\n \"agent_key\": None,\n \"agent_key_id\": None,\n \"agent_key_expires_at\": None,\n \"agent_key_expires_in\": None,\n \"agent_key_reused\": None,\n \"agent_key_obtained_at\": None,\n }\n try:\n return refresh_nous_oauth_from_state(\n auth_state,\n min_key_ttl_seconds=min_key_ttl_seconds,\n timeout_seconds=timeout_seconds,\n force_refresh=False,\n force_mint=True,\n )\n except AuthError as exc:\n if exc.code == \"subscription_required\":\n portal_url = auth_state.get(\n \"portal_base_url\", DEFAULT_NOUS_PORTAL_URL\n ).rstrip(\"/\")\n print()\n print(\"Your Nous Portal account does not have an active subscription.\")\n print(f\" Subscribe here: {portal_url}/billing\")\n print()\n print(\"After subscribing, run `hermes model` again to finish setup.\")\n raise SystemExit(1)\n raise\n\n\ndef _login_nous(args, pconfig: ProviderConfig) -> None:\n \"\"\"Nous Portal device authorization flow.\"\"\"\n timeout_seconds = getattr(args, \"timeout\", None) or 15.0\n insecure = bool(getattr(args, \"insecure\", False))\n ca_bundle = (\n getattr(args, \"ca_bundle\", None)\n or os.getenv(\"HERMES_CA_BUNDLE\")\n or os.getenv(\"SSL_CERT_FILE\")\n )\n\n try:\n auth_state = _nous_device_code_login(\n portal_base_url=getattr(args, \"portal_url\", None),\n inference_base_url=getattr(args, \"inference_url\", None),\n client_id=getattr(args, \"client_id\", None) or pconfig.client_id,\n scope=getattr(args, \"scope\", None) or pconfig.scope,\n open_browser=not getattr(args, \"no_browser\", False),\n timeout_seconds=timeout_seconds,\n insecure=insecure,\n ca_bundle=ca_bundle,\n min_key_ttl_seconds=5 * 60,\n )\n\n inference_base_url = auth_state[\"inference_base_url\"]\n\n # Snapshot the prior active_provider BEFORE _save_provider_state\n # overwrites it to \"nous\". If the user picks \"Skip (keep current)\"\n # during model selection below, we restore this so the user's previous\n # provider (e.g. openrouter) is preserved.\n with _auth_store_lock():\n _prior_store = _load_auth_store()\n prior_active_provider = _prior_store.get(\"active_provider\")\n\n with _auth_store_lock():\n auth_store = _load_auth_store()\n _save_provider_state(auth_store, \"nous\", auth_state)\n saved_to = _save_auth_store(auth_store)\n\n print()\n print(\"Login successful!\")\n print(f\" Auth state: {saved_to}\")\n\n # Resolve model BEFORE writing provider to config.yaml so we never\n # leave the config in a half-updated state (provider=nous but model\n # still set to the previous provider's model, e.g. opus from\n # OpenRouter). The auth.json active_provider was already set above.\n selected_model = None\n try:\n runtime_key = auth_state.get(\"agent_key\") or auth_state.get(\"access_token\")\n if not isinstance(runtime_key, str) or not runtime_key:\n raise AuthError(\n \"No runtime API key available to fetch models\",\n provider=\"nous\",\n code=\"invalid_token\",\n )\n\n from hermes_cli.models import (\n _PROVIDER_MODELS, get_pricing_for_provider,\n check_nous_free_tier, partition_nous_models_by_tier,\n )\n model_ids = _PROVIDER_MODELS.get(\"nous\", [])\n\n print()\n unavailable_models: list = []\n if model_ids:\n pricing = get_pricing_for_provider(\"nous\")\n free_tier = check_nous_free_tier()\n if free_tier:\n model_ids, unavailable_models = partition_nous_models_by_tier(\n model_ids, pricing, free_tier=True,\n )\n _portal = auth_state.get(\"portal_base_url\", \"\")\n if model_ids:\n print(f\"Showing {len(model_ids)} curated models — use \\\"Enter custom model name\\\" for others.\")\n selected_model = _prompt_model_selection(\n model_ids, pricing=pricing,\n unavailable_models=unavailable_models,\n portal_url=_portal,\n )\n elif unavailable_models:\n _url = (_portal or DEFAULT_NOUS_PORTAL_URL).rstrip(\"/\")\n print(\"No free models currently available.\")\n print(f\"Upgrade at {_url} to access paid models.\")\n else:\n print(\"No curated models available for Nous Portal.\")\n except Exception as exc:\n message = format_auth_error(exc) if isinstance(exc, AuthError) else str(exc)\n print()\n print(f\"Login succeeded, but could not fetch available models. Reason: {message}\")\n\n # Write provider + model atomically so config is never mismatched.\n # If no model was selected (user picked \"Skip (keep current)\",\n # model list fetch failed, or no curated models were available),\n # preserve the user's previous provider — don't silently switch\n # them to Nous with a mismatched model. The Nous OAuth tokens\n # stay saved for future use.\n if not selected_model:\n # Restore the prior active_provider that _save_provider_state\n # overwrote to \"nous\". config.yaml model.provider is left\n # untouched, so the user's previous provider is fully preserved.\n with _auth_store_lock():\n auth_store = _load_auth_store()\n if prior_active_provider:\n auth_store[\"active_provider\"] = prior_active_provider\n else:\n auth_store.pop(\"active_provider\", None)\n _save_auth_store(auth_store)\n print()\n print(\"No provider change. Nous credentials saved for future use.\")\n print(\" Run `hermes model` again to switch to Nous Portal.\")\n return\n\n config_path = _update_config_for_provider(\n \"nous\", inference_base_url, default_model=selected_model,\n )\n if selected_model:\n _save_model_choice(selected_model)\n print(f\"Default model set to: {selected_model}\")\n print(f\" Config updated: {config_path} (model.provider=nous)\")\n\n except KeyboardInterrupt:\n print(\"\\nLogin cancelled.\")\n raise SystemExit(130)\n except Exception as exc:\n print(f\"Login failed: {exc}\")\n raise SystemExit(1)\n\n\ndef logout_command(args) -> None:\n \"\"\"Clear auth state for a provider.\"\"\"\n provider_id = getattr(args, \"provider\", None)\n\n if provider_id and not is_known_auth_provider(provider_id):\n print(f\"Unknown provider: {provider_id}\")\n raise SystemExit(1)\n\n active = get_active_provider()\n target = provider_id or active or _logout_default_provider_from_config()\n\n if not target:\n print(\"No provider is currently logged in.\")\n return\n\n config_matches = _config_provider_matches(target)\n provider_name = get_auth_provider_display_name(target)\n\n if clear_provider_auth(target) or config_matches:\n _reset_config_provider()\n print(f\"Logged out of {provider_name}.\")\n if os.getenv(\"OPENROUTER_API_KEY\"):\n print(\"Hermes will use OpenRouter for inference.\")\n else:\n print(\"Run `hermes model` or configure an API key to use Hermes.\")\n else:\n print(f\"No auth state found for {provider_name}.\")\n"}}, "hermes_cli/dump.py": {"160ae748d243940671329e425cc67a3f82c2a2a0": {"t": 1785745444.7268355, "n": 10675, "h": "6b5d2f44b091c74a", "c": "\"\"\"\nDump command for hermes CLI.\n\nOutputs a compact, plain-text summary of the user's Hermes setup\nthat can be copy-pasted into Discord/GitHub/Telegram for support context.\nNo ANSI colors, no checkmarks — just data.\n\"\"\"\n\nimport json\nimport os\nimport platform\nimport subprocess\nimport sys\nfrom pathlib import Path\n\nfrom hermes_cli.config import get_hermes_home, get_env_path, get_project_root, load_config\nfrom hermes_constants import display_hermes_home\n\n\ndef _get_git_commit(project_root: Path) -> str:\n \"\"\"Return short git commit hash, or '(unknown)'.\"\"\"\n try:\n result = subprocess.run(\n [\"git\", \"rev-parse\", \"--short=8\", \"HEAD\"],\n capture_output=True, text=True, timeout=5,\n cwd=str(project_root),\n )\n if result.returncode == 0:\n return result.stdout.strip()\n except Exception:\n pass\n return \"(unknown)\"\n\n\ndef _redact(value: str) -> str:\n \"\"\"Redact all but first 4 and last 4 chars.\"\"\"\n if not value:\n return \"\"\n if len(value) < 12:\n return \"***\"\n return value[:4] + \"...\" + value[-4:]\n\n\ndef _gateway_status() -> str:\n \"\"\"Return a short gateway status string.\"\"\"\n try:\n from hermes_cli.gateway import get_gateway_runtime_snapshot\n\n snapshot = get_gateway_runtime_snapshot()\n if snapshot.running:\n mode = snapshot.manager\n if snapshot.has_process_service_mismatch:\n mode = \"manual\"\n return f\"running ({mode}, pid {snapshot.gateway_pids[0]})\"\n if snapshot.service_installed and not snapshot.service_running:\n return f\"stopped ({snapshot.manager})\"\n return f\"stopped ({snapshot.manager})\"\n except Exception:\n return \"unknown\" if sys.platform.startswith((\"linux\", \"darwin\")) else \"N/A\"\n\n\ndef _count_skills(hermes_home: Path) -> int:\n \"\"\"Count installed skills.\"\"\"\n skills_dir = hermes_home / \"skills\"\n if not skills_dir.is_dir():\n return 0\n count = 0\n for item in skills_dir.rglob(\"SKILL.md\"):\n count += 1\n return count\n\n\ndef _count_mcp_servers(config: dict) -> int:\n \"\"\"Count configured MCP servers.\"\"\"\n mcp = config.get(\"mcp\", {})\n servers = mcp.get(\"servers\", {})\n return len(servers)\n\n\ndef _cron_summary(hermes_home: Path) -> str:\n \"\"\"Return cron jobs summary.\"\"\"\n jobs_file = hermes_home / \"cron\" / \"jobs.json\"\n if not jobs_file.exists():\n return \"0\"\n try:\n with open(jobs_file, encoding=\"utf-8\") as f:\n data = json.load(f)\n jobs = data.get(\"jobs\", [])\n active = sum(1 for j in jobs if j.get(\"enabled\", True))\n return f\"{active} active / {len(jobs)} total\"\n except Exception:\n return \"(error reading)\"\n\n\ndef _configured_platforms() -> list[str]:\n \"\"\"Return list of configured messaging platform names.\"\"\"\n checks = {\n \"telegram\": \"TELEGRAM_BOT_TOKEN\",\n \"discord\": \"DISCORD_BOT_TOKEN\",\n \"slack\": \"SLACK_BOT_TOKEN\",\n \"whatsapp\": \"WHATSAPP_ENABLED\",\n \"signal\": \"SIGNAL_HTTP_URL\",\n \"email\": \"EMAIL_ADDRESS\",\n \"sms\": \"TWILIO_ACCOUNT_SID\",\n \"matrix\": \"MATRIX_HOMESERVER_URL\",\n \"mattermost\": \"MATTERMOST_URL\",\n \"homeassistant\": \"HASS_TOKEN\",\n \"dingtalk\": \"DINGTALK_CLIENT_ID\",\n \"feishu\": \"FEISHU_APP_ID\",\n \"wecom\": \"WECOM_BOT_ID\",\n \"wecom_callback\": \"WECOM_CALLBACK_CORP_ID\",\n \"weixin\": \"WEIXIN_ACCOUNT_ID\",\n \"qqbot\": \"QQ_APP_ID\",\n }\n return [name for name, env in checks.items() if os.getenv(env)]\n\n\ndef _memory_provider(config: dict) -> str:\n \"\"\"Return the active memory provider name.\"\"\"\n mem = config.get(\"memory\", {})\n provider = mem.get(\"provider\", \"\")\n return provider if provider else \"built-in\"\n\n\ndef _get_model_and_provider(config: dict) -> tuple[str, str]:\n \"\"\"Extract model and provider from config.\"\"\"\n model_cfg = config.get(\"model\", \"\")\n if isinstance(model_cfg, dict):\n model = model_cfg.get(\"default\") or model_cfg.get(\"model\") or model_cfg.get(\"name\") or \"(not set)\"\n provider = model_cfg.get(\"provider\") or \"(auto)\"\n elif isinstance(model_cfg, str):\n model = model_cfg or \"(not set)\"\n provider = \"(auto)\"\n else:\n model = \"(not set)\"\n provider = \"(auto)\"\n return model, provider\n\n\ndef _config_overrides(config: dict) -> dict[str, str]:\n \"\"\"Find non-default config values worth reporting.\n \n Returns a flat dict of dotpath -> value for interesting overrides.\n \"\"\"\n from hermes_cli.config import DEFAULT_CONFIG\n\n overrides = {}\n\n # Sections with interesting user-facing overrides\n interesting_paths = [\n (\"agent\", \"max_turns\"),\n (\"agent\", \"gateway_timeout\"),\n (\"agent\", \"tool_use_enforcement\"),\n (\"terminal\", \"backend\"),\n (\"terminal\", \"docker_image\"),\n (\"terminal\", \"persistent_shell\"),\n (\"browser\", \"allow_private_urls\"),\n (\"compression\", \"enabled\"),\n (\"compression\", \"threshold\"),\n (\"display\", \"streaming\"),\n (\"display\", \"skin\"),\n (\"display\", \"show_reasoning\"),\n (\"privacy\", \"redact_pii\"),\n (\"tts\", \"provider\"),\n ]\n\n for section, key in interesting_paths:\n default_section = DEFAULT_CONFIG.get(section, {})\n user_section = config.get(section, {})\n if not isinstance(default_section, dict) or not isinstance(user_section, dict):\n continue\n default_val = default_section.get(key)\n user_val = user_section.get(key)\n if user_val is not None and user_val != default_val:\n overrides[f\"{section}.{key}\"] = str(user_val)\n\n # Toolsets (if different from default)\n default_toolsets = DEFAULT_CONFIG.get(\"toolsets\", [])\n user_toolsets = config.get(\"toolsets\", [])\n if user_toolsets != default_toolsets:\n overrides[\"toolsets\"] = str(user_toolsets)\n\n # Fallback providers\n fallbacks = config.get(\"fallback_providers\", [])\n if fallbacks:\n overrides[\"fallback_providers\"] = str(fallbacks)\n\n return overrides\n\n\ndef run_dump(args):\n \"\"\"Output a compact, copy-pasteable setup summary.\"\"\"\n show_keys = getattr(args, \"show_keys\", False)\n\n # Load env from .env file so key checks work\n from dotenv import load_dotenv\n env_path = get_env_path()\n if env_path.exists():\n try:\n load_dotenv(env_path, encoding=\"utf-8\")\n except UnicodeDecodeError:\n load_dotenv(env_path, encoding=\"latin-1\")\n # Also try project .env as dev fallback\n load_dotenv(get_project_root() / \".env\", override=False, encoding=\"utf-8\")\n\n project_root = get_project_root()\n hermes_home = get_hermes_home()\n\n try:\n from hermes_cli import __version__, __release_date__\n except ImportError:\n __version__ = \"(unknown)\"\n __release_date__ = \"\"\n\n commit = _get_git_commit(project_root)\n\n try:\n config = load_config()\n except Exception:\n config = {}\n\n model, provider = _get_model_and_provider(config)\n\n # Profile\n try:\n from hermes_cli.profiles import get_active_profile_name\n profile = get_active_profile_name() or \"(default)\"\n except Exception:\n profile = \"(default)\"\n\n # Terminal backend\n terminal_cfg = config.get(\"terminal\", {})\n backend = terminal_cfg.get(\"backend\", \"local\")\n\n # OpenAI SDK version\n try:\n import openai\n openai_ver = openai.__version__\n except ImportError:\n openai_ver = \"not installed\"\n\n # OS info\n os_info = f\"{platform.system()} {platform.release()} {platform.machine()}\"\n\n lines = []\n lines.append(\"--- hermes dump ---\")\n ver_str = f\"{__version__}\"\n if __release_date__:\n ver_str += f\" ({__release_date__})\"\n ver_str += f\" [{commit}]\"\n lines.append(f\"version: {ver_str}\")\n lines.append(f\"os: {os_info}\")\n lines.append(f\"python: {sys.version.split()[0]}\")\n lines.append(f\"openai_sdk: {openai_ver}\")\n lines.append(f\"profile: {profile}\")\n lines.append(f\"hermes_home: {display_hermes_home()}\")\n lines.append(f\"model: {model}\")\n lines.append(f\"provider: {provider}\")\n lines.append(f\"terminal: {backend}\")\n\n # API keys\n lines.append(\"\")\n lines.append(\"api_keys:\")\n api_keys = [\n (\"OPENROUTER_API_KEY\", \"openrouter\"),\n (\"OPENAI_API_KEY\", \"openai\"),\n (\"ANTHROPIC_API_KEY\", \"anthropic\"),\n (\"ANTHROPIC_TOKEN\", \"anthropic_token\"),\n (\"NOUS_API_KEY\", \"nous\"),\n (\"GOOGLE_API_KEY\", \"google/gemini\"),\n (\"GEMINI_API_KEY\", \"gemini\"),\n (\"GLM_API_KEY\", \"glm/zai\"),\n (\"ZAI_API_KEY\", \"zai\"),\n (\"KIMI_API_KEY\", \"kimi\"),\n (\"MINIMAX_API_KEY\", \"minimax\"),\n (\"DEEPSEEK_API_KEY\", \"deepseek\"),\n (\"DASHSCOPE_API_KEY\", \"dashscope\"),\n (\"HF_TOKEN\", \"huggingface\"),\n (\"NVIDIA_API_KEY\", \"nvidia\"),\n (\"AI_GATEWAY_API_KEY\", \"ai_gateway\"),\n (\"OPENCODE_ZEN_API_KEY\", \"opencode_zen\"),\n (\"OPENCODE_GO_API_KEY\", \"opencode_go\"),\n (\"KILOCODE_API_KEY\", \"kilocode\"),\n (\"FIRECRAWL_API_KEY\", \"firecrawl\"),\n (\"TAVILY_API_KEY\", \"tavily\"),\n (\"BROWSERBASE_API_KEY\", \"browserbase\"),\n (\"FAL_KEY\", \"fal\"),\n (\"ELEVENLABS_API_KEY\", \"elevenlabs\"),\n (\"GITHUB_TOKEN\", \"github\"),\n ]\n\n for env_var, label in api_keys:\n val = os.getenv(env_var, \"\")\n if show_keys and val:\n display = _redact(val)\n else:\n display = \"set\" if val else \"not set\"\n lines.append(f\" {label:<20} {display}\")\n\n # Features summary\n lines.append(\"\")\n lines.append(\"features:\")\n\n toolsets = config.get(\"toolsets\", [\"hermes-cli\"])\n lines.append(f\" toolsets: {', '.join(toolsets) if toolsets else '(default)'}\")\n lines.append(f\" mcp_servers: {_count_mcp_servers(config)}\")\n lines.append(f\" memory_provider: {_memory_provider(config)}\")\n lines.append(f\" gateway: {_gateway_status()}\")\n\n platforms = _configured_platforms()\n lines.append(f\" platforms: {', '.join(platforms) if platforms else 'none'}\")\n lines.append(f\" cron_jobs: {_cron_summary(hermes_home)}\")\n lines.append(f\" skills: {_count_skills(hermes_home)}\")\n\n # Config overrides (non-default values)\n overrides = _config_overrides(config)\n if overrides:\n lines.append(\"\")\n lines.append(\"config_overrides:\")\n for key, val in overrides.items():\n lines.append(f\" {key}: {val}\")\n\n lines.append(\"--- end dump ---\")\n\n output = \"\\n\".join(lines)\n print(output)\n"}}}}