auth_commands.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. """Credential-pool auth subcommands."""
  2. from __future__ import annotations
  3. from pm import install_hint
  4. from hermes_cli.cli_output import line_input
  5. import math
  6. import sys
  7. import time
  8. from dataclasses import dataclass
  9. from types import SimpleNamespace
  10. from typing import Any, Callable
  11. import uuid
  12. from agent.credential_pool import (
  13. AUTH_TYPE_API_KEY, AUTH_TYPE_OAUTH, CUSTOM_POOL_PREFIX, SOURCE_MANUAL,
  14. SOURCE_MANUAL_DEVICE_CODE, STATUS_EXHAUSTED, STRATEGY_FILL_FIRST, STRATEGY_ROUND_ROBIN,
  15. STRATEGY_RANDOM, STRATEGY_LEAST_USED, PooledCredential, _codex_principal_identity,
  16. _exhausted_until, _normalize_custom_pool_name, get_pool_strategy, label_from_token, list_custom_pool_providers,
  17. load_pool)
  18. from agent.credential_pool_admin import CredentialNotSavedError
  19. import hermes_cli.auth as auth_mod
  20. from hermes_cli.auth import PROVIDER_REGISTRY
  21. from hermes_cli.auth_plugin_providers import (
  22. canonical_registry_rows, dispatch_plugin_auth, is_refreshable_oauth_provider, plugin_missing_auth_handler_error)
  23. from hermes_constants import OPENROUTER_BASE_URL
  24. from hermes_cli.secret_prompt import masked_secret_prompt
  25. # Providers that support OAuth login in addition to API keys.
  26. _OAUTH_CAPABLE_PROVIDERS = {"anthropic", "nous", "openai-codex", "xai-oauth", "qwen-oauth", "minimax-oauth", "openrouter"}
  27. # ...and default to it when ``--type`` is omitted. OpenRouter stays API-key-first: the documented
  28. # ``hermes auth add openrouter --api-key sk-or-...`` must keep working with no ``--type``.
  29. _OAUTH_DEFAULT_PROVIDERS = _OAUTH_CAPABLE_PROVIDERS - {"openrouter"}
  30. # Providers whose sibling CLI login Hermes may borrow (``auth.adopt_external_logins``).
  31. EXTERNAL_LOGIN_PROVIDERS = {"anthropic", "openai-codex"}
  32. def _get_custom_provider_entries() -> list[dict]:
  33. """Return configured provider entries with legacy and canonical pool IDs."""
  34. try:
  35. from hermes_cli.config import get_compatible_custom_providers, load_config
  36. config = load_config()
  37. except Exception:
  38. return []
  39. result: list[dict] = []
  40. for entry in get_compatible_custom_providers(config):
  41. name = entry.get("name") if isinstance(entry, dict) else None
  42. if isinstance(name, str) and name.strip():
  43. result.append({
  44. **entry, "name": name.strip(),
  45. "pool_key": f"{CUSTOM_POOL_PREFIX}{_normalize_custom_pool_name(name)}",
  46. "provider_key": str(entry.get("provider_key", "") or "").strip()})
  47. return result
  48. def _configured_provider_entry(provider: str) -> dict | None:
  49. """Resolve a canonical ``providers.<key>`` entry."""
  50. normalized = (provider or "").strip().lower()
  51. if not normalized or normalized.startswith(CUSTOM_POOL_PREFIX):
  52. return None
  53. return next((e for e in _get_custom_provider_entries() if e["provider_key"].lower() == normalized), None)
  54. def _resolve_custom_provider_input(raw: str) -> str | None:
  55. """Resolve legacy names and keyed providers to their credential-pool ID."""
  56. normalized = (raw or "").strip().lower().replace(" ", "-")
  57. if not normalized:
  58. return None
  59. if normalized.startswith(CUSTOM_POOL_PREFIX):
  60. return normalized
  61. for entry in _get_custom_provider_entries():
  62. # ``providers:`` entries already have a durable runtime slug; keep credentials under it
  63. # instead of leaking the legacy ``custom:`` identity into auth.json and discovery.
  64. provider_key = entry["provider_key"].lower()
  65. if provider_key and provider_key == normalized:
  66. return provider_key
  67. if _normalize_custom_pool_name(entry["name"]) == normalized:
  68. return provider_key or entry["pool_key"]
  69. return None
  70. _PROVIDER_ALIASES = {
  71. "or": "openrouter", "open-router": "openrouter", "grok-oauth": "xai-oauth",
  72. "xai-oauth": "xai-oauth", "x-ai-oauth": "xai-oauth", "xai-grok-oauth": "xai-oauth"}
  73. def _normalize_provider(provider: str) -> str:
  74. normalized = (provider or "").strip().lower()
  75. return (_PROVIDER_ALIASES.get(normalized) or _resolve_custom_provider_input(normalized)
  76. or auth_mod._plugin_aliases().get(normalized) or normalized)
  77. def _migrate_legacy_custom_pool_key(provider: str, legacy_key: str) -> None:
  78. """Move a keyed provider's old ``custom:`` pool into its runtime slug."""
  79. with auth_mod._auth_store_lock():
  80. auth_store = auth_mod._load_auth_store()
  81. credential_pool = auth_store.get("credential_pool")
  82. if not isinstance(credential_pool, dict):
  83. return
  84. legacy_entries = credential_pool.get(legacy_key)
  85. if not isinstance(legacy_entries, list) or not legacy_entries:
  86. return
  87. current_entries = credential_pool.get(provider)
  88. merged = list(current_entries) if isinstance(current_entries, list) else []
  89. known_ids = {e.get("id") for e in merged if isinstance(e, dict) and e.get("id")}
  90. for entry in legacy_entries:
  91. entry_id = entry.get("id") if isinstance(entry, dict) else None
  92. if not entry_id or entry_id not in known_ids:
  93. merged.append(entry)
  94. if entry_id:
  95. known_ids.add(entry_id)
  96. credential_pool[provider] = merged
  97. del credential_pool[legacy_key]
  98. auth_mod._save_auth_store(auth_store)
  99. try:
  100. from hermes_cli.models import clear_provider_models_cache
  101. clear_provider_models_cache(legacy_key)
  102. except Exception:
  103. pass
  104. def _provider_base_url(provider: str) -> str:
  105. if provider == "openrouter":
  106. return OPENROUTER_BASE_URL
  107. if provider.startswith(CUSTOM_POOL_PREFIX):
  108. from agent.credential_pool import _get_custom_provider_config
  109. return str((_get_custom_provider_config(provider) or {}).get("base_url") or "").strip()
  110. configured = _configured_provider_entry(provider)
  111. if configured is not None:
  112. return str(configured.get("base_url") or "").strip()
  113. pconfig = PROVIDER_REGISTRY.get(provider)
  114. return pconfig.inference_base_url if pconfig else ""
  115. def _is_known_provider(provider: str, configured_provider: dict | None) -> bool:
  116. return (provider in PROVIDER_REGISTRY or provider == "openrouter"
  117. or provider.startswith(CUSTOM_POOL_PREFIX) or configured_provider is not None)
  118. def _unknown_provider_exit(provider: str) -> SystemExit:
  119. """Did-you-mean over the known provider ids plus the two commands that list/pick them."""
  120. import difflib
  121. known = sorted({pid for pid, _ in canonical_registry_rows()} | {"openrouter"}
  122. | {entry["name"] for entry in _get_custom_provider_entries()})
  123. from hermes_cli.left_core_migration import provider_install_hint
  124. if moved := provider_install_hint(provider):
  125. return SystemExit(f"Unknown provider '{provider}'. {moved}")
  126. close = difflib.get_close_matches(provider, known, n=3, cutoff=0.5)
  127. hint = f" Did you mean {', '.join(close)}?" if close else ""
  128. return SystemExit(
  129. f"Unknown provider '{provider}'.{hint} Run `hermes auth` to see the provider list, or "
  130. "`hermes model` to pick one interactively.")
  131. def _display_source(source: str) -> str:
  132. return source.split(":", 1)[1] if source.startswith("manual:") else source
  133. # (label, show_retry_window, http codes, reason substrings, message substrings) — first match wins.
  134. _EXHAUSTED_CLASSES = (
  135. ("rate-limited", True, {429},
  136. ("rate_limit", "usage_limit", "quota", "exhausted"),
  137. ("rate limit", "usage limit", "quota", "too many requests")),
  138. ("auth failed", False, {401, 403},
  139. ("invalid_token", "invalid_grant", "unauthorized", "forbidden", "auth"),
  140. ("unauthorized", "forbidden", "expired", "revoked", "invalid token", "authentication")))
  141. def _classify_exhausted_status(entry) -> tuple[str, bool]:
  142. code = getattr(entry, "last_error_code", None)
  143. reason = str(getattr(entry, "last_error_reason", "") or "").strip().lower()
  144. message = str(getattr(entry, "last_error_message", "") or "").strip().lower()
  145. for label, retry_window, codes, reason_tokens, message_tokens in _EXHAUSTED_CLASSES:
  146. if (code in codes or any(t in reason for t in reason_tokens)
  147. or any(t in message for t in message_tokens)):
  148. return label, retry_window
  149. return "exhausted", True
  150. def _format_exhausted_status(entry) -> str:
  151. if entry.last_status != STATUS_EXHAUSTED:
  152. return ""
  153. label, show_retry_window = _classify_exhausted_status(entry)
  154. reason = getattr(entry, "last_error_reason", None)
  155. reason_text = f" {reason}" if isinstance(reason, str) and reason.strip() else ""
  156. code = f" ({entry.last_error_code})" if entry.last_error_code else ""
  157. head = f" {label}{reason_text}{code}"
  158. if not show_retry_window:
  159. return f"{head} (re-auth may be required)"
  160. exhausted_until = _exhausted_until(entry)
  161. if exhausted_until is None:
  162. return head
  163. remaining = max(0, math.ceil(exhausted_until - time.time()))
  164. if remaining <= 0:
  165. return f"{head} (ready to retry)"
  166. minutes, seconds = divmod(remaining, 60)
  167. hours, minutes = divmod(minutes, 60)
  168. days, hours = divmod(hours, 24)
  169. parts = [(days, "d"), (hours, "h"), (minutes, "m"), (seconds, "s")]
  170. first = next(i for i, (value, _) in enumerate(parts) if value or i == 3)
  171. wait = " ".join(f"{value}{unit}" for value, unit in parts[first:first + 2])
  172. return f"{head} ({wait} left)"
  173. def _anthropic_oauth_login(args) -> dict:
  174. from agent import anthropic_credentials as anthropic_mod
  175. creds = anthropic_mod.run_hermes_oauth_login_pure()
  176. if not creds:
  177. raise SystemExit("Anthropic OAuth login did not return credentials.")
  178. return creds
  179. def _qwen_oauth_login(args) -> dict:
  180. from hermes_cli.auth_qwen import _mark_qwen_oauth_active
  181. creds = auth_mod.resolve_qwen_runtime_credentials(refresh_if_expiring=False)
  182. _mark_qwen_oauth_active(creds)
  183. return creds
  184. @dataclass(frozen=True)
  185. class _OAuthAddSpec:
  186. """Per-provider parameters for the generic ``hermes auth add <provider> --type oauth`` path."""
  187. login: Callable[[Any], dict]
  188. token: Callable[[dict], str]
  189. # Pool ``source`` string, or a callable deriving it from the login result when one provider
  190. # offers several flows (Codex: device code vs browser PKCE).
  191. source: str | Callable[[dict], str]
  192. fields: Callable[[dict, str], dict]
  193. activate_first: bool = False
  194. # OpenRouter's PKCE exchange mints a plain API key (no refresh pair), so its pool entry is an
  195. # ``api_key`` row that happens to come from a browser login.
  196. auth_type: str = AUTH_TYPE_OAUTH
  197. def _codex_login(args) -> dict:
  198. from hermes_cli.auth_codex_browser import codex_oauth_login
  199. return codex_oauth_login(args)
  200. def _codex_pool_source(creds: dict) -> str:
  201. if creds.get("source") == "loopback_pkce":
  202. return f"{SOURCE_MANUAL}:loopback_pkce"
  203. return SOURCE_MANUAL_DEVICE_CODE
  204. _OAUTH_ADD_SPECS: dict[str, _OAuthAddSpec] = {
  205. "anthropic": _OAuthAddSpec(
  206. login=_anthropic_oauth_login,
  207. token=lambda creds: creds["access_token"],
  208. source=f"{SOURCE_MANUAL}:hermes_pkce",
  209. fields=lambda creds, provider: {
  210. "refresh_token": creds.get("refresh_token"),
  211. "expires_at_ms": creds.get("expires_at_ms"),
  212. "base_url": _provider_base_url(provider)}),
  213. "openai-codex": _OAuthAddSpec(
  214. login=_codex_login,
  215. token=lambda creds: creds["tokens"]["access_token"],
  216. source=_codex_pool_source,
  217. fields=lambda creds, provider: {
  218. "refresh_token": creds["tokens"].get("refresh_token"),
  219. "base_url": creds.get("base_url"),
  220. "last_refresh": creds.get("last_refresh")},
  221. activate_first=True),
  222. "xai-oauth": _OAuthAddSpec(
  223. login=lambda args: auth_mod._xai_oauth_device_code_login(
  224. timeout_seconds=getattr(args, "timeout", None) or 20.0,
  225. open_browser=not getattr(args, "no_browser", False)),
  226. token=lambda creds: creds["tokens"]["access_token"],
  227. source=SOURCE_MANUAL_DEVICE_CODE,
  228. fields=lambda creds, provider: {
  229. "refresh_token": creds["tokens"].get("refresh_token"),
  230. "base_url": creds.get("base_url") or auth_mod.DEFAULT_XAI_OAUTH_BASE_URL,
  231. "last_refresh": creds.get("last_refresh")},
  232. activate_first=True),
  233. "qwen-oauth": _OAuthAddSpec(
  234. login=_qwen_oauth_login,
  235. token=lambda creds: creds["api_key"],
  236. source=f"{SOURCE_MANUAL}:qwen_cli",
  237. fields=lambda creds, provider: {"base_url": creds.get("base_url")}),
  238. "minimax-oauth": _OAuthAddSpec(
  239. login=lambda args: auth_mod._minimax_oauth_login(
  240. open_browser=not getattr(args, "no_browser", False),
  241. timeout_seconds=getattr(args, "timeout", None) or 15.0),
  242. token=lambda creds: creds["access_token"],
  243. source=f"{SOURCE_MANUAL}:minimax_oauth",
  244. fields=lambda creds, provider: {
  245. "refresh_token": creds.get("refresh_token"), "base_url": creds.get("inference_base_url")}),
  246. "openrouter": _OAuthAddSpec(
  247. login=lambda args: auth_mod._openrouter_pkce_login(
  248. open_browser=not getattr(args, "no_browser", False),
  249. timeout_seconds=float(getattr(args, "timeout", None) or 300.0)),
  250. token=lambda creds: creds["api_key"],
  251. source=f"{SOURCE_MANUAL}:openrouter_pkce",
  252. fields=lambda creds, provider: {"base_url": _provider_base_url(provider)},
  253. auth_type=AUTH_TYPE_API_KEY),
  254. }
  255. def _ask(prompt: str, reader: Callable[[str], str] | None = None) -> str | None:
  256. """Stripped answer from *reader* (default ``input``); None when the user hits EOF / Ctrl-C."""
  257. try:
  258. return (reader or input)(prompt).strip()
  259. except (EOFError, KeyboardInterrupt):
  260. return None
  261. def _add_nous_oauth_credential(args, provider: str) -> PooledCredential:
  262. """``hermes auth add nous --type oauth``: shared-credential import, else device-code login."""
  263. custom_label = (getattr(args, "label", None) or "").strip() or None
  264. timeout = getattr(args, "timeout", None) or 15.0
  265. def _persist(creds: dict, what: str) -> PooledCredential:
  266. # `--label` is embedded into providers.nous so label_from_token doesn't overwrite it on every
  267. # subsequent load_pool("nous").
  268. from hermes_cli.anon_auth import settle_after_upgrade
  269. from hermes_cli.guest_handoff import drain, result_lines
  270. entry = auth_mod.persist_nous_credentials(creds, label=custom_label)
  271. handoff = drain() # a replaced free tier hands its apps over once the save lands
  272. settle_after_upgrade(creds) # a config left on the free tier's route moves to the account
  273. shown_label = entry.label if entry is not None else label_from_token(
  274. creds.get("access_token", ""), f"{provider}-oauth-1")
  275. print(f'{what} {provider} OAuth {"device-code " if what == "Saved" else ""}credentials: "{shown_label}"')
  276. for line in (line for view in handoff for line in result_lines(view)):
  277. print(f" {line}")
  278. return entry
  279. # Codex-style auto-import: a shared Nous credential at <hermes-root>/shared/nous_auth.json
  280. # (written by any previous login) makes `hermes --profile <name> auth add nous --type oauth`
  281. # a one-tap operation for multi-profile users.
  282. from hermes_cli.anon_auth import is_guest_state
  283. if (shared := auth_mod._read_shared_nous_state()) and not is_guest_state(shared):
  284. try:
  285. found = f"Found existing Nous OAuth credentials at {auth_mod._nous_shared_store_path()}"
  286. except RuntimeError:
  287. found = "Found existing shared Nous OAuth credentials"
  288. print()
  289. print(found)
  290. do_import = _ask("Import these credentials? [Y/n]: ")
  291. if do_import is None or do_import.lower() in {"", "y", "yes"}:
  292. print("Rehydrating Nous session from shared credentials...")
  293. rehydrated = auth_mod._try_import_shared_nous_state(timeout_seconds=timeout)
  294. if rehydrated is not None:
  295. return _persist(rehydrated, "Imported")
  296. # Expired refresh_token, portal down, etc. — fall through to device-code.
  297. print("Could not refresh shared credentials — falling back to device-code login.")
  298. creds = auth_mod._nous_device_code_login(
  299. portal_base_url=getattr(args, "portal_url", None),
  300. inference_base_url=getattr(args, "inference_url", None),
  301. client_id=getattr(args, "client_id", None), scope=getattr(args, "scope", None),
  302. open_browser=not getattr(args, "no_browser", False), timeout_seconds=timeout,
  303. insecure=bool(getattr(args, "insecure", False)), ca_bundle=getattr(args, "ca_bundle", None))
  304. return _persist(creds, "Saved")
  305. def _unsuppress_provider_sources(provider: str) -> None:
  306. """Clear ALL suppressions for this provider — re-adding a credential is a strong signal the
  307. user wants auth re-enabled. Covers env:* (shell-exported vars), provider CLI tokens, claude_code,
  308. qwen-cli, device_code (codex), etc. — one consistent re-engagement pattern."""
  309. try:
  310. suppressed = auth_mod._load_auth_store().get("suppressed_sources", {})
  311. for src in list(suppressed.get(provider, []) or []):
  312. auth_mod.unsuppress_credential_source(provider, src)
  313. except Exception:
  314. pass
  315. def _add_api_key_credential(args, provider: str, pool) -> PooledCredential:
  316. token = ((getattr(args, "api_key", None) or "").strip()
  317. or masked_secret_prompt("Paste your API key: ").strip())
  318. if not token:
  319. raise SystemExit("No API key provided.")
  320. default_label = f"api-key-{len(pool.entries()) + 1}"
  321. label = (getattr(args, "label", None) or "").strip()
  322. if not label and sys.stdin.isatty():
  323. label = line_input(f"Label (optional, default: {default_label}): ").strip()
  324. label = label or default_label
  325. entry = PooledCredential(
  326. provider=provider, id=uuid.uuid4().hex[:6], label=label, auth_type=AUTH_TYPE_API_KEY,
  327. priority=0, source=SOURCE_MANUAL, access_token=token, base_url=_provider_base_url(provider))
  328. entry = pool.add_entry(entry)
  329. print(f'Added {provider} credential #{len(pool.entries())}: "{label}"')
  330. return entry
  331. def auth_add_command(args) -> None:
  332. provider = _normalize_provider(getattr(args, "provider", ""))
  333. if dispatch_plugin_auth("add", args, provider):
  334. return
  335. configured_provider = _configured_provider_entry(provider)
  336. if not _is_known_provider(provider, configured_provider):
  337. raise _unknown_provider_exit(provider)
  338. if (error := plugin_missing_auth_handler_error(provider, "add")) is not None:
  339. raise error
  340. if configured_provider is not None:
  341. _migrate_legacy_custom_pool_key(provider, configured_provider["pool_key"])
  342. is_custom = provider.startswith(CUSTOM_POOL_PREFIX)
  343. requested_type = str(getattr(args, "auth_type", "") or "").strip().lower()
  344. if requested_type == "api-key":
  345. requested_type = AUTH_TYPE_API_KEY
  346. elif not requested_type:
  347. oauth_default = provider in _OAUTH_DEFAULT_PROVIDERS and not is_custom
  348. requested_type = AUTH_TYPE_OAUTH if oauth_default else AUTH_TYPE_API_KEY
  349. pool = load_pool(provider)
  350. if not is_custom:
  351. _unsuppress_provider_sources(provider)
  352. wanted_priority = getattr(args, "priority", None)
  353. try:
  354. entry = _add_credential(args, provider, pool, requested_type)
  355. except auth_mod.AuthError as exc:
  356. # A denied / mismatched / timed-out OAuth login is a user-facing outcome, not a crash.
  357. raise SystemExit(f"Login failed: {auth_mod.format_auth_error(exc)}") from exc
  358. except CredentialNotSavedError as exc:
  359. raise SystemExit(str(exc)) from exc
  360. if wanted_priority is not None:
  361. placed_pool = load_pool(provider)
  362. moved = placed_pool.move_entry(entry.id, int(wanted_priority))
  363. _report_priority(provider, placed_pool, moved, int(wanted_priority), "Placed", "at")
  364. def _add_credential(args, provider: str, pool, requested_type: str) -> PooledCredential:
  365. if requested_type == AUTH_TYPE_API_KEY:
  366. return _add_api_key_credential(args, provider, pool)
  367. if provider == "nous":
  368. return _add_nous_oauth_credential(args, provider)
  369. spec = _OAUTH_ADD_SPECS.get(provider)
  370. if spec is None:
  371. raise SystemExit(f"`hermes auth add {provider}` is not implemented for auth type {requested_type} yet.")
  372. creds = spec.login(args)
  373. token = spec.token(creds)
  374. label = (getattr(args, "label", None) or "").strip() or label_from_token(
  375. token, f"{provider}-oauth-{len(pool.entries()) + 1}")
  376. # Every account gets a distinct, self-contained pool entry instead of routing through a
  377. # singleton save path (which collapsed every added account into the latest login).
  378. # ``manual:*`` entries refresh from their own token pair, so they need no singleton shadow.
  379. entry = PooledCredential(
  380. provider=provider, id=uuid.uuid4().hex[:6], label=label, auth_type=spec.auth_type, priority=0,
  381. source=spec.source(creds) if callable(spec.source) else spec.source,
  382. access_token=token, **spec.fields(creds, provider))
  383. existing = pool.entries()
  384. entry = pool.add_entry(entry)
  385. # The first Codex/xAI credential becomes the active provider (as the old singleton save path
  386. # did implicitly); subsequent adds leave the active provider as-is.
  387. if spec.activate_first and not existing:
  388. auth_mod.mark_provider_active_if_unset(provider)
  389. print(f'Added {provider} OAuth credential #{len(pool.entries())}: "{entry.label}"')
  390. if provider == "openai-codex":
  391. _warn_same_codex_account(token, existing)
  392. return entry
  393. def _warn_same_codex_account(token: str, existing: list[PooledCredential]) -> None:
  394. """Tell the user when a fresh Codex login is the same OpenAI account as a pooled credential.
  395. Two logins of one account share a single token family upstream: the provider revokes the
  396. older grant, so the second credential adds no quota and silently kills the first (#47096).
  397. Only distinct accounts rotate independently — the pool cannot keep both alive.
  398. """
  399. identity = _codex_principal_identity(token)
  400. if identity is None:
  401. return
  402. for position, sibling in enumerate(existing, start=1):
  403. if _codex_principal_identity(sibling.access_token) == identity:
  404. print(f'warning: this login is the same OpenAI account as openai-codex credential #{position} '
  405. f'("{sibling.label}"). Both logins share one token family, so OpenAI will revoke the older one '
  406. "and you gain no extra quota. Log into a different account instead, or keep just one "
  407. f"(`hermes auth remove openai-codex {position}`).", file=sys.stderr)
  408. return
  409. def _report_priority(provider: str, pool, moved, requested: int, verb: str, prep: str) -> None:
  410. """Print the effective priority and say why it differs from the request, if it does."""
  411. print(f'{verb} {provider} credential "{moved.label}" {prep} priority {moved.priority} '
  412. f"(#{moved.priority + 1} in `hermes auth list {provider}`)")
  413. size = len(pool.entries())
  414. if moved.priority != requested:
  415. if requested < 0 or requested >= size:
  416. reason = f"the pool has {size} credentials, so it was clamped"
  417. else:
  418. reason = "anthropic keeps manually added credentials ahead of seeded ones"
  419. print(f"note: requested priority {requested}; effective priority is {moved.priority} "
  420. f"because {reason}.", file=sys.stderr)
  421. strategy = get_pool_strategy(provider)
  422. if strategy != STRATEGY_FILL_FIRST:
  423. print(f"note: {provider} uses the {strategy} strategy; priority only orders "
  424. f"fill_first selection.", file=sys.stderr)
  425. def auth_priority_command(args) -> None:
  426. """`hermes auth priority <provider> <target> <priority>`: reorder one pooled credential."""
  427. provider = _normalize_provider(getattr(args, "provider", ""))
  428. pool = load_pool(provider)
  429. index, matched, error = pool.resolve_target(getattr(args, "target", None))
  430. if matched is None or index is None:
  431. raise SystemExit(f"{error} Provider: {provider}.")
  432. requested = int(args.priority)
  433. moved = pool.move_entry(matched.id, requested)
  434. if moved is None:
  435. raise SystemExit(f'No credential matching "{getattr(args, "target", None)}" for provider {provider}.')
  436. _report_priority(provider, pool, moved, requested, "Set", "to")
  437. def _free_tier_lines() -> tuple[str, str]:
  438. """The two-line free-tier rendering shared by every auth display surface (R-USR-1)."""
  439. from hermes_cli.anon_auth import FREE_TIER_LABEL, GUEST_MODEL, UPGRADE_HINT
  440. return f"{FREE_TIER_LABEL} · {GUEST_MODEL}", UPGRADE_HINT
  441. def _is_free_tier_entry(entry) -> bool:
  442. from hermes_cli.anon_auth import is_guest_state
  443. return is_guest_state(getattr(entry, "extra", None))
  444. def auth_list_command(args) -> None:
  445. provider_filter = _normalize_provider(getattr(args, "provider", "") or "")
  446. if provider_filter:
  447. providers = [provider_filter]
  448. else:
  449. credential_pool = auth_mod._load_auth_store().get("credential_pool")
  450. providers = sorted({
  451. *(pid for pid, _ in canonical_registry_rows()), "openrouter", *list_custom_pool_providers(),
  452. *(e["provider_key"] for e in _get_custom_provider_entries() if e["provider_key"]),
  453. *(credential_pool.keys() if isinstance(credential_pool, dict) else ())})
  454. for provider in providers:
  455. pool = load_pool(provider)
  456. entries = pool.entries()
  457. if not entries:
  458. continue
  459. current = pool.peek()
  460. if provider == "nous" and all(_is_free_tier_entry(e) for e in entries):
  461. # The free tier is not a credential the user added; never list it as one.
  462. label, hint = _free_tier_lines()
  463. print(f"{provider}: {label}")
  464. print(f" {hint}")
  465. print()
  466. continue
  467. print(f"{provider} ({len(entries)} credentials):")
  468. for idx, entry in enumerate(entries, start=1):
  469. marker = "← " if current is not None and entry.id == current.id else " "
  470. status = _format_exhausted_status(entry)
  471. source = _display_source(entry.source)
  472. row = (
  473. f" #{idx} {entry.label:<20} {entry.auth_type:<7} "
  474. f"id={entry.id} priority={entry.priority} {source}{status} {marker}"
  475. )
  476. print(row.rstrip())
  477. print()
  478. if not provider_filter or provider_filter in EXTERNAL_LOGIN_PROVIDERS:
  479. _print_external_login_notice()
  480. def _print_external_login_notice() -> None:
  481. """One line telling the user why no Codex CLI / Claude Code login shows up when adoption is off."""
  482. from agent.credential_sources import EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE, adopt_external_logins_enabled
  483. if not adopt_external_logins_enabled():
  484. print(EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE)
  485. _print_oauth_heal_notices()
  486. def _print_oauth_heal_notices() -> None:
  487. """Tell the user when load_pool() just consolidated a forked OAuth grant."""
  488. for note in auth_mod.consume_oauth_heal_notices():
  489. print(f"note: {note}")
  490. def auth_remove_command(args) -> None:
  491. provider = _normalize_provider(getattr(args, "provider", ""))
  492. target = getattr(args, "target", None)
  493. target = getattr(args, "index", None) if target is None else target
  494. pool = load_pool(provider)
  495. index, matched, error = pool.resolve_target(target)
  496. if matched is None or index is None:
  497. raise SystemExit(f"{error} Provider: {provider}.")
  498. removed = pool.remove_index(index)
  499. if removed is None:
  500. raise SystemExit(f'No credential matching "{target}" for provider {provider}.')
  501. print(f"Removed {provider} credential #{index} ({removed.label})")
  502. # Every credential source Hermes reads from (env vars, external OAuth files, auth.json blocks,
  503. # custom config) has a RemovalStep in agent.credential_sources; it does the source-specific
  504. # cleanup while suppression + user-facing output are centralised here.
  505. from agent.credential_sources import find_removal_step
  506. step = find_removal_step(provider, removed.source)
  507. if step is None: # unregistered source, e.g. "manual": nothing external to clean up
  508. return
  509. result = step.remove_fn(provider, removed)
  510. for line in result.cleaned:
  511. print(line)
  512. if result.suppress:
  513. auth_mod.suppress_credential_source(provider, removed.source)
  514. for line in result.hints:
  515. print(line)
  516. def auth_reset_command(args) -> None:
  517. provider = _normalize_provider(getattr(args, "provider", ""))
  518. target = getattr(args, "target", None)
  519. pool = load_pool(provider)
  520. if target is None or not str(target).strip():
  521. count = pool.reset_statuses()
  522. print(f"Reset status on {count} {provider} credentials")
  523. return
  524. index, matched, error = pool.resolve_target(target)
  525. if matched is None or index is None:
  526. raise SystemExit(f"{error} Provider: {provider}.")
  527. cleared = pool.reset_status(matched.id)
  528. if cleared is None:
  529. raise SystemExit(f'No credential matching "{target}" for provider {provider}.')
  530. print(f"Reset status on {provider} credential #{index} ({cleared.label})")
  531. def auth_refresh_command(args) -> None:
  532. """`hermes auth refresh <provider> [target]`: force one pooled OAuth entry to refresh.
  533. A successful refresh rotates the stored tokens and clears the entry's local
  534. exhaustion block, returning it to rotation before its persisted
  535. ``last_error_reset_at`` elapses. It proves the grant is alive, not that the
  536. provider's quota is back: if the account is still capped, the next request
  537. 429s and benches it again. Failure leaves the pool's own verdict in place.
  538. """
  539. provider = _normalize_provider(getattr(args, "provider", ""))
  540. if dispatch_plugin_auth("refresh", args, provider):
  541. return
  542. target = getattr(args, "target", None)
  543. pool = load_pool(provider)
  544. entries = pool.entries()
  545. if not entries:
  546. raise SystemExit(f"No {provider} credentials in the pool.")
  547. if target is None or not str(target).strip():
  548. if len(entries) != 1:
  549. raise SystemExit(
  550. f"{provider} has {len(entries)} credentials; pass an index, entry id, or exact "
  551. f"label (see `hermes auth list {provider}`).")
  552. index, matched = 1, entries[0]
  553. else:
  554. index, matched, error = pool.resolve_target(target)
  555. if matched is None or index is None:
  556. raise SystemExit(f"{error} Provider: {provider}.")
  557. if (not is_refreshable_oauth_provider(provider) or matched.auth_type != AUTH_TYPE_OAUTH
  558. or not matched.refresh_token):
  559. raise SystemExit(
  560. f"{provider} credential #{index} ({matched.label}) is not a refreshable OAuth "
  561. f"credential.")
  562. # Nous's resolver is singleton-bound, not an independent-account refresher.
  563. if provider == "nous" and matched.source != "device_code":
  564. raise SystemExit(
  565. f"nous credential #{index} ({matched.label}) is not a refreshable OAuth "
  566. "credential: only the device_code singleton supports refresh. "
  567. "Reauthenticate with `hermes auth add nous --type oauth`.")
  568. refreshed = pool.try_refresh_matching(credential_id=matched.id)
  569. if refreshed is None:
  570. after = next((e for e in pool.entries() if e.id == matched.id), None)
  571. label = PROVIDER_REGISTRY[provider].name if provider in PROVIDER_REGISTRY else provider
  572. state = ("it was removed from the pool" if after is None
  573. else "the saved session is no longer valid")
  574. raise SystemExit(
  575. f"Could not renew the {label} sign-in for credential #{index} ({matched.label}); {state}. "
  576. f"Sign in again with `hermes auth add {provider} --type oauth`.")
  577. status = refreshed.last_status or "ok"
  578. if status == "ok":
  579. print(f"Refreshed {provider} credential #{index} ({refreshed.label}); status: ok")
  580. else:
  581. # A peer already rotated this grant and the pool adopted it without clearing status.
  582. print(f"Adopted current tokens for {provider} credential #{index} ({refreshed.label}); "
  583. f"status still: {status}")
  584. def _moved_auth_hint(action: str, provider: str) -> str:
  585. """``hermes auth status|logout spotify`` after Spotify left core for its plugin's own command."""
  586. from hermes_cli.left_core_migration import moved_command_hint
  587. return moved_command_hint("hermes auth", provider, action)
  588. def auth_status_command(args) -> None:
  589. provider = _normalize_provider(getattr(args, "provider", "") or "")
  590. if not provider:
  591. raise SystemExit("Provider is required. Example: `hermes auth status nous`.")
  592. if dispatch_plugin_auth("status", args, provider):
  593. return
  594. if moved := _moved_auth_hint("status", provider):
  595. raise SystemExit(moved)
  596. if provider in auth_mod.SINGLE_USE_REFRESH_POOL_PROVIDERS:
  597. load_pool(provider) # runs the forked-grant heal first so the report reflects the consolidated grant
  598. status = auth_mod.get_auth_status(provider)
  599. _print_oauth_heal_notices()
  600. if status.get("free_tier"):
  601. # Free tier: not an account login, so no account fields; point at the upgrade path.
  602. label, hint = _free_tier_lines()
  603. print(f"{provider}: {label}")
  604. print(f" {hint}")
  605. return
  606. if not status.get("logged_in"):
  607. reason = status.get("error")
  608. print(f"{provider}: logged out" + (f" ({reason})" if reason else ""))
  609. if provider in EXTERNAL_LOGIN_PROVIDERS:
  610. _print_external_login_notice()
  611. return
  612. print(f"{provider}: logged in")
  613. for key in ("auth_type", "client_id", "redirect_uri", "scope", "expires_at", "api_base_url"):
  614. value = status.get(key)
  615. if value:
  616. print(f" {key}: {value}")
  617. if provider == "nous":
  618. from hermes_cli.guest_handoff import drain, handoff_status, status_lines
  619. drain() # a move left retrying gets its next try now
  620. for line in status_lines(handoff_status()):
  621. print(f" {line}")
  622. def auth_logout_command(args) -> None:
  623. # The built-in path keeps receiving the raw provider id (byte-for-byte
  624. # unchanged); the normalized alias is used only for the handler lookup.
  625. raw_provider = getattr(args, "provider", None)
  626. if dispatch_plugin_auth("logout", args, _normalize_provider(raw_provider or "")):
  627. return
  628. if moved := _moved_auth_hint("logout", _normalize_provider(raw_provider or "")):
  629. raise SystemExit(moved)
  630. auth_mod.logout_command(SimpleNamespace(provider=raw_provider))
  631. def _print_bedrock_status() -> None:
  632. """Show AWS Bedrock credential status (not in the pool — uses boto3 chain)."""
  633. try:
  634. from agent.bedrock_adapter import has_aws_credentials, resolve_aws_auth_env_var, resolve_bedrock_region
  635. if not has_aws_credentials():
  636. return
  637. region = resolve_bedrock_region()
  638. print("bedrock (AWS SDK credential chain):")
  639. print(f" Auth: {resolve_aws_auth_env_var() or 'unknown'}")
  640. print(f" Region: {region}")
  641. try:
  642. import boto3
  643. arn = boto3.client("sts", region_name=region).get_caller_identity().get("Arn", "unknown")
  644. print(f" Identity: {arn}")
  645. except Exception:
  646. print(" Identity: (could not resolve — boto3 STS call failed)")
  647. print()
  648. except ImportError:
  649. pass # boto3 or bedrock_adapter not available
  650. def _print_azure_entra_status() -> None:
  651. """Show Azure Foundry Entra ID status when model.provider is azure-foundry with entra_id auth."""
  652. try:
  653. from hermes_cli.config import load_config
  654. cfg = load_config()
  655. model_cfg = cfg.get("model") if isinstance(cfg, dict) else None
  656. if not isinstance(model_cfg, dict) or (
  657. str(model_cfg.get("provider") or "").strip().lower() != "azure-foundry"
  658. or str(model_cfg.get("auth_mode") or "").strip().lower() != "entra_id"):
  659. return
  660. from agent.azure_identity_adapter import (
  661. EntraIdentityConfig, SCOPE_AI_AZURE_DEFAULT, describe_active_credential, has_azure_identity_installed,
  662. )
  663. base_url = str(model_cfg.get("base_url") or "").strip()
  664. entra = model_cfg.get("entra") or {}
  665. scope = (str(entra.get("scope") or "").strip() if isinstance(entra, dict) else "") or SCOPE_AI_AZURE_DEFAULT
  666. print("azure-foundry (Microsoft Entra ID):")
  667. print(f" Endpoint: {base_url or '(not configured)'}")
  668. print(f" Scope: {scope}")
  669. if not has_azure_identity_installed():
  670. print(" Status: ⚠ azure-identity not installed")
  671. print(" From the Hermes environment, run: "
  672. f"{install_hint('azure-identity')}")
  673. print(" Then restart Hermes.")
  674. else:
  675. info = describe_active_credential(config=EntraIdentityConfig(scope=scope), timeout_seconds=10.0)
  676. env_sources = info.get("env_sources") or []
  677. if info.get("ok"):
  678. print(f" Status: ✓ token acquired ({', '.join(env_sources) if env_sources else 'default chain'})")
  679. else:
  680. print(f" Status: ⚠ {info.get('error') or 'credential chain exhausted'}")
  681. if info.get("hint"):
  682. print(f" Hint: {info['hint']}")
  683. print()
  684. except Exception:
  685. pass
  686. def _interactive_auth() -> None:
  687. """Interactive credential pool management when `hermes auth` is called bare."""
  688. print("Credential Pool Status")
  689. print("=" * 50)
  690. auth_list_command(SimpleNamespace(provider=None))
  691. _print_bedrock_status()
  692. _print_azure_entra_status()
  693. print()
  694. choices = [
  695. "Add a credential", "Remove a credential", "Reset cooldowns for a provider",
  696. "Set rotation strategy for a provider", "Exit"]
  697. print("What would you like to do?")
  698. for i, choice in enumerate(choices, 1):
  699. print(f" {i}. {choice}")
  700. raw = _ask("\nChoice: ")
  701. handler = {"1": _interactive_add, "2": _interactive_remove, "3": _interactive_reset,
  702. "4": _interactive_strategy}.get(raw)
  703. if handler is not None:
  704. handler()
  705. def _pick_provider(prompt: str = "Provider") -> str:
  706. """Prompt for a provider name with auto-complete hints."""
  707. from providers import unlisted_provider_names
  708. known = sorted(({pid for pid, _ in canonical_registry_rows()} - unlisted_provider_names()) | {"openrouter"})
  709. custom_display = [entry["name"] for entry in _get_custom_provider_entries()]
  710. print(f"\nKnown providers: {', '.join(known)}")
  711. if custom_display:
  712. print(f"Custom endpoints: {', '.join(custom_display)}")
  713. raw = _ask(f"{prompt}: ", line_input)
  714. if raw is None:
  715. raise SystemExit()
  716. return _normalize_provider(raw)
  717. def _interactive_add() -> None:
  718. provider = _pick_provider("Provider to add credential for")
  719. if dispatch_plugin_auth("add", SimpleNamespace(provider=provider), provider):
  720. return
  721. configured_provider = _configured_provider_entry(provider)
  722. if not _is_known_provider(provider, configured_provider):
  723. raise _unknown_provider_exit(provider)
  724. if (error := plugin_missing_auth_handler_error(provider, "add")) is not None:
  725. raise error
  726. auth_type = "api_key"
  727. if provider in _OAUTH_CAPABLE_PROVIDERS:
  728. print(f"\n{provider} supports both API keys and OAuth login.")
  729. print(" 1. API key (paste a key from the provider dashboard)")
  730. print(" 2. OAuth login (authenticate via browser)")
  731. type_choice = _ask("Type [1/2]: ")
  732. if type_choice is None:
  733. return
  734. if type_choice == "2":
  735. auth_type = "oauth"
  736. label = _ask("Label / account name (optional): ", line_input)
  737. if label is None:
  738. return
  739. auth_add_command(SimpleNamespace(
  740. provider=provider, auth_type=auth_type, label=label or None, api_key=None,
  741. portal_url=None, inference_url=None, client_id=None, scope=None,
  742. no_browser=False, timeout=None, insecure=False, ca_bundle=None))
  743. def _interactive_remove() -> None:
  744. provider = _pick_provider("Provider to remove credential from")
  745. pool = load_pool(provider)
  746. if not pool.has_credentials():
  747. print(f"No credentials for {provider}.")
  748. return
  749. for i, e in enumerate(pool.entries(), 1):
  750. print(f" #{i} {e.label:25s} {e.auth_type:10s} {e.source}{_format_exhausted_status(e)} [id:{e.id}]")
  751. raw = _ask("Remove #, id, or label (blank to cancel): ", line_input)
  752. if raw:
  753. auth_remove_command(SimpleNamespace(provider=provider, target=raw))
  754. def _interactive_reset() -> None:
  755. auth_reset_command(SimpleNamespace(provider=_pick_provider("Provider to reset cooldowns for")))
  756. _STRATEGY_DESCRIPTIONS = {
  757. STRATEGY_FILL_FIRST: "Use first key until exhausted, then next",
  758. STRATEGY_ROUND_ROBIN: "Cycle through keys evenly",
  759. STRATEGY_LEAST_USED: "Always pick the least-used key",
  760. STRATEGY_RANDOM: "Random selection"}
  761. def _interactive_strategy() -> None:
  762. provider = _pick_provider("Provider to set strategy for")
  763. current = get_pool_strategy(provider)
  764. strategies = list(_STRATEGY_DESCRIPTIONS)
  765. print(f"\nCurrent strategy for {provider}: {current}")
  766. print()
  767. for i, s in enumerate(strategies, 1):
  768. print(f" {i}. {s:15s} — {_STRATEGY_DESCRIPTIONS[s]}{' ←' if s == current else ''}")
  769. raw = _ask("\nStrategy [1-4]: ")
  770. if not raw:
  771. return
  772. try:
  773. strategy = strategies[int(raw) - 1]
  774. except (ValueError, IndexError):
  775. print("Invalid choice.")
  776. return
  777. from hermes_cli.config import load_config, save_config
  778. cfg = load_config()
  779. pool_strategies = cfg.get("credential_pool_strategies")
  780. if not isinstance(pool_strategies, dict):
  781. pool_strategies = {}
  782. pool_strategies[provider] = strategy
  783. cfg["credential_pool_strategies"] = pool_strategies
  784. save_config(cfg)
  785. print(f"Set {provider} strategy to: {strategy}")
  786. def auth_upgrade_command(args) -> None:
  787. """``hermes auth upgrade``: sign the free tier into a Nous account, keeping its connectors."""
  788. from hermes_cli.anon_auth import upgrade_guest
  789. code = upgrade_guest(args)
  790. if code:
  791. raise SystemExit(code)
  792. _AUTH_ACTIONS = {
  793. "add": auth_add_command, "list": auth_list_command, "remove": auth_remove_command,
  794. "reset": auth_reset_command, "priority": auth_priority_command, "refresh": auth_refresh_command, "status": auth_status_command,
  795. "logout": auth_logout_command, "upgrade": auth_upgrade_command}
  796. def auth_command(args) -> None:
  797. handler = _AUTH_ACTIONS.get(getattr(args, "auth_action", ""))
  798. if handler is not None:
  799. handler(args)
  800. else:
  801. _interactive_auth() # no subcommand