setup_summary.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """Setup-completion summary (tool availability + "Setup Complete!" banner). setup.py names are
  2. resolved through the module object so test patches on ``hermes_cli.setup.<name>`` take effect."""
  3. import logging
  4. from tools import tool_backend_helpers
  5. from hermes_cli import nous_subscription
  6. logger = logging.getLogger("hermes_cli.setup")
  7. # provider -> (label, env vars: any one set means available; empty = always).
  8. # Local engines are (label, module, hint) and must be importable.
  9. _TTS_SUMMARY_ROWS = {
  10. "elevenlabs": ("ElevenLabs", ("ELEVENLABS_API_KEY",)),
  11. "openai": ("OpenAI", ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY")),
  12. "minimax": ("MiniMax", ("MINIMAX_API_KEY",)), "mistral": ("Mistral Voxtral", ("MISTRAL_API_KEY",)),
  13. "gemini": ("Google Gemini", ("GEMINI_API_KEY", "GOOGLE_API_KEY")),
  14. "neutts": ("NeuTTS", "neutts", "run 'hermes setup tts'"),
  15. "kittentts": ("KittenTTS", "kittentts", "run 'hermes setup tts'")}
  16. _TTS_SUMMARY_DEFAULT = ("Edge TTS", ())
  17. _STT_SUMMARY_ROWS = {
  18. "openai": ("OpenAI", ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY")), "groq": ("Groq Whisper", ("GROQ_API_KEY",)),
  19. "elevenlabs": ("ElevenLabs Scribe", ("ELEVENLABS_API_KEY",)), "xai": ("xAI", ()),
  20. "deepinfra": ("DeepInfra", ("DEEPINFRA_API_KEY",))}
  21. _STT_SUMMARY_DEFAULT = ("Local Whisper", "faster_whisper", "run 'hermes tools' → Speech-to-Text")
  22. # Browser "missing" hint keyed by the configured provider; anything else gets the generic hint.
  23. _BROWSER_MISSING_HINTS = {
  24. "Browserbase": "BROWSERBASE_API_KEY/BROWSERBASE_PROJECT_ID",
  25. "Browser Use": "BROWSER_USE_API_KEY",
  26. "Local browser": "Chromium: run 'hermes pm install chromium'"}
  27. _BROWSER_MISSING_DEFAULT = "Chromium (run 'hermes pm install chromium'), or configure Browser Use or Browserbase"
  28. _WEB_MISSING = ("EXA_API_KEY, PARALLEL_API_KEY, FIRECRAWL_API_KEY/FIRECRAWL_API_URL, TAVILY_API_KEY, "
  29. "PERPLEXITY_API_KEY, KEENABLE_API_KEY, or SEARXNG_URL")
  30. _DONE_BANNER = (
  31. "┌─────────────────────────────────────────────────────────┐",
  32. "│ ✓ Setup Complete! │",
  33. "└─────────────────────────────────────────────────────────┘")
  34. # (command, description) rows; the description carries its own alignment padding.
  35. _EDIT_WIZARD_ROWS = (
  36. ("hermes setup", " Re-run the full wizard"), ("hermes setup model", " Change model/provider"),
  37. ("hermes setup terminal", " Change terminal backend"), ("hermes setup gateway", " Configure messaging"),
  38. ("hermes setup tools", " Configure tool providers"))
  39. _EDIT_CONFIG_ROWS = (
  40. ("hermes config", " View current settings"), ("hermes config edit", " Open config in your editor"),
  41. ("hermes config set <key> <value>", ""))
  42. _READY_ROWS = (
  43. ("hermes", " Start chatting"), ("hermes gateway", " Start messaging gateway"),
  44. ("hermes doctor", " Check for issues"))
  45. def _voice_provider_status(kind: str, provider: str, rows: dict, default: tuple) -> tuple:
  46. """Summary row for a TTS/STT provider. A keyed provider whose key is missing
  47. falls through to the default row, matching the runtime fallback."""
  48. row = rows.get(provider, default)
  49. if isinstance(row[1], tuple) and row[1] and not any(_setup.get_env_value(v) for v in row[1]):
  50. row = default
  51. if isinstance(row[1], tuple):
  52. return (f"{kind} ({row[0]})", True, None)
  53. label, module, hint = row
  54. if _setup._module_installed(module):
  55. return (f"{kind} ({label}{' local' if kind == 'Text-to-Speech' else ''})", True, None)
  56. return (f"{kind} ({label} — not installed)", False, hint)
  57. def _first_available_plugin_provider(registry: str, skip: str | None = None):
  58. """display_name of the first plugin-registered provider in ``agent.<registry>`` that reports
  59. available (fail-soft: any error means none), skipping ``skip``."""
  60. try:
  61. import importlib
  62. from hermes_cli.plugins import _ensure_plugins_discovered
  63. _ensure_plugins_discovered()
  64. for provider in importlib.import_module(f"agent.{registry}").list_providers():
  65. if provider.name == skip:
  66. continue
  67. try:
  68. if provider.is_available():
  69. return provider.display_name
  70. except Exception:
  71. continue
  72. except Exception:
  73. pass
  74. return None
  75. # ---- tool_status row builders: each takes (config, subscription_features) and returns
  76. # a (name, available, hint) row or None (row omitted). Evaluated in _TOOL_ROW_BUILDERS order.
  77. def _vision_row(config, feats):
  78. # Use the same runtime resolver as the actual vision tools.
  79. try:
  80. from agent.auxiliary_client import get_available_vision_backends
  81. ok = bool(get_available_vision_backends())
  82. except Exception:
  83. ok = False
  84. return ("Vision (image analysis)", ok, None if ok else "run 'hermes setup' to configure")
  85. def _managed_or_provider_row(feature, name: str, managed_label: str, missing_hint: str):
  86. """Row for a Nous-manageable feature: managed > available (with provider) > missing hint."""
  87. if feature.managed_by_nous:
  88. return (f"{name} ({managed_label})", True, None)
  89. if feature.available:
  90. return (f"{name} ({feature.current_provider})" if feature.current_provider else name, True, None)
  91. return (name, False, missing_hint)
  92. def _web_row(config, feats):
  93. # Web tools (Exa, Parallel, Firecrawl, Tavily, or Keenable)
  94. return _managed_or_provider_row(feats.web, "Web Search & Extract", "Nous subscription", _WEB_MISSING)
  95. def _browser_row(config, feats):
  96. # Browser tools (local Chromium, Lightpanda, Browserbase, Browser Use, or Firecrawl)
  97. hint = _BROWSER_MISSING_HINTS.get(feats.browser.current_provider, _BROWSER_MISSING_DEFAULT)
  98. return _managed_or_provider_row(feats.browser, "Browser Automation", "Nous Browser Use", hint)
  99. def _image_gen_row(config, feats):
  100. # FAL (direct or via Nous), or any plugin-registered provider (OpenAI, etc.)
  101. if feats.image_gen.managed_by_nous:
  102. return ("Image Generation (Nous subscription)", True, None)
  103. if feats.image_gen.available:
  104. return ("Image Generation", True, None)
  105. # Probe plugin-registered providers so OpenAI-only setups don't show as "missing FAL_KEY".
  106. backend = _first_available_plugin_provider("image_gen_registry", skip="fal")
  107. if backend:
  108. return (f"Image Generation ({backend})", True, None)
  109. return ("Image Generation", False, "FAL_KEY or OPENAI_API_KEY")
  110. def _video_gen_row(config, feats):
  111. # Opt-in via `hermes tools` → Video Generation. Only show the row when a plugin reports
  112. # available so we don't badger users who don't care about video gen with a "missing" line.
  113. if feats.video_gen.managed_by_nous:
  114. return ("Video Generation (FAL via Nous subscription)", True, None)
  115. backend = _first_available_plugin_provider("video_gen_registry")
  116. return (f"Video Generation ({backend})", True, None) if backend else None
  117. def _tts_row(config, feats):
  118. # Configured provider, gated on its key (or local install)
  119. if feats.tts.managed_by_nous:
  120. return ("Text-to-Speech (OpenAI via Nous subscription)", True, None)
  121. provider = _setup.cfg_get(config, "tts", "provider", default="edge")
  122. return _voice_provider_status("Text-to-Speech", provider, _TTS_SUMMARY_ROWS, _TTS_SUMMARY_DEFAULT)
  123. def _stt_row(config, feats):
  124. stt_feature = feats.features.get("stt")
  125. if stt_feature is not None and stt_feature.managed_by_nous:
  126. return ("Speech-to-Text (OpenAI via Nous subscription)", True, None)
  127. provider = _setup.cfg_get(config, "stt", "provider", default="local") or "local"
  128. return _voice_provider_status("Speech-to-Text", provider, _STT_SUMMARY_ROWS, _STT_SUMMARY_DEFAULT)
  129. def _modal_row(config, feats):
  130. if feats.modal.managed_by_nous:
  131. return ("Modal Execution (Nous subscription)", True, None)
  132. if _setup.cfg_get(config, "terminal", "backend") == "modal":
  133. if feats.modal.direct_override:
  134. return ("Modal Execution (direct Modal)", True, None)
  135. return ("Modal Execution", False, "run 'hermes setup terminal'")
  136. if tool_backend_helpers.managed_nous_tools_enabled() and feats.nous_auth_present:
  137. return ("Modal Execution (optional via Nous subscription)", True, None)
  138. return None
  139. def _skills_hub_row(config, feats):
  140. ok = bool(_setup.get_env_value("GITHUB_TOKEN"))
  141. return ("Skills Hub (GitHub)", ok, None if ok else "GITHUB_TOKEN")
  142. def _always_on_rows(config, feats):
  143. # Terminal (system deps met), task planning (in-memory), skills (bundled + user-created).
  144. return [("Terminal/Commands", True, None), ("Task Planning (todo)", True, None),
  145. ("Skills (view, create, edit)", True, None)]
  146. _TOOL_ROW_BUILDERS = (
  147. _vision_row, _web_row, _browser_row, _image_gen_row, _video_gen_row, _tts_row, _stt_row,
  148. _modal_row, _skills_hub_row, _always_on_rows)
  149. def _print_cmd_rows(rows):
  150. """Print (command, description) rows as ' <green cmd><desc>'."""
  151. for cmd, desc in rows:
  152. print(f" {_setup.color(cmd, _setup.Colors.GREEN)}{desc}")
  153. def _print_section_header(title):
  154. print(_setup.color("─" * 60, _setup.Colors.DIM), end="\n\n")
  155. print(_setup.color(title, _setup.Colors.CYAN, _setup.Colors.BOLD), end="\n\n")
  156. def _print_setup_summary(config: dict, hermes_home):
  157. """Print the setup completion summary."""
  158. from hermes_constants import display_hermes_home as _dhh
  159. # Provider readiness — the one thing setup must produce. A user who cancelled the API-key
  160. # prompt mid-wizard used to exit "successfully" with NO working model; say so loudly.
  161. try:
  162. from hermes_cli.auth import resolve_provider
  163. resolve_provider()
  164. except Exception:
  165. print()
  166. _setup.print_warning("No inference provider is configured — Hermes cannot chat yet.")
  167. _setup._info(" Finish this one step with either of:",
  168. " hermes model (pick any provider/model)",
  169. " hermes setup --portal (Nous Portal OAuth, no API key)")
  170. print()
  171. _setup.print_header("Tool Availability Summary")
  172. tool_status = []
  173. subscription_features = nous_subscription.get_nous_subscription_features(config)
  174. for build in _TOOL_ROW_BUILDERS:
  175. row = build(config, subscription_features)
  176. tool_status.extend(row if isinstance(row, list) else [] if row is None else [row])
  177. available_count = sum(1 for _, avail, _ in tool_status if avail)
  178. _setup._info(f"{available_count}/{len(tool_status)} tool categories available:", None)
  179. for name, available, missing_var in tool_status:
  180. print(f" {_setup.color('✓', _setup.Colors.GREEN)} {name}" if available else
  181. f" {_setup.color('✗', _setup.Colors.RED)} {name} "
  182. f"{_setup.color(f'(missing {missing_var})', _setup.Colors.DIM)}")
  183. print()
  184. if available_count < len(tool_status):
  185. _setup.print_warning("Some tools are disabled. Run 'hermes setup tools' to configure them,")
  186. _setup.print_warning(f"or edit {_dhh()}/.env directly to add the missing API keys.")
  187. print()
  188. print()
  189. for line in _DONE_BANNER:
  190. print(_setup.color(line, _setup.Colors.GREEN))
  191. print()
  192. print(_setup.color(f"📁 All your files are in {_dhh()}/:", _setup.Colors.CYAN, _setup.Colors.BOLD), end="\n\n")
  193. for label, value in (("Settings:", f" {_setup.get_config_path()}"), ("API Keys:", f" {_setup.get_env_path()}"),
  194. ("Data:", f" {hermes_home}/cron/, sessions/, logs/")):
  195. print(f" {_setup.color(label, _setup.Colors.YELLOW)}{value}")
  196. print()
  197. _print_section_header("📝 To edit your configuration:")
  198. _print_cmd_rows(_EDIT_WIZARD_ROWS)
  199. print()
  200. _print_cmd_rows(_EDIT_CONFIG_ROWS)
  201. print(" Set a specific value\n\n Or edit the files directly:")
  202. for path in (_setup.get_config_path(), _setup.get_env_path()):
  203. print(f" {_setup.color(f'nano {path}', _setup.Colors.DIM)}")
  204. print()
  205. _print_section_header("🚀 Ready to go!")
  206. _print_cmd_rows(_READY_ROWS)
  207. print()
  208. import hermes_cli.setup as _setup