setup_quick.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. """Streamlined setup flows: the Nous Portal one-shot (`hermes portal`), first-time quick setup,
  2. Blank Slate setup and the `--quick` missing-items pass. Names from setup.py are imported lazily
  3. per function so test patches on ``hermes_cli.setup`` take effect."""
  4. import contextlib
  5. import logging
  6. import os
  7. import sys
  8. from pathlib import Path
  9. logger = logging.getLogger("hermes_cli.setup")
  10. # (env-var name substring, platform label, emoji) — order matters: first match wins.
  11. _MESSAGING_PLATFORMS = (("TELEGRAM", "Telegram", "📱"), ("DISCORD", "Discord", "💬"), ("SLACK", "Slack", "💼"))
  12. def _blank_slate_done(config: dict, hermes_home, tools_line: str, *extra: str, intro: str | None = None) -> None:
  13. """Shared Blank Slate epilogue: success banner, the "enable later" hints, then the summary."""
  14. from hermes_cli.setup import _info, _print_setup_summary, print_success
  15. print()
  16. print_success("Blank Slate setup complete — minimal agent ready.")
  17. _info(*([intro] if intro else []), tools_line, " Seed skills: hermes skills opt-in --sync",
  18. " Add MCP servers: hermes mcp add", *extra, " Tune agent settings: hermes setup agent", None)
  19. _print_setup_summary(config, hermes_home)
  20. def _reload_config_into(config: dict, *, dict_only: bool = False) -> None:
  21. """Re-sync the in-memory config dict from disk after a sub-flow that saved via its own
  22. load/save cycle, so a later save_config(config) can't clobber it."""
  23. from hermes_cli.setup import load_config
  24. refreshed = load_config()
  25. if not dict_only or isinstance(refreshed, dict):
  26. config.clear()
  27. config.update(refreshed)
  28. def _run_nous_flow(config: dict, *, context: str, cancel_exc: tuple, cancel_lines: tuple, print_error) -> bool:
  29. """Run ``_model_flow_nous`` (login, model pick, provider switch, Tool Gateway opt-in) — the
  30. single source of truth shared with ``hermes model``. False when cancelled or failed (the
  31. message is already printed)."""
  32. from hermes_cli.setup import _info
  33. try:
  34. from hermes_cli.model_setup_flows import _model_flow_nous
  35. _model_flow_nous(config)
  36. return True
  37. except cancel_exc:
  38. # _login_nous raises SystemExit(130)/(1) on cancel/failure; the expired-session re-login
  39. # path inside _model_flow_nous only catches Exception, so SystemExit would kill the CLI.
  40. _info(*cancel_lines)
  41. except Exception as exc:
  42. logger.debug("_model_flow_nous error during %s: %s", context, exc)
  43. print_error(exc)
  44. return False
  45. def _run_portal_one_shot(config: dict) -> None:
  46. """One-shot Nous Portal setup (``hermes setup --portal`` / ``hermes portal``)."""
  47. from hermes_cli.setup import _info, _print_banner, _record_setup_completed, print_error, print_info, print_success
  48. _print_banner("│ ☤ Hermes Setup — Nous Portal (one-shot) │")
  49. _info(None, " One subscription, 300+ models, plus the Tool Gateway:",
  50. " web search, image generation, TTS, browser automation",
  51. " — all routed through your Nous Portal sub.", None,
  52. " Sign up: https://portal.nousresearch.com/manage-subscription", None)
  53. def _on_error(exc: Exception) -> None:
  54. from hermes_cli.auth_error_copy import provider_setup_failure_lines
  55. print()
  56. lead, *rest = provider_setup_failure_lines(exc, retry_command="hermes portal")
  57. print_error(f" {lead}")
  58. for line in rest:
  59. print_info(f" {line}")
  60. if not _run_nous_flow(config, context="`hermes portal`", cancel_exc=(KeyboardInterrupt, EOFError, SystemExit),
  61. cancel_lines=(None, " Setup cancelled.", " You can retry later with `hermes portal`."),
  62. print_error=_on_error):
  63. return
  64. # Re-sync from disk so a caller's later save_config(config) can't clobber the login save.
  65. with contextlib.suppress(Exception):
  66. _reload_config_into(config, dict_only=True)
  67. print()
  68. print_success("Portal setup complete.")
  69. _info(" Run `hermes portal info` to inspect routing.", " Run `hermes` to start chatting.")
  70. _record_setup_completed(config)
  71. def _imported_model_label(config: dict) -> str:
  72. """``"<provider> · <model>"`` when *config* (just written by an agent import) names a model
  73. Hermes has credentials for, else ``""``."""
  74. from hermes_cli.auth import AuthError, resolve_provider
  75. from hermes_cli.models import provider_label
  76. from hermes_cli.setup_migration import _model_section_has_credentials
  77. model = config.get("model")
  78. name = model.get("default") if isinstance(model, dict) else model
  79. if not (isinstance(name, str) and name.strip()) or not _model_section_has_credentials(config):
  80. return ""
  81. try:
  82. provider = resolve_provider()
  83. except AuthError:
  84. return ""
  85. return f"{provider_label(provider)} · {name.strip()}"
  86. def _keep_imported_model(config: dict, imported_from: str) -> bool:
  87. """After an import that brought a model, ask whether to keep it (the default) or switch to
  88. Nous Portal; True keeps it."""
  89. from hermes_cli.setup import _info, print_header, prompt_choice
  90. label = _imported_model_label(config) if imported_from else ""
  91. if not label:
  92. return False
  93. print_header("Model & Provider", gap=True)
  94. _info(f"Settings were imported from {imported_from}.")
  95. return prompt_choice(f"Keep your imported model ({label}) or switch to Nous Portal?", [
  96. f"Keep {label}",
  97. "Switch to Nous Portal — free OAuth login, 300+ models plus the Tool Gateway",
  98. ], 0, description=f" Settings were imported from {imported_from}.") == 0
  99. def _quick_setup_nous_portal(config: dict) -> None:
  100. """Quick Setup's Nous Portal step: OAuth login + model selection (provider set to "nous" by the save)."""
  101. from hermes_cli.setup import _info, print_header, print_info, print_warning
  102. print_header("Nous Portal", gap=True)
  103. _info("One subscription, 300+ models, plus the Tool Gateway:",
  104. " web search, image generation, TTS, browser automation.",
  105. "Sign up: https://portal.nousresearch.com/manage-subscription", None)
  106. def _on_error(exc: Exception) -> None:
  107. from hermes_cli.auth_error_copy import provider_setup_failure_lines
  108. lead, *rest = provider_setup_failure_lines(exc, retry_command="hermes model")
  109. print_warning(lead)
  110. for line in rest:
  111. print_info(line)
  112. _run_nous_flow(config, context="quick setup", cancel_exc=(KeyboardInterrupt, EOFError),
  113. cancel_lines=(None, "Nous Portal setup cancelled."), print_error=_on_error)
  114. # The wizard's later save_config(config) must not clobber the login/model save.
  115. _reload_config_into(config)
  116. def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool, imported_from: str = ""):
  117. """Streamlined first-time setup via Nous Portal: OAuth, model, terminal & messaging;
  118. everything else gets defaults. A model brought by an agent import (*imported_from* names the
  119. agents) is offered first and kept by default, which skips the Nous Portal step."""
  120. from hermes_cli.setup import (
  121. _apply_default_agent_settings, _info, print_info, _print_setup_summary, print_success,
  122. prompt_choice, save_config, setup_gateway, setup_terminal_backend
  123. )
  124. # Step 1: the imported model, or Nous Portal.
  125. if not _keep_imported_model(config, imported_from):
  126. _quick_setup_nous_portal(config)
  127. # Step 2: Terminal Backend; Step 3: defaults for everything else.
  128. setup_terminal_backend(config)
  129. _apply_default_agent_settings(config)
  130. save_config(config)
  131. # Step 4: Offer messaging gateway setup
  132. print()
  133. gateway_choice = prompt_choice("Connect a messaging platform? (Telegram, Discord, etc.)", [
  134. "Set up messaging now (recommended)", "Skip — set up later with 'hermes setup gateway'",
  135. ], 0)
  136. if gateway_choice == 0:
  137. setup_gateway(config)
  138. save_config(config)
  139. else:
  140. # Messaging is optional; service persistence still requires explicit consent.
  141. from hermes_cli.gateway_setup_service import ensure_gateway_service
  142. ensure_gateway_service(context="setup", interactive=True, config=config)
  143. print()
  144. print_success("Setup complete! You're ready to go.")
  145. _info(None, " Configure all settings: hermes setup")
  146. if gateway_choice != 0:
  147. print_info(" Connect Telegram/Discord: hermes setup gateway")
  148. _print_macos_fda_tip()
  149. print()
  150. _print_setup_summary(config, hermes_home)
  151. def _print_macos_fda_tip() -> None:
  152. """One-time macOS tip: one Full Disk Access grant kills every per-folder prompt. Same
  153. prompt-free probe as doctor's check_macos_full_disk_access (the FDA-gated TCC dir never
  154. triggers a dialog); silent on non-macOS and when FDA is granted or indeterminate.
  155. every per-folder permission prompt, permanently (issue #52010 follow-up).
  156. """
  157. from hermes_cli.setup import _info
  158. if sys.platform != "darwin":
  159. return
  160. try:
  161. os.listdir(Path.home() / "Library" / "Application Support" / "com.apple.TCC")
  162. return # already granted — nothing to teach
  163. except PermissionError:
  164. pass
  165. except OSError:
  166. return # indeterminate — don't nag
  167. _info(None, " macOS tip: silence ALL folder permission prompts with one switch —",
  168. " System Settings → Privacy & Security → Full Disk Access → enable",
  169. " your terminal (and Hermes.app if you use Desktop), or run:",
  170. " open \"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles\"",
  171. " The grant is permanent — it survives every Hermes update.")
  172. def _blank_slate_minimal_toolsets(config: dict):
  173. """Write the minimal toolset state for a Blank Slate install: only ``file``, ``terminal``,
  174. ``vision`` (``read_file`` can't read images) and ``skills`` (the seeded ``hermes-agent`` skill
  175. needs ``skill_view``) stay on. Two layers enforce it: ``platform_toolsets["cli"]`` (explicit,
  176. so defaults aren't re-expanded) and ``agent.disabled_toolsets`` (hard-suppression applied last
  177. in ``_get_platform_tools``, overriding the recovery that would re-add e.g. ``kanban``)."""
  178. keep = {"file", "terminal", "vision", "skills"}
  179. config.setdefault("platform_toolsets", {})["cli"] = sorted(keep)
  180. try:
  181. from toolsets import TOOLSETS, resolve_toolset
  182. from hermes_cli.tools_config import CONFIGURABLE_TOOLSETS, _get_plugin_toolset_keys
  183. all_keys = {k for k, _, _ in CONFIGURABLE_TOOLSETS}
  184. all_keys.update(_get_plugin_toolset_keys())
  185. # Tools reachable through a checklist row. A plain TOOLSETS entry fully inside one of these (e.g.
  186. # `search` = web_search ⊂ `web`) has no row of its own, so disabling it would silently strip those
  187. # tools after the user re-enables the superset, with no UI to undo it (#134593).
  188. # resolve_toolset returns [] for unknown names and guards cycles, so it needs no try/except.
  189. configurable_tool_sets = [set(resolve_toolset(ck)) for ck, _, _ in CONFIGURABLE_TOOLSETS]
  190. # Plain TOOLSETS entries catch recovered toolsets like ``kanban``. Skip "hermes-*" platform
  191. # composites, "includes" groupings, and posture toolsets (session-level picks by
  192. # agent/coding_context.py — disabling them would subtract terminal/read_file).
  193. for k, tdef in TOOLSETS.items():
  194. if k.startswith("hermes-") or (isinstance(tdef, dict) and (tdef.get("includes") or tdef.get("posture"))):
  195. continue
  196. # selections made by agent/coding_context.py — not permanent user-facing disables. Adding them
  197. # here causes model_tools to subtract their tools (terminal, read_file, …) from the minimal
  198. # Blank Slate surface (#57315).
  199. if k not in all_keys:
  200. tools = set(resolve_toolset(k))
  201. if tools and any(tools <= cts for cts in configurable_tool_sets):
  202. continue # subset of a checklist toolset — the superset's entry already covers it (#134593)
  203. all_keys.add(k)
  204. disabled = sorted(all_keys - keep)
  205. if disabled:
  206. config.setdefault("agent", {})["disabled_toolsets"] = disabled
  207. except Exception as exc:
  208. logger.debug("blank-slate disabled_toolsets computation skipped: %s", exc)
  209. def _blank_slate_minimize_config(config: dict):
  210. """Turn OFF every optional config feature; all opt back in via ``hermes setup agent``."""
  211. config.setdefault("agent", {})["max_turns"] = 90
  212. config.setdefault("compression", {})["enabled"] = False
  213. mem = config.setdefault("memory", {})
  214. mem["memory_enabled"] = False
  215. mem["user_profile_enabled"] = False
  216. config.setdefault("checkpoints", {})["enabled"] = False
  217. config.setdefault("smart_model_routing", {})["enabled"] = False
  218. def _set_bundled_skills_opt_out(opt_out: bool, log_label: str, on_success=None, on_error=None) -> None:
  219. """Record the bundled-skills opt-out marker and sync (essential skills are always seeded);
  220. ``on_success(sync_result)`` / ``on_error(exc)`` report the outcome."""
  221. try:
  222. from tools.skills_sync import sync_skills
  223. from tools.skills_sync_bundled_ops import set_bundled_skills_opt_out
  224. set_bundled_skills_opt_out(opt_out)
  225. result = sync_skills(quiet=True)
  226. if on_success is not None:
  227. on_success(result)
  228. except Exception as exc:
  229. logger.debug("blank-slate %s error: %s", log_label, exc)
  230. if on_error is not None:
  231. on_error(exc)
  232. def _run_blank_slate_setup(config: dict, hermes_home, is_existing: bool):
  233. """Blank Slate setup — essentials only, everything else OFF; then finish now or walk through
  234. opting capabilities back in. Nothing is enabled that the user did not explicitly choose."""
  235. from hermes_cli.setup import (
  236. _info, print_header, print_info, print_success, prompt_choice, save_config, setup_model_provider,
  237. setup_terminal_backend
  238. )
  239. print_header("Blank Slate Setup", gap=True)
  240. _info("Everything starts OFF. First we force-enable only what's required",
  241. "to run an agent, then you choose whether to stop there or walk",
  242. "through enabling more — opting in to exactly what you want.", "",
  243. "Forced on: Provider & Model, File Operations, Terminal, Vision, Skills.",
  244. "Everything else (web, browser, code exec, memory,",
  245. "delegation, cron, plugins, MCP, …) starts disabled. The",
  246. "essential `hermes-agent` skill is always kept so the agent",
  247. "can help you drive and configure Hermes itself.", None)
  248. # Step 1: Provider & Model (REQUIRED — the agent cannot run without it)
  249. print_header("Step 1 — Provider & Model (required)")
  250. setup_model_provider(config)
  251. save_config(config)
  252. # Step 2: Terminal backend (where commands run — a core decision)
  253. print_header("Step 2 — Terminal Backend")
  254. setup_terminal_backend(config)
  255. # Step 3: Lock in the minimal toolset + minimized config knobs
  256. _blank_slate_minimal_toolsets(config)
  257. _blank_slate_minimize_config(config)
  258. save_config(config)
  259. print()
  260. print_success("Minimal baseline applied:")
  261. print_info(" Toolsets: file, terminal, vision, skills (everything else off)")
  262. print_info(" Compression, memory, checkpoints, smart routing: off")
  263. # The fork: stop here, or walk through enabling things
  264. print_header("How far do you want to go?", gap=True)
  265. path = prompt_choice("Your minimal agent is ready. What next?", [
  266. "Start with everything disabled — finish now (most minimal)",
  267. "Walk through all configurations — opt in to tools, skills, plugins, MCP",
  268. ], 0)
  269. if path != 0:
  270. _blank_slate_walkthrough(config, hermes_home)
  271. return
  272. save_config(config)
  273. # Blank Slate means no bundled skills; record the opt-out so future `hermes update` runs
  274. # don't re-inject them.
  275. _set_bundled_skills_opt_out(True, "skill opt-out")
  276. _blank_slate_done(config, hermes_home, " Enable tools: hermes tools", " Enable plugins: hermes plugins",
  277. intro="Enable anything later, on demand:")
  278. def _blank_slate_walkthrough(config: dict, hermes_home):
  279. """Opt-in walkthrough for Blank Slate: skills, tools, plugins, MCP, gateway."""
  280. from hermes_cli.setup import (
  281. _info, print_header, print_info, print_success, print_warning, prompt_yes_no, save_config, setup_gateway,
  282. )
  283. # Bundled skills — default to NONE, offer to seed all
  284. print_header("Bundled Skills", gap=True)
  285. print_info("Blank Slate ships with NO bundled skills by default.")
  286. seed_skills = prompt_yes_no("Seed the full bundled skill catalog? (No = start with zero skills)", default=False)
  287. def _seeded(result) -> None:
  288. copied = len(result.get("copied", [])) if isinstance(result, dict) else 0
  289. print_success(f"Seeded {copied} bundled skills.")
  290. def _opted_out(_result) -> None:
  291. _info("No skills seeded (except the essential `hermes-agent`",
  292. "skill). A .no-bundled-skills marker keeps future",
  293. "`hermes update` runs from re-injecting them. Opt back in any",
  294. "time with `hermes skills opt-in --sync`.")
  295. # Seeding first clears any stale opt-out marker; declining sets it (essential skills still seed).
  296. _set_bundled_skills_opt_out(
  297. not seed_skills, "skill handling", on_success=_seeded if seed_skills else _opted_out,
  298. on_error=lambda exc: print_warning(f"Skill setup step encountered an error: {exc}"),
  299. )
  300. # Walk through enabling additional tools
  301. print_header("Tools", gap=True)
  302. _info("Pick exactly which additional toolsets to turn on.",
  303. "(file and terminal are already on; leave the rest off if you want", " the most minimal agent.)")
  304. if prompt_yes_no("Open the tool selector to enable more tools?", default=False):
  305. try:
  306. from hermes_cli.tools_config import tools_command
  307. tools_command(first_install=False, config=config)
  308. _reload_config_into(config) # tools_command saves via its own load/save cycle
  309. except Exception as exc:
  310. logger.debug("blank-slate tools_command error: %s", exc)
  311. print_warning(f"Tool selector encountered an error: {exc}")
  312. else:
  313. print_info("Keeping the minimal toolset. Add tools later with `hermes tools`.")
  314. # Built-in plugins and MCP servers (off unless chosen)
  315. for header, question, yes_msg, no_msg in (
  316. ("Plugins", "Review and enable built-in plugins now?",
  317. "Manage plugins with `hermes plugins list` / `hermes plugins install`.",
  318. "No plugins enabled. Add later with `hermes plugins`."),
  319. ("MCP Servers", "Add an MCP server now?",
  320. "Add servers with `hermes mcp add <name> --url ... | --command ...`.",
  321. "No MCP servers configured. Add later with `hermes mcp add`."),
  322. ):
  323. print_header(header, gap=True)
  324. print_info(yes_msg if prompt_yes_no(question, default=False) else no_msg)
  325. # Optional messaging gateway
  326. print()
  327. if prompt_yes_no("Connect a messaging platform (Telegram, Discord, …)?", default=False):
  328. setup_gateway(config)
  329. save_config(config)
  330. _blank_slate_done(config, hermes_home, " Enable more tools: hermes tools")
  331. def _run_quick_setup(config: dict, hermes_home):
  332. """Quick setup — only configure items that are missing."""
  333. from hermes_cli.setup import (
  334. color, Colors, _info, print_header, print_info, _print_setup_summary, print_success,
  335. _prompt_and_save_env_var, _prompt_api_key, _section_rule, prompt_checklist, save_config,
  336. )
  337. from hermes_cli.config import (get_missing_env_vars, get_missing_config_fields, check_config_version)
  338. print_header("Quick Setup — Missing Items Only", gap=True)
  339. # Check what's missing
  340. missing_env = get_missing_env_vars(required_only=False)
  341. missing_required = [v for v in missing_env if v.get("is_required")]
  342. missing_optional = [v for v in missing_env if not v.get("is_required")]
  343. missing_config = get_missing_config_fields()
  344. current_ver, latest_ver = check_config_version()
  345. if not (missing_required or missing_optional or missing_config or current_ver < latest_ver):
  346. print_success("Everything is configured! Nothing to do.")
  347. _info(None, "Run 'hermes setup' and choose 'Full Setup' to reconfigure,",
  348. "or pick a specific section from the menu.")
  349. return
  350. if missing_required:
  351. _info(None, f"{len(missing_required)} required setting(s) missing:")
  352. for var in missing_required:
  353. print(f" • {var['name']}")
  354. print()
  355. for var in missing_required:
  356. print()
  357. print(color(f" {var['name']}", Colors.CYAN))
  358. print_info(f" {var.get('description', '')}")
  359. if var.get("url"):
  360. print_info(f" Get key at: {var['url']}")
  361. _prompt_and_save_env_var(var, f" Saved {var['name']}", f" Skipped {var['name']}")
  362. missing_tools = [v for v in missing_optional if v.get("category") == "tool"]
  363. missing_messaging = [v for v in missing_optional if v.get("category") == "messaging" and not v.get("advanced")]
  364. if missing_tools: # checklist, then the API-key screen for each pick
  365. print_header("Tool API Keys", gap=True)
  366. labels = [var.get("description", var["name"]) + (f" → {', '.join(var['tools'][:2])}" if var.get("tools") else "")
  367. for var in missing_tools]
  368. for idx in prompt_checklist("Which tools would you like to configure?", labels):
  369. _prompt_api_key(missing_tools[idx])
  370. if missing_messaging: # checklist, then prompt for each selected platform's vars
  371. print_header("Messaging Platforms", gap=True)
  372. _info("Connect Hermes to messaging apps to chat from anywhere.",
  373. "You can configure these later with 'hermes setup gateway'.")
  374. # Group by platform in first-seen order; vars matching no platform are dropped.
  375. grouped: dict[str, list] = {}
  376. emojis = {}
  377. for var in missing_messaging:
  378. match = next(((plat, emoji) for needle, plat, emoji in _MESSAGING_PLATFORMS if needle in var["name"]), None)
  379. if match:
  380. grouped.setdefault(match[0], []).append(var)
  381. emojis[match[0]] = match[1]
  382. platform_order = list(grouped)
  383. labels = [f"{emojis[p]} {p}" for p in platform_order]
  384. for idx in prompt_checklist("Which platforms would you like to set up?", labels):
  385. plat = platform_order[idx]
  386. _section_rule(f"{emojis[plat]} {plat}")
  387. for var in grouped[plat]:
  388. print_info(f" {var.get('description', '')}")
  389. if var.get("url"):
  390. print_info(f" {var['url']}")
  391. _prompt_and_save_env_var(var, " ✓ Saved", " Skipped")
  392. print()
  393. # Handle missing config fields
  394. if missing_config:
  395. _info(None, f"Adding {len(missing_config)} new config option(s) with defaults...")
  396. for field in missing_config:
  397. print_success(f" Added {field['key']} = {field['default']}")
  398. config["_config_version"] = latest_ver
  399. save_config(config)
  400. _print_setup_summary(config, hermes_home)