setup.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. """Interactive setup wizard for Hermes Agent (config lives in ~/.hermes/).
  2. Independently-runnable sections: Model & Provider, Terminal Backend, Agent Settings, Messaging
  3. Platforms, Tools. Section bodies live in sibling setup_* modules and are re-exported here; they
  4. resolve shared prompt/config helpers lazily through this module so test patches on
  5. ``hermes_cli.setup.<name>`` keep working.
  6. """
  7. import importlib.util
  8. import logging
  9. import os
  10. import re
  11. import sys
  12. import copy
  13. from contextlib import contextmanager
  14. from contextvars import ContextVar
  15. from pathlib import Path
  16. from typing import Callable
  17. from hermes_cli.curses_ui import MenuNavigationEvent, MenuNavigationStart
  18. # Config helpers are re-exported (tests patch them on this module). display_hermes_home is
  19. # imported lazily at call sites (stale-module safety during hermes update).
  20. from hermes_cli.config import (
  21. cfg_get, DEFAULT_CONFIG, get_hermes_home, get_config_path, get_env_path, load_config, save_config,
  22. save_env_value, remove_env_value, get_env_value, ensure_hermes_home,
  23. )
  24. from hermes_cli.colors import Colors, color
  25. from hermes_cli.cli_output import print_error, print_info, print_success, print_warning
  26. from hermes_cli.secret_prompt import masked_secret_prompt
  27. logger = logging.getLogger(__name__)
  28. PROJECT_ROOT = Path(__file__).parent.parent.resolve()
  29. _DOCS_BASE = "https://hermes-agent.nousresearch.com/docs"
  30. _BRACKETED_PASTE_PATTERN = re.compile(r"\x1b\[\s*200~|\x1b\[\s*201~")
  31. def print_header(title: str, *, gap: bool = False):
  32. """Print a section header (``gap`` adds an extra blank line before it)."""
  33. if gap:
  34. print()
  35. print()
  36. print(color(f"◆ {title}", Colors.CYAN, Colors.BOLD))
  37. def _info(*lines: str | None) -> None:
  38. """print_info each line in order; ``None`` emits a bare blank ``print()``."""
  39. for line in lines:
  40. print() if line is None else print_info(line)
  41. def _sub_dict(parent: dict, key: str) -> dict:
  42. """``parent[key]`` as a dict, replacing a missing or non-dict value with ``{}``."""
  43. child = parent.get(key)
  44. if not isinstance(child, dict):
  45. child = parent[key] = {}
  46. return child
  47. def _current_reasoning_effort(config: dict) -> str:
  48. agent_cfg = config.get("agent")
  49. if not isinstance(agent_cfg, dict):
  50. return ""
  51. effort = agent_cfg.get("reasoning_effort")
  52. if isinstance(effort, dict): # {enabled, effort} form: the tier name, never str(dict)
  53. from hermes_constants import parse_reasoning_effort
  54. parsed = parse_reasoning_effort(effort) or {}
  55. effort = "none" if parsed.get("enabled") is False else parsed.get("effort")
  56. return str(effort or "").strip().lower()
  57. def _set_reasoning_effort(config: dict, effort: str) -> None:
  58. _sub_dict(config, "agent")["reasoning_effort"] = effort
  59. def is_interactive_stdin() -> bool:
  60. """Return True when stdin looks like a usable interactive TTY."""
  61. try:
  62. return bool(sys.stdin.isatty())
  63. except Exception:
  64. return False
  65. def print_noninteractive_setup_guidance(reason: str | None = None) -> None:
  66. """Print guidance for headless/non-interactive setup flows."""
  67. print()
  68. print(color("☤ Hermes Setup — Non-interactive mode", Colors.CYAN, Colors.BOLD))
  69. print()
  70. if reason:
  71. print_info(reason)
  72. _info("The interactive wizard cannot be used here.", None,
  73. "Configure Hermes using environment variables or config commands:",
  74. " hermes config set model.provider custom",
  75. " hermes config set model.base_url http://localhost:8080/v1",
  76. " hermes config set model.default your-model-name", None,
  77. "Or set OPENROUTER_API_KEY (OpenRouter) / OPENAI_API_KEY (OpenAI) in your environment.",
  78. "Run 'hermes setup' in an interactive terminal to use the full wizard.", None)
  79. def _sanitize_pasted_input(value: str) -> str:
  80. """Strip terminal bracketed-paste control markers from pasted text."""
  81. return _BRACKETED_PASTE_PATTERN.sub("", value) if isinstance(value, str) and value else value
  82. def prompt(question: str, default: str | None = None, password: bool = False) -> str:
  83. """Prompt for input with optional default."""
  84. display = color(f"{question} [{default}]: " if default else f"{question}: ", Colors.YELLOW)
  85. try:
  86. if password:
  87. value = masked_secret_prompt(display)
  88. else:
  89. from hermes_cli.cli_output import line_input
  90. value = line_input(display)
  91. return _sanitize_pasted_input(value).strip() or default or ""
  92. except (KeyboardInterrupt, EOFError):
  93. print()
  94. sys.exit(1)
  95. # ── Setup navigation (Escape cancels, Left arrow goes back): a ContextVar state machine shared
  96. # with the curses menus. ──
  97. class _SetupControlFlow(BaseException):
  98. """Bypass provider error handlers that intentionally catch ``Exception`` so navigation reaches
  99. the outer state machine unchanged and it can replay the prior prompt."""
  100. class _SetupCancelled(_SetupControlFlow):
  101. """Internal control flow for cancelling the interactive setup wizard."""
  102. class _SetupGoBack(_SetupControlFlow):
  103. """Internal control flow for returning to an earlier setup choice."""
  104. def __init__(self, prompt_index: int):
  105. super().__init__(prompt_index)
  106. self.prompt_index = prompt_index
  107. class _SetupNavigationState:
  108. """Per-invocation navigation state for the synchronous setup wizard."""
  109. def __init__(self, *, section_index: int = -1, prompt_index: int = 0):
  110. self.reset(section_index)
  111. self.prompt_index = prompt_index
  112. def reset(self, section_index: int = -1, replay: list | None = None) -> None:
  113. """Rewind per-section counters (entering a section, or leaving the wizard)."""
  114. self.section_index = section_index
  115. self.prompt_index = 0
  116. self.active_prompt_index = -1
  117. self.resolved_choices: list[object] = []
  118. self.replay_choices: list[object] = copy.deepcopy(replay or [])
  119. _SETUP_NAVIGATION: ContextVar[_SetupNavigationState | None] = ContextVar("hermes_setup_navigation", default=None)
  120. def _handle_setup_menu_navigation(event: MenuNavigationEvent, value: object = None) -> MenuNavigationStart | None:
  121. """Translate shared curses menu events into setup control flow."""
  122. state = _SETUP_NAVIGATION.get()
  123. if state is None:
  124. return None
  125. if event is MenuNavigationEvent.BEGIN:
  126. if state.section_index < 0:
  127. state.active_prompt_index = -1
  128. return MenuNavigationStart()
  129. idx = state.active_prompt_index = state.prompt_index
  130. state.prompt_index += 1
  131. allow_back = state.section_index > 0 or idx > 0
  132. if idx < len(state.replay_choices):
  133. return MenuNavigationStart(allow_back=allow_back, replay_value=copy.deepcopy(state.replay_choices[idx]))
  134. return MenuNavigationStart(allow_back=allow_back)
  135. if event is MenuNavigationEvent.RESOLVE:
  136. prompt_index = state.active_prompt_index
  137. if prompt_index >= 0: # replace this answer and drop every later one
  138. state.resolved_choices[prompt_index:] = [copy.deepcopy(value)]
  139. return None
  140. if event is MenuNavigationEvent.CANCEL:
  141. raise _SetupCancelled()
  142. if event is MenuNavigationEvent.BACK:
  143. raise _SetupGoBack(state.active_prompt_index)
  144. return None
  145. @contextmanager
  146. def _setup_navigation_scope():
  147. """Install and reliably restore the setup menu navigation context."""
  148. from hermes_cli.curses_ui import reset_menu_navigation_handler, set_menu_navigation_handler
  149. token = _SETUP_NAVIGATION.set(_SetupNavigationState())
  150. menu_token = set_menu_navigation_handler(_handle_setup_menu_navigation)
  151. try:
  152. yield
  153. finally:
  154. reset_menu_navigation_handler(menu_token)
  155. _SETUP_NAVIGATION.reset(token)
  156. def _run_setup_steps(steps: list[tuple[str, Callable[[], None]]]) -> None:
  157. """Run setup sections with left-arrow navigation: at a section's first choice it returns to
  158. the previous section; from a later choice it replays earlier selections invisibly and reopens
  159. only the preceding prompt."""
  160. state = _SETUP_NAVIGATION.get()
  161. section_index = 0
  162. answers_by_section: dict[int, list[object]] = {}
  163. replay_by_section: dict[int, list[object]] = {}
  164. def _record_answers() -> None:
  165. if state is not None:
  166. answers_by_section[section_index] = copy.deepcopy(state.resolved_choices)
  167. try:
  168. while section_index < len(steps):
  169. label, action = steps[section_index]
  170. if state is not None:
  171. state.reset(section_index, replay_by_section.pop(section_index, []))
  172. try:
  173. action()
  174. except _SetupGoBack as navigation:
  175. _record_answers()
  176. if navigation.prompt_index > 0:
  177. previous_index = section_index
  178. target_prompt = navigation.prompt_index - 1
  179. else:
  180. previous_index = max(0, section_index - 1)
  181. target_prompt = max(0, len(answers_by_section.get(previous_index, [])) - 1)
  182. replay_by_section[previous_index] = copy.deepcopy(
  183. answers_by_section.get(previous_index, [])[:target_prompt])
  184. print()
  185. if previous_index == section_index:
  186. print_info(f"Returning to the previous choice in {label}...")
  187. else:
  188. print_info(f"Returning to {steps[previous_index][0]}...")
  189. section_index = previous_index
  190. continue
  191. _record_answers()
  192. section_index += 1
  193. finally:
  194. if state is not None:
  195. state.reset()
  196. def run_setup_action_with_navigation(
  197. label: str, action: Callable[[], None], *, cancelled_message: str = "Setup cancelled."
  198. ) -> None:
  199. """Run a setup-style menu flow with Escape and nested Left navigation — for commands such as
  200. ``hermes model`` that use the wizard's pickers outside ``run_setup_wizard``."""
  201. with _setup_navigation_scope():
  202. try:
  203. _run_setup_steps([(label, action)])
  204. except _SetupCancelled:
  205. _info(None, cancelled_message)
  206. # ── Prompt primitives ──
  207. def _curses_prompt_choice(question: str, choices: list, default: int = 0, description: str | None = None) -> int:
  208. """Single-select menu using curses. Delegates to curses_radiolist."""
  209. from hermes_cli.curses_ui import curses_radiolist
  210. return curses_radiolist(question, choices, selected=default, cancel_returns=-1, description=description)
  211. def prompt_choice(question: str, choices: list, default: int = 0, description: str | None = None) -> int:
  212. """Prompt for a choice from a list with arrow key navigation. Escape cancels an active setup
  213. wizard; outside setup it keeps the default (the curses component owns its own numbered
  214. fallback, so a cancel result must never open another prompt). Ctrl+C exits the wizard."""
  215. idx = _curses_prompt_choice(question, choices, default, description=description)
  216. if idx < 0:
  217. return default
  218. if idx == default:
  219. _info(" Skipped (keeping current)", None)
  220. return default
  221. print()
  222. return idx
  223. def is_noninteractive() -> bool:
  224. """True when no human is available to answer a prompt: the dashboard/desktop spawn CLI actions
  225. with ``stdin=DEVNULL`` and ``HERMES_NONINTERACTIVE=1`` (``hermes_cli/web_server.py``), where a
  226. prompt that aborts on EOF would kill the spawned action — callers fall back to their default."""
  227. return os.environ.get("HERMES_NONINTERACTIVE", "").strip().lower() in {"1", "true", "yes", "on"}
  228. def prompt_yes_no(question: str, default: bool = True, description: str | None = None) -> bool:
  229. """Prompt for yes/no. Ctrl+C exits; empty input, ``HERMES_NONINTERACTIVE=1`` or a
  230. closed/redirected stdin return ``default`` instead of aborting the whole process.
  231. ``description`` is the context the question refers to, shown above it in setup's full-screen
  232. menu, which hides everything printed before it; the line prompt keeps that text on screen."""
  233. if is_noninteractive():
  234. return default
  235. # Inside setup, route binary selections through the curses menu so ESC and left-arrow work
  236. # consistently; every other caller keeps the traditional line prompt.
  237. if _SETUP_NAVIGATION.get() is not None:
  238. return _curses_prompt_choice(question, ["Yes", "No"], 0 if default else 1, description=description) == 0
  239. default_str = "Y/n" if default else "y/N"
  240. while True:
  241. try:
  242. value = input(color(f"{question} [{default_str}]: ", Colors.YELLOW)).strip().lower()
  243. except KeyboardInterrupt:
  244. print()
  245. sys.exit(1)
  246. except EOFError:
  247. # No stdin (closed/redirected, e.g. stdin=DEVNULL): accept the default so the caller
  248. # proceeds unattended instead of failing the whole command.
  249. print()
  250. return default
  251. answer = {"": default, "y": True, "yes": True, "n": False, "no": False}.get(value)
  252. if answer is not None:
  253. return answer
  254. print_error("Please enter 'y' or 'n'")
  255. def prompt_checklist(title: str, items: list, pre_selected: list | None = None) -> list:
  256. """Multi-select checklist; returns the sorted indices of selected items. ``pre_selected``
  257. start checked; Space toggles, Enter confirms, cancel keeps the pre-selection."""
  258. from hermes_cli.curses_ui import curses_checklist
  259. pre = set(pre_selected or [])
  260. return sorted(curses_checklist(title, items, pre, cancel_returns=pre))
  261. def _section_rule(title: str) -> None:
  262. """Blank-padded cyan ``─── title ───`` divider used by the key-entry screens."""
  263. print()
  264. print(color(f" ─── {title} ───", Colors.CYAN))
  265. print()
  266. def _prompt_api_key(var: dict):
  267. """Display a nicely formatted API key input screen for a single env var."""
  268. tools = var.get("tools", [])
  269. tools_str = ", ".join(tools[:3])
  270. if len(tools) > 3:
  271. tools_str += f", +{len(tools) - 3} more"
  272. _section_rule(var.get("description", var["name"]))
  273. if tools_str:
  274. print_info(f" Enables: {tools_str}")
  275. if var.get("url"):
  276. print_info(f" Get your key at: {var['url']}")
  277. print()
  278. _prompt_and_save_env_var(var, " ✓ Saved", " Skipped (configure later with 'hermes setup')")
  279. def _prompt_and_save_env_var(var: dict, saved_msg: str, skipped_msg: str) -> None:
  280. """Prompt for one env-var value (masked when secret); persist and confirm, or report the skip."""
  281. value = prompt(f" {var.get('prompt', var['name'])}", password=bool(var.get("password")))
  282. if value:
  283. save_env_value(var["name"], value)
  284. print_success(saved_msg)
  285. else:
  286. print_warning(skipped_msg)
  287. def _module_installed(name: str) -> bool:
  288. try:
  289. return importlib.util.find_spec(name) is not None
  290. except Exception:
  291. return False
  292. def _print_banner(*lines: str) -> None:
  293. """Print the magenta box banner: top border, the given body lines, bottom border."""
  294. print()
  295. print(color("┌─────────────────────────────────────────────────────────┐", Colors.MAGENTA))
  296. for line in lines:
  297. print(color(line, Colors.MAGENTA))
  298. print(color("└─────────────────────────────────────────────────────────┘", Colors.MAGENTA))
  299. # =============================================================================
  300. # Section 1: Model & Provider Configuration
  301. # =============================================================================
  302. def setup_model_provider(config: dict, *, quick: bool = False):
  303. """Configure the inference provider and default model via the ``hermes model`` flow (one code
  304. path — any provider added there is available here). *quick* is accepted for the first-time
  305. quick setup caller; rotation, vision and TTS keep safe defaults either way."""
  306. from hermes_cli.config import load_config, save_config
  307. print_header("Inference Provider")
  308. _info("Choose how to connect to your main chat model.",
  309. f" Guide: {_DOCS_BASE}/integrations/providers", None)
  310. from hermes_cli.main import select_provider_and_model
  311. from hermes_cli.observability.shared_metrics_setup import provider_setup_surface
  312. try:
  313. with provider_setup_surface("cli_setup"):
  314. select_provider_and_model()
  315. except (SystemExit, KeyboardInterrupt):
  316. _info(None, "Provider setup skipped.")
  317. except Exception as exc:
  318. logger.debug("select_provider_and_model error during setup: %s", exc)
  319. from hermes_cli.auth_error_copy import provider_setup_failure_lines
  320. lead, *rest = provider_setup_failure_lines(exc, retry_command="hermes model")
  321. print_warning(lead)
  322. for line in rest:
  323. print_info(line)
  324. # Re-sync from disk in place: cmd_model saved via its own load/save cycle and the wizard's
  325. # final save_config(config) must not clobber it with stale values. Rotation, vision and TTS
  326. # keep safe defaults (configure via `hermes auth add` / `hermes setup tts`).
  327. config.clear()
  328. config.update(load_config())
  329. save_config(config)
  330. # =============================================================================
  331. # Section 3: Agent Settings
  332. # =============================================================================
  333. def _apply_default_agent_settings(config: dict):
  334. """Apply recommended defaults for all agent settings without prompting."""
  335. config.setdefault("agent", {})["max_turns"] = 150
  336. # config.yaml is authoritative for max_turns (the gateway bridges it into HERMES_MAX_ITERATIONS);
  337. # a stale .env entry silently shadowing it caused the 60-vs-500 bug, so drop it.
  338. remove_env_value("HERMES_MAX_ITERATIONS")
  339. config.setdefault("compression", {})["enabled"] = True
  340. config["compression"]["threshold"] = 0.50
  341. save_config(config)
  342. print_success("Applied recommended defaults:")
  343. _info(" Max iterations: 150", " Compression threshold: 0.50",
  344. " Run `hermes setup agent` later to customize.")
  345. def _prompt_number(label: str, current, cast=int):
  346. """Prompt for a number; ``None`` when the answer does not parse."""
  347. try:
  348. return cast(prompt(label, str(current)))
  349. except ValueError:
  350. return None
  351. def _prompt_int_setting(section: dict, key: str, label: str, current, accept) -> None:
  352. """Prompt for an int; store it under *key* only when it parses and *accept* holds."""
  353. value = _prompt_number(label, current)
  354. if value is not None and accept(value):
  355. section[key] = value
  356. _TOOL_PROGRESS_HELP = (
  357. "Tool Progress Display", "Controls how much tool activity is shown (CLI and messaging).",
  358. " off — Silent, just the final response",
  359. " new — Show tool name only when it changes (less noise)",
  360. " all — Show every tool call with a short preview",
  361. " verbose — Full args, results, and debug logs",
  362. " log — Silent in chat; write every tool call to ~/.hermes/logs/tool_calls.log (gateway only)",
  363. )
  364. def setup_agent_settings(config: dict):
  365. """Configure agent behavior: iterations, progress display and compression."""
  366. print_header("Agent Settings")
  367. _info(f" Guide: {_DOCS_BASE}/user-guide/configuration", None)
  368. # ── Max Iterations ── (config.yaml is authoritative; never surface a stale legacy .env value)
  369. # If a legacy .env entry is still around (from pre-PR#18413 setups), prefer the config value so we don't
  370. # surface a stale number to the user.
  371. current_max = str(cfg_get(config, "agent", "max_turns", default=90))
  372. _info("Maximum tool-calling iterations per conversation.",
  373. "Higher = more complex tasks, but costs more tokens.",
  374. f"Press Enter to keep {current_max}. Use 90 for most tasks or 150+ for open exploration.")
  375. max_iter = _prompt_number("Max iterations", current_max)
  376. if max_iter is None:
  377. print_warning("Invalid number, keeping current value")
  378. elif max_iter > 0:
  379. # config.yaml only; gateway/run.py derives HERMES_MAX_ITERATIONS from agent.max_turns.
  380. config.setdefault("agent", {})["max_turns"] = max_iter
  381. config.pop("max_turns", None)
  382. remove_env_value("HERMES_MAX_ITERATIONS")
  383. print_success(f"Max iterations set to {max_iter}")
  384. # ── Tool Progress Display ──
  385. _info("", *_TOOL_PROGRESS_HELP)
  386. # Unset = each platform keeps its own default (CLI all, Telegram/Slack off). Enter on an unset key must keep
  387. # that: a global display.tool_progress beats every platform tier (#121230).
  388. current_mode = cfg_get(config, "display", "tool_progress")
  389. mode = prompt("Tool progress mode" if current_mode else "Tool progress mode (Enter keeps per-platform defaults)",
  390. current_mode)
  391. if not mode and not current_mode:
  392. print_info("Keeping each platform's default tool progress")
  393. elif mode.lower() in {"off", "new", "all", "verbose", "log"}:
  394. config.setdefault("display", {})["tool_progress"] = mode.lower()
  395. save_config(config)
  396. print_success(f"Tool progress set to: {mode.lower()}")
  397. else:
  398. print_warning(f"Unknown mode '{mode}', keeping '{current_mode or 'per-platform defaults'}'")
  399. # ── Context Compression ──
  400. print_header("Context Compression")
  401. _info("Automatically summarizes old messages when context gets too long.",
  402. "Higher threshold = compress later (use more context). Lower = compress sooner.")
  403. config.setdefault("compression", {})["enabled"] = True
  404. current_threshold = cfg_get(config, "compression", "threshold", default=0.50)
  405. threshold = _prompt_number("Compression threshold (0.5-0.95)", current_threshold, float)
  406. if threshold is not None and 0.5 <= threshold <= 0.95:
  407. config["compression"]["threshold"] = threshold
  408. print_success(f"Context compression threshold set to {config['compression'].get('threshold', 0.50)}")
  409. save_config(config)
  410. # ── Section 5: Tool Configuration (delegates to unified tools_config.py) ──
  411. def setup_tools(config: dict, first_install: bool = False):
  412. """`hermes setup tools` == `hermes tools`: platform selection → toolset toggles → provider keys.
  413. ``first_install`` selects the simplified flow (no platform menu, prompts for all missing keys)."""
  414. from hermes_cli.tools_config import tools_command
  415. tools_command(first_install=first_install, config=config)
  416. # ── Shared Metrics ──
  417. _SEND_CONSENT_EXPLAINER = (
  418. "", "Sharing uploads each daily package to the Nous telemetry",
  419. "service. Packages carry your profile-scoped install ID, a",
  420. "stable random UUID that identifies this profile across days",
  421. "(it contains no personal information and is reset by deleting",
  422. "the shared-metrics directory). Only packages whose entire",
  423. "collection period falls inside a recorded consent window are",
  424. "ever sent. Apart from the fresh-install note (noted on this",
  425. "machine and counted only once you opt in), data from before",
  426. "you opt in is never sent. Sharing can be turned off again at",
  427. "any time.",
  428. )
  429. def setup_telemetry(config: dict):
  430. """Turn shared metrics on (collect and send to Nous) or off: one answer sets both keys."""
  431. print_header("Shared Metrics")
  432. _info("Shared metrics contain only bounded counters: activity, session length,",
  433. "outcomes, error classes (with a fixed-list reason when a memory write or",
  434. "context compression is refused, fails or is skipped), model routes and",
  435. "token totals, built-in tool, command and catalog names, bucketed setup",
  436. "counts, update and install results and timing (with a fixed-list reason",
  437. "and the stage when one fails; a fresh install is noted on this machine and",
  438. "counted only once you opt in), crashes,",
  439. "startup and reply speed, messaging-platform health, how Hermes gets used",
  440. "(agent accuracy and efficiency, active time per surface, which features and",
  441. "settings are used or switched off, provider setup outcomes), and coarse",
  442. "machine facts (RAM range, GPU type, version age and channel, updates behind,",
  443. "local model server yes/no). Never prompts, files, paths, setting values or",
  444. "error text.")
  445. _info(*_SEND_CONSENT_EXPLAINER)
  446. # The answer is written to config.yaml here, not by the caller's later save: that save strips
  447. # values equal to the defaults, so a "no" would vanish and every surface would ask again.
  448. from hermes_cli.observability.shared_metrics_consent import save_consent
  449. shared_metrics = _sub_dict(_sub_dict(config, "telemetry"), "shared_metrics")
  450. sharing = shared_metrics.get("enabled") is True and shared_metrics.get("send") is True
  451. # One answer for both keys: off also withdraws send consent and stops collection.
  452. share = prompt_yes_no("Send shared metrics to Nous?", default=sharing)
  453. save_consent(share, share, config)
  454. if share:
  455. print_success("Shared metrics sent to Nous once a day.")
  456. else:
  457. print_info("Shared metrics off.")
  458. def _record_send_consent_change(*, enabled: bool) -> None:
  459. """Reconcile consent windows at the moment the user decides — same single writer as the relay
  460. and the sender, so wizard, relay and mid-pass callers cannot disagree."""
  461. try:
  462. from hermes_cli.observability.shared_metrics import SharedMetricsStore
  463. from hermes_cli.observability.shared_metrics_sender import reconcile_send_consent
  464. from hermes_cli.sqlite_util import write_txn
  465. with SharedMetricsStore()._connection() as connection, write_txn(connection):
  466. reconcile_send_consent(connection, enabled)
  467. except Exception:
  468. # Never block the wizard on telemetry bookkeeping; the relay reconciles on the next hook.
  469. logger.debug("Unable to record shared-metrics consent change", exc_info=True)
  470. # Extracted sections, re-exported so callers and test patches keep resolving through
  471. # hermes_cli.setup. They import this module lazily inside bodies, so this is cycle-free.
  472. from hermes_cli.setup_tts import setup_tts
  473. from hermes_cli.setup_terminal import setup_terminal_backend
  474. from hermes_cli.setup_platforms import setup_gateway
  475. from hermes_cli.setup_summary import _print_setup_summary
  476. from hermes_cli.setup_migration import _skip_configured_section
  477. from hermes_cli.setup_agent_import import offer_agent_import
  478. from hermes_cli.setup_quick import _run_portal_one_shot, _run_quick_setup
  479. # ── Main Wizard Orchestrator ──
  480. SETUP_SECTIONS = [
  481. ("model", "Model & Provider", setup_model_provider),
  482. ("tts", "Text-to-Speech", setup_tts),
  483. ("terminal", "Terminal Backend", setup_terminal_backend),
  484. ("gateway", "Messaging Platforms (Gateway)", setup_gateway),
  485. ("tools", "Tools", setup_tools),
  486. ("telemetry", "Shared Metrics", setup_telemetry),
  487. ("agent", "Agent Settings", setup_agent_settings),
  488. ]
  489. def run_setup_wizard(args):
  490. """Run setup with navigation control scoped to this invocation."""
  491. with _setup_navigation_scope():
  492. try:
  493. return _run_setup_wizard_impl(args)
  494. except _SetupCancelled:
  495. _info(None, "Setup cancelled. Remaining sections were not changed.")
  496. return None
  497. def _run_setup_section(config: dict, section: str) -> None:
  498. """``hermes setup <section>``: run one SETUP_SECTIONS entry under the banner."""
  499. entry = next(((label, func) for key, label, func in SETUP_SECTIONS if key == section), None)
  500. if entry is None:
  501. print_error(f"Unknown setup section: {section}")
  502. print_info(f"Available sections: {', '.join(k for k, _, _ in SETUP_SECTIONS)}")
  503. return
  504. label, func = entry
  505. _print_banner(f"│ ☤ Hermes Setup — {label:<34s} │")
  506. _run_setup_steps([(label, lambda: func(config))])
  507. save_config(config)
  508. print()
  509. print_success(f"{label} configuration complete!")
  510. def _run_full_setup(config: dict, hermes_home, *, is_existing: bool, imported_from: str = "") -> None:
  511. """Full Setup — run all sections; after an import (*imported_from* names the agents) each
  512. already-configured section offers to skip."""
  513. print_header("Configuration Location")
  514. _info(f"Config file: {get_config_path()}", f"Secrets file: {get_env_path()}",
  515. f"Data folder: {hermes_home}", f"Install dir: {PROJECT_ROOT}", None,
  516. "You can edit these files directly or use 'hermes config edit'")
  517. if imported_from:
  518. _info(None, f"Settings were imported from {imported_from}.",
  519. "Each section below shows what is already set up — keep it,",
  520. "or choose to reconfigure it.")
  521. # Agent Settings are not prompted: first installs get defaults, existing keep theirs.
  522. if not is_existing:
  523. _apply_default_agent_settings(config)
  524. def _skip(key: str, label: str) -> bool:
  525. return bool(imported_from) and _skip_configured_section(config, key, label)
  526. def _gateway_step() -> None:
  527. if not _skip("gateway", "Messaging Platforms"):
  528. setup_gateway(config)
  529. return
  530. # An import does not imply consent to install a persistent service.
  531. from hermes_cli.gateway_setup_service import ensure_gateway_service
  532. ensure_gateway_service(context="setup", interactive=True, config=config)
  533. def _step(key: str, label: str, run) -> tuple:
  534. return label, lambda: None if _skip(key, label) else run()
  535. _run_setup_steps([
  536. _step("model", "Model & Provider", lambda: setup_model_provider(config)),
  537. _step("terminal", "Terminal Backend", lambda: setup_terminal_backend(config)),
  538. ("Messaging Platforms", _gateway_step),
  539. _step("tools", "Tools", lambda: setup_tools(config, first_install=not is_existing))])
  540. # First-time mode picker: (menu label, setup_quick runner name) — None falls through to Full Setup.
  541. _FIRST_TIME_MODES = (
  542. ("Quick Setup (Nous Portal) — free OAuth login, no API keys, model + tools (recommended)",
  543. "_run_first_time_quick_setup"),
  544. ("Full setup — configure every provider, tool & option yourself (bring your own keys)", None),
  545. ("Blank Slate — everything off except the bare minimum; opt in to each capability", "_run_blank_slate_setup"),
  546. )
  547. def _run_setup_wizard_impl(args):
  548. """Run the interactive setup wizard: full/quick (auto-detected), ``--portal``, or one
  549. ``hermes setup <section>`` from SETUP_SECTIONS."""
  550. from hermes_cli.config import is_managed, managed_error
  551. if is_managed():
  552. managed_error("run setup wizard")
  553. return
  554. ensure_hermes_home()
  555. # Back up BEFORE --reset: save_config below overwrites the very file we copy (#3522, #77299).
  556. config_path = get_config_path()
  557. from hermes_cli.config_backups import backup_config
  558. _backup_path = backup_config(config_path, "pre-setup")
  559. if getattr(args, "reset", False):
  560. save_config(copy.deepcopy(DEFAULT_CONFIG))
  561. print_success("Configuration reset to defaults.")
  562. if _backup_path: # --reset may exit before the end-of-wizard notice
  563. _info(f"Previous config backed up to: {_backup_path}")
  564. reconfigure_requested = bool(getattr(args, "reconfigure", False))
  565. quick_requested = bool(getattr(args, "quick", False))
  566. config = load_config()
  567. hermes_home = get_hermes_home()
  568. # Non-interactive environments (headless SSH, Docker, CI/CD)
  569. if getattr(args, 'non_interactive', False) or not is_interactive_stdin():
  570. print_noninteractive_setup_guidance("Running in a non-interactive environment (no TTY detected).")
  571. return
  572. if getattr(args, "portal", False): # one-shot Nous Portal setup; skips the rest
  573. _run_portal_one_shot(config)
  574. return
  575. section = getattr(args, "section", None)
  576. if section:
  577. _run_setup_section(config, section)
  578. return
  579. # Existing installation == a provider is configured
  580. from hermes_cli.auth import get_active_provider
  581. is_existing = bool(get_env_value("OPENROUTER_API_KEY") or get_env_value("OPENAI_BASE_URL")
  582. or get_active_provider() is not None)
  583. _print_banner("│ ☤ Hermes Agent Setup Wizard │",
  584. "├─────────────────────────────────────────────────────────┤",
  585. "│ Let's configure your Hermes Agent installation. │",
  586. "│ Press Ctrl+C at any time to exit. │")
  587. imported_from = ""
  588. if is_existing:
  589. # Full reconfigure wizard is the default (Enter keeps each current value); `--quick`
  590. # narrows it to missing items (partial import, cleared key). --reconfigure is a
  591. # backwards-compatible no-op here.
  592. if quick_requested:
  593. _run_setup_steps([("Quick Setup", lambda: _run_quick_setup(config, hermes_home))])
  594. _record_setup_completed(config)
  595. return
  596. print_header("Reconfigure", gap=True)
  597. print_success("You already have Hermes configured.")
  598. _info("Running the full wizard — each prompt shows your current value.",
  599. "Press Enter to keep it, or type a new value to change it.", "",
  600. "Tip: jump straight to a section with 'hermes setup model|terminal|",
  601. " gateway|tools|agent', or fill only missing items with --quick.")
  602. else:
  603. # First-time setup (--reconfigure / --quick are meaningless here; fall through)
  604. print()
  605. if reconfigure_requested or quick_requested:
  606. _info("No existing configuration found — running first-time setup.", None)
  607. # Before configuration begins. The plugin install and the import write config.yaml from
  608. # outside this dict (the import from another process), so reload it.
  609. imported_from = offer_agent_import(hermes_home)
  610. config = load_config()
  611. setup_mode = prompt_choice("How would you like to set up Hermes?", [label for label, _ in _FIRST_TIME_MODES], 0)
  612. label, runner = _FIRST_TIME_MODES[setup_mode]
  613. if runner is not None:
  614. from hermes_cli import setup_quick
  615. # Quick Setup offers to keep a model the import brought (Full setup acknowledges it below).
  616. run_args = (config, hermes_home, is_existing) + (
  617. (imported_from,) if runner == "_run_first_time_quick_setup" else ())
  618. _run_setup_steps([(label, lambda: getattr(setup_quick, runner)(*run_args))])
  619. _record_setup_completed(config)
  620. return
  621. _run_full_setup(config, hermes_home, is_existing=is_existing, imported_from=imported_from)
  622. # Save and show summary
  623. save_config(config)
  624. if _backup_path and _backup_path.exists():
  625. _info(f"Previous config backed up to: {_backup_path}",
  626. "If setup changed a value you customized, restore it with:",
  627. f" cp {_backup_path} {config_path}")
  628. _print_setup_summary(config, hermes_home)
  629. _record_setup_completed(config)
  630. def _record_setup_completed(config: dict) -> None:
  631. """Count a wizard run that finished. Every setup flow ends here, so the one-time
  632. shared-metrics offer runs first: a user who opts in now is counted; the API checks enablement."""
  633. from hermes_cli.observability.shared_metrics_consent import offer_consent_if_undecided
  634. offer_consent_if_undecided(config)
  635. from hermes_cli.observability.shared_metrics_events import record_setup_completed
  636. model = config.get("model")
  637. record_setup_completed(surface="cli", provider=model.get("provider") if isinstance(model, dict) else None)