auth.py 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424
  1. """Multi-provider authentication system for Hermes Agent.
  2. - ``ProviderConfig`` / ``PROVIDER_REGISTRY`` describe every known inference provider.
  3. - The auth store (``~/.hermes/auth.json``) holds per-provider state, the credential pool and
  4. suppression markers; ``_auth_store_lock`` / ``_load_auth_store`` / ``_save_auth_store`` are the
  5. only I/O primitives (cross-process flock, atomic 0o600 writes).
  6. - ``resolve_provider()`` picks the active provider via the documented priority chain.
  7. - ``OAUTH_PROVIDER_FLOWS`` maps each OAuth provider to its resolver/status builder; the flows live in
  8. ``auth_nous``/``auth_codex``/``auth_xai``/``auth_qwen``/``auth_minimax``/``auth_openrouter`` and are
  9. re-imported here so ``hermes_cli.auth.<name>`` stays the public/patchable surface."""
  10. from __future__ import annotations
  11. from pm import install_hint
  12. import errno
  13. import json
  14. import logging
  15. import os
  16. import shutil
  17. import shlex
  18. import threading
  19. import time
  20. import webbrowser
  21. from contextlib import ExitStack, contextmanager
  22. from dataclasses import dataclass, field
  23. from functools import partial
  24. from datetime import datetime, timezone, UTC
  25. from pathlib import Path
  26. from typing import Any, Callable, Dict, FrozenSet, Iterable, List, Optional, Tuple
  27. from urllib.parse import urlparse
  28. from hermes_constants import OPENROUTER_BASE_URL, hermes_home_key, secure_parent_dir
  29. from agent.credential_persistence import sanitize_borrowed_credential_payload
  30. from utils import atomic_json_write, env_float, file_cache_version, is_truthy_value
  31. from hermes_cli.auth_zai_kimi import (
  32. KIMI_CODE_BASE_URL, ZAI_ENDPOINTS, _normalize_lmstudio_runtime_base_url, _resolve_kimi_base_url,
  33. _resolve_zai_base_url, detect_zai_endpoint)
  34. from hermes_cli.auth_model_picker import (
  35. _prompt_model_selection, _save_model_choice)
  36. from hermes_cli.auth_device_flow import (
  37. _can_open_graphical_browser, _default_verify, _is_remote_session,
  38. _nous_device_auth_timeout_message, _offer_existing_oauth_credentials,
  39. _poll_device_token_generic, _poll_for_token, _print_device_code_instructions,
  40. _print_login_success, _print_loopback_ssh_hint, _prompt_yes_no, _request_device_code,
  41. _resolve_verify, _ssh_user_at_host)
  42. from hermes_cli.auth_oauth_grants import (
  43. SINGLE_USE_REFRESH_POOL_PROVIDERS, _oauth_heal_clean_marks, _oauth_heal_notices,
  44. consume_oauth_heal_notices, heal_forked_single_use_oauth_grants,
  45. strip_cloned_single_use_oauth_grants)
  46. from hermes_cli.auth_nous import (
  47. NOUS_SESSION_TERMINAL, NOUS_SESSION_UNKNOWN, NOUS_SESSION_VALID, _ALLOWED_NOUS_INFERENCE_HOSTS,
  48. _agent_key_is_usable, _apply_nous_refreshed_tokens, _assert_nous_inference_jwt_usable,
  49. _compute_nous_auth_status, _format_nous_entitlement_auth_error, _healed_nous_inference_url,
  50. _login_nous, _merge_shared_nous_oauth_state, _migrate_stale_nous_portal_url,
  51. _nous_device_code_login, _nous_inference_env_override, _nous_invoke_jwt_is_usable,
  52. _nous_invoke_jwt_status, _nous_portal_base_url, _nous_portal_env_override, _nous_shared_store_lock,
  53. _nous_shared_store_path, _pool_first_oauth_status, _quarantine_nous_oauth_state,
  54. _quarantine_nous_pool_entries, _read_shared_nous_state, _refresh_access_token,
  55. _refresh_nous_or_quarantine, _select_nous_invoke_jwt, _sync_nous_pool_from_auth_store,
  56. _token_fingerprint, _try_import_shared_nous_state, _validate_nous_inference_url_from_network,
  57. _write_shared_nous_state, fetch_nous_models, get_nous_auth_status_local,
  58. get_nous_session_validity, persist_nous_credentials, refresh_nous_oauth_from_state,
  59. resolve_nous_runtime_credentials, step_up_nous_billing_scope)
  60. from hermes_cli.auth_minimax import (
  61. _MINIMAX_OAUTH_ERROR_BODY_LIMIT, _login_minimax_oauth, _minimax_oauth_login, _minimax_pkce_pair,
  62. _minimax_poll_token, _minimax_post_form, _minimax_request_user_code,
  63. _minimax_resolve_token_expiry_unix, _minimax_response_error_text, _minimax_save_auth_state,
  64. _refresh_minimax_oauth_state, build_minimax_oauth_token_provider,
  65. resolve_minimax_oauth_runtime_credentials)
  66. from hermes_cli.auth_xai import (
  67. _login_xai_oauth, _read_xai_oauth_tokens, _refresh_xai_oauth_tokens, _save_xai_oauth_tokens,
  68. _write_through_xai_oauth_to_global_root, _xai_access_token_is_expiring,
  69. _xai_oauth_device_code_login, _xai_oauth_discovery, _xai_oauth_poll_device_token,
  70. _xai_oauth_request_device_code, _xai_proactive_refresh_skew_seconds,
  71. _xai_validate_inference_base_url, refresh_xai_oauth_pure, resolve_xai_oauth_runtime_credentials)
  72. from hermes_cli.auth_codex import (
  73. _codex_access_token_is_expiring, _codex_device_code_login, _codex_http_client,
  74. _codex_pool_rate_limit_status, _codex_quota_probe_cache, _codex_usage_probe_url,
  75. _import_codex_cli_tokens, _is_codex_rate_limit_shaped, _login_openai_codex,
  76. _probe_codex_quota_restored, _read_codex_tokens, _refresh_codex_auth_tokens,
  77. _refresh_expired_codex_probe_token, _save_codex_tokens, clear_codex_pool_quota_cooldowns,
  78. refresh_codex_oauth_pure, resolve_codex_runtime_credentials)
  79. from hermes_cli.auth_openrouter import _openrouter_pkce_login
  80. from hermes_cli.guest_handoff import note_store_write
  81. from hermes_cli.auth_qwen import (
  82. _qwen_access_token_is_expiring, _qwen_base_url, _qwen_cli_auth_path, _read_qwen_cli_tokens,
  83. _refresh_qwen_cli_tokens, _save_qwen_cli_tokens, get_qwen_auth_status,
  84. resolve_qwen_runtime_credentials)
  85. from hermes_cli.auth_constants import (
  86. _decode_jwt_claims, AUTH_STORE_VERSION, AUTH_LOCK_TIMEOUT_SECONDS, DEFAULT_NOUS_PORTAL_URL,
  87. DEFAULT_NOUS_INFERENCE_URL, DEFAULT_NOUS_CLIENT_ID, NOUS_BILLING_MANAGE_SCOPE,
  88. DEFAULT_NOUS_SCOPE, NOUS_DEVICE_CODE_SOURCE, NOUS_AUTH_PATH_INVOKE_JWT,
  89. ACCESS_TOKEN_REFRESH_SKEW_SECONDS, NOUS_INVOKE_JWT_MIN_TTL_SECONDS, DEFAULT_CODEX_BASE_URL,
  90. DEFAULT_XAI_OAUTH_BASE_URL, MINIMAX_OAUTH_CLIENT_ID, MINIMAX_OAUTH_SCOPE,
  91. MINIMAX_OAUTH_GLOBAL_BASE, MINIMAX_OAUTH_CN_BASE, MINIMAX_OAUTH_GLOBAL_INFERENCE,
  92. MINIMAX_OAUTH_CN_INFERENCE, MINIMAX_OAUTH_REFRESH_SKEW_SECONDS, DEFAULT_QWEN_BASE_URL,
  93. DEFAULT_OLLAMA_CLOUD_BASE_URL, DEFAULT_ACTUAL_BASE_URL, DEFAULT_ACTUAL_LOCAL_BASE_URL, STEPFUN_STEP_PLAN_INTL_BASE_URL,
  94. STEPFUN_STEP_PLAN_CN_BASE_URL, CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL,
  95. CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, XAI_OAUTH_CLIENT_ID, XAI_OAUTH_SCOPE,
  96. XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS,
  97. LMSTUDIO_NOAUTH_PLACEHOLDER,
  98. ACTUAL_LOCAL_NOAUTH_PLACEHOLDER, CODEX_RATE_LIMITED_CODE, AuthError, _nous_err, httpx)
  99. logger = logging.getLogger(__name__)
  100. try:
  101. import fcntl
  102. except Exception:
  103. fcntl = None
  104. try:
  105. import msvcrt
  106. except Exception:
  107. msvcrt = None
  108. def is_actual_local_base_url(base_url: str) -> bool:
  109. """Return True for Actual's loopback local API endpoint."""
  110. try:
  111. host = (urlparse(base_url or "").hostname or "").lower().rstrip(".")
  112. except Exception:
  113. return False
  114. return host in {"localhost", "127.0.0.1", "::1", "0.0.0.0"}
  115. def normalize_actual_base_url(base_url: str) -> str:
  116. """Return Actual's OpenAI-compatible base URL (hosted api.actual.inc or the loopback local server;
  117. both expose a /v1 surface for the selected OpenAI-compatible transport)."""
  118. url = str(base_url or "").strip().rstrip("/")
  119. if not url:
  120. return DEFAULT_ACTUAL_BASE_URL
  121. try:
  122. parsed = urlparse(url)
  123. host = (parsed.hostname or "").lower().rstrip(".")
  124. path = parsed.path.rstrip("/")
  125. except Exception:
  126. return url
  127. if path in {"", "/"} and (host == "api.actual.inc" or is_actual_local_base_url(url)):
  128. return url + "/v1"
  129. return url
  130. # ── Provider Registry ───────────────────────────────────────────────────────────────────────────────
  131. @dataclass
  132. class ProviderConfig:
  133. """Describes a known inference provider."""
  134. id: str
  135. name: str
  136. auth_type: str # "oauth_device_code", "oauth_external", "oauth_minimax", "api_key", ...
  137. portal_base_url: str = ""
  138. inference_base_url: str = ""
  139. client_id: str = ""
  140. scope: str = ""
  141. extra: dict[str, Any] = field(default_factory=dict)
  142. api_key_env_vars: tuple = () # API-key providers: env vars to check, in priority order
  143. base_url_env_var: str = "" # optional env var overriding the base URL
  144. def _api_key_provider(
  145. id: str, name: str, inference_base_url: str, api_key_env_vars: tuple,
  146. base_url_env_var: str = "", auth_type: str = "api_key") -> ProviderConfig:
  147. """Compact constructor for the common env-var-keyed provider shape."""
  148. return ProviderConfig(
  149. id=id, name=name, auth_type=auth_type, inference_base_url=inference_base_url,
  150. api_key_env_vars=api_key_env_vars, base_url_env_var=base_url_env_var)
  151. # Registry rows in priority order (resolve_provider() scans api_key rows in this order). A tuple
  152. # row is ``_api_key_provider(id, name, inference_base_url, api_key_env_vars[, base_url_env_var
  153. # [, auth_type]])``; OAuth / bespoke rows are full ``ProviderConfig`` objects.
  154. _REGISTRY_ROWS: tuple[Any, ...] = (
  155. ProviderConfig(
  156. "nous", "Nous Portal", "oauth_device_code", portal_base_url=DEFAULT_NOUS_PORTAL_URL,
  157. inference_base_url=DEFAULT_NOUS_INFERENCE_URL, client_id=DEFAULT_NOUS_CLIENT_ID,
  158. scope=DEFAULT_NOUS_SCOPE),
  159. ProviderConfig("openai-codex", "OpenAI Codex", "oauth_external", inference_base_url=DEFAULT_CODEX_BASE_URL),
  160. ("openai-api", "OpenAI API", "https://api.openai.com/v1", ("OPENAI_API_KEY",), "OPENAI_BASE_URL"),
  161. ProviderConfig(
  162. "xai-oauth", "xAI Grok OAuth (SuperGrok / Premium+)", "oauth_external",
  163. inference_base_url=DEFAULT_XAI_OAUTH_BASE_URL),
  164. ProviderConfig("qwen-oauth", "Qwen OAuth", "oauth_external", inference_base_url=DEFAULT_QWEN_BASE_URL),
  165. ("lmstudio", "LM Studio", "http://127.0.0.1:1234/v1", ("LM_API_KEY",), "LM_BASE_URL"),
  166. ("gemini", "Google AI Studio", "https://generativelanguage.googleapis.com/v1beta",
  167. ("GOOGLE_API_KEY", "GEMINI_API_KEY"), "GEMINI_BASE_URL"),
  168. ("zai", "Z.AI / GLM", "https://api.z.ai/api/paas/v4",
  169. ("GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"), "GLM_BASE_URL"),
  170. # Legacy platform.moonshot.ai keys use this endpoint (OpenAI-compat); sk-kimi- (Kimi Code)
  171. # keys are auto-redirected to api.kimi.com/coding by _resolve_kimi_base_url().
  172. ("kimi-coding", "Kimi / Moonshot", "https://api.moonshot.ai/v1",
  173. ("KIMI_API_KEY", "KIMI_CODING_API_KEY"), "KIMI_BASE_URL"),
  174. ("kimi-coding-cn", "Kimi / Moonshot (China)", "https://api.moonshot.cn/v1", ("KIMI_CN_API_KEY",)),
  175. ("stepfun", "StepFun Step Plan", STEPFUN_STEP_PLAN_INTL_BASE_URL, ("STEPFUN_API_KEY",), "STEPFUN_BASE_URL"),
  176. ("arcee", "Arcee AI", "https://api.arcee.ai/api/v1", ("ARCEEAI_API_KEY",), "ARCEE_BASE_URL"),
  177. ("gmi", "GMI Cloud", "https://api.gmi-serving.com/v1", ("GMI_API_KEY",), "GMI_BASE_URL"),
  178. ("actual", "Actual Computer", DEFAULT_ACTUAL_BASE_URL, ("ACTUAL_API_KEY",), "ACTUAL_BASE_URL"),
  179. ("minimax", "MiniMax", "https://api.minimax.io/anthropic", ("MINIMAX_API_KEY",), "MINIMAX_BASE_URL"),
  180. ProviderConfig(
  181. "minimax-oauth", "MiniMax (OAuth \u00b7 minimax.io)", "oauth_minimax",
  182. portal_base_url=MINIMAX_OAUTH_GLOBAL_BASE, inference_base_url=MINIMAX_OAUTH_GLOBAL_INFERENCE,
  183. client_id=MINIMAX_OAUTH_CLIENT_ID, scope=MINIMAX_OAUTH_SCOPE,
  184. extra={"region": "global", "cn_portal_base_url": MINIMAX_OAUTH_CN_BASE,
  185. "cn_inference_base_url": MINIMAX_OAUTH_CN_INFERENCE}),
  186. # CLAUDE_CODE_OAUTH_TOKEN is NOT an API key despite auth_type="api_key": `claude setup-token`
  187. # yields an `sk-ant-oat01…` OAuth token (401s as x-api-key, 429s as bare Bearer). It stays in
  188. # this tuple because the tuple doubles as the credential-DISCOVERY list
  189. # (agent/credential_pool.py builds its env scan from it); the adapter routes it down the OAuth
  190. # path by prefix. Only ANTHROPIC_API_KEY and ANTHROPIC_TOKEN are usable as literal API keys.
  191. ("anthropic", "Anthropic", "https://api.anthropic.com",
  192. ("ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"), "ANTHROPIC_BASE_URL"),
  193. ("alibaba", "Qwen Cloud", "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
  194. ("DASHSCOPE_API_KEY",), "DASHSCOPE_BASE_URL"),
  195. ("alibaba-coding-plan", "Alibaba Cloud (Coding Plan)", "https://coding-intl.dashscope.aliyuncs.com/v1",
  196. ("ALIBABA_CODING_PLAN_API_KEY", "DASHSCOPE_API_KEY"), "ALIBABA_CODING_PLAN_BASE_URL"),
  197. ("minimax-cn", "MiniMax (China)", "https://api.minimaxi.com/anthropic", ("MINIMAX_CN_API_KEY",),
  198. "MINIMAX_CN_BASE_URL"),
  199. ("deepseek", "DeepSeek", "https://api.deepseek.com/v1", ("DEEPSEEK_API_KEY",), "DEEPSEEK_BASE_URL"),
  200. ("xai", "xAI", "https://api.x.ai/v1", ("XAI_API_KEY",), "XAI_BASE_URL"),
  201. ("nvidia", "NVIDIA NIM", "https://integrate.api.nvidia.com/v1", ("NVIDIA_API_KEY",), "NVIDIA_BASE_URL"),
  202. ("ai-gateway", "Vercel AI Gateway", "https://ai-gateway.vercel.sh/v1", ("AI_GATEWAY_API_KEY",),
  203. "AI_GATEWAY_BASE_URL"),
  204. ("opencode-zen", "OpenCode Zen", "https://opencode.ai/zen/v1", ("OPENCODE_ZEN_API_KEY",),
  205. "OPENCODE_ZEN_BASE_URL"),
  206. # OpenCode Go mixes API surfaces by model (GLM/Kimi: OpenAI chat under /v1; MiniMax and
  207. # Qwen 3.7: Anthropic Messages under /v1/messages). Keep the base at /v1; api_mode is per-model.
  208. ("opencode-go", "OpenCode Go", "https://opencode.ai/zen/go/v1", ("OPENCODE_GO_API_KEY",),
  209. "OPENCODE_GO_BASE_URL"),
  210. ("kilocode", "Kilo Code", "https://api.kilo.ai/api/gateway", ("KILOCODE_API_KEY",), "KILOCODE_BASE_URL"),
  211. ("huggingface", "Hugging Face", "https://router.huggingface.co/v1", ("HF_TOKEN",), "HF_BASE_URL"),
  212. ("xiaomi", "Xiaomi MiMo", "https://api.xiaomimimo.com/v1", ("XIAOMI_API_KEY",), "XIAOMI_BASE_URL"),
  213. ("tencent-tokenhub", "Tencent TokenHub", "https://tokenhub.tencentmaas.com/v1", ("TOKENHUB_API_KEY",),
  214. "TOKENHUB_BASE_URL"),
  215. ("tencent-tokenplan", "Tencent TokenPlan", "https://api.lkeap.cloud.tencent.com/plan/anthropic",
  216. ("TOKENPLAN_API_KEY",), "TOKENPLAN_BASE_URL"),
  217. ("ollama-cloud", "Ollama Cloud", DEFAULT_OLLAMA_CLOUD_BASE_URL, ("OLLAMA_API_KEY",), "OLLAMA_BASE_URL"),
  218. ("bedrock", "AWS Bedrock", "https://bedrock-runtime.us-east-1.amazonaws.com", (), "BEDROCK_BASE_URL",
  219. "aws_sdk"),
  220. # No static inference_base_url: Vertex's endpoint is computed per request from project_id +
  221. # region (agent/vertex_adapter.py build_vertex_base_url), not a fixed host.
  222. ("vertex", "Google Vertex AI", "", (), "", "vertex"),
  223. ("azure-foundry", "Azure Foundry", "", ("AZURE_FOUNDRY_API_KEY",), "AZURE_FOUNDRY_BASE_URL"))
  224. from hermes_cli.auth_plugin_providers import HomeScopedRegistry # mirrored rows are read per home
  225. PROVIDER_REGISTRY: dict[str, ProviderConfig] = HomeScopedRegistry(
  226. (p.id, p) for p in (r if isinstance(r, ProviderConfig) else _api_key_provider(*r) for r in _REGISTRY_ROWS))
  227. # The rows above, before any plugin touches the dict (a user plugin may override these; #48450).
  228. BUILTIN_PROVIDER_IDS = frozenset(dict.keys(PROVIDER_REGISTRY))
  229. # ``hermes_cli.config`` discovers model-provider plugins while importing, and a plugin may read this
  230. # module's registry during that discovery. Keep the import below ProviderConfig / PROVIDER_REGISTRY so
  231. # a plugin never observes a partially initialized auth module (CONTRACT: during discovery a plugin may
  232. # rely only on ``ProviderConfig`` and ``PROVIDER_REGISTRY`` from here — nothing defined below).
  233. from hermes_cli.config import (
  234. atomic_config_replace, config_exists, get_hermes_home, get_config_path, read_raw_config, require_readable_config_before_write)
  235. # Plugin profiles (plugins/model-providers/<name>/) are mirrored into PROVIDER_REGISTRY with the
  236. # auth_type they declare; the mirror lives in the sibling so it can be re-run after discovery.
  237. from hermes_cli.auth_plugin_providers import (
  238. canonical_registry_rows as _canonical_registry_rows, get_plugin_oauth_auth_status,
  239. registry_lookup as _registry_lookup, sync_plugin_provider_registry)
  240. PROVIDER_REGISTRY.sync_before_first_read() # not at import: listing providers reads config
  241. def get_anthropic_key() -> str:
  242. """First usable Anthropic credential (``.env`` preferred over a stale shell export), or ``""``.
  243. Order mirrors ``PROVIDER_REGISTRY["anthropic"].api_key_env_vars``.
  244. Checks both the ``.env`` file and the process environment, preferring ``~/.hermes/.env`` so a deliberate
  245. key rotation isn't shadowed by a stale shell export (matches the api-key resolution path — see #20591).
  246. """
  247. from hermes_cli.config import get_env_value_prefer_dotenv
  248. env_vars = PROVIDER_REGISTRY["anthropic"].api_key_env_vars
  249. return next((v for v in (get_env_value_prefer_dotenv(var) or "" for var in env_vars) if v), "")
  250. # ── Secret validation ───────────────────────────────────────────────────────────────────────────────
  251. _PLACEHOLDER_SECRET_VALUES = {
  252. "*", "**", "***", "changeme", "your_api_key", "your_api_key_here", "your-api-key",
  253. "placeholder", "example", "dummy", "null", "none"}
  254. # The two placeholder shapes this repo ships itself, in ``.env.example`` (four providers) and in
  255. # the quickstart / MCP / skill references (``ghp_xxx``, ``hf_xxx``, ``sk-xxxxxxxx``). Both are
  256. # copied verbatim by users, so both must read as "not configured" rather than as a credential.
  257. _PLACEHOLDER_KEY_PREFIXES = ("sk-", "ghp_", "hf_")
  258. def _is_placeholder_shape(value: str) -> bool:
  259. """True for the placeholder shapes shipped in .env.example and the docs."""
  260. lowered = value.lower()
  261. if lowered.startswith("your_") and lowered.endswith("_here"):
  262. return True
  263. for prefix in _PLACEHOLDER_KEY_PREFIXES:
  264. if lowered.startswith(prefix):
  265. tail = lowered[len(prefix):]
  266. if tail and all(c == "x" for c in tail):
  267. return True
  268. stripped = lowered.replace(" ", "").replace("-", "").replace("_", "")
  269. return bool(stripped) and all(c == "x" for c in stripped)
  270. def has_usable_secret(value: Any, *, min_length: int = 4) -> bool:
  271. """Return True when a configured secret looks usable, not empty/placeholder."""
  272. if not isinstance(value, str):
  273. return False
  274. cleaned = value.strip()
  275. return (len(cleaned) >= min_length
  276. and cleaned.lower() not in _PLACEHOLDER_SECRET_VALUES
  277. and not _is_placeholder_shape(cleaned))
  278. # Known API-key prefixes per provider. Only listed providers get prefix validation; everyone else
  279. # is fail-open. Keeps an obviously malformed key in .env (truncated paste, wrong provider's key)
  280. # from silently shadowing a valid credential-pool entry and producing opaque 401s.
  281. # See #93593.
  282. KNOWN_PROVIDER_KEY_PREFIXES: dict[str, tuple] = {
  283. "openrouter": ("sk-or-",), # all OpenRouter keys are sk-or-... (currently sk-or-v1-)
  284. }
  285. def _matches_key_prefix(provider_id: str, val: str) -> bool:
  286. """True when *val* starts with one of *provider_id*'s declared key prefixes (False when the
  287. provider declares none)."""
  288. return val.startswith(KNOWN_PROVIDER_KEY_PREFIXES.get(provider_id, ()))
  289. def looks_like_openrouter_key(value: Any) -> bool:
  290. """True when *value* carries an OpenRouter key prefix. OPENAI_API_KEY is a legacy home for an
  291. OpenRouter key, so only a value shaped like one may be read as an OpenRouter credential: a real
  292. OpenAI key must never be auto-routed to, or sent to, openrouter.ai."""
  293. return _matches_key_prefix("openrouter", str(value or "").strip())
  294. def _usable_declared_secret(provider_id: str, value: Any, source: str) -> Optional[str]:
  295. """*value* stripped when it is a usable, prefix-valid secret; None (after warning on a provable
  296. prefix mismatch, so it never shadows a later credential source) otherwise. Providers without a
  297. declared prefix are fail-open."""
  298. val = str(value or "").strip()
  299. if not has_usable_secret(val):
  300. return None
  301. prefixes = KNOWN_PROVIDER_KEY_PREFIXES.get(provider_id)
  302. if prefixes and not _matches_key_prefix(provider_id, val):
  303. logger.warning(
  304. "Ignoring %s for provider %r: value does not match the expected key "
  305. "prefix (%s). Falling back to the next credential source. Fix or "
  306. "remove the malformed key to silence this warning.",
  307. source, provider_id, " or ".join(prefixes))
  308. return None
  309. return val
  310. def _model_level_key_env(provider_id: str) -> str:
  311. """``model.key_env`` when config.yaml's main model targets *provider_id*, else ``""``.
  312. The Desktop settings UI saves registry-provider keys as a credential pointer
  313. (``model.key_env`` → ``$HERMES_HOME/.env``) instead of the registry's canonical env var,
  314. so credential resolution must consult it (#106336).
  315. """
  316. try:
  317. from hermes_cli.config import load_config
  318. model_cfg = (load_config() or {}).get("model")
  319. except Exception:
  320. return ""
  321. if not isinstance(model_cfg, dict):
  322. return ""
  323. if str(model_cfg.get("provider") or "").strip().lower() != provider_id:
  324. return ""
  325. return str(model_cfg.get("key_env") or model_cfg.get("api_key_env") or "").strip()
  326. def _resolve_api_key_provider_secret(provider_id: str, pconfig: ProviderConfig) -> tuple[str, str]:
  327. """Resolve an API-key provider's token and indicate where it came from."""
  328. profile = _credential_profile(provider_id)
  329. owned = profile.resolve_api_key_secret() if profile else None
  330. if owned is not None: # provider-owned resolution (token validation / exchange) is final
  331. return owned
  332. # Prefer ~/.hermes/.env over os.environ so a deliberate key rotation in .env isn't shadowed by
  333. # a stale shell export inherited from a parent process (Codex CLI, test runners, etc.).
  334. from hermes_cli.config import get_env_value_prefer_dotenv
  335. # Desktop-saved credential pointer: the settings UI persists registry-provider keys as
  336. # model.key_env → $HERMES_HOME/.env (e.g. HERMES_CUSTOM_LMSTUDIO_API_KEY) while keeping
  337. # model.provider on the registry id, so the pointer must be honored here or the UI-saved
  338. # key is silently ignored and lmstudio falls through to its no-auth placeholder (#106336).
  339. key_env = _model_level_key_env(provider_id)
  340. if key_env:
  341. val = _usable_declared_secret(provider_id, get_env_value_prefer_dotenv(key_env), key_env)
  342. if val:
  343. return val, key_env
  344. for env_var in pconfig.api_key_env_vars:
  345. val = _usable_declared_secret(provider_id, get_env_value_prefer_dotenv(env_var), env_var)
  346. if val:
  347. # A provably malformed key (declared prefix mismatch) must not shadow a valid credential-pool
  348. # entry (#93593). Warn and keep looking instead of returning it.
  349. return val, env_var
  350. # Fallback: credential pool (e.g. zai key stored via auth.json). Prefer the pool's own
  351. # selection (peek) but try the rest too so one malformed entry doesn't block a valid one.
  352. pool_source = f"credential_pool:{provider_id}"
  353. try:
  354. from agent.credential_pool import load_pool
  355. pool = load_pool(provider_id)
  356. if pool and pool.has_credentials():
  357. entry = pool.peek()
  358. candidates = [entry] if entry is not None else []
  359. try:
  360. for extra in pool.entries():
  361. if extra is not None and all(extra is not c for c in candidates):
  362. candidates.append(extra)
  363. except Exception:
  364. pass
  365. for entry in candidates:
  366. key = getattr(entry, "access_token", "") or getattr(entry, "runtime_api_key", "")
  367. val = _usable_declared_secret(provider_id, key, pool_source)
  368. if val:
  369. return val, pool_source
  370. except Exception:
  371. pass
  372. return "", ""
  373. # ── Error formatting (AuthError itself lives in auth_constants) ─────────────────────────────────────
  374. def is_rate_limited_auth_error(error: Exception) -> bool:
  375. """True when an :class:`AuthError` is upstream rate-limiting / quota: transient, and
  376. re-authenticating cannot fix it, so callers should say "retry later", not ``hermes auth``."""
  377. return (isinstance(error, AuthError) and not error.relogin_required
  378. and error.code == CODEX_RATE_LIMITED_CODE)
  379. def primary_failure_wording(error: Exception) -> tuple[str, str]:
  380. """``(log_phrase, user_phrase)`` for a primary-provider failure that triggers the fallback
  381. chain. A 429/quota AuthError leaves the credentials valid; labelling it "auth failed" sends
  382. operators hunting for an expired token (#117482), so it reads as quota at every surface."""
  383. if is_rate_limited_auth_error(error):
  384. return "rate-limited (429)", "Primary provider quota exhausted"
  385. return "auth failed", "Primary auth failed"
  386. # Entitlement failures: Nous gets a Portal-aware message; other providers a fixed generic one (or
  387. # the raw error when no generic text exists for the code).
  388. _GENERIC_ENTITLEMENT_MESSAGES = {
  389. "subscription_required": "No active paid subscription found. Please purchase/activate a subscription, then retry.",
  390. "insufficient_credits": "Subscription credits are exhausted. Top up/renew credits, then retry."}
  391. _ENTITLEMENT_ERROR_CODES = frozenset(_GENERIC_ENTITLEMENT_MESSAGES) | {
  392. "subscription_expired", "no_usable_credits", "account_missing", "member_spend_cap_exceeded"}
  393. def format_auth_error(error: Exception) -> str:
  394. """Map auth failures to concise user-facing guidance."""
  395. if not isinstance(error, AuthError) or is_rate_limited_auth_error(error):
  396. # Rate-limit / quota errors are not credential problems: never append "re-authenticate".
  397. return str(error)
  398. if error.relogin_required:
  399. # Profile-aware: a bare `hermes model` from a named profile re-signs the ROOT store (#114012).
  400. from hermes_constants import profile_cli_selector
  401. return f"{error} Run `hermes {profile_cli_selector()}model` to re-authenticate."
  402. if error.code in _ENTITLEMENT_ERROR_CODES:
  403. if error.provider == "nous":
  404. return _format_nous_entitlement_auth_error(error)
  405. generic = _GENERIC_ENTITLEMENT_MESSAGES.get(error.code)
  406. if generic:
  407. return generic
  408. if error.code == "temporarily_unavailable":
  409. return f"{error} Please retry in a few seconds."
  410. return str(error)
  411. def _nonempty_str(value: Any) -> bool:
  412. return isinstance(value, str) and bool(value.strip())
  413. # ── Auth Store — persistence layer for ~/.hermes/auth.json ──────────────────────────────────────────
  414. def _auth_file_path() -> Path:
  415. path = get_hermes_home() / "auth.json"
  416. # Seat belt: under pytest, refuse to touch the real user's auth store (tests that forgot to
  417. # monkeypatch HERMES_HOME or escaped the hermetic conftest). In production: one dict lookup.
  418. if (os.environ.get("PYTEST_CURRENT_TEST")
  419. and _same_path(path, Path.home() / ".hermes" / "auth.json")):
  420. raise RuntimeError(
  421. f"Refusing to touch real user auth store during test run: {path}. "
  422. "Set HERMES_HOME to a tmp_path in your test fixture, or run "
  423. "via scripts/run_tests.sh for hermetic CI-parity env.")
  424. return path
  425. def _global_auth_file_path() -> Optional[Path]:
  426. """Global-root auth.json in profile mode; None when profile and global root are the same dir.
  427. Read-only fallback path, so no pytest seat belt here (it lives on ``_auth_file_path()``)."""
  428. try:
  429. from hermes_constants import get_default_hermes_root
  430. global_root = get_default_hermes_root()
  431. except Exception:
  432. return None
  433. return None if _same_path(get_hermes_home(), global_root) else global_root / "auth.json"
  434. def _load_global_auth_store() -> dict[str, Any]:
  435. """Load the global-root auth store (read-only fallback, mtime-memoised); ``{}`` when absent or
  436. unreadable — a malformed global store must never break profile reads."""
  437. global _global_auth_store_cache
  438. global_path = _global_auth_file_path()
  439. if global_path is None or not global_path.exists():
  440. _global_auth_store_cache = None
  441. return {}
  442. try:
  443. cache_key: Optional[tuple[str, tuple[Any, ...]]] = (
  444. str(global_path.resolve(strict=False)), file_cache_version(global_path))
  445. except Exception:
  446. cache_key = None
  447. cached = _global_auth_store_cache
  448. if cache_key is not None and cached is not None and cached[:2] == cache_key:
  449. return cached[2]
  450. if os.environ.get("PYTEST_CURRENT_TEST") and os.environ.get("HOME"):
  451. real_root = Path(os.environ["HOME"]) / ".hermes" / "auth.json"
  452. try:
  453. if os.path.normcase(os.path.abspath(global_path)) == os.path.normcase(os.path.abspath(real_root)):
  454. _global_auth_store_cache = None
  455. return {}
  456. except Exception:
  457. pass
  458. try:
  459. store = _load_auth_store(global_path)
  460. except Exception:
  461. _global_auth_store_cache = None
  462. return {}
  463. if cache_key is not None:
  464. _global_auth_store_cache = (*cache_key, store)
  465. return store
  466. _auth_target_lock_holders: dict[str, threading.local] = {}
  467. _auth_target_lock_holders_guard = threading.Lock()
  468. def _same_path(left: Path, right: Path) -> bool:
  469. try:
  470. return left.resolve(strict=False) == right.resolve(strict=False)
  471. except Exception:
  472. return left == right
  473. def _is_same_auth_store(left: Path, right: Path) -> bool:
  474. """True when two auth paths name ONE store rather than two copies.
  475. ``_same_path`` resolves symlinks and ``..``; ``samefile`` adds hardlinks and bind-mounts
  476. (same inode under two resolved names). Used by the forked-grant heal: a shared store has
  477. no "other side" to consolidate.
  478. See #101356.
  479. """
  480. if _same_path(left, right):
  481. return True
  482. try:
  483. return left.samefile(right)
  484. except OSError:
  485. return False
  486. def _resolved_key(path: Path) -> str:
  487. """Canonical string for *path* (resolved when possible) used as a cache / lock-holder key."""
  488. try:
  489. return str(path.resolve(strict=False))
  490. except Exception:
  491. return str(path)
  492. def _auth_lock_holder_for(target_path: Path) -> threading.local:
  493. """Return a reentrancy tracker keyed to one canonical auth-store path."""
  494. with _auth_target_lock_holders_guard:
  495. return _auth_target_lock_holders.setdefault(_resolved_key(target_path), threading.local())
  496. def _kernel_lock(lock_file: Any, acquire: bool) -> None:
  497. """Non-blocking exclusive flock (fcntl) or 1-byte msvcrt lock at offset 0; ``acquire=False`` releases."""
  498. if fcntl:
  499. fcntl.flock(lock_file.fileno(), (fcntl.LOCK_EX | fcntl.LOCK_NB) if acquire else fcntl.LOCK_UN)
  500. else:
  501. lock_file.seek(0)
  502. msvcrt.locking(lock_file.fileno(), msvcrt.LK_NBLCK if acquire else msvcrt.LK_UNLCK, 1)
  503. # Errnos that mean the lock is held rather than broken. POSIX flock contention is a
  504. # ``BlockingIOError`` (EAGAIN); msvcrt reports contention as EACCES — which a real ACL denial
  505. # also uses, so EACCES stays retried rather than aborting every Windows lock. Anything else
  506. # (ENOSYS, EOPNOTSUPP, EIO, ...) cannot clear by retrying and must propagate immediately.
  507. _LOCK_CONTENTION_ERRNOS = frozenset(
  508. code for code in (errno.EACCES, errno.EAGAIN, getattr(errno, "EDEADLK", None)) if code is not None)
  509. def _is_lock_contention(exc: OSError) -> bool:
  510. if isinstance(exc, BlockingIOError):
  511. return True
  512. return exc.errno in _LOCK_CONTENTION_ERRNOS
  513. def _lock_holder_hint(lock_path: Path) -> str:
  514. """Live-holder hint from the pid a holder stamps into the lock file; empty when there is none.
  515. Holders stamp their pid on acquire and clear it on release, so a leftover pid from a dead
  516. process is filtered by a liveness probe — stay silent instead of blaming a ghost."""
  517. try:
  518. first_token = lock_path.read_text(encoding="utf-8-sig", errors="replace").split()[0]
  519. pid = int(first_token)
  520. except (OSError, ValueError, IndexError):
  521. return ""
  522. if pid <= 0 or pid == os.getpid():
  523. return ""
  524. if os.name == "posix":
  525. try:
  526. os.kill(pid, 0) # windows-footgun: ok — inside `if os.name == "posix"` gate
  527. except ProcessLookupError:
  528. return ""
  529. except OSError:
  530. pass # exists but is not signalable (e.g. EPERM): still a live holder
  531. # No example holder: many stores use this lock; the caller's timeout_message names which one.
  532. return f"another hermes process (pid {pid}) probably still holds it"
  533. def _stamp_lock_holder_pid(lock_file: Any) -> None:
  534. """Best-effort pid stamp so a timing-out waiter can name the holder (#124533)."""
  535. try:
  536. lock_file.truncate(0)
  537. lock_file.write(f"{os.getpid()}\n") # "a+" writes land at the (now empty) end
  538. lock_file.flush()
  539. except OSError:
  540. pass
  541. def _clear_stamped_lock_holder_pid(lock_file: Any) -> None:
  542. try:
  543. lock_file.truncate(0)
  544. if msvcrt:
  545. lock_file.write(" ") # msvcrt.locking needs a non-empty file
  546. lock_file.flush()
  547. except OSError:
  548. pass
  549. @contextmanager
  550. def _file_lock(
  551. lock_path: Path, holder: threading.local, timeout_seconds: float, timeout_message: str):
  552. """Cross-process advisory flock helper, reentrant per-thread via ``holder.depth``.
  553. Falls back to a depth-only guard when neither ``fcntl`` nor ``msvcrt`` is available. Callers
  554. supply their own ``threading.local`` so independent locks (profile store vs global root vs the
  555. shared Nous store) track reentrancy separately."""
  556. if getattr(holder, "depth", 0) > 0:
  557. holder.depth += 1
  558. try:
  559. yield
  560. finally:
  561. holder.depth -= 1
  562. return
  563. lock_path.parent.mkdir(parents=True, exist_ok=True)
  564. with ExitStack() as stack:
  565. lock_file = None
  566. if fcntl is not None or msvcrt is not None:
  567. # msvcrt.locking needs a non-empty file with the pointer at 0. This convenience write can
  568. # race another holder's byte-range lock and raise PermissionError (reproduced with 20
  569. # concurrent processes on Windows); losing the race just means the file already has
  570. # content, so swallow it.
  571. if msvcrt and (not lock_path.exists() or lock_path.stat().st_size == 0):
  572. try:
  573. lock_path.write_text(" ", encoding="utf-8")
  574. except (OSError, PermissionError):
  575. pass
  576. lock_file = stack.enter_context(lock_path.open("r+" if msvcrt else "a+", encoding="utf-8"))
  577. deadline = time.monotonic() + max(1.0, timeout_seconds)
  578. while True:
  579. try:
  580. _kernel_lock(lock_file, True)
  581. break
  582. except (BlockingIOError, OSError, PermissionError) as exc:
  583. if not _is_lock_contention(exc):
  584. # Permanent failure (flock-unsupported filesystem, bad fd, ...): retrying
  585. # to the deadline would burn the timeout blaming a holder that does not
  586. # exist. Let the original error through instead.
  587. raise
  588. if time.monotonic() >= deadline:
  589. hint = _lock_holder_hint(lock_path)
  590. raise TimeoutError(f"{timeout_message}; {hint}" if hint else timeout_message)
  591. time.sleep(0.05)
  592. holder.depth = 1
  593. try:
  594. if lock_file is not None:
  595. _stamp_lock_holder_pid(lock_file)
  596. yield
  597. finally:
  598. holder.depth = 0
  599. if lock_file is not None:
  600. _clear_stamped_lock_holder_pid(lock_file)
  601. try:
  602. _kernel_lock(lock_file, False)
  603. except OSError:
  604. pass
  605. @contextmanager
  606. def _auth_store_lock(
  607. timeout_seconds: float = AUTH_LOCK_TIMEOUT_SECONDS, *, target_path: Optional[Path] = None):
  608. """Cross-process advisory lock for one auth.json read/write transaction.
  609. ``target_path`` is required for profile-to-global write-throughs: each path has its own
  610. reentrancy tracker and kernel lock. Lock ordering invariant: ``_auth_store_lock`` FIRST (outer),
  611. ``_nous_shared_store_lock`` SECOND (inner), else deadlock against a concurrent shared import."""
  612. auth_path = target_path if target_path is not None else _auth_file_path()
  613. lock_path = auth_path.with_suffix(".lock")
  614. with _file_lock(
  615. lock_path, _auth_lock_holder_for(auth_path), timeout_seconds,
  616. f"Timed out waiting for auth store lock ({lock_path})"):
  617. yield
  618. def _empty_auth_store() -> dict[str, Any]:
  619. return {"version": AUTH_STORE_VERSION, "providers": {}}
  620. def _load_auth_store(auth_file: Optional[Path] = None) -> dict[str, Any]:
  621. auth_file = auth_file or _auth_file_path()
  622. if not auth_file.exists():
  623. return _empty_auth_store()
  624. try:
  625. raw = json.loads(auth_file.read_text(encoding="utf-8-sig"))
  626. except OSError:
  627. # Exists but unreadable (EMFILE, EACCES, EIO, stalled mount): contents are not bad, and this
  628. # module read-modify-writes everywhere, so an empty store here is one _save_auth_store()
  629. # away from erasing every credential. Fail loudly.
  630. logger.warning(
  631. "auth: could not read %s, leaving the store on disk untouched "
  632. "rather than degrading to an empty one",
  633. auth_file, exc_info=True)
  634. raise
  635. except Exception as exc:
  636. # Genuine corruption: unparseable JSON or non-UTF-8 bytes. Preserve a copy, but never
  637. # advertise a backup that was not written.
  638. corrupt_path = auth_file.with_suffix(".json.corrupt")
  639. try:
  640. shutil.copy2(auth_file, corrupt_path)
  641. preserved = True
  642. except Exception:
  643. preserved = False
  644. logger.debug("auth: could not preserve a copy of the corrupt store at %s", corrupt_path,
  645. exc_info=True)
  646. logger.warning(
  647. "auth: failed to parse %s (%s), starting with empty store. %s %s",
  648. auth_file, exc,
  649. "Corrupt file preserved at" if preserved else "A copy could NOT be preserved at",
  650. corrupt_path)
  651. return _empty_auth_store()
  652. if isinstance(raw, dict) and (
  653. isinstance(raw.get("providers"), dict) or isinstance(raw.get("credential_pool"), dict)):
  654. raw.setdefault("providers", {})
  655. if isinstance(raw.get("providers"), dict):
  656. _migrate_stale_nous_portal_url(raw["providers"])
  657. return raw
  658. if isinstance(raw, dict) and isinstance(raw.get("systems"), dict): # legacy "systems" format
  659. systems = raw["systems"]
  660. providers = {"nous": systems["nous_portal"]} if "nous_portal" in systems else {}
  661. return {**_empty_auth_store(), "providers": providers,
  662. "active_provider": "nous" if providers else None}
  663. return _empty_auth_store()
  664. def _save_private_json(target: Path, data: Any, *, fsync_dir: bool = False, **dump_kwargs: Any) -> None:
  665. """0600 credential JSON under a 0700 parent (``secure_parent_dir`` refuses ``/``, top-level dirs
  666. and the install tree). ``atomic_json_write`` creates the temp file 0600 before any byte lands."""
  667. from hermes_constants import mkdir_under_hermes_home
  668. mkdir_under_hermes_home(target.parent)
  669. secure_parent_dir(target)
  670. atomic_json_write(target, data, mode=0o600, fsync_dir=fsync_dir, **dump_kwargs)
  671. def _save_auth_store(auth_store: dict[str, Any], target_path: Optional[Path] = None) -> Path:
  672. """Atomically persist *auth_store* (0o600, parent tightened to 0o700) to the active store, or to
  673. an explicit *target_path* (e.g. the global-root write-through for rotating xAI OAuth grants)."""
  674. auth_file = target_path if target_path is not None else _auth_file_path()
  675. auth_store["version"] = AUTH_STORE_VERSION
  676. auth_store["updated_at"] = datetime.now(UTC).isoformat()
  677. _save_private_json(auth_file, auth_store, fsync_dir=True)
  678. if target_path is not None:
  679. # A write-through to the global root must not be masked by the mtime memo: on coarse-mtime
  680. # filesystems a read-after-write in the same tick would keep serving the pre-write store.
  681. global _global_auth_store_cache
  682. _global_auth_store_cache = None
  683. return auth_file
  684. def _store_section(auth_store: dict[str, Any], key: str) -> dict[str, Any]:
  685. """Return ``auth_store[key]`` as a dict, replacing a missing/non-dict value in place."""
  686. section = auth_store.get(key)
  687. if not isinstance(section, dict):
  688. section = auth_store[key] = {}
  689. return section
  690. def _provider_state_in(store: dict[str, Any], provider_id: str) -> Optional[dict[str, Any]]:
  691. """Shallow copy of ``store["providers"][provider_id]`` when it is a dict, else None."""
  692. providers = store.get("providers") if store else None
  693. state = providers.get(provider_id) if isinstance(providers, dict) else None
  694. return dict(state) if isinstance(state, dict) else None
  695. def _load_provider_state_with_source(
  696. auth_store: dict[str, Any], provider_id: str,
  697. ) -> tuple[Optional[dict[str, Any]], Optional[Path]]:
  698. """Provider state plus the auth.json path it came from (profile first, then the global root).
  699. Refresh paths that rotate single-use OAuth refresh tokens must write the updated chain back to
  700. the same store they read."""
  701. state = _provider_state_in(auth_store, provider_id)
  702. if state is not None:
  703. return state, _auth_file_path()
  704. global_state = _provider_state_in(_load_global_auth_store(), provider_id)
  705. return (global_state, _global_auth_file_path()) if global_state is not None else (None, None)
  706. def _load_provider_state(auth_store: dict[str, Any], provider_id: str) -> Optional[dict[str, Any]]:
  707. """Provider state; in profile mode falls back to the global-root ``auth.json`` per provider (same
  708. shadowing as ``read_credential_pool``), so profile workers see globally-authed providers."""
  709. return _load_provider_state_with_source(auth_store, provider_id)[0]
  710. @contextmanager
  711. def _provider_state_transaction(
  712. provider_id: str, timeout_seconds: float = AUTH_LOCK_TIMEOUT_SECONDS):
  713. """Lock the active auth store and any global fallback source, in that order.
  714. Re-reading the source after its lock is acquired prevents stale refreshes and whole-file lost
  715. updates without inverting the documented auth -> shared lock order. ``timeout_seconds`` applies
  716. to BOTH locks: a transaction that spans a network call must let waiters outlive that call."""
  717. with _auth_store_lock(timeout_seconds):
  718. auth_store = _load_auth_store()
  719. state, source_path = _load_provider_state_with_source(auth_store, provider_id)
  720. if source_path is None or _same_path(source_path, _auth_file_path()):
  721. yield auth_store, state, source_path
  722. return
  723. with _auth_store_lock(timeout_seconds, target_path=source_path):
  724. yield auth_store, _provider_state_in(_load_auth_store(source_path), provider_id), source_path
  725. def _store_provider_state(auth_store: dict[str, Any], provider_id: str, state: dict[str, Any], *, set_active: bool = True) -> None:
  726. note_store_write(auth_store, provider_id, state)
  727. _store_section(auth_store, "providers")[provider_id] = state
  728. if set_active:
  729. auth_store["active_provider"] = provider_id
  730. def _save_provider_state(auth_store: dict[str, Any], provider_id: str, state: dict[str, Any]) -> None:
  731. """Write *state* under ``providers`` and make *provider_id* the active provider."""
  732. _store_provider_state(auth_store, provider_id, state, set_active=True)
  733. def _save_active_provider_state(provider_id: str, state: dict[str, Any]) -> Path:
  734. """Lock, load, write *state* as the active provider, save. Returns the auth store path."""
  735. with _auth_store_lock():
  736. auth_store = _load_auth_store()
  737. _save_provider_state(auth_store, provider_id, state)
  738. return _save_auth_store(auth_store)
  739. def _persist_provider_state_to_store(
  740. provider_id: str, state: dict[str, Any], target_path: Path, *, set_active: bool = False,
  741. ) -> Path:
  742. """Merge one provider into a specific auth store under that store's lock."""
  743. with _auth_store_lock(target_path=target_path):
  744. auth_store = _load_auth_store(target_path)
  745. _store_provider_state(auth_store, provider_id, dict(state), set_active=set_active)
  746. return _save_auth_store(auth_store, target_path=target_path)
  747. def _save_provider_state_to_source(
  748. auth_store: dict[str, Any], provider_id: str, state: dict[str, Any], source_path: Optional[Path],
  749. ) -> None:
  750. """Persist provider state back to the auth store it was read from.
  751. A token refresh rewrites credentials, not the user's choice of provider: ``active_provider`` is
  752. left as it is (a Nous free-tier identity refreshed for a connector call must not become the
  753. inference provider of an install that has its own key)."""
  754. if source_path is None or _same_path(source_path, _auth_file_path()):
  755. _store_provider_state(auth_store, provider_id, state, set_active=False)
  756. _save_auth_store(auth_store)
  757. else:
  758. _persist_provider_state_to_store(provider_id, state, source_path, set_active=False)
  759. def mark_provider_active_if_unset(provider_id: str) -> None:
  760. """Set ``active_provider`` only when none is set yet: the first ``hermes auth add`` credential must
  761. make its provider active (else setup reports "No inference provider configured"); later adds
  762. leave the user's choice untouched."""
  763. with _auth_store_lock():
  764. auth_store = _load_auth_store()
  765. if not (auth_store.get("active_provider") or "").strip():
  766. auth_store["active_provider"] = provider_id
  767. _save_auth_store(auth_store)
  768. def is_known_auth_provider(provider_id: str) -> bool:
  769. normalized = (provider_id or "").strip().lower()
  770. return _registry_lookup(normalized) is not None
  771. def get_auth_provider_display_name(provider_id: str) -> str:
  772. normalized = (provider_id or "").strip().lower()
  773. if normalized in PROVIDER_REGISTRY:
  774. return PROVIDER_REGISTRY[normalized].name
  775. return provider_id
  776. def is_runtime_provider_routable(provider_id: str) -> bool:
  777. """Whether runtime resolution recognizes a provider identity (a capability check, not a credential
  778. check): ``resolve_provider`` normalization plus the special runtime identities outside the registry."""
  779. normalized = (provider_id or "").strip().lower()
  780. if not normalized:
  781. return False
  782. if normalized in {"auto", "openrouter", "custom", "moa"} or normalized.startswith("custom:"):
  783. return True
  784. try:
  785. resolve_provider(normalized)
  786. except AuthError:
  787. return False
  788. return True
  789. def read_credential_pool(provider_id: Optional[str] = None) -> dict[str, Any]:
  790. """Return the persisted credential pool, or one provider slice.
  791. In profile mode the global-root ``auth.json`` is a read-only fallback applied per provider ONLY
  792. when the profile has zero entries for it (``hermes auth add`` in the profile shadows global)."""
  793. pool = _load_auth_store().get("credential_pool")
  794. pool = pool if isinstance(pool, dict) else {}
  795. global_pool = _load_global_auth_store().get("credential_pool")
  796. global_pool = global_pool if isinstance(global_pool, dict) else {}
  797. if provider_id is None:
  798. merged = dict(pool)
  799. for gp_key, gp_entries in global_pool.items():
  800. existing = merged.get(gp_key)
  801. if not (isinstance(gp_entries, list) and gp_entries):
  802. continue
  803. if not (isinstance(existing, list) and existing): # profile wins when it has ANY entries
  804. merged[gp_key] = list(gp_entries)
  805. return merged
  806. provider_entries = pool.get(provider_id)
  807. if isinstance(provider_entries, list) and provider_entries:
  808. return list(provider_entries)
  809. global_entries = global_pool.get(provider_id)
  810. return list(global_entries) if isinstance(global_entries, list) else []
  811. _POOL_STATUS_FIELDS = (
  812. "last_status", "last_status_at", "last_error_code", "last_error_reason", "last_error_message",
  813. "last_error_reset_at", "status_cleared_at")
  814. _POOL_TOKEN_GENERATION_FIELDS = (
  815. "access_token", "refresh_token", "expires_at", "expires_at_ms", "expires_in", "obtained_at",
  816. "last_refresh", "agent_key", "agent_key_expires_at", "agent_key_expires_in", "agent_key_id",
  817. "agent_key_obtained_at", "agent_key_reused",
  818. # Refresh-coupled metadata: a Nous refresh rewrites scope and the validated
  819. # inference route together with the new pair, so they travel with it.
  820. "scope", "inference_base_url",
  821. )
  822. def _credential_token_pair(row: Any) -> tuple[Any, Any]:
  823. if not isinstance(row, dict):
  824. return (None, None)
  825. return row.get("access_token"), row.get("refresh_token")
  826. def _token_pairs_by_id(rows: Iterable[Any]) -> dict[str, tuple[Any, Any]]:
  827. """Token-generation base per row id, INCLUDING ``(None, None)`` for token-less rows.
  828. A blank base is a known generation ("no pair when we last looked"), so a peer that
  829. later lands a pair on that row is kept by ``_merge_pool_row_generation`` on every
  830. flush alike; dropping blank bases would make the first and later flushes disagree."""
  831. return {row_id: _credential_token_pair(row) for row_id, row in _entry_ids(rows).items()}
  832. def _merge_pool_row_generation(
  833. entry: dict[str, Any],
  834. disk_entry: Optional[dict[str, Any]],
  835. provider_id: str,
  836. *,
  837. base_pair: Optional[tuple[Any, Any]] = None,
  838. status_cleared: bool = False,
  839. ) -> dict[str, Any]:
  840. """Keep a newer on-disk token generation authoritative during stale writes.
  841. Only a terminal auth verdict (``last_status == dead``) is scoped to the token pair
  842. it was observed on; account-wide cooldowns (402 billing, 429 throttle) from the
  843. stale writer still apply to the rotated pair and go through the ordinary recency
  844. merge in ``_merge_disk_cooldown_state``."""
  845. from agent.credential_pool import STATUS_DEAD
  846. merge_disk = None if status_cleared else disk_entry
  847. disk_pair = _credential_token_pair(disk_entry)
  848. if base_pair is None or not any(disk_pair) or disk_pair == base_pair:
  849. return _merge_disk_cooldown_state(entry, merge_disk, provider_id)
  850. merged = dict(entry)
  851. def _take_from_disk(fields: Iterable[str]) -> None:
  852. # Absent-on-disk fields are popped, not set to None: a None would make the
  853. # UPDATE-only root merge see a changed row and force a spurious save.
  854. for field in fields:
  855. if field in disk_entry:
  856. merged[field] = disk_entry[field]
  857. else:
  858. merged.pop(field, None)
  859. _take_from_disk(_POOL_TOKEN_GENERATION_FIELDS)
  860. if not status_cleared and entry.get("last_status") == STATUS_DEAD:
  861. _take_from_disk((*_POOL_STATUS_FIELDS, "failure_reason"))
  862. return _merge_disk_cooldown_state(merged, merge_disk, provider_id)
  863. def _merge_disk_cooldown_state(
  864. entry: dict[str, Any], disk_entry: Optional[dict[str, Any]], provider_id: str,
  865. ) -> dict[str, Any]:
  866. """Keep a newer on-disk cooldown/quarantine over a stale in-memory one.
  867. ``write_credential_pool`` persists an in-memory snapshot that may predate another process
  868. marking the same credential exhausted/dead; without this merge the later rewrite resurrects a
  869. rate-limited key as healthy and both processes resume hammering it. The mirror image is a
  870. ``hermes auth reset`` that postdates the snapshot's cooldown (``status_cleared_at`` newer than
  871. its ``last_status_at``): the disk row wins there too, or a live session's next ordinary flush
  872. would write the reset cooldown straight back (#89415)."""
  873. if not isinstance(disk_entry, dict):
  874. return entry
  875. try:
  876. from agent.credential_pool import (
  877. PooledCredential, STATUS_DEAD, STATUS_EXHAUSTED, _exhausted_until, _parse_absolute_timestamp,
  878. )
  879. # Model cooldowns are independent observations: keep the latest reset per model so a
  880. # writer that just cooled one model cannot erase another process's cooldown for another.
  881. from agent.credential_pool_model_cooldowns import merge_model_cooldowns
  882. merged_cooldowns = merge_model_cooldowns(disk_entry.get("model_cooldowns"), entry.get("model_cooldowns"))
  883. merged = {**entry, "model_cooldowns": merged_cooldowns} if merged_cooldowns else entry
  884. disk_status_fields = {f: disk_entry.get(f) for f in _POOL_STATUS_FIELDS}
  885. mem_ts = _parse_absolute_timestamp(entry.get("last_status_at")) or 0.0
  886. cleared_ts = _parse_absolute_timestamp(disk_entry.get("status_cleared_at")) or 0.0
  887. if entry.get("last_status") in (STATUS_DEAD, STATUS_EXHAUSTED) and cleared_ts > mem_ts:
  888. return {**merged, **disk_status_fields}
  889. disk_status = disk_entry.get("last_status")
  890. if disk_status not in (STATUS_DEAD, STATUS_EXHAUSTED):
  891. return merged
  892. # A token change means the caller re-authed this entry and intentionally cleared its status:
  893. # never resurrect the old cooldown onto fresh credentials.
  894. mem_access = entry.get("access_token") or ""
  895. disk_access = disk_entry.get("access_token") or ""
  896. if mem_access and disk_access and mem_access != disk_access:
  897. return entry
  898. disk_ts = _parse_absolute_timestamp(disk_entry.get("last_status_at")) or 0.0
  899. if disk_ts <= mem_ts:
  900. return merged
  901. if disk_status == STATUS_EXHAUSTED:
  902. until = _exhausted_until(PooledCredential.from_dict(provider_id, disk_entry))
  903. if until is None or until <= time.time():
  904. return merged
  905. return {**merged, **disk_status_fields}
  906. except Exception: # pragma: no cover - best-effort merge
  907. return entry
  908. def _entry_ids(entries: Iterable[Any]) -> dict[str, dict[str, Any]]:
  909. return {e.get("id"): e for e in entries if isinstance(e, dict) and e.get("id")}
  910. def write_credential_pool(
  911. provider_id: str, entries: list[dict[str, Any]], *,
  912. removed_ids: Optional[Iterable[str]] = None,
  913. status_cleared_ids: Optional[Iterable[str]] = None,
  914. token_bases: Optional[dict[str, tuple[Any, Any]]] = None,
  915. ) -> list[dict[str, Any]]:
  916. """Persist one provider's credential pool under auth.json.
  917. Final disk-boundary sanitizer for borrowed credentials (callers may pass raw dicts). Entries on
  918. disk but missing from *entries* (added concurrently) are merged back unless in *removed_ids*,
  919. so a rotation/exhaustion rewrite never drops a concurrent credential. Entries in
  920. *status_cleared_ids* were cleared deliberately (``hermes auth reset``) and skip the
  921. recency merge, which would otherwise read their cleared ``last_status_at`` (None ->
  922. epoch 0) as a stale snapshot and copy a still-binding cooldown back."""
  923. removed = {rid for rid in (removed_ids or ()) if rid}
  924. bases = token_bases or {}
  925. with _auth_store_lock():
  926. auth_store = _load_auth_store()
  927. pool = _store_section(auth_store, "credential_pool")
  928. sanitized = [
  929. sanitize_borrowed_credential_payload(e, provider_id) if isinstance(e, dict) else e
  930. for e in entries]
  931. existing_list = pool.get(provider_id)
  932. existing_list = existing_list if isinstance(existing_list, list) else []
  933. existing_by_id = _entry_ids(existing_list)
  934. new_ids = set(_entry_ids(sanitized))
  935. status_cleared = {cid for cid in (status_cleared_ids or ()) if cid}
  936. merged: list[dict[str, Any]] = [
  937. _merge_pool_row_generation(
  938. e, existing_by_id.get(e.get("id")), provider_id,
  939. base_pair=bases.get(e.get("id")),
  940. status_cleared=e.get("id") in status_cleared,
  941. )
  942. if isinstance(e, dict) else e
  943. for e in sanitized]
  944. for disk_entry in existing_list:
  945. disk_id = disk_entry.get("id") if isinstance(disk_entry, dict) else None
  946. if disk_id and disk_id not in new_ids and disk_id not in removed:
  947. merged.append(sanitize_borrowed_credential_payload(disk_entry, provider_id))
  948. pool[provider_id] = merged
  949. _save_auth_store(auth_store)
  950. return merged
  951. def _suppressed_source_list(suppressed: dict[str, Any], provider_id: str) -> Optional[list[str]]:
  952. """Canonical (list-form) suppressed sources for *provider_id*; a legacy mapping (keys = source
  953. names) is migrated to the list form in place."""
  954. raw_sources = suppressed.get(provider_id)
  955. if isinstance(raw_sources, list):
  956. return raw_sources
  957. if isinstance(raw_sources, dict):
  958. suppressed[provider_id] = [str(name) for name in raw_sources]
  959. return suppressed[provider_id]
  960. return None
  961. def suppress_credential_source(provider_id: str, source: str) -> None:
  962. """Mark a credential source as suppressed so it won't be re-seeded."""
  963. with _auth_store_lock():
  964. auth_store = _load_auth_store()
  965. suppressed = _store_section(auth_store, "suppressed_sources")
  966. provider_list = _suppressed_source_list(suppressed, provider_id)
  967. if provider_list is None:
  968. provider_list = suppressed[provider_id] = []
  969. if source not in provider_list:
  970. provider_list.append(source)
  971. _save_auth_store(auth_store)
  972. def is_source_suppressed(provider_id: str, source: str) -> bool:
  973. """Check if a credential source has been suppressed by the user."""
  974. try:
  975. return source in _load_auth_store().get("suppressed_sources", {}).get(provider_id, [])
  976. except Exception:
  977. return False
  978. def suppressed_credential_sources(provider_id: str) -> frozenset[str]:
  979. """Every credential source the user suppressed for *provider_id* (unreadable store = none)."""
  980. try:
  981. section = _load_auth_store().get("suppressed_sources")
  982. except OSError: # unreadable store (logged by the loader): nothing to honour, as before
  983. return frozenset()
  984. listed = section.get(provider_id) if isinstance(section, dict) else None
  985. return frozenset(map(str, listed)) if isinstance(listed, (list, dict)) else frozenset()
  986. def unsuppress_credential_source(provider_id: str, source: str) -> bool:
  987. """Clear a suppression marker so the source will be re-seeded on the next load."""
  988. with _auth_store_lock():
  989. auth_store = _load_auth_store()
  990. suppressed = auth_store.get("suppressed_sources")
  991. if not isinstance(suppressed, dict):
  992. return False
  993. provider_list = _suppressed_source_list(suppressed, provider_id)
  994. if provider_list is None or source not in provider_list:
  995. return False
  996. provider_list.remove(source)
  997. if not provider_list:
  998. suppressed.pop(provider_id, None)
  999. if not suppressed:
  1000. auth_store.pop("suppressed_sources", None)
  1001. _save_auth_store(auth_store)
  1002. return True
  1003. def get_provider_auth_state(provider_id: str) -> Optional[dict[str, Any]]:
  1004. """Persisted auth state for a provider (profile first, global-root fallback), or None."""
  1005. return _load_provider_state(_load_auth_store(), provider_id)
  1006. def nous_token_has_billing_scope() -> bool:
  1007. """Return True if the currently-held Nous token carries ``billing:manage``.
  1008. Reads the persisted ``scope`` string saved at login (``_save_provider_state``
  1009. stores ``token_data.get("scope") or scope``). A space-delimited match. Used by
  1010. the lazy step-up: if False, the first billing call will 403 ``insufficient_scope``
  1011. anyway, but checking up front lets a surface skip a doomed round-trip.
  1012. """
  1013. try:
  1014. state = get_provider_auth_state("nous") or {}
  1015. except Exception:
  1016. return False
  1017. scope = state.get("scope")
  1018. if not isinstance(scope, str):
  1019. return False
  1020. return NOUS_BILLING_MANAGE_SCOPE in scope.split()
  1021. def get_active_provider() -> Optional[str]:
  1022. """Return the currently active provider ID from auth store."""
  1023. return _load_auth_store().get("active_provider")
  1024. def _active_provider_is(normalized: str) -> bool:
  1025. active = (_load_auth_store().get("active_provider") or "").strip().lower()
  1026. return bool(active) and active == normalized
  1027. def _slot_selects(slot: Any, normalized: str) -> bool:
  1028. return isinstance(slot, dict) and (slot.get("provider") or "").strip().lower() == normalized
  1029. def _config_selects_provider(normalized: str) -> bool:
  1030. """config.yaml ``model.provider``, or a MoA advisor/aggregator slot naming the provider.
  1031. MoA presets are explicit model selections too: ``provider: anthropic`` in a MoA slot opts into
  1032. Anthropic credentials for that slot even when the main model is another provider; otherwise
  1033. Claude Code OAuth entries get pruned by ``load_pool("anthropic")`` and MoA advisors fail with
  1034. "no ANTHROPIC_API_KEY" while the picker says Anthropic is logged in."""
  1035. from hermes_cli.config import load_config
  1036. cfg = load_config()
  1037. if _slot_selects(cfg.get("model"), normalized):
  1038. return True
  1039. # ``auxiliary.<task>.provider: <id>`` selects the provider for that task the same way a MoA
  1040. # slot does — without this the seeder treats the credential as merely discovered (#114740).
  1041. aux_cfg = cfg.get("auxiliary")
  1042. if isinstance(aux_cfg, dict) and any(_slot_selects(s, normalized) for s in aux_cfg.values()):
  1043. return True
  1044. def _moa_block_matches(block: Any) -> bool:
  1045. return isinstance(block, dict) and (
  1046. any(_slot_selects(s, normalized) for s in block.get("reference_models") or [])
  1047. or _slot_selects(block.get("aggregator"), normalized))
  1048. moa_cfg = cfg.get("moa")
  1049. if not isinstance(moa_cfg, dict):
  1050. return False
  1051. presets = moa_cfg.get("presets")
  1052. presets = presets.values() if isinstance(presets, dict) else ()
  1053. return _moa_block_matches(moa_cfg) or any(_moa_block_matches(p) for p in presets)
  1054. def _explicit_pool_entry_present(normalized: str) -> bool:
  1055. """Pool rows from EXPLICIT Hermes flows (manual add / device-code / PKCE) or live env keys;
  1056. ambient borrowed sources (gh_cli / claude_code / qwen-cli) are deliberately excluded."""
  1057. return any(_pool_entry_is_explicit(entry) for entry in read_credential_pool(normalized))
  1058. # Set by Claude Code itself, not by the user explicitly configuring anthropic in Hermes.
  1059. _IMPLICIT_ENV_VARS = frozenset({"CLAUDE_CODE_OAUTH_TOKEN"})
  1060. _EXPLICIT_POOL_SOURCES = frozenset({"device_code", "loopback_pkce", "hermes_pkce", "manual"})
  1061. _VERTEX_PROVIDER_IDS = ("vertex", "google-vertex", "vertex-ai", "gcp-vertex", "vertexai")
  1062. def _env_secret(name: str) -> bool:
  1063. """True when *name* resolves to a usable secret in the active profile scope.
  1064. Must not read raw ``os.getenv``: under ``hermes serve`` / Desktop multiplex the
  1065. process environ is the *launch* profile, so a DeepSeek key pasted into another
  1066. profile's ``.env`` would be invisible to ``explicit_only`` Settings → Model
  1067. until a Bot-chat Refresh ran against that profile's own backend.
  1068. Same reader as the credential resolver (``get_env_value_prefer_dotenv``: the current
  1069. HERMES_HOME ``.env`` first, then the scope-checked environ) so the gate and the key that
  1070. actually authenticates never disagree — an empty ``DEEPSEEK_API_KEY=`` export in the parent
  1071. shell must not hide a real key in ``.env`` (#77007).
  1072. """
  1073. from hermes_cli.config import get_env_value_prefer_dotenv
  1074. return has_usable_secret(get_env_value_prefer_dotenv(name) or "")
  1075. def _explicit_env_credentials_present(normalized: str) -> bool:
  1076. """True when the user has pasted an explicit credential env var for *normalized*.
  1077. Falls back to the models.dev ``ProviderDef`` (same shape) for non-registry providers such as
  1078. openrouter. AWS SDK providers are checked via explicit env vars only — NOT boto3's chain, so
  1079. ambient EC2 IMDS / SSO profiles never auto-surface."""
  1080. pconfig = PROVIDER_REGISTRY.get(normalized)
  1081. if pconfig is None:
  1082. from hermes_cli.providers import get_provider
  1083. pconfig = get_provider(normalized)
  1084. if not pconfig:
  1085. return False
  1086. if pconfig.auth_type == "api_key":
  1087. return any(_env_secret(v) for v in pconfig.api_key_env_vars if v not in _IMPLICIT_ENV_VARS)
  1088. if pconfig.auth_type == "aws_sdk":
  1089. return _env_secret("AWS_BEARER_TOKEN_BEDROCK") or (
  1090. _env_secret("AWS_ACCESS_KEY_ID") and _env_secret("AWS_SECRET_ACCESS_KEY"))
  1091. return False
  1092. def _pool_entry_is_explicit(entry: Any) -> bool:
  1093. """True for pool rows the user created via an explicit Hermes flow (or a still-live env key)."""
  1094. if not isinstance(entry, dict):
  1095. return False
  1096. source = str(entry.get("source") or "").strip().lower()
  1097. if source.startswith("env:"):
  1098. # A stale env-seeded entry survives in auth.json after the user deletes the env var: only
  1099. # count it when the referenced var still resolves to a usable secret NOW.
  1100. # See #55790.
  1101. env_var = entry.get("source", "").split(":", 1)[1].strip()
  1102. return bool(env_var and _env_secret(env_var))
  1103. return bool(source) and (source in _EXPLICIT_POOL_SOURCES or source.startswith("manual:"))
  1104. def _keyless_provider_has_explicit_config(normalized: str) -> bool:
  1105. """Vertex / Bedrock count as explicit when Hermes-scoped routing config is present.
  1106. Uses has_explicit_vertex_config(), NOT has_vertex_credentials(): the latter also counts an
  1107. ambient GOOGLE_APPLICATION_CREDENTIALS path (commonly set for unrelated GCP work). Only
  1108. Hermes-scoped signals (VERTEX_PROJECT_ID / vertex.project_id / VERTEX_CREDENTIALS_PATH) count
  1109. here."""
  1110. if normalized in _VERTEX_PROVIDER_IDS:
  1111. from agent.vertex_adapter import has_explicit_vertex_config
  1112. return bool(has_explicit_vertex_config())
  1113. if normalized == "bedrock":
  1114. from hermes_cli.config import load_config
  1115. bedrock_cfg = load_config().get("bedrock")
  1116. return isinstance(bedrock_cfg, dict) and bool(str(bedrock_cfg.get("region") or "").strip())
  1117. return False
  1118. # Ordered explicit-configuration checks: ``(check, best_effort)``. Best-effort checks treat an
  1119. # exception as "no"; the env-var check is NOT best-effort — a failure there must surface rather
  1120. # than let a later, weaker signal decide.
  1121. _EXPLICIT_CONFIG_CHECKS: tuple[tuple[Callable[[str], bool], bool], ...] = (
  1122. (_active_provider_is, True), (_config_selects_provider, True),
  1123. (_explicit_env_credentials_present, False), (_explicit_pool_entry_present, True),
  1124. (_keyless_provider_has_explicit_config, True))
  1125. def is_provider_explicitly_configured(provider_id: str) -> bool:
  1126. """True only if the user explicitly configured this provider: auth.json ``active_provider``,
  1127. config.yaml ``model.provider`` / MoA slots, a pasted provider env var, a pool entry from a
  1128. Hermes-initiated flow, or Hermes-scoped routing config for keyless cloud-SDK providers. Ambient
  1129. borrowed credentials (gh CLI, qwen-cli, ~/.claude/.credentials.json) never count."""
  1130. normalized = (provider_id or "").strip().lower()
  1131. for check, best_effort in _EXPLICIT_CONFIG_CHECKS:
  1132. try:
  1133. if check(normalized):
  1134. return True
  1135. except Exception as exc:
  1136. if not best_effort:
  1137. raise
  1138. logger.debug("explicit-config check %s failed for %s: %s", check.__name__, provider_id, exc)
  1139. return False
  1140. def clear_provider_auth(provider_id: Optional[str] = None) -> bool:
  1141. """Clear auth state for a provider (the active one when *provider_id* is None). Used by
  1142. ``hermes logout``. Returns True if something was cleared."""
  1143. with _auth_store_lock():
  1144. auth_store = _load_auth_store()
  1145. target = provider_id or auth_store.get("active_provider")
  1146. if not target:
  1147. return False
  1148. cleared = False
  1149. for section in ("providers", "credential_pool"):
  1150. entries = _store_section(auth_store, section)
  1151. if target in entries:
  1152. del entries[target]
  1153. cleared = True
  1154. if auth_store.get("active_provider") == target:
  1155. auth_store["active_provider"] = None
  1156. cleared = True
  1157. if cleared:
  1158. _save_auth_store(auth_store)
  1159. return cleared
  1160. def deactivate_provider() -> None:
  1161. """Clear active_provider without deleting credentials: used when the user switches to a non-OAuth
  1162. provider (OpenRouter, custom) so auto-resolution doesn't keep picking the OAuth provider."""
  1163. with _auth_store_lock():
  1164. auth_store = _load_auth_store()
  1165. auth_store["active_provider"] = None
  1166. _save_auth_store(auth_store)
  1167. # ── Provider Resolution — picks which provider to use ───────────────────────────────────────────────
  1168. def _refuse_env_adoption_if_config_corrupt() -> None:
  1169. """Refuse env-key/pool auto-adoption of openrouter while config.yaml is corrupt.
  1170. A corrupt config loads as ``DEFAULT_CONFIG`` (no ``model.provider``), so the env sniff would
  1171. silently adopt the PAID openrouter provider over whatever the broken config really names.
  1172. Fires ONLY on the auto path and clears itself once the file parses again."""
  1173. try:
  1174. from hermes_cli.config_read_errors import get_active_config_parse_failure
  1175. err = get_active_config_parse_failure()
  1176. if not err:
  1177. return
  1178. path = get_config_path()
  1179. except Exception as e:
  1180. logger.debug("Could not probe config parse-failure state: %s", e)
  1181. return
  1182. raise AuthError(
  1183. f"config.yaml at {path} is corrupt ({err}) — refusing to auto-select "
  1184. f"an inference provider from environment keys. Fix the YAML (a backup "
  1185. f"was saved next to it) or run hermes setup.",
  1186. code="corrupt_config")
  1187. # Provider aliases accepted by resolve_provider(). Plugin-declared aliases
  1188. # (plugins/model-providers/<name>/) are layered on at call time; this hardcoded
  1189. # table remains authoritative for existing names.
  1190. _PROVIDER_ALIASES: dict[str, str] = {
  1191. "glm": "zai", "z-ai": "zai", "z.ai": "zai", "zhipu": "zai",
  1192. "google": "gemini", "google-gemini": "gemini", "google-ai-studio": "gemini",
  1193. "x-ai": "xai", "x.ai": "xai", "grok": "xai",
  1194. "xai-oauth": "xai-oauth", "x-ai-oauth": "xai-oauth",
  1195. "grok-oauth": "xai-oauth", "xai-grok-oauth": "xai-oauth",
  1196. "kimi": "kimi-coding", "kimi-for-coding": "kimi-coding", "moonshot": "kimi-coding",
  1197. "kimi-cn": "kimi-coding-cn", "moonshot-cn": "kimi-coding-cn",
  1198. "step": "stepfun", "stepfun-coding-plan": "stepfun",
  1199. "arcee-ai": "arcee", "arceeai": "arcee",
  1200. "gmi-cloud": "gmi", "gmicloud": "gmi",
  1201. "actual-computer": "actual", "actualcomputer": "actual", "aci": "actual",
  1202. "minimax-china": "minimax-cn", "minimax_cn": "minimax-cn",
  1203. "minimax-portal": "minimax-oauth", "minimax-global": "minimax-oauth", "minimax_oauth": "minimax-oauth",
  1204. "alibaba_coding": "alibaba-coding-plan", "alibaba-coding": "alibaba-coding-plan",
  1205. "alibaba_coding_plan": "alibaba-coding-plan",
  1206. "claude": "anthropic", "claude-code": "anthropic",
  1207. "aigateway": "ai-gateway", "vercel": "ai-gateway", "vercel-ai-gateway": "ai-gateway",
  1208. "opencode": "opencode-zen", "zen": "opencode-zen",
  1209. "qwen-portal": "qwen-oauth", "qwen-cli": "qwen-oauth", "qwen-oauth": "qwen-oauth",
  1210. "hf": "huggingface", "hugging-face": "huggingface", "huggingface-hub": "huggingface",
  1211. "mimo": "xiaomi", "xiaomi-mimo": "xiaomi",
  1212. "tencent": "tencent-tokenhub", "tokenhub": "tencent-tokenhub",
  1213. "tencent-cloud": "tencent-tokenhub", "tencentmaas": "tencent-tokenhub",
  1214. "tokenplan": "tencent-tokenplan", "tencent-lkeap": "tencent-tokenplan",
  1215. "aws": "bedrock", "aws-bedrock": "bedrock", "amazon-bedrock": "bedrock", "amazon": "bedrock",
  1216. "go": "opencode-go", "opencode-go-sub": "opencode-go",
  1217. "kilo": "kilocode", "kilo-code": "kilocode", "kilo-gateway": "kilocode",
  1218. "lmstudio": "lmstudio", "lm-studio": "lmstudio", "lm_studio": "lmstudio",
  1219. "chatgpt": "openai-codex", "chatgpt-codex": "openai-codex",
  1220. # Local server aliases — route through the generic custom provider
  1221. "local": "custom",
  1222. "ollama": "custom", "ollama_cloud": "ollama-cloud",
  1223. "vllm": "custom", "llamacpp": "custom",
  1224. "llama.cpp": "custom", "llama-cpp": "custom"}
  1225. def _plugin_aliases() -> dict[str, str]:
  1226. """``_PROVIDER_ALIASES`` extended with aliases declared in plugins/model-providers/<name>/."""
  1227. aliases = dict(_PROVIDER_ALIASES)
  1228. try:
  1229. from providers import list_providers as _lp
  1230. for _pp in _lp():
  1231. for _alias in _pp.aliases:
  1232. aliases.setdefault(_alias, _pp.name)
  1233. except Exception:
  1234. pass
  1235. return aliases
  1236. def _scoped_key_env_reader() -> Callable[[str], str]:
  1237. """Scope-aware key reader for provider auto-detection.
  1238. Under multiplex a secondary profile's keys live only in its secret scope, not os.environ. Catch
  1239. ONLY ImportError: any other auxiliary_client failure must propagate rather than silently
  1240. falling back to os.getenv (a traceless fail-open)."""
  1241. try:
  1242. # Scope-aware key reads: under multiplex a secondary profile's API keys live only in its secret
  1243. # scope, not os.environ — a bare getenv here would find nothing and auto-resolution would report "No
  1244. # LLM provider configured" for every secondary profile (same class as #86905).
  1245. from agent.auxiliary_client import _scoped_key_env
  1246. return _scoped_key_env
  1247. except ImportError:
  1248. logger.warning(
  1249. "agent.auxiliary_client unavailable (%s); provider auto-detection "
  1250. "will read keys from the process environment only — under "
  1251. "multiplex, secondary profiles may report 'No LLM provider'.",
  1252. "import failed")
  1253. return lambda name: os.getenv(name) or ""
  1254. def _openrouter_auto_detected(scoped_key_env: Callable[[str], str]) -> bool:
  1255. """True when an OpenRouter credential exists via env key or the credential pool (a key added via
  1256. `hermes auth add openrouter` has no env var; without the pool check it is invisible to
  1257. auto-detection and requests go out with no Authorization header)."""
  1258. if has_usable_secret(scoped_key_env("OPENROUTER_API_KEY")):
  1259. return True
  1260. # OPENAI_API_KEY counts only when it holds an OpenRouter-shaped key (legacy home); a real OpenAI
  1261. # key falls through to the ``openai-api`` registry row instead of being shipped to OpenRouter.
  1262. legacy_key = scoped_key_env("OPENAI_API_KEY")
  1263. if has_usable_secret(legacy_key) and looks_like_openrouter_key(legacy_key):
  1264. return True
  1265. try:
  1266. # Auto-detect an OpenRouter credential added via `hermes auth add openrouter` (manual pool entry, no
  1267. # env var). Without this, a key that only lives in the credential pool is invisible to
  1268. # auto-detection — the user sees `hermes auth list` showing the credential while requests go out
  1269. # with no Authorization header ("HTTP 401: Missing Authentication header"). The env-var check above
  1270. # only covers OPENROUTER_API_KEY and an sk-or- key in OPENAI_API_KEY. See issue #42130.
  1271. from agent.credential_pool import load_pool as _load_pool
  1272. return bool(_load_pool("openrouter").has_credentials())
  1273. except Exception as e:
  1274. logger.debug("Could not check OpenRouter credential pool: %s", e)
  1275. return False
  1276. def _logged_in_oauth_active_provider(*, skip_free_tier: bool = False) -> Optional[str]:
  1277. """auth.json ``active_provider`` when it is a registry provider that reports logged in."""
  1278. try:
  1279. _maybe = _load_auth_store().get("active_provider")
  1280. if _maybe == "nous":
  1281. from hermes_cli.anon_auth import free_inference_active, has_guest
  1282. if has_guest() and (skip_free_tier or not free_inference_active()):
  1283. return None # this guest carries no inference here (or is being discounted): not a login
  1284. if _maybe and _maybe in PROVIDER_REGISTRY and get_auth_status(_maybe).get("logged_in"):
  1285. return _maybe
  1286. except Exception as e:
  1287. logger.debug("Could not pre-read active auth provider: %s", e)
  1288. return None
  1289. def _config_model_provider() -> tuple[Any, Optional[str]]:
  1290. """``(model_cfg, provider)`` from config.yaml when ``model.provider`` names a registry provider
  1291. or a custom OpenAI-compatible endpoint (``custom``, ``custom:<name>``, ``vllm``/``ollama``/...).
  1292. A ``model.provider: openrouter`` pin and a bare ``providers:`` entry name are explicit intent too.
  1293. The normal chat/gateway path resolves config.provider upstream in resolve_requested_provider();
  1294. this is the safety net for the direct ``resolve_provider("auto")`` callers. A configured custom
  1295. endpoint is explicit intent like any registry pin: without this rung the boot inventory
  1296. (``free_tier_bootstrap``) read a llama.cpp/vLLM install as "nothing configured" and the
  1297. dashboard's Ink chat parked every session on Setup Required while ``hermes chat`` worked
  1298. (#108383)."""
  1299. try:
  1300. from hermes_cli.config import load_config
  1301. model_cfg = (load_config() or {}).get("model")
  1302. provider = model_cfg.get("provider") if isinstance(model_cfg, dict) else None
  1303. provider = provider.strip().lower() if isinstance(provider, str) else ""
  1304. provider = _plugin_aliases().get(provider, provider)
  1305. if provider == "custom" or provider.startswith("custom:"):
  1306. return model_cfg, "custom"
  1307. # openrouter is absent from PROVIDER_REGISTRY on purpose, so it needs its own rung (#109397);
  1308. # a non-openrouter base_url under it is a deliberate mirror (#10622), not a contradiction.
  1309. if provider == "openrouter" or provider in PROVIDER_REGISTRY:
  1310. return model_cfg, provider
  1311. # Bare ``providers:`` name (the ``custom:<name>`` intent spelled without the prefix); reuse the
  1312. # runtime's own lookup so disabled / endpoint-less entries stay excluded.
  1313. if provider:
  1314. from hermes_cli.runtime_provider_custom import has_named_custom_provider
  1315. if has_named_custom_provider(provider):
  1316. return model_cfg, "custom"
  1317. # No provider pin but a base_url the bare-custom runtime rung would honour (a loopback
  1318. # llama.cpp/vLLM/ollama server) — same explicit intent, spelled by URL.
  1319. base_url = str(model_cfg.get("base_url") or "").strip() if isinstance(model_cfg, dict) else ""
  1320. if base_url:
  1321. from hermes_cli.runtime_provider import _config_base_url_trustworthy_for_bare_custom
  1322. if _config_base_url_trustworthy_for_bare_custom(base_url, provider):
  1323. return model_cfg, "custom"
  1324. return model_cfg, None
  1325. except Exception as e:
  1326. logger.debug("Could not read config.yaml model.provider for auto-resolution: %s", e)
  1327. return None, None
  1328. # API-key providers never auto-selected from env: LM Studio is a local server whose availability
  1329. # isn't implied by LM_API_KEY (may be offline; no-auth setup uses a placeholder), and a profile with
  1330. # ``ambient_credentials`` reads tokens commonly present for other purposes (repo/tool access) that
  1331. # must not hijack inference. Both need an explicit choice.
  1332. _NO_AUTO_DETECT_PROVIDERS = frozenset({"lmstudio"})
  1333. def _credential_profile(provider_id: str) -> Any:
  1334. """The provider's registered profile (credential seams), or None."""
  1335. from providers import get_provider_profile
  1336. return get_provider_profile(provider_id)
  1337. def _env_key_auto_detected(
  1338. scoped_key_env: Callable[[str], str], oauth_active: Optional[str]) -> Optional[str]:
  1339. """First registry api_key provider (registry order) with a usable env key, warning when it
  1340. preempts a logged-in OAuth provider so a stale key in ~/.hermes/.env never switches silently."""
  1341. from providers import list_providers
  1342. ambient = {p.name for p in list_providers() if p.ambient_credentials} # never per-pid lookups: a miss walks the ladder
  1343. for pid, pconfig in _canonical_registry_rows():
  1344. if pconfig.auth_type != "api_key" or pid in _NO_AUTO_DETECT_PROVIDERS or pid in ambient:
  1345. continue
  1346. for env_var in pconfig.api_key_env_vars:
  1347. if has_usable_secret(scoped_key_env(env_var)):
  1348. if oauth_active and oauth_active != pid:
  1349. logger.warning(
  1350. # An exported API key now wins over a logged-in OAuth provider (the #29285 fix).
  1351. # Surface that so a user who deliberately uses OAuth but has a stale key in
  1352. # ~/.hermes/.env isn't silently switched without knowing why.
  1353. "Provider resolved to %r via %s, preempting your "
  1354. "logged-in OAuth provider %r. If you meant to use the "
  1355. "OAuth login, unset %s or set `model.provider` "
  1356. "explicitly.",
  1357. pid, env_var, oauth_active, env_var)
  1358. return pid
  1359. return None
  1360. def resolve_provider(
  1361. requested: Optional[str] = None,
  1362. *,
  1363. explicit_api_key: Optional[str] = None,
  1364. explicit_base_url: Optional[str] = None,
  1365. skip_free_tier: bool = False) -> str:
  1366. """Determine which inference provider to use.
  1367. "auto" priority (explicit intent beats a stale OAuth login): 1. CLI api_key/base_url ->
  1368. "openrouter"; 2. config.yaml ``model.provider``; 3. OPENROUTER_API_KEY (or an sk-or- key in
  1369. OPENAI_API_KEY) -> "openrouter"; 4. OpenRouter pool; 5. provider env keys; 6. auth.json ``active_provider``;
  1370. 7. Nous free tier when a claimed guest exists on the desktop's local backend (never created here);
  1371. 8. AWS Bedrock chain; 9. AuthError(no_provider_configured).
  1372. ``skip_free_tier`` hides rungs 6-for-a-free-tier-identity and 7: the boot bootstrap asks
  1373. "what would carry inference if the free tier did not exist?" to decide whether a fresh identity
  1374. may become ``active_provider``.
  1375. 1. 3. 4. 5. Provider-specific API keys (GLM, Kimi, MiniMax, ...) -> that provider 7. 8. Error (no
  1376. provider configured) See #29285.
  1377. """
  1378. normalized = (requested or "auto").strip().lower()
  1379. normalized = _plugin_aliases().get(normalized, normalized)
  1380. if normalized in ("openrouter", "custom") or _registry_lookup(normalized) is not None:
  1381. return normalized
  1382. if normalized != "auto":
  1383. from hermes_cli.auth_error_copy import unknown_provider_hint
  1384. hint = unknown_provider_hint(normalized)
  1385. tail = (f"\n\n{hint}" if hint else " Check 'hermes model' for available providers, "
  1386. "or run 'hermes doctor' to diagnose config issues.")
  1387. raise AuthError(f"Unknown provider '{normalized}'." + tail, code="invalid_provider")
  1388. if explicit_api_key or explicit_base_url: # one-off CLI creds always mean openrouter/custom
  1389. return "openrouter"
  1390. _model_cfg, cfg_provider = _config_model_provider()
  1391. if cfg_provider:
  1392. return cfg_provider
  1393. _scoped_key_env = _scoped_key_env_reader()
  1394. if _openrouter_auto_detected(_scoped_key_env):
  1395. _refuse_env_adoption_if_config_corrupt()
  1396. return "openrouter"
  1397. # Determined up front so the env-key tier can warn when an exported key preempts it; the actual
  1398. # OAuth fallback still happens after the env-key tier.
  1399. _oauth_active = _logged_in_oauth_active_provider(skip_free_tier=skip_free_tier)
  1400. env_pid = _env_key_auto_detected(_scoped_key_env, _oauth_active)
  1401. if env_pid:
  1402. return env_pid
  1403. # Logged-in OAuth provider is a LAST-RESORT fallback (it used to sit above the env/config
  1404. # checks, so a stale login silently overrode explicit intent).
  1405. # Logged-in OAuth provider (auth.json `active_provider`) — a LAST-RESORT fallback, chosen only when the
  1406. # user expressed no other preference above. Demoted here so explicit intent always wins. See #29285.
  1407. if _oauth_active:
  1408. if isinstance(_model_cfg, dict) and _model_cfg and not _model_cfg.get("provider"):
  1409. logger.warning(
  1410. "Provider resolved to logged-in OAuth provider %r because "
  1411. "config.yaml `model` has no `provider` key. If you meant a "
  1412. "different provider, set `model.provider` explicitly.",
  1413. _oauth_active)
  1414. return _oauth_active
  1415. # Nous free tier, when this guest claimed the welcome trial and this is the desktop's local
  1416. # backend (``anon_auth.free_inference_active``). This rung sits ABOVE the Bedrock
  1417. # chain on purpose: every rung above this line is explicit user intent (CLI creds, config, env
  1418. # keys, a sign-in); the boto chain below is implicit host state, and a leftover ~/.aws profile
  1419. # used to win the first turn of a fresh install (NS-829). The rung never CREATES the identity:
  1420. # only the desktop's trial claim does (welcome_trial), so provider resolution stays free of network.
  1421. if not skip_free_tier:
  1422. try:
  1423. from hermes_cli.anon_auth import free_inference_active
  1424. if free_inference_active():
  1425. return "nous"
  1426. except Exception as exc:
  1427. logger.debug("free tier check during provider resolution skipped: %s", exc)
  1428. # AWS Bedrock via the boto3 credential chain (IAM roles, SSO, env vars): implicit host state,
  1429. # below explicit keys and below the free tier.
  1430. try:
  1431. from agent.bedrock_adapter import has_aws_credentials
  1432. from hermes_cli.anon_auth import on_local_desktop_backend # a laptop: no EC2 metadata lookup
  1433. if has_aws_credentials(instance_metadata=not on_local_desktop_backend()):
  1434. return "bedrock"
  1435. except ImportError:
  1436. pass # boto3 not installed
  1437. from hermes_constants import display_hermes_home
  1438. raise AuthError(
  1439. "Hermes is not connected to any AI provider yet. Run `hermes model` to pick one, type `/login` in chat, "
  1440. f"or add a key with `hermes auth add <provider>`. (Advanced: put an API key such as OPENROUTER_API_KEY in "
  1441. f"{display_hermes_home()}/.env.)",
  1442. code="no_provider_configured")
  1443. # ── Timestamp / TTL helpers ─────────────────────────────────────────────────────────────────────────
  1444. def _utc_now_z() -> str:
  1445. """Current UTC time as an ISO-8601 string with a ``Z`` suffix (last_refresh format)."""
  1446. return datetime.now(UTC).isoformat().replace("+00:00", "Z")
  1447. def _parse_iso_timestamp(value: Any) -> Optional[float]:
  1448. text = value.strip() if isinstance(value, str) else ""
  1449. if not text:
  1450. return None
  1451. if text.endswith("Z"):
  1452. text = text[:-1] + "+00:00"
  1453. try:
  1454. parsed = datetime.fromisoformat(text)
  1455. except Exception:
  1456. return None
  1457. if parsed.tzinfo is None:
  1458. parsed = parsed.replace(tzinfo=UTC)
  1459. return parsed.timestamp()
  1460. def _is_expiring(expires_at_iso: Any, skew_seconds: int) -> bool:
  1461. expires_epoch = _parse_iso_timestamp(expires_at_iso)
  1462. return expires_epoch is None or expires_epoch <= (time.time() + skew_seconds)
  1463. def _tls_state_from_verify(verify: Any) -> dict[str, Any]:
  1464. """Persistable ``tls`` block derived from an httpx ``verify`` value."""
  1465. return {"insecure": verify is False, "ca_bundle": verify if isinstance(verify, str) else None}
  1466. def _last_auth_error_marker(
  1467. provider: str, error: AuthError, *, reason: str, default_code: Optional[str] = None,
  1468. ) -> dict[str, Any]:
  1469. """The ``last_auth_error`` record persisted when dead OAuth material is quarantined."""
  1470. return {
  1471. "provider": provider, "message": str(error), "reason": reason, "relogin_required": True,
  1472. "code": error.code if default_code is None else (error.code or default_code),
  1473. "at": datetime.now(UTC).isoformat()}
  1474. _FLAT_OAUTH_TOKEN_KEYS = ("access_token", "refresh_token", "expires_at", "expires_in", "obtained_at")
  1475. def _quarantine_flat_oauth_state(state: dict[str, Any], provider: str, exc: AuthError) -> None:
  1476. """Strip dead tokens from a flat OAuth state after a terminal runtime refresh failure so
  1477. subsequent calls fail fast without a network retry (mirrors the Nous / xAI / Codex pattern)."""
  1478. for _k in _FLAT_OAUTH_TOKEN_KEYS:
  1479. state.pop(_k, None)
  1480. state["last_auth_error"] = _last_auth_error_marker(
  1481. provider, exc, reason="runtime_refresh_failure", default_code="refresh_failed")
  1482. def _coerce_ttl_seconds(expires_in: Any) -> int:
  1483. try:
  1484. return max(0, int(expires_in))
  1485. except Exception:
  1486. return 0
  1487. def _optional_base_url(value: Any) -> Optional[str]:
  1488. cleaned = value.strip().rstrip("/") if isinstance(value, str) else ""
  1489. return cleaned or None
  1490. # Valid Nous Portal hosts; a stored portal_base_url outside this set is a misconfiguration and falls
  1491. # back to the default. localhost / 127.0.0.1 are for local development and testing.
  1492. _NOUS_PORTAL_ALLOWED_HOSTS: frozenset[str] = frozenset({
  1493. "portal.nousresearch.com", "localhost", "127.0.0.1"})
  1494. # Per-process memo for resolve_nous_access_token: startup runs one check_fn per managed tool and
  1495. # each would trigger its own ~15s blocking refresh of an expired token; a short-TTL memo collapses
  1496. # the burst into one round-trip. Callers needing freshness use force_fresh/refresh_nous_oauth_pure.
  1497. # Keyed by hermes_home_key(): the resolution itself is profile-scoped (_auth_file_path reads the
  1498. # per-turn HERMES_HOME override a multiplex gateway sets), so a single slot would hand profile A's
  1499. # Portal bearer to profile B for up to the TTL.
  1500. _RESOLVE_TOKEN_CACHE_LOCK = threading.Lock()
  1501. _RESOLVE_TOKEN_CACHE: dict[str, tuple[float, str]] = {}
  1502. _RESOLVE_TOKEN_CACHE_TTL_S = 5.0
  1503. def resolve_nous_access_token(
  1504. *,
  1505. timeout_seconds: float = 15.0,
  1506. insecure: Optional[bool] = None,
  1507. ca_bundle: Optional[str] = None,
  1508. refresh_skew_seconds: int = ACCESS_TOKEN_REFRESH_SKEW_SECONDS) -> str:
  1509. """Refresh-aware Nous Portal token for managed tool gateways, connectors and account reads, never
  1510. the free model: a guest gets a live held token, else a connectors-only mint NAS never challenges.
  1511. Only a NAS from before hermes-portal#1516 challenges that mint; it is worked here as before."""
  1512. from hermes_cli.anon_challenge import run_with_challenge
  1513. return run_with_challenge(lambda: _resolve_nous_access_token(
  1514. timeout_seconds=timeout_seconds, insecure=insecure, ca_bundle=ca_bundle,
  1515. refresh_skew_seconds=refresh_skew_seconds))
  1516. def _resolve_nous_access_token(
  1517. *,
  1518. timeout_seconds: float,
  1519. insecure: Optional[bool],
  1520. ca_bundle: Optional[str],
  1521. refresh_skew_seconds: int) -> str:
  1522. # Only a default-TLS resolution is memoised; error paths never populate the memo.
  1523. memoable = not insecure and ca_bundle is None
  1524. cache_key = hermes_home_key()
  1525. if memoable:
  1526. with _RESOLVE_TOKEN_CACHE_LOCK:
  1527. cached = _RESOLVE_TOKEN_CACHE.get(cache_key)
  1528. if cached is not None and (time.monotonic() - cached[0]) < _RESOLVE_TOKEN_CACHE_TTL_S:
  1529. return cached[1]
  1530. def _memo(token: str) -> str:
  1531. if memoable:
  1532. with _RESOLVE_TOKEN_CACHE_LOCK:
  1533. _RESOLVE_TOKEN_CACHE[cache_key] = (time.monotonic(), token)
  1534. return token
  1535. with _provider_state_transaction("nous") as (auth_store, state, state_source_path):
  1536. if not state:
  1537. raise _nous_err("Hermes is not logged into Nous Portal.", "nous_auth_missing", relogin=True)
  1538. portal_base_url = _nous_portal_base_url(state)
  1539. client_id = str(state.get("client_id") or DEFAULT_NOUS_CLIENT_ID)
  1540. verify = _resolve_verify(insecure=insecure, ca_bundle=ca_bundle, auth_state=state)
  1541. persist = lambda: _save_provider_state_to_source(
  1542. auth_store, "nous", state, state_source_path)
  1543. lock_timeout = max(timeout_seconds + 5.0, AUTH_LOCK_TIMEOUT_SECONDS)
  1544. with _nous_shared_store_lock(timeout_seconds=lock_timeout):
  1545. from hermes_cli.anon_auth import held_connectors_token, is_guest_state, refresh_guest_state
  1546. if is_guest_state(state):
  1547. # A live held token serves (an inference one is a superset); else mint connectors-only.
  1548. if access_token := held_connectors_token(state, skew_seconds=refresh_skew_seconds):
  1549. return _memo(access_token)
  1550. with httpx.Client(timeout=httpx.Timeout(timeout_seconds or 15.0),
  1551. headers={"Accept": "application/json"}, verify=verify) as client:
  1552. minted = refresh_guest_state(state, client, purpose="connectors")
  1553. persist()
  1554. _write_shared_nous_state(state, renewal=True)
  1555. return _memo(minted)
  1556. merged_shared = _merge_shared_nous_oauth_state(state)
  1557. access_token = state.get("access_token")
  1558. refresh_token = state.get("refresh_token")
  1559. if not isinstance(access_token, str) or not access_token:
  1560. raise _nous_err(
  1561. "No access token found for Nous Portal login.", "nous_auth_missing_access_token", relogin=True)
  1562. if not _is_expiring(state.get("expires_at"), refresh_skew_seconds):
  1563. if merged_shared:
  1564. persist()
  1565. # Memoise the valid-token fast path too: each check_fn otherwise pays two
  1566. # cross-process file locks to get here. The token has >= refresh_skew_seconds (>=
  1567. # 120s) of life, so a 5s memo can never serve an expired token.
  1568. return _memo(access_token)
  1569. if not isinstance(refresh_token, str) or not refresh_token:
  1570. raise _nous_err(
  1571. "Session expired and no refresh token is available.", "nous_auth_missing_refresh_token",
  1572. relogin=True)
  1573. with httpx.Client(timeout=httpx.Timeout(timeout_seconds or 15.0),
  1574. headers={"Accept": "application/json"}, verify=verify) as client:
  1575. refreshed = _refresh_nous_or_quarantine(
  1576. client=client, auth_store=auth_store, state=state, portal_base_url=portal_base_url,
  1577. client_id=client_id, refresh_token=refresh_token,
  1578. reason="managed_access_token_refresh_failure", persist=persist)
  1579. _apply_nous_refreshed_tokens(state, refreshed, refresh_token)
  1580. state["portal_base_url"] = portal_base_url
  1581. state["client_id"] = client_id
  1582. state["tls"] = _tls_state_from_verify(verify)
  1583. persist()
  1584. _write_shared_nous_state(state, renewal=True)
  1585. return _memo(state["access_token"])
  1586. # ── Status helpers ──────────────────────────────────────────────────────────────────────────────────
  1587. # Process-level memo for get_nous_auth_status(): it validates via a synchronous refresh POST
  1588. # (~350ms) and read-only UI surfaces call it many times per render (~31x per menu paint), burning
  1589. # single-use refresh tokens. Keyed on auth.json path + file_cache_version so profile switches don't share a memo
  1590. # and login/logout/add/remove invalidate naturally.
  1591. _NOUS_AUTH_STATUS_CACHE_TTL = 15.0 # seconds
  1592. _nous_auth_status_cache: Optional[tuple[float, str, Optional[tuple[Any, ...]], dict[str, Any]]] = None
  1593. # Memo for _load_global_auth_store(): (path, file_cache_version, store); same invalidation rule.
  1594. _global_auth_store_cache: Optional[tuple[str, tuple[Any, ...], dict[str, Any]]] = None
  1595. def _auth_file_cache_key() -> tuple[str, Optional[tuple[Any, ...]]]:
  1596. auth_file = _auth_file_path()
  1597. try:
  1598. return _resolved_key(auth_file), file_cache_version(auth_file)
  1599. except Exception: # missing file included: key without an mtime
  1600. return _resolved_key(auth_file), None
  1601. def invalidate_nous_auth_status_cache() -> None:
  1602. """Clear the get_nous_auth_status() memo (for code paths that mutate Nous auth state without
  1603. touching auth.json, e.g. tests; login/logout invalidate via the mtime check automatically)."""
  1604. global _nous_auth_status_cache
  1605. _nous_auth_status_cache = None
  1606. def get_nous_auth_status() -> dict[str, Any]:
  1607. """Status snapshot for Nous auth, memoised ~15s keyed on the auth.json mtime.
  1608. Prefers the auth-store provider state (the live source of truth for refresh) and validates it by
  1609. resolving runtime credentials so revoked refresh sessions do not show up as a healthy login."""
  1610. global _nous_auth_status_cache
  1611. now = time.monotonic()
  1612. auth_file_key, mtime = _auth_file_cache_key()
  1613. cached = _nous_auth_status_cache
  1614. if (cached is not None and cached[1:3] == (auth_file_key, mtime)
  1615. and (now - cached[0]) < _NOUS_AUTH_STATUS_CACHE_TTL):
  1616. return dict(cached[3])
  1617. status = _compute_nous_auth_status()
  1618. _nous_auth_status_cache = (now, auth_file_key, mtime, dict(status))
  1619. return status
  1620. @dataclass(frozen=True)
  1621. class OAuthProviderFlow:
  1622. """Per-provider OAuth plumbing, keyed by provider id in ``OAUTH_PROVIDER_FLOWS``.
  1623. Callables are named (strings) and looked up in this module at call time so
  1624. ``monkeypatch.setattr("hermes_cli.auth.resolve_codex_runtime_credentials", ...)`` applies."""
  1625. provider_id: str
  1626. resolve_fn: str
  1627. status_fn: str
  1628. terminal_refresh_codes: frozenset[str] = frozenset() # retrying the same refresh token cannot succeed
  1629. # ``hermes logout`` with no active provider falls back to config.yaml ``model.provider`` only
  1630. # for providers whose credentials live in auth.json.
  1631. logout_from_config: bool = False
  1632. def resolve(self, **kwargs: Any) -> dict[str, Any]:
  1633. return globals()[self.resolve_fn](**kwargs)
  1634. def status(self) -> dict[str, Any]:
  1635. return globals()[self.status_fn]()
  1636. def is_terminal_refresh_error(self, exc: Exception) -> bool:
  1637. return (
  1638. isinstance(exc, AuthError) and exc.provider == self.provider_id
  1639. and exc.code in self.terminal_refresh_codes and bool(exc.relogin_required))
  1640. _OAUTH_GRANT_DEAD_CODES = frozenset({"invalid_grant", "invalid_token", "refresh_token_reused"})
  1641. # Nous state-shape failures raised BEFORE any refresh POST (no login, no token pair): retrying
  1642. # cannot succeed either, so the pool must not bench them as a transient outage (#113718).
  1643. _NOUS_AUTH_MISSING_CODES = frozenset({
  1644. "nous_auth_missing", "nous_auth_missing_access_token", "nous_auth_missing_refresh_token"})
  1645. OAUTH_PROVIDER_FLOWS: dict[str, OAuthProviderFlow] = {
  1646. "nous": OAuthProviderFlow(
  1647. "nous", "resolve_nous_runtime_credentials", "get_nous_auth_status",
  1648. terminal_refresh_codes=_OAUTH_GRANT_DEAD_CODES | _NOUS_AUTH_MISSING_CODES, logout_from_config=True),
  1649. "openai-codex": OAuthProviderFlow(
  1650. "openai-codex", "resolve_codex_runtime_credentials", "get_codex_auth_status",
  1651. terminal_refresh_codes=_OAUTH_GRANT_DEAD_CODES | {"codex_refresh_failed", "codex_auth_missing_refresh_token"},
  1652. logout_from_config=True),
  1653. "xai-oauth": OAuthProviderFlow(
  1654. "xai-oauth", "resolve_xai_oauth_runtime_credentials", "get_xai_oauth_auth_status",
  1655. terminal_refresh_codes=frozenset({"xai_refresh_failed", "xai_auth_missing_refresh_token"}),
  1656. logout_from_config=True),
  1657. "qwen-oauth": OAuthProviderFlow(
  1658. "qwen-oauth", "resolve_qwen_runtime_credentials", "get_qwen_auth_status"),
  1659. "minimax-oauth": OAuthProviderFlow(
  1660. "minimax-oauth", "resolve_minimax_oauth_runtime_credentials", "get_minimax_oauth_auth_status"),
  1661. }
  1662. def _is_terminal_refresh_error(exc: Exception, provider: str) -> bool:
  1663. """True when retrying the same *provider* refresh token cannot succeed."""
  1664. return OAUTH_PROVIDER_FLOWS[provider].is_terminal_refresh_error(exc)
  1665. _is_terminal_nous_refresh_error = partial(_is_terminal_refresh_error, provider="nous")
  1666. _is_terminal_xai_oauth_refresh_error = partial(_is_terminal_refresh_error, provider="xai-oauth")
  1667. _is_terminal_codex_oauth_refresh_error = partial(
  1668. _is_terminal_refresh_error, provider="openai-codex")
  1669. def _codex_pool_rate_limited_status() -> Optional[dict[str, Any]]:
  1670. rate_limit = _codex_pool_rate_limit_status()
  1671. if not rate_limit:
  1672. return None
  1673. return {
  1674. "logged_in": True, "auth_store": str(_auth_file_path()),
  1675. "last_refresh": rate_limit.get("last_refresh"), "auth_mode": "chatgpt",
  1676. "source": f"pool:{rate_limit.get('label') or 'unknown'}", "rate_limited": True,
  1677. "error_code": CODEX_RATE_LIMITED_CODE,
  1678. "error": (rate_limit.get("message")
  1679. or "Codex provider quota exhausted; retry after the usage limit resets."),
  1680. "reset_at": rate_limit.get("reset_at")}
  1681. def get_codex_auth_status() -> dict[str, Any]:
  1682. """Status snapshot for Codex auth (pool first, then legacy provider state).
  1683. Read-only by contract: status/doctor must never adopt, refresh or persist a credential (#68004)."""
  1684. status = _pool_first_oauth_status(
  1685. "openai-codex", is_expiring=_codex_access_token_is_expiring, auth_mode="chatgpt",
  1686. resolve=lambda: resolve_codex_runtime_credentials(read_only=True),
  1687. on_pool_miss=_codex_pool_rate_limited_status)
  1688. if str(status.get("source") or "").startswith("pool:"):
  1689. # Pool rows keep the canonical URL; the chat route may send this key to model.base_url.
  1690. from hermes_cli.auth_codex import _codex_pool_route_base_url
  1691. status["base_url"] = _codex_pool_route_base_url(status.get("base_url"))
  1692. return status
  1693. def get_xai_oauth_auth_status() -> dict[str, Any]:
  1694. # auth_mode is display/telemetry only; device-code is the only xAI OAuth flow, so report it
  1695. # unconditionally (auth.json may still carry a legacy ``oauth_pkce`` label).
  1696. return _pool_first_oauth_status(
  1697. "xai-oauth", is_expiring=_xai_access_token_is_expiring, auth_mode="oauth_device_code",
  1698. resolve=lambda: resolve_xai_oauth_runtime_credentials(refresh_if_expiring=False))
  1699. def _provider_env_base_url(pconfig: ProviderConfig) -> str:
  1700. if pconfig.id == "actual":
  1701. from hermes_cli.providers import normalize_provider
  1702. model = read_raw_config().get("model")
  1703. if isinstance(model, dict) and normalize_provider(str(model.get("provider") or "")) == "actual":
  1704. configured_url = str(model.get("base_url") or "").strip()
  1705. if configured_url:
  1706. return configured_url
  1707. return os.getenv(pconfig.base_url_env_var, "").strip() if pconfig.base_url_env_var else ""
  1708. def get_api_key_provider_status(provider_id: str) -> dict[str, Any]:
  1709. """Status snapshot for API-key providers (z.ai, Kimi, MiniMax)."""
  1710. pconfig = _registry_lookup(provider_id)
  1711. if not pconfig or pconfig.auth_type != "api_key":
  1712. return {"configured": False}
  1713. api_key, key_source = _resolve_api_key_provider_secret(provider_id, pconfig)
  1714. env_url = _provider_env_base_url(pconfig)
  1715. if provider_id in {"kimi-coding", "kimi-coding-cn"}:
  1716. base_url = _resolve_kimi_base_url(api_key, pconfig.inference_base_url, env_url)
  1717. else:
  1718. base_url = env_url or pconfig.inference_base_url
  1719. actual_local_noauth = False
  1720. if provider_id == "actual":
  1721. base_url = normalize_actual_base_url(base_url)
  1722. actual_local_noauth = not api_key and is_actual_local_base_url(base_url)
  1723. configured = bool(api_key) or actual_local_noauth
  1724. return { # logged_in mirrors configured for compat with the OAuth status shape
  1725. "configured": configured, "provider": provider_id, "name": pconfig.name,
  1726. "key_source": key_source or ("local-offline" if actual_local_noauth else ""),
  1727. "base_url": base_url, "logged_in": configured}
  1728. def _external_process_auth_evidence(provider_id: str, resolved_command: Optional[str]) -> tuple[bool, Optional[str]]:
  1729. """Best-effort POSITIVE evidence ``(verified, source)`` that an external-process CLI is authed.
  1730. False means "not verifiable from here", NOT "signed out". Subprocess-free (spawning the CLI from
  1731. status endpoints/pickers re-creates a cold-start stall). Generic evidence
  1732. for any external-process profile is its binary resolving: the subprocess owns real auth and Hermes
  1733. has nothing else to inspect, so out-of-tree ACP rows pass credential-gated surfaces (Desktop
  1734. ``explicit_only`` picker); a profile whose CLI exposes readable token stores answers
  1735. ``external_auth_evidence()`` instead."""
  1736. evidence = _credential_profile(provider_id)
  1737. evidence = evidence.external_auth_evidence() if evidence else None
  1738. if evidence is not None:
  1739. return evidence
  1740. return (True, f"command: {resolved_command}") if resolved_command else (False, None)
  1741. def _external_process_spec(
  1742. pconfig: ProviderConfig) -> tuple[str, list[str], str, Optional[str], tuple[str, ...]]:
  1743. """``(command, args, base_url, resolved_command, command_env_vars)`` for an ACP provider.
  1744. Launch details come from the provider's own profile (``process_command`` and its env overrides),
  1745. so out-of-tree providers describe their binary."""
  1746. base_url = _provider_env_base_url(pconfig) or pconfig.inference_base_url
  1747. try:
  1748. from providers import get_provider_profile as _get_provider_profile
  1749. profile = _get_provider_profile(pconfig.id)
  1750. except Exception:
  1751. profile = None
  1752. command_env_vars = tuple(getattr(profile, "process_command_env_vars", ()) or ())
  1753. args_env_var = str(getattr(profile, "process_args_env_var", "") or "")
  1754. command = (next((v for v in (os.getenv(var, "").strip() for var in command_env_vars) if v), "")
  1755. or str(getattr(profile, "process_command", "") or ""))
  1756. raw_args = os.getenv(args_env_var, "").strip() if args_env_var else ""
  1757. args = shlex.split(raw_args) if raw_args else list(getattr(profile, "process_args", ()) or [])
  1758. from hermes_cli.auth_external_process import resolve_external_process_command
  1759. return command, args, base_url, resolve_external_process_command(command), command_env_vars
  1760. def get_external_process_provider_status(provider_id: str) -> dict[str, Any]:
  1761. """Status snapshot for providers that run a local subprocess.
  1762. ``configured``/``logged_in`` are structural (executable resolves or TCP endpoint set): the
  1763. subprocess owns real auth. ``auth_verified``/``auth_source`` carry positive evidence only."""
  1764. pconfig = _registry_lookup(provider_id)
  1765. if not pconfig or pconfig.auth_type != "external_process":
  1766. return {"configured": False}
  1767. command, args, base_url, resolved_command, _ = _external_process_spec(pconfig)
  1768. available = bool(resolved_command or base_url.startswith("acp+tcp://"))
  1769. auth_verified, auth_source = _external_process_auth_evidence(provider_id, resolved_command)
  1770. return {
  1771. "configured": available, "provider": provider_id, "name": pconfig.name, "command": command,
  1772. "args": args, "resolved_command": resolved_command, "base_url": base_url,
  1773. "logged_in": available, "auth_verified": auth_verified, "auth_source": auth_source}
  1774. def _get_aws_sdk_auth_status(target: str) -> dict[str, Any]:
  1775. """AWS SDK providers (Bedrock) — check via boto3 credential chain."""
  1776. try:
  1777. from agent.bedrock_adapter import has_aws_credentials
  1778. return {"logged_in": has_aws_credentials(), "provider": target}
  1779. except ImportError:
  1780. return {"logged_in": False, "provider": target, "error": "boto3 not installed"}
  1781. def get_auth_status(provider_id: Optional[str] = None) -> dict[str, Any]:
  1782. """Generic auth status dispatcher: bespoke builders (``OAUTH_PROVIDER_FLOWS`` plus Azure
  1783. Foundry) first, then the registry ``auth_type`` so a whole provider class (e.g. every
  1784. external-process ACP backend) gets a real status. Builders are looked up by NAME at call time so
  1785. tests that patch ``hermes_cli.auth.get_*_auth_status`` still apply."""
  1786. target = (provider_id or get_active_provider() or "").strip().lower()
  1787. if not target:
  1788. return {"logged_in": False}
  1789. status_fn_name = _BESPOKE_STATUS_FUNCTIONS.get(target)
  1790. if status_fn_name:
  1791. return globals()[status_fn_name]()
  1792. pconfig = _registry_lookup(target)
  1793. if pconfig and pconfig.auth_type in _STATUS_BY_AUTH_TYPE:
  1794. return globals()[_STATUS_BY_AUTH_TYPE[pconfig.auth_type]](target)
  1795. return {"logged_in": False}
  1796. # Bespoke status builders (name -> looked up in this module at call time) win over the
  1797. # auth_type-keyed fallbacks below.
  1798. _BESPOKE_STATUS_FUNCTIONS: dict[str, str] = {
  1799. **{pid: flow.status_fn for pid, flow in OAUTH_PROVIDER_FLOWS.items()},
  1800. "azure-foundry": "_get_azure_foundry_auth_status"}
  1801. _STATUS_BY_AUTH_TYPE: dict[str, str] = {
  1802. "external_process": "get_external_process_provider_status",
  1803. "api_key": "get_api_key_provider_status",
  1804. "aws_sdk": "_get_aws_sdk_auth_status",
  1805. # OAuth-shaped plugin providers (their login lives in the plugin's auth_handler, tokens in the pool).
  1806. "oauth_device_code": "get_plugin_oauth_auth_status",
  1807. "oauth_external": "get_plugin_oauth_auth_status"}
  1808. def _get_azure_foundry_auth_status() -> dict[str, Any]:
  1809. """Structural auth status for Azure Foundry.
  1810. ``entra_id``: ``azure-identity`` importable — never invokes the Entra credential chain (keeps
  1811. CLI startup flat; ``hermes doctor`` runs the live probe). ``api_key`` (default): usable
  1812. ``AZURE_FOUNDRY_API_KEY``."""
  1813. info: dict[str, Any] = {"provider": "azure-foundry"}
  1814. try:
  1815. from hermes_cli.config import load_config, get_env_value_prefer_dotenv
  1816. cfg = load_config()
  1817. except Exception:
  1818. cfg = {}
  1819. model_cfg = cfg.get("model") if isinstance(cfg, dict) else None
  1820. if not isinstance(model_cfg, dict):
  1821. model_cfg = {}
  1822. auth_mode = str(model_cfg.get("auth_mode") or "api_key").strip().lower() or "api_key"
  1823. info["auth_mode"] = auth_mode
  1824. info["base_url"] = str(model_cfg.get("base_url") or "").strip()
  1825. if auth_mode == "entra_id":
  1826. try:
  1827. from agent.azure_identity_adapter import (
  1828. EntraIdentityConfig, SCOPE_AI_AZURE_DEFAULT, has_azure_identity_installed)
  1829. installed = has_azure_identity_installed()
  1830. entra_cfg = model_cfg["entra"] if isinstance(model_cfg.get("entra"), dict) else {}
  1831. identity_config = EntraIdentityConfig.from_dict(entra_cfg, default_scope=SCOPE_AI_AZURE_DEFAULT)
  1832. info.update(
  1833. azure_identity_installed=installed, scope=identity_config.scope, credential_probe="not_run",
  1834. credential_verified=False, logged_in=bool(installed),
  1835. hint=(
  1836. "azure-identity is installed; live credential validation "
  1837. "is skipped here. Run `hermes doctor` to verify token acquisition."
  1838. ) if installed else (
  1839. "azure-identity not installed. From the Hermes environment, run: "
  1840. f"{install_hint('azure-identity')}. "
  1841. "Then restart Hermes."))
  1842. except Exception as exc:
  1843. info["logged_in"] = False
  1844. info["error"] = f"azure-identity check failed: {exc}"
  1845. return info
  1846. try:
  1847. api_key = get_env_value_prefer_dotenv("AZURE_FOUNDRY_API_KEY") or ""
  1848. except Exception:
  1849. api_key = os.getenv("AZURE_FOUNDRY_API_KEY", "")
  1850. info["logged_in"] = has_usable_secret(api_key)
  1851. return info
  1852. def _default_api_key_base_url(api_key: str, default: str, env_url: str) -> str:
  1853. return env_url.rstrip("/") if env_url else default
  1854. # Providers whose runtime base URL is not simply env-override-or-registry-default:
  1855. # ``(api_key, registry_default, env_override) -> base_url``.
  1856. _API_KEY_BASE_URL_RESOLVERS: dict[str, Callable[[str, str, str], str]] = {
  1857. "kimi-coding": _resolve_kimi_base_url,
  1858. "kimi-coding-cn": _resolve_kimi_base_url,
  1859. "zai": _resolve_zai_base_url,
  1860. "lmstudio": lambda *a: _normalize_lmstudio_runtime_base_url(_default_api_key_base_url(*a)),
  1861. "actual": lambda *a: normalize_actual_base_url(_default_api_key_base_url(*a))}
  1862. def resolve_api_key_provider_credentials(provider_id: str) -> dict[str, Any]:
  1863. """Resolve API key and base URL for an API-key provider."""
  1864. pconfig = _registry_lookup(provider_id)
  1865. if not pconfig or pconfig.auth_type != "api_key":
  1866. raise AuthError(
  1867. f"Provider '{provider_id}' is not an API-key provider.",
  1868. provider=provider_id, code="invalid_provider")
  1869. api_key, key_source = _resolve_api_key_provider_secret(provider_id, pconfig)
  1870. # No-auth LM Studio: a placeholder so runtime / auxiliary_client see the local server as
  1871. # configured. doctor still reports unconfigured because the status path uses the raw secret.
  1872. if not api_key and provider_id == "lmstudio":
  1873. api_key = LMSTUDIO_NOAUTH_PLACEHOLDER
  1874. key_source = key_source or "default"
  1875. env_url = _provider_env_base_url(pconfig)
  1876. resolve_url = _API_KEY_BASE_URL_RESOLVERS.get(provider_id, _default_api_key_base_url)
  1877. profile = _credential_profile(provider_id)
  1878. base_url = (profile.runtime_base_url(api_key=api_key, default=pconfig.inference_base_url, env_url=env_url)
  1879. if profile else None)
  1880. base_url = resolve_url(api_key, pconfig.inference_base_url, env_url) if base_url is None else base_url
  1881. # An API-key provider must never hand back an empty base URL (a set-but-empty
  1882. # <PROVIDER>_BASE_URL env override otherwise wedges chat inference).
  1883. if not _nonempty_str(base_url):
  1884. base_url = pconfig.inference_base_url
  1885. if not api_key and provider_id == "actual" and is_actual_local_base_url(base_url):
  1886. api_key = ACTUAL_LOCAL_NOAUTH_PLACEHOLDER
  1887. key_source = key_source or "local-offline"
  1888. return {
  1889. "provider": provider_id, "api_key": api_key, "base_url": base_url.rstrip("/"),
  1890. "source": key_source or "default"}
  1891. def resolve_external_process_provider_credentials(provider_id: str) -> dict[str, Any]:
  1892. """Resolve runtime details for local subprocess-backed providers."""
  1893. pconfig = _registry_lookup(provider_id)
  1894. if not pconfig or pconfig.auth_type != "external_process":
  1895. raise AuthError(
  1896. f"Provider '{provider_id}' is not an external-process provider.",
  1897. provider=provider_id, code="invalid_provider")
  1898. command, args, base_url, resolved_command, command_env_vars = _external_process_spec(pconfig)
  1899. if not resolved_command and not base_url.startswith("acp+tcp://"):
  1900. _hint = " or set " + "/".join(command_env_vars) if command_env_vars else ""
  1901. raise AuthError(
  1902. f"Could not find the '{provider_id}' CLI command "
  1903. f"'{command or '(none configured)'}'. Install it{_hint}.",
  1904. provider=provider_id,
  1905. code="missing_external_process_cli")
  1906. # api_key is a placeholder: the subprocess owns real auth. Keyed on the provider id so each
  1907. # external-process provider gets a distinct value.
  1908. return {
  1909. "provider": provider_id, "api_key": pconfig.id or provider_id,
  1910. "base_url": base_url.rstrip("/"), "command": resolved_command or command, "args": args,
  1911. "source": "process"}
  1912. # ── CLI Commands — login / logout ───────────────────────────────────────────────────────────────────
  1913. def _update_config_for_provider(
  1914. provider_id: str, inference_base_url: str, default_model: Optional[str] = None,
  1915. *, clear_default: bool = False) -> Path:
  1916. """Update config.yaml and auth.json to reflect the active provider.
  1917. *default_model*, when given, is written as ``model.default`` in the same step so the gateway
  1918. (which re-reads config per message) can't pick up the new provider before model selection
  1919. finishes and send an OpenRouter-style ``vendor/model`` name to a direct API. *clear_default*
  1920. removes ``model.default`` in that same write, for a caller that has no model to offer and must
  1921. not leave the previous provider's model paired with the new host."""
  1922. with _auth_store_lock(): # so auto-resolution picks this provider
  1923. auth_store = _load_auth_store()
  1924. auth_store["active_provider"] = provider_id
  1925. _save_auth_store(auth_store)
  1926. config_path = get_config_path()
  1927. config_path.parent.mkdir(parents=True, exist_ok=True)
  1928. require_readable_config_before_write(config_path)
  1929. config = read_raw_config()
  1930. current_model = config.get("model")
  1931. if isinstance(current_model, dict):
  1932. model_cfg = dict(current_model)
  1933. else:
  1934. model_cfg = {"default": current_model.strip()} if _nonempty_str(current_model) else {}
  1935. model_cfg["provider"] = provider_id
  1936. if inference_base_url and inference_base_url.strip():
  1937. model_cfg["base_url"] = inference_base_url.rstrip("/")
  1938. else:
  1939. model_cfg.pop("base_url", None) # clear stale base_url when switching providers
  1940. # Built-in providers resolve credentials from env/auth state, not inline model.api_key left
  1941. # over from a previous custom provider.
  1942. from hermes_cli.config import clear_model_endpoint_credentials
  1943. clear_model_endpoint_credentials(model_cfg)
  1944. # An OpenRouter-formatted default like "anthropic/claude-opus-4.6" fails on direct-API
  1945. # providers.
  1946. if default_model:
  1947. cur_default = model_cfg.get("default", "")
  1948. if not cur_default or "/" in cur_default:
  1949. model_cfg["default"] = default_model
  1950. elif clear_default:
  1951. model_cfg.pop("default", None)
  1952. config["model"] = model_cfg
  1953. atomic_config_replace(config_path, config)
  1954. return config_path
  1955. def _get_config_provider() -> Optional[str]:
  1956. """Return model.provider from config.yaml, normalized, if present."""
  1957. try:
  1958. config = read_raw_config()
  1959. except Exception:
  1960. return None
  1961. model = config.get("model") if config else None
  1962. provider = model.get("provider") if isinstance(model, dict) else None
  1963. return (provider.strip().lower() or None) if isinstance(provider, str) else None
  1964. def _should_reset_config_provider_on_logout(provider_id: Optional[str]) -> bool:
  1965. """True when logout should reset model.provider (a registry provider config.yaml selects)."""
  1966. normalized = (provider_id or "").strip().lower()
  1967. return normalized in PROVIDER_REGISTRY and _get_config_provider() == normalized
  1968. def _logout_default_provider_from_config() -> Optional[str]:
  1969. """Fallback logout target when auth.json has no active provider but config.yaml still selects an
  1970. OAuth provider (e.g. openai-codex) — otherwise logout said "No provider is currently logged in"
  1971. and never reset model.provider."""
  1972. provider = _get_config_provider()
  1973. flow = OAUTH_PROVIDER_FLOWS.get(provider or "")
  1974. return provider if flow and flow.logout_from_config else None
  1975. def _reset_config_provider() -> Path:
  1976. """Reset config.yaml provider back to auto after logout."""
  1977. config_path = get_config_path()
  1978. if not config_exists(config_path):
  1979. return config_path
  1980. require_readable_config_before_write(config_path)
  1981. config = read_raw_config()
  1982. if not config:
  1983. return config_path
  1984. model = config.get("model")
  1985. if isinstance(model, dict):
  1986. model["provider"] = "auto"
  1987. if "base_url" in model:
  1988. model["base_url"] = OPENROUTER_BASE_URL
  1989. atomic_config_replace(config_path, config)
  1990. return config_path
  1991. def login_command(args) -> None:
  1992. """Deprecated: use 'hermes model' or 'hermes setup' instead."""
  1993. print("The 'hermes login' command has been removed.\nUse 'hermes auth' to manage credentials,\n"
  1994. "'hermes model' to select a provider, or 'hermes setup' for full setup.")
  1995. raise SystemExit(0)
  1996. def get_minimax_oauth_auth_status() -> dict[str, Any]:
  1997. """Return auth status dict for MiniMax OAuth provider."""
  1998. state = get_provider_auth_state("minimax-oauth")
  1999. if not state or not state.get("access_token"):
  2000. return {"logged_in": False, "provider": "minimax-oauth"}
  2001. try:
  2002. token_valid = datetime.fromisoformat(state.get("expires_at", "")).timestamp() > time.time()
  2003. except Exception:
  2004. token_valid = True # access_token is known non-empty here
  2005. return {
  2006. "logged_in": token_valid, "provider": "minimax-oauth",
  2007. "region": state.get("region", "global"), "expires_at": state.get("expires_at")}
  2008. def logout_command(args) -> None:
  2009. """Clear auth state for a provider."""
  2010. provider_id = getattr(args, "provider", None)
  2011. if provider_id and not is_known_auth_provider(provider_id):
  2012. print(f"Unknown provider: {provider_id}")
  2013. raise SystemExit(1)
  2014. target = provider_id or get_active_provider() or _logout_default_provider_from_config()
  2015. if not target:
  2016. print("No provider is currently logged in.")
  2017. return
  2018. if target == "nous":
  2019. from hermes_cli.anon_auth import FREE_TIER_NOT_SIGNED_IN, is_guest_state
  2020. if is_guest_state(get_provider_auth_state("nous")):
  2021. # Free tier is not a login; there is nothing to log out of and nothing is cleared.
  2022. print(FREE_TIER_NOT_SIGNED_IN)
  2023. return
  2024. should_reset_config = _should_reset_config_provider_on_logout(target)
  2025. provider_name = get_auth_provider_display_name(target)
  2026. if not (clear_provider_auth(target) or should_reset_config):
  2027. print(f"No auth state found for {provider_name}.")
  2028. return
  2029. if target == "nous":
  2030. # A profile logout must not be re-adopted from the cross-profile store on the next boot.
  2031. from hermes_cli.auth_nous import _clear_shared_nous_state
  2032. _clear_shared_nous_state("logout")
  2033. if should_reset_config:
  2034. _reset_config_provider()
  2035. print(f"Logged out of {provider_name}.")
  2036. if not should_reset_config:
  2037. print("Model provider configuration was unchanged.")
  2038. elif os.getenv("OPENROUTER_API_KEY"):
  2039. print("Hermes will use OpenRouter for inference.")
  2040. else:
  2041. print("Run `hermes model` or configure an API key to use Hermes.")