status_auth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. """Credential sections of `hermes status`, run through ``status._SECTIONS`` with its shared context.
  2. Origin helpers (``_row``, ``_first_env_value``, ...) are resolved through the ``hermes_cli.status``
  3. module object so tests that monkeypatch that module keep working."""
  4. from datetime import datetime, timezone, UTC
  5. from hermes_cli.auth import AuthError
  6. from hermes_cli.nous_account import (
  7. format_nous_portal_entitlement_message, get_nous_portal_account_info)
  8. from hermes_cli.nous_subscription import get_nous_subscription_features
  9. from tools.tool_backend_helpers import managed_nous_tools_enabled
  10. from hermes_cli import config
  11. from hermes_time import safe_strftime
  12. def _format_iso_timestamp(value) -> str:
  13. """Format ISO timestamps for status output, converting to local timezone."""
  14. text = value.strip() if isinstance(value, str) else ""
  15. if not text:
  16. return "(unknown)"
  17. try:
  18. parsed = datetime.fromisoformat(text[:-1] + "+00:00" if text.endswith("Z") else text)
  19. except Exception:
  20. return value
  21. if parsed.tzinfo is None:
  22. parsed = parsed.replace(tzinfo=UTC)
  23. return safe_strftime(parsed.astimezone(), "%Y-%m-%d %H:%M:%S %Z")
  24. def _qwen_expiry(expires_at_ms) -> str:
  25. return datetime.fromtimestamp(int(expires_at_ms) / 1000, tz=UTC).isoformat()
  26. def _oauth_block(name: str, status: dict, hint: str, rows) -> None:
  27. """Print an OAuth provider row plus its conditional detail lines.
  28. ``rows`` are ``(label, status_key, formatter, gate)``: a detail prints when the raw value is
  29. truthy and ``gate`` is None or equals the logged-in state (False = only while logged out).
  30. """
  31. logged_in = bool(status.get("logged_in"))
  32. _status._row(name, logged_in, "logged in" if logged_in else f"not logged in (run: {hint})")
  33. for label, key, fmt, gate in rows:
  34. raw = status.get(key)
  35. if raw and (gate is None or gate == logged_in):
  36. _status._detail(label, fmt(raw) if fmt else raw)
  37. # Values may be a single env var name (str) or a tuple of alternates (first found wins).
  38. _API_KEYS: dict[str, str | tuple[str, ...]] = {
  39. "OpenRouter": "OPENROUTER_API_KEY", "OpenAI": "OPENAI_API_KEY",
  40. "Google / Gemini": ("GOOGLE_API_KEY", "GEMINI_API_KEY"), "DeepSeek": "DEEPSEEK_API_KEY",
  41. "xAI / Grok": "XAI_API_KEY", "NVIDIA NIM": "NVIDIA_API_KEY", "Z.AI / GLM": "GLM_API_KEY",
  42. "Kimi": "KIMI_API_KEY", "StepFun Step Plan": "STEPFUN_API_KEY", "MiniMax": "MINIMAX_API_KEY",
  43. "MiniMax-CN": "MINIMAX_CN_API_KEY", "DeepInfra": "DEEPINFRA_API_KEY", "Firecrawl": "FIRECRAWL_API_KEY",
  44. "Tavily": "TAVILY_API_KEY", "Perplexity": "PERPLEXITY_API_KEY", "Keenable": "KEENABLE_API_KEY",
  45. "Browser Use": "BROWSER_USE_API_KEY", # Optional — local browser works without this
  46. "Browserbase": "BROWSERBASE_API_KEY", # Optional — direct credentials only
  47. "FAL": "FAL_KEY", "ElevenLabs": "ELEVENLABS_API_KEY", "GitHub": "GITHUB_TOKEN"}
  48. # OAuth detail rows: (label, status key, formatter, gate) — see _oauth_block.
  49. _FILE_REFRESH_ROWS = (
  50. ("Auth file:", "auth_store", None, None),
  51. ("Refreshed:", "last_refresh", _format_iso_timestamp, None), ("Error:", "error", None, False))
  52. _OAUTH_BLOCKS = (
  53. # (row name, auth getter, login hint, detail rows)
  54. ("OpenAI Codex", "get_codex_auth_status", "hermes model", _FILE_REFRESH_ROWS),
  55. ("Qwen OAuth", "get_qwen_auth_status", "qwen auth qwen-oauth", (
  56. ("Auth file:", "auth_file", None, None),
  57. ("Access exp:", "expires_at_ms", _qwen_expiry, None),
  58. ("Error:", "error", None, False))),
  59. ("MiniMax OAuth", "get_minimax_oauth_auth_status", "hermes auth add minimax-oauth", (
  60. ("Region:", "region", None, True),
  61. ("Access exp:", "expires_at", None, None),
  62. ("Error:", "error", None, False))),
  63. ("xAI OAuth", "get_xai_oauth_auth_status", "hermes auth add xai-oauth", _FILE_REFRESH_ROWS))
  64. _APIKEY_PROVIDERS = {
  65. "Z.AI / GLM": ("GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"), "Kimi / Moonshot": ("KIMI_API_KEY",),
  66. "StepFun Step Plan": ("STEPFUN_API_KEY",), "MiniMax": ("MINIMAX_API_KEY",),
  67. "MiniMax (China)": ("MINIMAX_CN_API_KEY",), "DeepInfra": ("DEEPINFRA_API_KEY",)}
  68. # Nous Tool Gateway per-feature state: first matching (predicate(feature, nous_auth), text(feature)).
  69. _FEATURE_STATES = (
  70. (lambda f, _: f.managed_by_nous, lambda f: "active via Nous subscription"),
  71. (lambda f, _: f.active, lambda f: f"active via {f.current_provider or 'configured provider'}"),
  72. (lambda f, auth: f.included_by_default and auth, lambda f: "included by subscription, not currently selected"),
  73. (lambda f, auth: f.key == "modal" and auth, lambda f: "available via subscription (optional)"))
  74. def _render_api_keys(ctx):
  75. _status._section("API Keys")
  76. from hermes_cli.auth import get_anthropic_key
  77. # Anthropic uses the dedicated lookup (it also resolves OAuth tokens).
  78. for name, env_ref in (*_API_KEYS.items(), ("Anthropic", get_anthropic_key)):
  79. value = env_ref() if callable(env_ref) else _status._first_env_value(env_ref)
  80. _status._row(name, bool(value), config.redact_key(value))
  81. def _render_auth_providers(ctx):
  82. _status._section("Auth Providers")
  83. from hermes_cli import auth
  84. try:
  85. # Read-only display: the refresh-free snapshot, so `hermes status` never performs an OAuth
  86. # refresh or burns a single-use refresh token.
  87. nous_status = auth.get_nous_auth_status_local()
  88. statuses = {getter: getattr(auth, getter)() for _, getter, _, _ in _OAUTH_BLOCKS[:3]}
  89. except Exception:
  90. nous_status, statuses = {}, {}
  91. # xAI OAuth is guarded separately so an import failure there cannot disrupt the other rows.
  92. try:
  93. statuses["get_xai_oauth_auth_status"] = auth.get_xai_oauth_auth_status() or {}
  94. except Exception:
  95. statuses["get_xai_oauth_auth_status"] = {}
  96. info = None
  97. if any(nous_status.get(k) for k in ("logged_in", "access_token", "portal_base_url",
  98. "inference_credential_present", "error_code")):
  99. try:
  100. info = get_nous_portal_account_info()
  101. except Exception:
  102. pass
  103. ctx.nous_account_info = info
  104. ctx.nous_logged_in = logged_in = bool(nous_status.get("logged_in") or (info and info.logged_in))
  105. ctx.nous_inference_present = inference = bool(
  106. nous_status.get("inference_credential_present") or (info and info.inference_credential_present)
  107. )
  108. if nous_status.get("free_tier"):
  109. # Free tier: never rendered as an account login (no account ids, no refresh row).
  110. from hermes_cli.anon_auth import FREE_TIER_LABEL, GUEST_MODEL, UPGRADE_HINT
  111. _status._row("Nous Portal", True, f"{FREE_TIER_LABEL} · {GUEST_MODEL}")
  112. _status._detail("", UPGRADE_HINT)
  113. inference_url = nous_status.get("inference_base_url")
  114. if inference_url:
  115. _status._detail("Inference:", inference_url)
  116. for name, getter, hint, rows in _OAUTH_BLOCKS:
  117. _oauth_block(name, statuses.get(getter, {}), hint, rows)
  118. return
  119. nous_error = nous_status.get("error")
  120. _status._row("Nous Portal", logged_in,
  121. "logged in" if logged_in else "not logged in (Nous inference key configured)" if inference
  122. else "not logged in (run: hermes portal)")
  123. portal_url = nous_status.get("portal_base_url") or "(unknown)"
  124. inference_url = nous_status.get("inference_base_url") or (info.inference_base_url if info else None)
  125. for label, value, show in (
  126. ("Portal URL:", portal_url, logged_in or portal_url != "(unknown)" or nous_error),
  127. ("Inference:", inference_url, inference and inference_url),
  128. ("Access exp:", _format_iso_timestamp(nous_status.get("access_expires_at")),
  129. logged_in or nous_status.get("access_expires_at")),
  130. ("Key exp:", _format_iso_timestamp(nous_status.get("agent_key_expires_at")),
  131. logged_in or inference or nous_status.get("agent_key_expires_at")),
  132. ("Refresh:", "yes" if nous_status.get("has_refresh_token") else "no",
  133. logged_in or nous_status.get("has_refresh_token")),
  134. ("Error:", nous_error, nous_error)):
  135. if show:
  136. _status._detail(label, value)
  137. for name, getter, hint, rows in _OAUTH_BLOCKS:
  138. _oauth_block(name, statuses.get(getter, {}), hint, rows)
  139. def _render_nous_gateway(ctx):
  140. if managed_nous_tools_enabled():
  141. features = get_nous_subscription_features(ctx.config)
  142. _status._section("Nous Tool Gateway")
  143. print(" Nous Portal ✓ managed tools available" if features.nous_auth_present
  144. else " Nous Portal ✗ not logged in")
  145. for f in features.items():
  146. state = next((text(f) for match, text in _FEATURE_STATES if match(f, features.nous_auth_present)),
  147. "not configured")
  148. _status._row(f.label, f.available or f.active or f.managed_by_nous, state, 15, " ")
  149. elif ctx.nous_logged_in or ctx.nous_inference_present:
  150. # Nous OAuth without entitlement, or an opaque inference key without Portal account
  151. # information, cannot enable the Tool Gateway.
  152. _status._section("Nous Tool Gateway")
  153. message = format_nous_portal_entitlement_message(
  154. ctx.nous_account_info, capability="managed web, image, TTS, STT, browser, and Modal tools"
  155. )
  156. for line in (message or "").splitlines():
  157. print(f" {line}")
  158. def _render_apikey_providers(ctx):
  159. _status._section("API-Key Providers")
  160. for pname, env_vars in _APIKEY_PROVIDERS.items():
  161. configured = bool(_status._first_env_value(env_vars))
  162. _status._row(pname, configured, "configured" if configured else "not configured (run: hermes model)", 16, " ")
  163. # LM Studio reachability: probe only when it is the active provider so users with foreign
  164. # configs see no noise. Auth rejection vs. a silent empty list is the common support case.
  165. if _status._effective_provider_label() == "LM Studio":
  166. from hermes_cli.models_local import probe_lmstudio_models
  167. model_cfg = ctx.config.get("model")
  168. base = ((model_cfg.get("base_url") if isinstance(model_cfg, dict) else None)
  169. or _status.get_env_value("LM_BASE_URL") or "http://127.0.0.1:1234/v1")
  170. try:
  171. models = probe_lmstudio_models(api_key=_status.get_env_value("LM_API_KEY") or "",
  172. base_url=base, timeout=1.5)
  173. ok = models is not None
  174. msg = f"reachable ({len(models)} model(s)) at {base}" if ok else f"unreachable at {base}"
  175. except AuthError:
  176. ok, msg = False, "auth rejected — set LM_API_KEY"
  177. _status._row("LM Studio", ok, msg, 16, " ")
  178. import hermes_cli.status as _status