The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cli/setup.py): split wizard into setup_{tts,terminal,platforms,summary,migration,quick} modules; table-drive summary/agent settings; shared banner helper
Teknium9128bb561010
diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex bce62d2d70d..e735fb14575 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -9,25 +9,27 @@ Modular wizard with independently-runnable sections:5. Tools — configure TTS, web search, image generation, etc.Config files are stored in ~/.hermes/ for easy access.++Section bodies live in sibling modules (setup_tts, setup_terminal, setup_platforms,+setup_summary, setup_migration, setup_quick) and are re-exported here; they resolve shared+prompt/config helpers lazily through this module so test patches on ``hermes_cli.setup.<name>``+keep working."""import importlib.util-import jsonimport loggingimport osimport re-import shutilimport sysimport copyfrom contextlib import contextmanagerfrom contextvars import ContextVarfrom pathlib import Path-from typing import Optional, Callable+from typing import Callablefrom hermes_cli.curses_ui import MenuNavigationEvent, MenuNavigationStart-from hermes_cli.nous_subscription import get_nous_subscription_features-from tools.tool_backend_helpers import managed_nous_tools_enabled-from hermes_constants import get_optional_skills_dir+from hermes_cli.nous_subscription import get_nous_subscription_features # noqa: F401 (re-export; patched by tests)+from tools.tool_backend_helpers import managed_nous_tools_enabled # noqa: F401 (re-export; patched by tests)logger = logging.getLogger(__name__)@@ -39,24 +41,11 @@ _DOCS_BASE = "https://hermes-agent.nousresearch.com/docs"# Default model lists per provider — used as fallback when the live# /models endpoint can't be reached._DEFAULT_PROVIDER_MODELS = {- "copilot-acp": [- "copilot-acp",- ],+ "copilot-acp": ["copilot-acp"],"copilot": [- "gpt-5.4",- "gpt-5.4-mini",- "gpt-5-mini",- "gpt-5.3-codex",- "gpt-5.2-codex",- "gpt-4.1",- "gpt-4o",- "gpt-4o-mini",- "claude-opus-4.6",- "claude-sonnet-5",- "claude-sonnet-4.6",- "claude-sonnet-4.5",- "claude-haiku-4.5",- "gemini-2.5-pro",+ "gpt-5.4", "gpt-5.4-mini", "gpt-5-mini", "gpt-5.3-codex", "gpt-5.2-codex", "gpt-4.1", "gpt-4o",+ "gpt-4o-mini", "claude-opus-4.6", "claude-sonnet-5", "claude-sonnet-4.6", "claude-sonnet-4.5",+ "claude-haiku-4.5", "gemini-2.5-pro",],"gemini": ["gemini-3.1-pro-preview", "gemini-3-pro-preview",@@ -87,8 +76,8 @@ _DEFAULT_PROVIDER_MODELS = {}-# Import config helpers-from hermes_cli.config import (+# Config helpers (re-exported; tests patch them on this module).+from hermes_cli.config import ( # noqa: E402cfg_get,DEFAULT_CONFIG,get_hermes_home,@@ -103,7 +92,7 @@ from hermes_cli.config import ()# display_hermes_home imported lazily at call sites (stale-module safety during hermes update)-from hermes_cli.colors import Colors, color+from hermes_cli.colors import Colors, color # noqa: E402def print_header(title: str):@@ -166,6 +155,16 @@ def print_noninteractive_setup_guidance(reason: str | None = None) -> None:print()+_BRACKETED_PASTE_PATTERN = re.compile(r"\x1b\[\s*200~|\x1b\[\s*201~")+++def _sanitize_pasted_input(value: str) -> str:+ """Strip terminal bracketed-paste control markers from pasted text."""+ if not isinstance(value, str) or not value:+ return value+ return _BRACKETED_PASTE_PATTERN.sub("", value)++def prompt(question: str, default: str = None, password: bool = False) -> str:"""Prompt for input with optional default."""display = f"{question} [{default}]: " if default else f"{question}: "@@ -185,6 +184,12 @@ def prompt(question: str, default: str = None, password: bool = False) -> str:sys.exit(1)+# =============================================================================+# Setup navigation (Escape cancels, Left arrow goes back) — a ContextVar state+# machine shared with the curses menus.+# =============================================================================++class _SetupControlFlow(BaseException):"""Bypass provider error handlers that intentionally catch ``Exception``.@@ -216,6 +221,14 @@ class _SetupNavigationState:self.resolved_choices: list[object] = []self.replay_choices: list[object] = []+ def reset(self, section_index: int = -1, replay: list | None = None) -> None:+ """Rewind per-section counters (entering a section, or leaving the wizard)."""+ self.section_index = section_index+ self.prompt_index = 0+ self.active_prompt_index = -1+ self.resolved_choices = []+ self.replay_choices = copy.deepcopy(replay or [])+_SETUP_NAVIGATION: ContextVar[_SetupNavigationState | None] = ContextVar("hermes_setup_navigation", default=None@@ -240,9 +253,7 @@ def _handle_setup_menu_navigation(if state.active_prompt_index < len(state.replay_choices):return MenuNavigationStart(allow_back=allow_back,- replay_value=copy.deepcopy(- state.replay_choices[state.active_prompt_index]- ),+ replay_value=copy.deepcopy(state.replay_choices[state.active_prompt_index]),)return MenuNavigationStart(allow_back=allow_back)if event is MenuNavigationEvent.RESOLVE:@@ -263,27 +274,95 @@ def _handle_setup_menu_navigation(return None-_BRACKETED_PASTE_PATTERN = re.compile(r"\x1b\[\s*200~|\x1b\[\s*201~")+@contextmanager+def _setup_navigation_scope():+ """Install and reliably restore the setup menu navigation context."""+ from hermes_cli.curses_ui import reset_menu_navigation_handler, set_menu_navigation_handler+ token = _SETUP_NAVIGATION.set(_SetupNavigationState())+ menu_token = set_menu_navigation_handler(_handle_setup_menu_navigation)+ try:+ yield+ finally:+ reset_menu_navigation_handler(menu_token)+ _SETUP_NAVIGATION.reset(token)+++def _run_setup_steps(steps: list[tuple[str, Callable[[], None]]]) -> None:+ """Run setup sections with left-arrow navigation between choices.++ Left arrow at a section's first choice returns to the previous section.+ From a later, nested choice it replays earlier selections invisibly and+ reopens only the immediately preceding prompt.+ """+ state = _SETUP_NAVIGATION.get()+ section_index = 0+ answers_by_section: dict[int, list[object]] = {}+ replay_by_section: dict[int, list[object]] = {}+ try:+ while section_index < len(steps):+ label, action = steps[section_index]+ if state is not None:+ state.reset(section_index, replay_by_section.pop(section_index, []))+ try:+ action()+ except _SetupGoBack as navigation:+ if state is not None:+ answers_by_section[section_index] = copy.deepcopy(state.resolved_choices)+ if navigation.prompt_index > 0:+ previous_index = section_index+ target_prompt = navigation.prompt_index - 1+ else:+ previous_index = max(0, section_index - 1)+ target_prompt = max(0, len(answers_by_section.get(previous_index, [])) - 1)+ replay_by_section[previous_index] = copy.deepcopy(+ answers_by_section.get(previous_index, [])[:target_prompt]+ )+ print()+ if previous_index == section_index:+ print_info(f"Returning to the previous choice in {label}...")+ else:+ print_info(f"Returning to {steps[previous_index][0]}...")+ section_index = previous_index+ continue+ if state is not None:+ answers_by_section[section_index] = copy.deepcopy(state.resolved_choices)+ section_index += 1+ finally:+ if state is not None:+ state.reset()+++def run_setup_action_with_navigation(+ label: str,+ action: Callable[[], None],+ *,+ cancelled_message: str = "Setup cancelled.",+) -> None:+ """Run a setup-style menu flow with Escape and nested Left navigation.++ Shared commands such as ``hermes model`` use the same provider/model+ pickers as the setup wizard, but run outside ``run_setup_wizard``. This+ installs the setup navigation context for that standalone command and+ reuses the same prompt replay state machine.+ """+ with _setup_navigation_scope():+ try:+ _run_setup_steps([(label, action)])+ except _SetupCancelled:+ print()+ print_info(cancelled_message)-def _sanitize_pasted_input(value: str) -> str:- """Strip terminal bracketed-paste control markers from pasted text."""- if not isinstance(value, str) or not value:- return value- return _BRACKETED_PASTE_PATTERN.sub("", value)++# =============================================================================+# Prompt primitives+# =============================================================================def _curses_prompt_choice(question: str, choices: list, default: int = 0, description: str | None = None) -> int:"""Single-select menu using curses. Delegates to curses_radiolist."""from hermes_cli.curses_ui import curses_radiolist- return curses_radiolist(- question,- choices,- selected=default,- cancel_returns=-1,- description=description,- )-+ return curses_radiolist(question, choices, selected=default, cancel_returns=-1, description=description)def prompt_choice(question: str, choices: list, default: int = 0, description: str | None = None) -> int:@@ -317,12 +396,7 @@ def is_noninteractive() -> bool:installed (the start path asks "Install it now?" with no one to answer).Honour the explicit env flag here so callers fall back to their default."""- return os.environ.get("HERMES_NONINTERACTIVE", "").strip().lower() in {- "1",- "true",- "yes",- "on",- }+ return os.environ.get("HERMES_NONINTERACTIVE", "").strip().lower() in {"1", "true", "yes", "on"}def prompt_yes_no(question: str, default: bool = True) -> bool:@@ -339,22 +413,13 @@ def prompt_yes_no(question: str, default: bool = True) -> bool:# through the same menu surface so ESC and left-arrow work consistently,# while preserving the traditional line prompt for every other caller.if _SETUP_NAVIGATION.get() is not None:- default_index = 0 if default else 1- return _curses_prompt_choice(- question,- ["Yes", "No"],- default_index,- ) == 0+ return _curses_prompt_choice(question, ["Yes", "No"], 0 if default else 1) == 0default_str = "Y/n" if default else "y/N"while True:try:- value = (- input(color(f"{question} [{default_str}]: ", Colors.YELLOW))- .strip()- .lower()- )+ value = input(color(f"{question} [{default_str}]: ", Colors.YELLOW)).strip().lower()except KeyboardInterrupt:print()sys.exit(1)@@ -375,31 +440,18 @@ def prompt_yes_no(question: str, default: bool = True) -> bool:def prompt_checklist(title: str, items: list, pre_selected: list = None) -> list:- """- Display a multi-select checklist and return the indices of selected items.-- Each item in `items` is a display string. `pre_selected` is a list of- indices that should be checked by default. A "Continue →" option is- appended at the end — the user toggles items with Space and confirms- with Enter on "Continue →".+ """Multi-select checklist; returns the sorted indices of selected items.- Falls back to a numbered toggle interface when curses is- unavailable.-- Returns:- List of selected indices (not including the Continue option).+ Each item is a display string; ``pre_selected`` indices start checked. The user toggles+ with Space and confirms with Enter on the appended "Continue →" option. Cancel keeps the+ pre-selection. Falls back to a numbered toggle interface when curses is unavailable."""if pre_selected is None:pre_selected = []from hermes_cli.curses_ui import curses_checklist- chosen = curses_checklist(- title,- items,- set(pre_selected),- cancel_returns=set(pre_selected),- )+ chosen = curses_checklist(title, items, set(pre_selected), cancel_returns=set(pre_selected))return sorted(chosen)@@ -419,10 +471,7 @@ def _prompt_api_key(var: dict):print_info(f" Get your key at: {var['url']}")print()- if var.get("password"):- value = prompt(f" {var.get('prompt', var['name'])}", password=True)- else:- value = prompt(f" {var.get('prompt', var['name'])}")+ value = prompt(f" {var.get('prompt', var['name'])}", password=bool(var.get("password")))if value:save_env_value(var["name"], value)@@ -438,404 +487,16 @@ def _module_installed(name: str) -> bool:return False-# provider -> (label, env vars: any one set means available; empty = always).-# Local engines are (label, module, hint) and must be importable.-_TTS_SUMMARY_ROWS = {- "elevenlabs": ("ElevenLabs", ("ELEVENLABS_API_KEY",)),- "openai": ("OpenAI", ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY")),- "minimax": ("MiniMax", ("MINIMAX_API_KEY",)),- "mistral": ("Mistral Voxtral", ("MISTRAL_API_KEY",)),- "gemini": ("Google Gemini", ("GEMINI_API_KEY", "GOOGLE_API_KEY")),- "neutts": ("NeuTTS", "neutts", "run 'hermes setup tts'"),- "kittentts": ("KittenTTS", "kittentts", "run 'hermes setup tts'"),-}-_TTS_SUMMARY_DEFAULT = ("Edge TTS", ())-_STT_SUMMARY_ROWS = {- "openai": ("OpenAI", ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY")),- "groq": ("Groq Whisper", ("GROQ_API_KEY",)),- "elevenlabs": ("ElevenLabs Scribe", ("ELEVENLABS_API_KEY",)),- "xai": ("xAI", ()),- "deepinfra": ("DeepInfra", ("DEEPINFRA_API_KEY",)),-}-_STT_SUMMARY_DEFAULT = ("Local Whisper", "faster_whisper", "run 'hermes tools' → Speech-to-Text")---def _voice_provider_status(kind: str, provider: str, rows: dict, default: tuple) -> tuple:- """Summary row for a TTS/STT provider. A keyed provider whose key is missing- falls through to the default row, matching the runtime fallback."""- row = rows.get(provider, default)- if isinstance(row[1], tuple) and row[1] and not any(get_env_value(v) for v in row[1]):- row = default- if isinstance(row[1], tuple):- return (f"{kind} ({row[0]})", True, None)- label, module, hint = row- if _module_installed(module):- return (f"{kind} ({label}{' local' if kind == 'Text-to-Speech' else ''})", True, None)- return (f"{kind} ({label} — not installed)", False, hint)---def _print_setup_summary(config: dict, hermes_home):- """Print the setup completion summary."""- # Provider readiness — the one thing setup absolutely must produce.- # Previously a user could cancel the API-key prompt mid-wizard (Enter →- # "Cancelled."), watch the wizard continue through Terminal/Gateway/Tools,- # and exit "successfully" with NO working model — believing they were set- # up. Say so loudly instead (consumer-onboarding audit finding #7).- try:- from hermes_cli.auth import resolve_provider-- resolve_provider()- _provider_ready = True- except Exception:- _provider_ready = False- if not _provider_ready:- print()- print_warning("No inference provider is configured — Hermes cannot chat yet.")- print_info(" Finish this one step with either of:")- print_info(" hermes model (pick any provider/model)")- print_info(" hermes setup --portal (Nous Portal OAuth, no API key)")-- # Tool availability summary- print()- print_header("Tool Availability Summary")-- tool_status = []- subscription_features = get_nous_subscription_features(config)-- # Vision — use the same runtime resolver as the actual vision tools- try:- from agent.auxiliary_client import get_available_vision_backends-- _vision_backends = get_available_vision_backends()- except Exception:- _vision_backends = []-- if _vision_backends:- tool_status.append(("Vision (image analysis)", True, None))- else:- tool_status.append(("Vision (image analysis)", False, "run 'hermes setup' to configure"))--- # Web tools (Exa, Parallel, Firecrawl, Tavily, or Keenable)- if subscription_features.web.managed_by_nous:- tool_status.append(("Web Search & Extract (Nous subscription)", True, None))- elif subscription_features.web.available:- label = "Web Search & Extract"- if subscription_features.web.current_provider:- label = f"Web Search & Extract ({subscription_features.web.current_provider})"- tool_status.append((label, True, None))- else:- tool_status.append(("Web Search & Extract", False, "EXA_API_KEY, PARALLEL_API_KEY, FIRECRAWL_API_KEY/FIRECRAWL_API_URL, TAVILY_API_KEY, KEENABLE_API_KEY, or SEARXNG_URL"))-- # Browser tools (local Chromium, Camofox, Browserbase, Browser Use, or Firecrawl)- browser_provider = subscription_features.browser.current_provider- if subscription_features.browser.managed_by_nous:- tool_status.append(("Browser Automation (Nous Browser Use)", True, None))- elif subscription_features.browser.available:- label = "Browser Automation"- if browser_provider:- label = f"Browser Automation ({browser_provider})"- tool_status.append((label, True, None))- else:- missing_browser_hint = "npm install -g agent-browser, set CAMOFOX_URL, or configure Browser Use or Browserbase"- if browser_provider == "Browserbase":- missing_browser_hint = (- "npm install -g agent-browser and set "- "BROWSERBASE_API_KEY/BROWSERBASE_PROJECT_ID"- )- elif browser_provider == "Browser Use":- missing_browser_hint = (- "npm install -g agent-browser and set BROWSER_USE_API_KEY"- )- elif browser_provider == "Camofox":- missing_browser_hint = "CAMOFOX_URL"- elif browser_provider == "Local browser":- missing_browser_hint = (- "npm install -g agent-browser && agent-browser install --with-deps"- )- tool_status.append(- ("Browser Automation", False, missing_browser_hint)- )-- # Image generation — FAL (direct or via Nous), or any plugin-registered- # provider (OpenAI, etc.)- if subscription_features.image_gen.managed_by_nous:- tool_status.append(("Image Generation (Nous subscription)", True, None))- elif subscription_features.image_gen.available:- tool_status.append(("Image Generation", True, None))- else:- # Fall back to probing plugin-registered providers so OpenAI-only- # setups don't show as "missing FAL_KEY".- _img_backend = None- try:- from agent.image_gen_registry import list_providers- from hermes_cli.plugins import _ensure_plugins_discovered-- _ensure_plugins_discovered()- for _p in list_providers():- if _p.name == "fal":- continue- try:- if _p.is_available():- _img_backend = _p.display_name- break- except Exception:- continue- except Exception:- pass- if _img_backend:- tool_status.append((f"Image Generation ({_img_backend})", True, None))- else:- tool_status.append(("Image Generation", False, "FAL_KEY or OPENAI_API_KEY"))-- # Video generation — opt-in via `hermes tools` → Video Generation.- # Only show the row when a plugin reports available so we don't badger- # users who don't care about video gen with a "missing" status line.- if subscription_features.video_gen.managed_by_nous:- tool_status.append(("Video Generation (FAL via Nous subscription)", True, None))- else:- try:- from agent.video_gen_registry import list_providers as _list_video_providers- from hermes_cli.plugins import _ensure_plugins_discovered as _ensure_plugins- _ensure_plugins()- _video_backend = None- for _vp in _list_video_providers():- try:- if _vp.is_available():- _video_backend = _vp.display_name- break- except Exception:- continue- except Exception:- _video_backend = None- if _video_backend:- tool_status.append((f"Video Generation ({_video_backend})", True, None))-- # TTS / STT — configured provider, gated on its key (or local install)- tts_provider = cfg_get(config, "tts", "provider", default="edge")- if subscription_features.tts.managed_by_nous:- tool_status.append(("Text-to-Speech (OpenAI via Nous subscription)", True, None))- else:- tool_status.append(_voice_provider_status("Text-to-Speech", tts_provider, _TTS_SUMMARY_ROWS, _TTS_SUMMARY_DEFAULT))- stt_provider = cfg_get(config, "stt", "provider", default="local") or "local"- _stt_feature = subscription_features.features.get("stt")- if _stt_feature is not None and _stt_feature.managed_by_nous:- tool_status.append(("Speech-to-Text (OpenAI via Nous subscription)", True, None))- else:- tool_status.append(_voice_provider_status("Speech-to-Text", stt_provider, _STT_SUMMARY_ROWS, _STT_SUMMARY_DEFAULT))-- if subscription_features.modal.managed_by_nous:- tool_status.append(("Modal Execution (Nous subscription)", True, None))- elif cfg_get(config, "terminal", "backend") == "modal":- if subscription_features.modal.direct_override:- tool_status.append(("Modal Execution (direct Modal)", True, None))- else:- tool_status.append(("Modal Execution", False, "run 'hermes setup terminal'"))- elif managed_nous_tools_enabled() and subscription_features.nous_auth_present:- tool_status.append(("Modal Execution (optional via Nous subscription)", True, None))-- # Home Assistant- if get_env_value("HASS_TOKEN"):- tool_status.append(("Smart Home (Home Assistant)", True, None))-- # Spotify (OAuth via hermes auth spotify — check auth.json, not env vars)- try:- from hermes_cli.auth import get_provider_auth_state- _spotify_state = get_provider_auth_state("spotify") or {}- if _spotify_state.get("access_token") or _spotify_state.get("refresh_token"):- tool_status.append(("Spotify (PKCE OAuth)", True, None))- except Exception:- pass-- # Skills Hub- if get_env_value("GITHUB_TOKEN"):- tool_status.append(("Skills Hub (GitHub)", True, None))- else:- tool_status.append(("Skills Hub (GitHub)", False, "GITHUB_TOKEN"))-- # Terminal (always available if system deps met)- tool_status.append(("Terminal/Commands", True, None))-- # Task planning (always available, in-memory)- tool_status.append(("Task Planning (todo)", True, None))-- # Skills (always available -- bundled skills + user-created skills)- tool_status.append(("Skills (view, create, edit)", True, None))-- # Print status- available_count = sum(1 for _, avail, _ in tool_status if avail)- total_count = len(tool_status)-- print_info(f"{available_count}/{total_count} tool categories available:")- print()-- for name, available, missing_var in tool_status:- if available:- print(f" {color('✓', Colors.GREEN)} {name}")- else:- print(- f" {color('✗', Colors.RED)} {name} {color(f'(missing {missing_var})', Colors.DIM)}"- )-- print()-- disabled_tools = [(name, var) for name, avail, var in tool_status if not avail]- if disabled_tools:- print_warning(- "Some tools are disabled. Run 'hermes setup tools' to configure them,"- )- from hermes_constants import display_hermes_home as _dhh- print_warning(f"or edit {_dhh()}/.env directly to add the missing API keys.")- print()-- # Done banner- print()- for line in (- "┌─────────────────────────────────────────────────────────┐",- "│ ✓ Setup Complete! │",- "└─────────────────────────────────────────────────────────┘",- ):- print(color(line, Colors.GREEN))- print()-- from hermes_constants import display_hermes_home as _dhh- print(color(f"📁 All your files are in {_dhh()}/:", Colors.CYAN, Colors.BOLD))- print()- print(f" {color('Settings:', Colors.YELLOW)} {get_config_path()}")- print(f" {color('API Keys:', Colors.YELLOW)} {get_env_path()}")- print(f" {color('Data:', Colors.YELLOW)} {hermes_home}/cron/, sessions/, logs/")- print()-- print(color("─" * 60, Colors.DIM))- print()- print(color("📝 To edit your configuration:", Colors.CYAN, Colors.BOLD))- print()- for cmd, desc in (- ("hermes setup", " Re-run the full wizard"),- ("hermes setup model", " Change model/provider"),- ("hermes setup terminal", " Change terminal backend"),- ("hermes setup gateway", " Configure messaging"),- ("hermes setup tools", " Configure tool providers"),- ):- print(f" {color(cmd, Colors.GREEN)}{desc}")- print()- print(f" {color('hermes config', Colors.GREEN)} View current settings")- print(f" {color('hermes config edit', Colors.GREEN)} Open config in your editor")- print(f" {color('hermes config set <key> <value>', Colors.GREEN)}")- print(" Set a specific value")- print()- print(" Or edit the files directly:")- print(f" {color(f'nano {get_config_path()}', Colors.DIM)}")- print(f" {color(f'nano {get_env_path()}', Colors.DIM)}")- print()-- print(color("─" * 60, Colors.DIM))- print()- print(color("🚀 Ready to go!", Colors.CYAN, Colors.BOLD))- print()- print(f" {color('hermes', Colors.GREEN)} Start chatting")- print(f" {color('hermes gateway', Colors.GREEN)} Start messaging gateway")- print(f" {color('hermes doctor', Colors.GREEN)} Check for issues")- print()---def _prompt_vercel_sandbox_settings(config: dict):- """Prompt for Vercel Sandbox settings without exposing unsupported disk sizing."""- terminal = config.setdefault("terminal", {})-+def _print_banner(*lines: str) -> None:+ """Print the magenta box banner: top border, the given body lines, bottom border."""print()- print_info("Vercel Sandbox settings:")- print_info(" Filesystem persistence uses Vercel snapshots.")- print_info(" Snapshots restore files only; live processes do not continue after sandbox recreation.")-- from tools.terminal_tool import _SUPPORTED_VERCEL_RUNTIMES-- current_runtime = terminal.get("vercel_runtime") or "node24"- supported_label = ", ".join(_SUPPORTED_VERCEL_RUNTIMES)- runtime = prompt(f" Runtime ({supported_label})", current_runtime).strip() or current_runtime- if runtime not in _SUPPORTED_VERCEL_RUNTIMES:- print_warning(f"Unsupported Vercel runtime '{runtime}', keeping {current_runtime}.")- runtime = current_runtime if current_runtime in _SUPPORTED_VERCEL_RUNTIMES else "node24"- terminal["vercel_runtime"] = runtime- save_env_value("TERMINAL_VERCEL_RUNTIME", runtime)-- current_persist = terminal.get("container_persistent", True)- persist_label = "yes" if current_persist else "no"- terminal["container_persistent"] = prompt(- " Persist filesystem with snapshots? (yes/no)", persist_label- ).lower() in {"yes", "true", "y", "1"}-- current_cpu = terminal.get("container_cpu", 1)- cpu_str = prompt(" CPU cores", str(current_cpu))- try:- terminal["container_cpu"] = float(cpu_str)- except ValueError:- pass-- current_mem = terminal.get("container_memory", 5120)- mem_str = prompt(" Memory in MB (5120 = 5GB)", str(current_mem))- try:- terminal["container_memory"] = int(mem_str)- except ValueError:- pass+ print(color("┌─────────────────────────────────────────────────────────┐", Colors.MAGENTA))+ for line in lines:+ print(color(line, Colors.MAGENTA))+ print(color("└─────────────────────────────────────────────────────────┘", Colors.MAGENTA))- if terminal.get("container_disk", 51200) not in {0, 51200}:- print_warning("Vercel Sandbox does not support custom disk sizing; resetting container_disk to 51200.")- terminal["container_disk"] = 51200- print()- print_info("Vercel authentication:")- print_info(" Use a long-lived Vercel access token plus project/team IDs.")- linked_project = _read_nearest_vercel_project()- if linked_project:- print_info(" Found defaults in nearest .vercel/project.json.")-- remove_env_value("VERCEL_OIDC_TOKEN")- token = prompt(" Vercel access token", get_env_value("VERCEL_TOKEN") or "", password=True)- project = prompt(- " Vercel project ID",- get_env_value("VERCEL_PROJECT_ID") or linked_project.get("projectId", ""),- )- team = prompt(- " Vercel team ID",- get_env_value("VERCEL_TEAM_ID") or linked_project.get("orgId", ""),- )- if token:- save_env_value("VERCEL_TOKEN", token)- if project:- save_env_value("VERCEL_PROJECT_ID", project)- if team:- save_env_value("VERCEL_TEAM_ID", team)---def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]:- """Read project/team defaults from the nearest Vercel link file."""- current = (start or Path.cwd()).resolve()- if current.is_file():- current = current.parent-- for directory in (current, *current.parents):- project_file = directory / ".vercel" / "project.json"- if not project_file.exists():- continue- try:- data = json.loads(project_file.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- return {}- if not isinstance(data, dict):- return {}- return {- key: value- for key, value in {- "projectId": data.get("projectId"),- "orgId": data.get("orgId"),- }.items()- if isinstance(value, str) and value.strip()- }- return {}---# Tool categories and provider config are now in tools_config.py (shared+# Tool categories and provider config are in tools_config.py (shared# between `hermes tools` and `hermes setup tools`).@@ -844,7 +505,6 @@ def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]:# =============================================================================-def setup_model_provider(config: dict, *, quick: bool = False):"""Configure the inference provider and default model.@@ -877,726 +537,112 @@ def setup_model_provider(config: dict, *, quick: bool = False):print_info("You can try again later with: hermes model")# Re-sync the wizard's config dict from what cmd_model saved to disk.- # This is critical: cmd_model writes to disk via its own load/save cycle,- # and the wizard's final save_config(config) must not overwrite those- # changes with stale values (#4172). Refresh the dict in place so callers- # that keep the same object see every section the shared model picker may- # have changed (model, custom_providers, auxiliary, provider metadata, etc.).- _refreshed = load_config()+ # cmd_model writes via its own load/save cycle, and the wizard's final+ # save_config(config) must not overwrite those changes with stale values+ # (#4172). Refresh in place so callers holding the same object see every+ # section the picker may have changed (model, custom_providers, auxiliary, ...).config.clear()- config.update(_refreshed)-- # Credential rotation, vision-backend selection, and TTS provider are no- # longer prompted here. They have safe defaults (rotation off, vision- # auto-detected from the main provider, TTS = Edge) and are configurable- # on demand via `hermes auth add`, `hermes setup` vision, and- # `hermes setup tts`. This keeps both quick and full setup thin.-+ config.update(load_config())+ # Credential rotation, vision-backend selection, and TTS provider have safe+ # defaults (rotation off, vision auto-detected, TTS = Edge) and are configured+ # on demand via `hermes auth add`, `hermes setup` vision, and `hermes setup tts`.# Tool Gateway prompt is already shown by _model_flow_nous() above.save_config(config)# =============================================================================-# Section 1b: TTS Provider Configuration+# Section 3: Agent Settings# =============================================================================-def _check_espeak_ng() -> bool:- """Check if espeak-ng is installed."""- return shutil.which("espeak-ng") is not None or shutil.which("espeak") is not None---def _pip_install_tts_package(name: str, pip_args: list, manual_cmd: str) -> bool:- """Install a local TTS engine through the canonical uv → pip → ensurepip- ladder so pip-less venvs (Ubuntu 25.10 ``python -m venv``, ``uv venv``) work."""- from hermes_cli.tools_config import _pip_install-- try:- result = _pip_install(pip_args, timeout=300)- except Exception as e:- print_error(f"Failed to install {name}: {e}")- print_info(f"Try manually: {manual_cmd}")- return False- if result.returncode == 0:- print_success(f"{name} installed successfully")- return True- err = (result.stderr or "").strip()- print_error(f"Failed to install {name}: {err[:300] if err else 'install failed'}")- print_info(f"Try manually: {manual_cmd}")- return False---def _install_neutts_deps() -> bool:- """Install NeuTTS dependencies with user approval. Returns True on success."""- import subprocess- import sys-- # Check espeak-ng- if not _check_espeak_ng():- print()- print_warning("NeuTTS requires espeak-ng for phonemization.")- if sys.platform == "darwin":- print_info("Install with: brew install espeak-ng")- elif sys.platform == "win32":- print_info("Install with: choco install espeak-ng")- else:- print_info("Install with: sudo apt install espeak-ng")- print()- if prompt_yes_no("Install espeak-ng now?", True):- try:- if sys.platform == "darwin":- subprocess.run(["brew", "install", "espeak-ng"], check=True)- elif sys.platform == "win32":- subprocess.run(["choco", "install", "espeak-ng", "-y"], check=True)- else:- subprocess.run(["sudo", "apt", "install", "-y", "espeak-ng"], check=True)- print_success("espeak-ng installed")- except (subprocess.CalledProcessError, FileNotFoundError) as e:- print_warning(f"Could not install espeak-ng automatically: {e}")- print_info("Please install it manually and re-run setup.")- return False- else:- print_warning("espeak-ng is required for NeuTTS. Install it manually before using NeuTTS.")+def _apply_default_agent_settings(config: dict):+ """Apply recommended defaults for all agent settings without prompting."""+ config.setdefault("agent", {})["max_turns"] = 150+ # config.yaml is the authoritative source for max_turns; the gateway+ # bridges it into HERMES_MAX_ITERATIONS at startup. We no longer write+ # to .env to avoid the dual-source inconsistency that caused the+ # 60-vs-500 bug (stale .env entry silently shadowing config.yaml).+ remove_env_value("HERMES_MAX_ITERATIONS")- # Install neutts Python package- print()- print_info("Installing neutts Python package...")- print_info("This will also download the TTS model (~300MB) on first use.")- print()+ config.setdefault("display", {})["tool_progress"] = "all"- return _pip_install_tts_package("neutts", ["-U", "neutts[all]", "--quiet"], "uv pip install -U 'neutts[all]'")+ config.setdefault("compression", {})["enabled"] = True+ config["compression"]["threshold"] = 0.50+ # Default: never auto-reset sessions. This matches the gateway's own+ # default (SessionResetPolicy.mode = "none"); we still write it+ # explicitly so the choice is visible/editable in config.yaml.+ config.setdefault("session_reset", {})["mode"] = "none"-def _install_kittentts_deps() -> bool:- """Install KittenTTS dependencies with user approval. Returns True on success."""+ save_config(config)+ print_success("Applied recommended defaults:")+ print_info(" Max iterations: 150")+ print_info(" Tool progress: all")+ print_info(" Compression threshold: 0.50")+ print_info(" Session reset: never (use /reset or compression)")+ print_info(" Run `hermes setup agent` later to customize.")- wheel_url = (- "https://github.com/KittenML/KittenTTS/releases/download/"- "0.8.1/kittentts-0.8.1-py3-none-any.whl"- )- print()- print_info("Installing kittentts Python package (~25-80MB model downloaded on first use)...")- print()- return _pip_install_tts_package(- "kittentts", ["-U", wheel_url, "soundfile", "--quiet"], f"uv pip install -U '{wheel_url}' soundfile",- )+def _prompt_int_setting(section: dict, key: str, label: str, current, accept) -> None:+ """Prompt for an int; store it under *key* only when it parses and *accept* holds."""+ try:+ value = int(prompt(label, str(current)))+ if accept(value):+ section[key] = value+ except ValueError:+ pass-def _xai_oauth_logged_in_for_setup() -> bool:- """True iff xAI Grok OAuth credentials are already stored locally.+_TOOL_PROGRESS_HELP = (+ "Tool Progress Display",+ "Controls how much tool activity is shown (CLI and messaging).",+ " off — Silent, just the final response",+ " new — Show tool name only when it changes (less noise)",+ " all — Show every tool call with a short preview",+ " verbose — Full args, results, and debug logs",+ " log — Silent in chat; write every tool call to ~/.hermes/logs/tool_calls.log (gateway only)",+)+_SESSION_RESET_HELP = (+ "Messaging sessions (Telegram, Discord, etc.) accumulate context over time.",+ "Each message adds to the conversation history, which means growing API costs.",+ "",+ "To manage this, sessions can automatically reset after a period of inactivity",+ "or at a fixed time each day. When a reset happens, the agent saves important",+ "things to its persistent memory first — but the conversation context is cleared.",+ "",+ "You can also manually reset anytime by typing /reset in chat.",+ "",+)+_SESSION_RESET_CHOICES = [+ "Inactivity + daily reset (reset whichever comes first)",+ "Inactivity only (reset after N minutes of no messages)",+ "Daily only (reset at a fixed hour each day)",+ "Never auto-reset (recommended - context lives until /reset or context compression)",+ "Keep current settings",+]+_SESSION_RESET_MODES = ("both", "idle", "daily", "none") # index 4 = keep current- Lets TTS / STT setup skip the API-key prompt for users who logged in- through ``hermes model`` -> xAI Grok OAuth (SuperGrok / Premium+).- """- try:- from hermes_cli.auth import get_xai_oauth_auth_status- return bool(get_xai_oauth_auth_status().get("logged_in"))- except Exception:- return False+def setup_agent_settings(config: dict):+ """Configure agent behavior: iterations, progress display, compression, session reset."""+ print_header("Agent Settings")+ print_info(f" Guide: {_DOCS_BASE}/user-guide/configuration")+ print()-def _run_xai_oauth_login_from_setup() -> bool:- """Run the xAI Grok OAuth device-code login from inside the setup wizard.+ # ── Max Iterations ──+ # config.yaml is authoritative; a legacy .env entry (pre-PR#18413) must not+ # surface a stale number, so read from config only.+ current_max = str(cfg_get(config, "agent", "max_turns", default=90))+ print_info("Maximum tool-calling iterations per conversation.")+ print_info("Higher = more complex tasks, but costs more tokens.")+ print_info(f"Press Enter to keep {current_max}. Use 90 for most tasks or 150+ for open exploration.")- Saves OAuth tokens only. Does **not** switch the active inference- provider or rewrite ``model.provider`` — callers (TTS setup, tools- config) only need credentials for side tools.-- Returns True on success, False on any failure (the caller falls back- to whatever the user picked next, e.g. Edge TTS).- """- try:- from hermes_cli.auth import (- _is_remote_session,- _save_xai_oauth_tokens,- _xai_oauth_device_code_login,- unsuppress_credential_source,- )- except Exception as exc:- print_warning(f"xAI Grok OAuth helpers unavailable: {exc}")- return False-- open_browser = not _is_remote_session()- print()- print_info("Signing in to xAI Grok OAuth (SuperGrok / Premium+)...")- try:- creds = _xai_oauth_device_code_login(open_browser=open_browser)- _save_xai_oauth_tokens(- creds["tokens"],- discovery=creds.get("discovery"),- redirect_uri=creds.get("redirect_uri", ""),- last_refresh=creds.get("last_refresh"),- auth_mode="oauth_device_code",- set_active=False,- )- # Mirror model/dashboard re-login: clear device_code suppression so- # the pool can seed from the singleton after a prior `auth remove`.- unsuppress_credential_source("xai-oauth", "device_code")- return True- except Exception as exc:- print_warning(f"xAI Grok OAuth login failed: {exc}")- return False---_TTS_PROVIDER_LABELS = {- "edge": "Edge TTS",- "elevenlabs": "ElevenLabs",- "openai": "OpenAI TTS",- "xai": "xAI TTS",- "minimax": "MiniMax TTS",- "mistral": "Mistral Voxtral TTS",- "gemini": "Google Gemini TTS",- "neutts": "NeuTTS",- "kittentts": "KittenTTS",-}-_TTS_PROVIDER_CHOICES = [- ("edge", "Edge TTS (free, cloud-based, no setup needed)"),- ("elevenlabs", "ElevenLabs (premium quality, needs API key)"),- ("openai", "OpenAI TTS (good quality, needs API key)"),- ("xai", "xAI TTS (Grok voices — OAuth login or API key)"),- ("minimax", "MiniMax TTS (high quality with voice cloning, needs API key)"),- ("mistral", "Mistral Voxtral TTS (multilingual, native Opus, needs API key)"),- ("gemini", "Google Gemini TTS (30 prebuilt voices, prompt-controllable, needs API key)"),- ("neutts", "NeuTTS (local on-device, free, ~300MB model download)"),- ("kittentts", "KittenTTS (local on-device, free, lightweight ~25-80MB ONNX)"),-]-# provider -> (env vars that satisfy it, env var to save, prompt, success line, pre-prompt hint)-_TTS_API_KEY_PROVIDERS = {- "elevenlabs": (("ELEVENLABS_API_KEY",), "ELEVENLABS_API_KEY", "ElevenLabs API key", "ElevenLabs API key saved", ""),- "openai": (- ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"), "VOICE_TOOLS_OPENAI_KEY",- "OpenAI API key for TTS", "OpenAI TTS API key saved", "",- ),- "minimax": (("MINIMAX_API_KEY",), "MINIMAX_API_KEY", "MiniMax API key for TTS", "MiniMax TTS API key saved", ""),- "mistral": (("MISTRAL_API_KEY",), "MISTRAL_API_KEY", "Mistral API key for TTS", "Mistral TTS API key saved", ""),- "gemini": (- ("GEMINI_API_KEY", "GOOGLE_API_KEY"), "GEMINI_API_KEY", "Gemini API key for TTS", "Gemini TTS API key saved",- "Get a free API key at https://aistudio.google.com/app/apikey",- ),-}-# provider -> (module, display name, requirement lines, install question, installer)-_TTS_LOCAL_PROVIDERS = {- "neutts": (- "neutts", "NeuTTS",- ("NeuTTS requires:", " • Python package: neutts (~50MB install + ~300MB model on first use)",- " • System package: espeak-ng (phonemizer)"),- "Install NeuTTS dependencies now?", _install_neutts_deps,- ),- "kittentts": (- "kittentts", "KittenTTS",- ("KittenTTS is lightweight (~25-80MB, CPU-only, no API key required).",- "Voices: Jasper, Bella, Luna, Bruno, Rosie, Hugo, Kiki, Leo"),- "Install KittenTTS now?", _install_kittentts_deps,- ),-}---def _tts_api_key_step(selected: str) -> str:- """Ensure the key for an API-key TTS provider exists; fall back to edge otherwise."""- env_vars, save_var, prompt_label, saved_msg, hint = _TTS_API_KEY_PROVIDERS[selected]- if any(get_env_value(v) for v in env_vars):- return selected- print()- if hint:- print_info(hint)- api_key = prompt(prompt_label, password=True)- if api_key:- save_env_value(save_var, api_key)- print_success(saved_msg)- return selected- print_warning("No API key provided. Falling back to Edge TTS.")- return "edge"---def _tts_local_install_step(selected: str) -> str:- """Offer to install a local TTS engine; fall back to edge if declined/failed."""- module, name, lines, question, installer = _TTS_LOCAL_PROVIDERS[selected]- if _module_installed(module):- print_success(f"{name} is already installed")- return selected- print()- for line in lines:- print_info(line)- print()- if not prompt_yes_no(question, True):- print_info(f"Skipping install. Set tts.provider to '{selected}' after installing manually.")- return "edge"- if not installer():- print_warning(f"{name} installation incomplete. Falling back to Edge TTS.")- return "edge"- return selected---def _tts_xai_step(config: dict) -> str:- """xAI TTS auth. Order: existing OAuth tokens (free for SuperGrok) > existing- XAI_API_KEY > offer both paths — xAI TTS works with OAuth bearer tokens too."""- selected = "xai"- if _xai_oauth_logged_in_for_setup():- print_success("xAI TTS will use your xAI Grok OAuth (SuperGrok / Premium+) credentials")- elif get_env_value("XAI_API_KEY"):- print_success("xAI TTS will use your existing XAI_API_KEY")- else:- print()- choice_idx = prompt_choice(- "How do you want xAI TTS to authenticate?",- choices=[- "Sign in with xAI Grok OAuth (SuperGrok / Premium+) — browser login",- "Paste an xAI API key (console.x.ai)",- "Skip → fallback to Edge TTS",- ],- default=0,- )- if choice_idx == 0:- if _run_xai_oauth_login_from_setup():- print_success("Logged in — xAI TTS will use these OAuth credentials")- else:- print_warning("xAI Grok OAuth login did not complete. Falling back to Edge TTS.")- selected = "edge"- elif choice_idx == 1:- api_key = prompt("xAI API key for TTS", password=True)- if api_key:- save_env_value("XAI_API_KEY", api_key)- print_success("xAI TTS API key saved")- else:- from hermes_constants import display_hermes_home as _dhh- print_warning(- "No xAI API key provided for TTS. Configure XAI_API_KEY "- f"via hermes setup model or {_dhh()}/.env to use xAI TTS. "- "Falling back to Edge TTS."- )- selected = "edge"- else:- print_warning("xAI TTS skipped. Falling back to Edge TTS.")- selected = "edge"-- if selected == "xai":- print()- voice_id = prompt("xAI voice_id (Enter for 'eve', or paste a custom voice ID)")- if voice_id and voice_id.strip():- config.setdefault("tts", {}).setdefault("xai", {})["voice_id"] = voice_id.strip()- print_success(f"xAI voice_id set to: {voice_id.strip()}")- return selected---def _setup_tts_provider(config: dict):- """Interactive TTS provider selection with install flow for local engines."""- current_provider = config.get("tts", {}).get("provider", "edge")- current_label = _TTS_PROVIDER_LABELS.get(current_provider, current_provider)-- print()- print_header("Text-to-Speech Provider (optional)")- print_info(f"Current: {current_label}")- print()-- options = list(_TTS_PROVIDER_CHOICES)- if managed_nous_tools_enabled() and get_nous_subscription_features(config).nous_auth_present:- options.insert(0, ("nous-openai", "Nous Subscription (managed OpenAI TTS, billed to your subscription)"))- choices = [label for _, label in options] + [f"Keep current ({current_label})"]- keep_current_idx = len(choices) - 1- idx = prompt_choice("Select TTS provider:", choices, keep_current_idx)- if idx == keep_current_idx:- return-- selected = options[idx][0]- selected_via_nous = selected == "nous-openai"- if selected_via_nous:- selected = "openai"- print_info("OpenAI TTS will use the managed Nous gateway and bill to your subscription.")- if get_env_value("VOICE_TOOLS_OPENAI_KEY") or get_env_value("OPENAI_API_KEY"):- print_warning(- "Direct OpenAI credentials are still configured and may take precedence until removed from ~/.hermes/.env."- )-- if selected in _TTS_LOCAL_PROVIDERS:- selected = _tts_local_install_step(selected)- elif selected in _TTS_API_KEY_PROVIDERS and not selected_via_nous:- selected = _tts_api_key_step(selected)- elif selected == "xai":- selected = _tts_xai_step(config)-- config.setdefault("tts", {})["provider"] = selected- save_config(config)- print_success(f"TTS provider set to: {_TTS_PROVIDER_LABELS.get(selected, selected)}")---def setup_tts(config: dict):- """Standalone TTS setup (for 'hermes setup tts')."""- _setup_tts_provider(config)---# =============================================================================-# Section 2: Terminal Backend Configuration-# =============================================================================---def _prompt_secret_env(label: str, env_var: str, *, confirm_msg: str = "") -> None:- """Prompt for a secret and persist it to .env when non-empty."""- value = prompt(label, password=True)- if value:- save_env_value(env_var, value)- if confirm_msg:- print_success(confirm_msg)---def _ensure_sdk(package: str, manual_hint: str, *, show_stderr: bool = False) -> None:- """Import *package*; if missing, install it via the venv pip helper."""- try:- __import__(package)- except ImportError:- print_info(f"Installing {package} SDK...")- from hermes_cli.tools_config import _pip_install-- result = _pip_install([package])- if result.returncode == 0:- print_success(f"{package} SDK installed")- else:- print_warning(f"Install failed — run manually: {manual_hint}")- if show_stderr and result.stderr:- print_info(f" Error: {result.stderr.strip().splitlines()[-1]}")---def _setup_backend_local(config: dict) -> None:- print_success("Terminal backend: Local")- print_info("Commands run directly on this machine.")- # Gateway working directory defaults to home; sudo stays off. Both are- # configurable later via `hermes setup terminal` / config.yaml.- config["terminal"].setdefault("cwd", str(Path.home()))---def _setup_backend_docker(config: dict) -> None:- print_success("Terminal backend: Docker")- docker_bin = shutil.which("docker")- if not docker_bin:- print_warning("Docker not found in PATH!")- print_info("Install Docker: https://docs.docker.com/get-docker/")- else:- print_info(f"Docker found: {docker_bin}")-- # Image and resource limits use defaults; tune via `hermes setup terminal`.- config["terminal"].setdefault("docker_image", "nikolaik/python-nodejs:python3.11-nodejs20")- print()- print_info("Docker sandboxes can be protected with the egress credential firewall.")- print_info(- "It routes sandbox traffic through iron-proxy so containers receive "- "proxy tokens instead of real API keys."- )- print_info(" Docker only for now; Modal, SSH, Daytona, and Singularity are not wired yet.")- if prompt_yes_no(" Enable egress firewall for Docker sandboxes?", False):- proxy_cfg = config.setdefault("proxy", {})- proxy_cfg["enabled"] = True- proxy_cfg.setdefault("enforce_on_docker", True)- print_success("Egress firewall enabled in config")- print_info("Run `hermes egress setup` then `hermes egress start` to mint tokens and launch the proxy.")- else:- print_info("Skipping egress firewall. You can enable it later with `hermes egress setup`.")---def _setup_backend_singularity(config: dict) -> None:- print_success("Terminal backend: Singularity/Apptainer")- sing_bin = shutil.which("apptainer") or shutil.which("singularity")- if not sing_bin:- print_warning("Singularity/Apptainer not found in PATH!")- print_info("Install: https://apptainer.org/docs/admin/main/installation.html")- else:- print_info(f"Found: {sing_bin}")- # Image and resource limits use defaults; tune via `hermes setup terminal`.- config["terminal"].setdefault("singularity_image", "docker://nikolaik/python-nodejs:python3.11-nodejs20")---def _setup_backend_modal(config: dict) -> None:- print_success("Terminal backend: Modal")- print_info("Serverless cloud sandboxes. Each session gets its own container.")- from tools.managed_tool_gateway import is_managed_tool_gateway_ready- from tools.tool_backend_helpers import normalize_modal_mode-- managed_modal_available = bool(- managed_nous_tools_enabled()- and get_nous_subscription_features(config).nous_auth_present- and is_managed_tool_gateway_ready("modal")- )- modal_mode = normalize_modal_mode(cfg_get(config, "terminal", "modal_mode"))- use_managed_modal = False- if managed_modal_available:- if modal_mode == "managed":- default_modal_idx = 0- elif modal_mode == "direct":- default_modal_idx = 1- else:- default_modal_idx = 1 if get_env_value("MODAL_TOKEN_ID") else 0- modal_mode_idx = prompt_choice(- "Select how Modal execution should be billed:",- ["Use my Nous subscription", "Use my own Modal account"],- default_modal_idx,- )- use_managed_modal = modal_mode_idx == 0-- if use_managed_modal:- config["terminal"]["modal_mode"] = "managed"- print_info("Modal execution will use the managed Nous gateway and bill to your subscription.")- if get_env_value("MODAL_TOKEN_ID") or get_env_value("MODAL_TOKEN_SECRET"):- print_info("Direct Modal credentials are still configured, but this backend is pinned to managed mode.")- return-- config["terminal"]["modal_mode"] = "direct"- print_info("Requires a Modal account: https://modal.com")- _ensure_sdk("modal", "uv pip install modal")- print()- print_info("Modal authentication:")- print_info(" Get your token at: https://modal.com/settings")- if get_env_value("MODAL_TOKEN_ID"):- print_info(" Modal token: already configured")- if not prompt_yes_no(" Update Modal credentials?", False):- return- _prompt_secret_env(" Modal Token ID", "MODAL_TOKEN_ID")- _prompt_secret_env(" Modal Token Secret", "MODAL_TOKEN_SECRET")---def _setup_backend_daytona(config: dict) -> None:- print_success("Terminal backend: Daytona")- print_info("Persistent cloud development environments.")- print_info("Each session gets a dedicated sandbox with filesystem persistence.")- print_info("Sign up at: https://daytona.io")- _ensure_sdk("daytona", "uv pip install daytona", show_stderr=True)- print()- if get_env_value("DAYTONA_API_KEY"):- print_info(" Daytona API key: already configured")- if prompt_yes_no(" Update API key?", False):- _prompt_secret_env(" Daytona API key", "DAYTONA_API_KEY", confirm_msg=" Updated")- else:- _prompt_secret_env(" Daytona API key", "DAYTONA_API_KEY", confirm_msg=" Configured")- # Image and resource limits use defaults; tune via `hermes setup terminal`.- config["terminal"].setdefault("daytona_image", "nikolaik/python-nodejs:python3.11-nodejs20")---def _setup_backend_vercel(config: dict) -> None:- print_success("Terminal backend: Vercel Sandbox")- print_info("Cloud microVM sandboxes with snapshot-backed filesystem persistence.")- print_info("Requires the optional SDK: pip install 'hermes-agent[vercel]'")try:- __import__("vercel")- except ImportError:- print_info("Installing vercel SDK...")- import subprocess-- # Managed uv first: $HERMES_HOME/bin is never on PATH, so a bare which()- # misses the uv Hermes installed; bootstrapping one mid-wizard is fine,- # and a `uv venv` venv may not even have pip.- from hermes_cli.managed_uv import ensure_uv-- uv_bin = ensure_uv()- cmd = (- [uv_bin, "pip", "install", "--python", sys.executable, "vercel"]- if uv_bin- else [sys.executable, "-m", "pip", "install", "vercel"]- )- result = subprocess.run(cmd, capture_output=True, text=True)- if result.returncode == 0:- print_success("vercel SDK installed")- else:- print_warning("Install failed — run manually: pip install 'hermes-agent[vercel]'")- if result.stderr:- print_info(f" Error: {result.stderr.strip().splitlines()[-1]}")- _prompt_vercel_sandbox_settings(config)---def _setup_backend_ssh(config: dict) -> None:- print_success("Terminal backend: SSH")- print_info("Run commands on a remote machine via SSH.")-- host = prompt(" SSH host (hostname or IP)", get_env_value("TERMINAL_SSH_HOST") or "")- if host:- save_env_value("TERMINAL_SSH_HOST", host)- user = prompt(" SSH user", (get_env_value("TERMINAL_SSH_USER") or "") or os.getenv("USER", ""))- if user:- save_env_value("TERMINAL_SSH_USER", user)- port = prompt(" SSH port", get_env_value("TERMINAL_SSH_PORT") or "22")- if port and port != "22":- save_env_value("TERMINAL_SSH_PORT", port)- default_key = str(Path.home() / ".ssh" / "id_rsa")- ssh_key = prompt(" SSH private key path", (get_env_value("TERMINAL_SSH_KEY") or "") or default_key)- if ssh_key:- save_env_value("TERMINAL_SSH_KEY", ssh_key)-- if host and prompt_yes_no(" Test SSH connection?", True):- print_info(" Testing connection...")- import subprocess-- ssh_cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5"]- if ssh_key:- ssh_cmd.extend(["-i", ssh_key])- if port and port != "22":- ssh_cmd.extend(["-p", port])- ssh_cmd.append(f"{user}@{host}" if user else host)- ssh_cmd.append("echo ok")- result = subprocess.run(ssh_cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)- if result.returncode == 0:- print_success(" SSH connection successful!")- else:- print_warning(f" SSH connection failed: {result.stderr.strip()}")- print_info(" Check your SSH key and host settings.")---def _setup_backend_plugin(config: dict, backend: str) -> None:- try:- from agent.terminal_env_registry import get_provider-- provider = get_provider(backend)- print_success(f"Terminal backend: {provider.display_name}")- for line in provider.setup_instructions():- print_info(line)- provider.post_setup()- except Exception as exc:- print_warning(f"Backend plugin setup hook failed: {exc}")---_BUILTIN_TERMINAL_BACKENDS = [- ("local", "Local - run directly on this machine (default)"),- ("docker", "Docker - isolated container with configurable resources"),- ("modal", "Modal - serverless cloud sandbox"),- ("ssh", "SSH - run on a remote machine"),- ("daytona", "Daytona - persistent cloud development environment"),- ("vercel_sandbox", "Vercel Sandbox - cloud microVM with snapshot filesystem persistence"),-]-_TERMINAL_BACKEND_SETUP = {- "local": _setup_backend_local,- "docker": _setup_backend_docker,- "singularity": _setup_backend_singularity,- "modal": _setup_backend_modal,- "daytona": _setup_backend_daytona,- "vercel_sandbox": _setup_backend_vercel,- "ssh": _setup_backend_ssh,-}---def setup_terminal_backend(config: dict):- """Configure the terminal execution backend."""- import platform as _platform- print_header("Terminal Backend")- print_info("Choose where Hermes runs shell commands and code.")- print_info("This affects tool execution, file access, and isolation.")- print_info(f" Guide: {_DOCS_BASE}/user-guide/configuration#terminal-backend-configuration")- print()-- current_backend = cfg_get(config, "terminal", "backend", default="local")- backends = list(_BUILTIN_TERMINAL_BACKENDS)- if _platform.system() == "Linux":- backends.append(("singularity", "Singularity/Apptainer - HPC-friendly container"))-- # Plugin-registered terminal backends (standalone plugin repos under- # ~/.hermes/plugins/). Fail-soft: a broken plugin must not take the wizard down.- plugin_backend_names = []- try:- from hermes_cli.plugins import discover_plugins-- discover_plugins() # idempotent — plugin state may not be loaded yet- from agent.terminal_env_registry import list_providers-- for provider in list_providers():- pname = provider.name.strip().lower()- backends.append((pname, f"{provider.display_name} - {provider.description}"))- plugin_backend_names.append(pname)- except Exception:- pass-- keep_current_idx = len(backends)- terminal_choices = [label for _, label in backends] + [f"Keep current ({current_backend})"]- terminal_idx = prompt_choice("Select terminal backend:", terminal_choices, keep_current_idx)- if terminal_idx == keep_current_idx:- print_info(f"Keeping current backend: {current_backend}")- return- selected_backend = backends[terminal_idx][0] if 0 <= terminal_idx < len(backends) else None-- config.setdefault("terminal", {})["backend"] = selected_backend- # Plugin names shadow only the ssh built-in (dispatch order of the original chain).- handler = _TERMINAL_BACKEND_SETUP.get(selected_backend)- if handler is not None and (selected_backend != "ssh" or selected_backend not in plugin_backend_names):- handler(config)- elif selected_backend in plugin_backend_names:- _setup_backend_plugin(config, selected_backend)-- # config.yaml is the source of truth, but terminal_tool reads TERMINAL_ENV- # from .env — keep them in sync.- save_env_value("TERMINAL_ENV", selected_backend)- if selected_backend == "modal":- save_env_value("TERMINAL_MODAL_MODE", config["terminal"].get("modal_mode", "auto"))- if selected_backend == "vercel_sandbox":- save_env_value("TERMINAL_VERCEL_RUNTIME", config["terminal"].get("vercel_runtime", "node24"))- save_config(config)- print()- print_success(f"Terminal backend set to: {selected_backend}")---# =============================================================================-# Section 3: Agent Settings-# =============================================================================---def _apply_default_agent_settings(config: dict):- """Apply recommended defaults for all agent settings without prompting."""- config.setdefault("agent", {})["max_turns"] = 150- # config.yaml is the authoritative source for max_turns; the gateway- # bridges it into HERMES_MAX_ITERATIONS at startup. We no longer write- # to .env to avoid the dual-source inconsistency that caused the- # 60-vs-500 bug (stale .env entry silently shadowing config.yaml).- remove_env_value("HERMES_MAX_ITERATIONS")-- config.setdefault("display", {})["tool_progress"] = "all"-- config.setdefault("compression", {})["enabled"] = True- config["compression"]["threshold"] = 0.50-- # Default: never auto-reset sessions. This matches the gateway's own- # default (SessionResetPolicy.mode = "none"); we still write it- # explicitly so the choice is visible/editable in config.yaml.- config.setdefault("session_reset", {})["mode"] = "none"-- save_config(config)- print_success("Applied recommended defaults:")- print_info(" Max iterations: 150")- print_info(" Tool progress: all")- print_info(" Compression threshold: 0.50")- print_info(" Session reset: never (use /reset or compression)")- print_info(" Run `hermes setup agent` later to customize.")---def _prompt_int_setting(section: dict, key: str, label: str, current, accept) -> None:- """Prompt for an int; store it under *key* only when it parses and *accept* holds."""- try:- value = int(prompt(label, str(current)))- if accept(value):- section[key] = value- except ValueError:- pass---def setup_agent_settings(config: dict):- """Configure agent behavior: iterations, progress display, compression, session reset."""-- print_header("Agent Settings")- print_info(f" Guide: {_DOCS_BASE}/user-guide/configuration")- print()-- # ── Max Iterations ──- # config.yaml is authoritative; read from there. If a legacy .env- # entry is still around (from pre-PR#18413 setups), prefer the- # config value so we don't surface a stale number to the user.- current_max = str(cfg_get(config, "agent", "max_turns", default=90))- print_info("Maximum tool-calling iterations per conversation.")- print_info("Higher = more complex tasks, but costs more tokens.")- print_info(- f"Press Enter to keep {current_max}. Use 90 for most tasks or 150+ for open exploration."- )-- max_iter_str = prompt("Max iterations", current_max)- try:- max_iter = int(max_iter_str)+ max_iter = int(prompt("Max iterations", current_max))if max_iter > 0:- # Write to config.yaml (authoritative) only. Also clean up any- # stale .env entry from earlier setup runs — the gateway's- # bridge in gateway/run.py now unconditionally derives+ # config.yaml only; drop any stale .env entry — gateway/run.py derives# HERMES_MAX_ITERATIONS from agent.max_turns at startup.config.setdefault("agent", {})["max_turns"] = max_iterconfig.pop("max_turns", None)@@ -1607,20 +653,13 @@ def setup_agent_settings(config: dict):# ── Tool Progress Display ──print_info("")- print_info("Tool Progress Display")- print_info("Controls how much tool activity is shown (CLI and messaging).")- print_info(" off — Silent, just the final response")- print_info(" new — Show tool name only when it changes (less noise)")- print_info(" all — Show every tool call with a short preview")- print_info(" verbose — Full args, results, and debug logs")- print_info(" log — Silent in chat; write every tool call to ~/.hermes/logs/tool_calls.log (gateway only)")+ for line in _TOOL_PROGRESS_HELP:+ print_info(line)current_mode = cfg_get(config, "display", "tool_progress", default="all")mode = prompt("Tool progress mode", current_mode)if mode.lower() in {"off", "new", "all", "verbose", "log"}:- if "display" not in config:- config["display"] = {}- config["display"]["tool_progress"] = mode.lower()+ config.setdefault("display", {})["tool_progress"] = mode.lower()save_config(config)print_success(f"Tool progress set to: {mode.lower()}")else:@@ -1629,508 +668,53 @@ def setup_agent_settings(config: dict):# ── Context Compression ──print_header("Context Compression")print_info("Automatically summarizes old messages when context gets too long.")- print_info(- "Higher threshold = compress later (use more context). Lower = compress sooner."- )+ print_info("Higher threshold = compress later (use more context). Lower = compress sooner.")config.setdefault("compression", {})["enabled"] = Truecurrent_threshold = cfg_get(config, "compression", "threshold", default=0.50)- threshold_str = prompt("Compression threshold (0.5-0.95)", str(current_threshold))try:- threshold = float(threshold_str)+ threshold = float(prompt("Compression threshold (0.5-0.95)", str(current_threshold)))if 0.5 <= threshold <= 0.95:config["compression"]["threshold"] = thresholdexcept ValueError:pass- print_success(- f"Context compression threshold set to {config['compression'].get('threshold', 0.50)}"- )+ print_success(f"Context compression threshold set to {config['compression'].get('threshold', 0.50)}")# ── Session Reset Policy ──print_header("Session Reset Policy")- print_info(- "Messaging sessions (Telegram, Discord, etc.) accumulate context over time."- )- print_info(- "Each message adds to the conversation history, which means growing API costs."- )- print_info("")- print_info(- "To manage this, sessions can automatically reset after a period of inactivity"- )- print_info(- "or at a fixed time each day. When a reset happens, the agent saves important"- )- print_info(- "things to its persistent memory first — but the conversation context is cleared."- )- print_info("")- print_info("You can also manually reset anytime by typing /reset in chat.")- print_info("")-- reset_choices = [- "Inactivity + daily reset (reset whichever comes first)",- "Inactivity only (reset after N minutes of no messages)",- "Daily only (reset at a fixed hour each day)",- "Never auto-reset (recommended - context lives until /reset or context compression)",- "Keep current settings",- ]+ for line in _SESSION_RESET_HELP:+ print_info(line)current_policy = config.get("session_reset", {})current_mode = current_policy.get("mode", "none")- current_idle = current_policy.get("idle_minutes", 1440)- current_hour = current_policy.get("at_hour", 4)-- default_reset = {"both": 0, "idle": 1, "daily": 2, "none": 3}.get(current_mode, 3)- reset_idx = prompt_choice("Session reset mode:", reset_choices, default_reset)-- reset_cfg = config.setdefault("session_reset", {})- mode = {0: "both", 1: "idle", 2: "daily", 3: "none"}.get(reset_idx) # 4 = keep current- if mode is not None:- reset_cfg["mode"] = mode- if mode in ("both", "idle"):- _prompt_int_setting(reset_cfg, "idle_minutes", " Inactivity timeout (minutes)", current_idle, lambda v: v > 0)- if mode in ("both", "daily"):- _prompt_int_setting(reset_cfg, "at_hour", " Daily reset hour (0-23, local time)", current_hour, lambda v: 0 <= v <= 23)- idle_now, hour_now = reset_cfg.get("idle_minutes", 1440), reset_cfg.get("at_hour", 4)- if mode == "both":- print_success(f"Sessions reset after {idle_now} min idle or daily at {hour_now}:00")- elif mode == "idle":- print_success(f"Sessions reset after {idle_now} min of inactivity")- elif mode == "daily":- print_success(f"Sessions reset daily at {hour_now}:00")- elif mode == "none":- print_info("Sessions will never auto-reset. Context is managed only by compression.")- print_warning("Long conversations will grow in cost. Use /reset manually when needed.")-- save_config(config)---# =============================================================================-# Section 4: Messaging Platforms (Gateway)-# =============================================================================---_TELEGRAM_BOT_TOKEN_RE = re.compile(r"^\d+:[A-Za-z0-9_-]{30,}$")---def _is_valid_telegram_bot_token(token: str) -> bool:- return bool(_TELEGRAM_BOT_TOKEN_RE.match(token))---def _setup_telegram_auto_result():- """Attempt automatic Telegram bot creation via managed QR onboarding."""- try:- from hermes_cli.telegram_managed_bot import auto_setup_telegram_bot_result- except ImportError:- return None-- profile_name: str | None = None- try:- profile_name = _profile_name_from_hermes_home(Path(get_hermes_home()))- except Exception:- pass-- return auto_setup_telegram_bot_result(profile_name=profile_name)---def _profile_name_from_hermes_home(hermes_home) -> str | None:- """Return the active profile name when HERMES_HOME is a profile dir."""- if hermes_home.parent.name == "profiles":- return hermes_home.name- return None---def _prompt_telegram_bot_token() -> str | None:- print_info("Create a bot via @BotFather on Telegram")- while True:- token = prompt("Telegram bot token", password=True)- if not token:- return None- if not _is_valid_telegram_bot_token(token):- print_error(- "Invalid token format. Expected: <numeric_id>:<alphanumeric_hash> "- "(e.g., 123456789:ABCdefGHI-jklMNOpqrSTUvwxYZ)"- )- continue- return token---def _setup_telegram():- """Configure Telegram bot credentials and allowlist."""- print_header("Telegram")- existing = get_env_value("TELEGRAM_BOT_TOKEN")- if existing:- print_info("Telegram: already configured")- if not prompt_yes_no("Reconfigure Telegram?", False):- # Check missing allowlist on existing config- if not get_env_value("TELEGRAM_ALLOWED_USERS"):- print_info("⚠️ Telegram has no user allowlist - anyone can use your bot!")- if prompt_yes_no("Add allowed users now?", True):- print_info(" To find your Telegram user ID: message @userinfobot")- allowed_users = prompt("Allowed user IDs (comma-separated)")- if allowed_users:- save_env_value("TELEGRAM_ALLOWED_USERS", allowed_users.replace(" ", ""))- print_success("Telegram allowlist configured")- return-- print_info("How would you like to create your Telegram bot?")- print()- print_info(" [1] Automatic (recommended)")- print_info(" Scan a QR code → confirm in Telegram → done.")- print_info(" No token copy-paste needed.")- print()- print_info(" [2] Manual")- print_info(" Create a bot via @BotFather yourself and paste the token.")- print()-- choice = prompt("Choice [1/2]", default="1")- token = None- setup_result = None-- if choice.strip() == "1":- setup_result = _setup_telegram_auto_result()- if setup_result:- token = setup_result.token- if not _is_valid_telegram_bot_token(token):- print_error("Automatic setup returned an invalid Telegram bot token.")- token = None- setup_result = None- else:- token = None- if not token:- print()- print_info("Falling back to manual setup...")- print()-- if not token:- token = _prompt_telegram_bot_token()- if not token:- return-- save_env_value("TELEGRAM_BOT_TOKEN", token)- print_success("Telegram token saved")-- print()- print_info("🔒 Security: Restrict who can use your bot")- print_info(" To find your Telegram user ID:")- print_info(" 1. Message @userinfobot on Telegram")- print_info(" 2. It will reply with your numeric ID (e.g., 123456789)")- print()-- detected_user_id = getattr(setup_result, "owner_user_id", None)- if detected_user_id:- detected_id = str(detected_user_id)- print_success(f"Detected your Telegram user ID: {detected_id}")- if prompt_yes_no("Allow this Telegram account to use the bot?", True):- extra = prompt("Additional allowed user IDs (comma-separated, optional)")- ids = [detected_id]- for uid in extra.replace(" ", "").split(","):- if uid and uid not in ids:- ids.append(uid)- allowed_users = ",".join(ids)- else:- allowed_users = prompt(- "Allowed user IDs (comma-separated, leave empty for open access)"- )- else:- allowed_users = prompt(- "Allowed user IDs (comma-separated, leave empty for open access)"- )-- if allowed_users:- allowed_users = allowed_users.replace(" ", "")- save_env_value("TELEGRAM_ALLOWED_USERS", allowed_users)- print_success("Telegram allowlist configured - only listed users can use the bot")- else:- print_info("⚠️ No allowlist set - anyone who finds your bot can use it!")-- print()- print_info("📬 Home Channel: where Hermes delivers cron job results,")- print_info(" cross-platform messages, and notifications.")- print_info(" For Telegram DMs, this is your user ID (same as above).")-- first_user_id = allowed_users.split(",")[0].strip() if allowed_users else ""- if first_user_id:- if prompt_yes_no(f"Use your user ID ({first_user_id}) as the home channel?", True):- save_env_value("TELEGRAM_HOME_CHANNEL", first_user_id)- print_success(f"Telegram home channel set to {first_user_id}")- else:- home_channel = prompt("Home channel ID (or leave empty to set later with /set-home in Telegram)")- if home_channel:- save_env_value("TELEGRAM_HOME_CHANNEL", home_channel)- else:- print_info(" You can also set this later by typing /set-home in your Telegram chat.")- home_channel = prompt("Home channel ID (leave empty to set later)")- if home_channel:- save_env_value("TELEGRAM_HOME_CHANNEL", home_channel)---# _setup_slack and _write_slack_manifest_and_instruct moved to the slack-# plugin: plugins/platforms/slack/adapter.py::interactive_setup (registered-# via setup_fn and dispatched through the plugin path). #41112 / #3823.---# _setup_matrix moved to plugins/platforms/matrix/adapter.py::interactive_setup-# (registered via setup_fn, dispatched through the plugin path). #41112.---def _setup_bluebubbles():- """Configure BlueBubbles iMessage gateway."""- print_header("BlueBubbles (iMessage)")- existing = get_env_value("BLUEBUBBLES_SERVER_URL")- if existing:- print_info("BlueBubbles: already configured")- if not prompt_yes_no("Reconfigure BlueBubbles?", False):- return-- print_info("Connects Hermes to iMessage via BlueBubbles — a free, open-source")- print_info("macOS server that bridges iMessage to any device.")- print_info(" Requires a Mac running BlueBubbles Server v1.0.0+")- print_info(" Download: https://bluebubbles.app/")- print()- print_info("In BlueBubbles Server → Settings → API, note your Server URL and Password.")- print()-- server_url = prompt("BlueBubbles server URL (e.g. http://192.168.1.10:1234)")- if not server_url:- print_warning("Server URL is required — skipping BlueBubbles setup")- return- save_env_value("BLUEBUBBLES_SERVER_URL", server_url.rstrip("/"))-- password = prompt("BlueBubbles server password", password=True)- if not password:- print_warning("Password is required — skipping BlueBubbles setup")- return- save_env_value("BLUEBUBBLES_PASSWORD", password)- print_success("BlueBubbles credentials saved")-- print()- print_info("🔒 Security: Restrict who can message your bot")- print_info(" Use iMessage addresses: email ([email protected]) or phone (+15551234567)")- print()- allowed_users = prompt("Allowed iMessage addresses (comma-separated, leave empty for open access)")- if allowed_users:- save_env_value("BLUEBUBBLES_ALLOWED_USERS", allowed_users.replace(" ", ""))- print_success("BlueBubbles allowlist configured")- else:- print_info("⚠️ No allowlist set — anyone who can iMessage you can use the bot!")-- print()- print_info("📬 Home Channel: phone or email for cron job delivery and notifications.")- print_info(" You can also set this later with /set-home in your iMessage chat.")- home_channel = prompt("Home channel address (leave empty to set later)")- if home_channel:- save_env_value("BLUEBUBBLES_HOME_CHANNEL", home_channel)-- print()- print_info("Advanced settings (defaults are fine for most setups):")- if prompt_yes_no("Configure webhook listener settings?", False):- webhook_port = prompt("Webhook listener port (default: 8645)")- if webhook_port:- try:- save_env_value("BLUEBUBBLES_WEBHOOK_PORT", str(int(webhook_port)))- print_success(f"Webhook port set to {webhook_port}")- except ValueError:- print_warning("Invalid port number, using default 8645")-- print()- print_info("Requires the BlueBubbles Private API helper for typing indicators,")- print_info("read receipts, and tapback reactions. Basic messaging works without it.")- print_info(" Install: https://docs.bluebubbles.app/helper-bundle/installation")---def _setup_qqbot():- """Configure QQ Bot (Official API v2) via gateway setup."""- from hermes_cli.gateway import _setup_qqbot as _gateway_setup_qqbot- _gateway_setup_qqbot()---def _setup_webhooks():- """Configure webhook integration."""- print_header("Webhooks")- existing = get_env_value("WEBHOOK_ENABLED")- if existing:- print_info("Webhooks: already configured")- if not prompt_yes_no("Reconfigure webhooks?", False):- return-- print()- print_warning("⚠ Webhook and SMS platforms require exposing gateway ports to the")- print_warning(" internet. For security, run the gateway in a sandboxed environment")- print_warning(" (Docker, VM, etc.) to limit blast radius from prompt injection.")- print()- print_info(" Full guide: https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/")- print()-- port = prompt("Webhook port (default 8644)")- if port:- try:- save_env_value("WEBHOOK_PORT", str(int(port)))- print_success(f"Webhook port set to {port}")- except ValueError:- print_warning("Invalid port number, using default 8644")-- secret = prompt("Global HMAC secret (shared across all routes)", password=True)- if secret:- save_env_value("WEBHOOK_SECRET", secret)- print_success("Webhook secret saved")- else:- print_warning("No secret set — you must configure per-route secrets in config.yaml")-- save_env_value("WEBHOOK_ENABLED", "true")- print()- print_success("Webhooks enabled! Next steps:")- from hermes_constants import display_hermes_home as _dhh- print_info(f" 1. Define webhook routes in {_dhh()}/config.yaml")- print_info(" 2. Point your service (GitHub, GitLab, etc.) at:")- print_info(" http://your-server:8644/webhooks/<route-name>")- print()- print_info(" Route configuration guide:")- print_info(" https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/#configuring-routes")- print()- print_info(" Open config in your editor: hermes config edit")- print_info(" Open config in your editor: hermes config edit")---# (platform label, credential env var, home-channel env vars — any one satisfies)-_HOME_CHANNEL_CHECKS = (- ("Telegram", "TELEGRAM_BOT_TOKEN", ("TELEGRAM_HOME_CHANNEL",)),- ("Discord", "DISCORD_BOT_TOKEN", ("DISCORD_HOME_CHANNEL",)),- ("Slack", "SLACK_BOT_TOKEN", ("SLACK_HOME_CHANNEL",)),- ("BlueBubbles", "BLUEBUBBLES_SERVER_URL", ("BLUEBUBBLES_HOME_CHANNEL",)),- ("QQBot", "QQ_APP_ID", ("QQBOT_HOME_CHANNEL", "QQ_HOME_CHANNEL")),-)---def setup_gateway(config: dict):- """Configure messaging platform integrations."""- from hermes_cli.gateway import _all_platforms, _platform_status, _configure_platform-- print_header("Messaging Platforms")- print_info("Connect to messaging platforms to chat with Hermes from anywhere.")- print_info("Toggle with Space, confirm with Enter.")- print()-- platforms = _all_platforms()-- # Build checklist, pre-selecting already-configured platforms.- items = []- pre_selected = []- for i, plat in enumerate(platforms):- status = _platform_status(plat)- items.append(f"{plat['emoji']} {plat['label']} ({status})")- if status == "configured":- pre_selected.append(i)-- selected = prompt_checklist("Select platforms to configure:", items, pre_selected)-- if not selected:- print_info("No platforms selected. Run 'hermes setup gateway' later to configure.")- else:- for idx in selected:- _configure_platform(platforms[idx])-- # ── Gateway Service Setup ──- # Count any platform (built-in or plugin) the user configured during this- # setup pass — reuses ``_platform_status`` so plugin platforms like IRC- # are picked up without another hard-coded env-var list.- def _is_progress(status: str) -> bool:- s = status.lower()- return not (- s == "not configured"- or s.startswith("partially")- or s.startswith("plugin disabled")- )-- any_messaging = any(- _is_progress(_platform_status(p)) for p in _all_platforms()- )- if any_messaging:- print()- print_info("━" * 50)- print_success("Messaging platforms configured!")-- # Platforms with a token but no home channel- missing_home = [- plat for plat, token_var, home_vars in _HOME_CHANNEL_CHECKS- if get_env_value(token_var) and not any(get_env_value(v) for v in home_vars)- ]-- if missing_home:- print()- print_warning(f"No home channel set for: {', '.join(missing_home)}")- print_info(" Without a home channel, cron jobs and cross-platform")- print_info(" messages can't be delivered to those platforms.")- print_info(" Set one later with /set-home in your chat, or:")- for plat in missing_home:- print_info(- f" hermes config set {plat.upper()}_HOME_CHANNEL <channel_id>"- )-- # ── Gateway Service Setup ──- # Runs UNCONDITIONALLY — even with zero platforms configured. A gateway- # without platforms is a supported mode (cron scheduler keeps running,- # and adapters come up automatically once tokens are added later, e.g.- # via `hermes import` or `hermes setup gateway`). Gating this on- # messaging config was the bug that left install-then-import machines- # with registered cron jobs and restored bot tokens but no process to- # serve them.- from hermes_cli.gateway import (- _is_service_running,- supports_systemd_services,- ensure_gateway_service,- systemd_restart,- launchd_restart,- UserSystemdUnavailableError,- SystemScopeRequiresRootError,- _system_scope_wizard_would_need_root,- _print_system_scope_remediation,- )- import platform as _platform+ current_idle = current_policy.get("idle_minutes", 1440)+ current_hour = current_policy.get("at_hour", 4)- _is_macos = _platform.system() == "Darwin"- _is_windows = _platform.system() == "Windows"- supports_systemd = supports_systemd_services()+ default_reset = _SESSION_RESET_MODES.index(current_mode) if current_mode in _SESSION_RESET_MODES else 3+ reset_idx = prompt_choice("Session reset mode:", _SESSION_RESET_CHOICES, default_reset)- print()- if _is_service_running():- # Already running: only offer a restart when this setup pass may- # have changed platform config — a restart interrupts any active- # session, so it stays behind a prompt.- if supports_systemd and _system_scope_wizard_would_need_root():- _print_system_scope_remediation("restart")- elif any_messaging and prompt_yes_no(- " Restart the gateway to pick up changes?", True- ):- try:- if supports_systemd:- systemd_restart()- elif _is_macos:- launchd_restart()- elif _is_windows:- from hermes_cli import gateway_windows- gateway_windows.restart()- except UserSystemdUnavailableError as e:- print_error(" Restart failed — user systemd not reachable:")- for line in str(e).splitlines():- print(f" {line}")- except SystemScopeRequiresRootError as e:- # Defense in depth: the pre-check above should have- # caught this, but a race (unit file appearing mid-run)- # could still land here. Previously this exited the- # whole wizard via sys.exit(1).- print_error(f" Restart failed: {e}")- _print_system_scope_remediation("restart")- except Exception as e:- print_error(f" Restart failed: {e}")- else:- # Not running: install (if needed) and start, no questions asked.- ensure_gateway_service(context="setup")+ reset_cfg = config.setdefault("session_reset", {})+ mode = _SESSION_RESET_MODES[reset_idx] if 0 <= reset_idx < len(_SESSION_RESET_MODES) else None+ if mode is not None:+ reset_cfg["mode"] = mode+ if mode in ("both", "idle"):+ _prompt_int_setting(reset_cfg, "idle_minutes", " Inactivity timeout (minutes)", current_idle, lambda v: v > 0)+ if mode in ("both", "daily"):+ _prompt_int_setting(reset_cfg, "at_hour", " Daily reset hour (0-23, local time)", current_hour, lambda v: 0 <= v <= 23)+ idle_now, hour_now = reset_cfg.get("idle_minutes", 1440), reset_cfg.get("at_hour", 4)+ if mode == "both":+ print_success(f"Sessions reset after {idle_now} min idle or daily at {hour_now}:00")+ elif mode == "idle":+ print_success(f"Sessions reset after {idle_now} min of inactivity")+ elif mode == "daily":+ print_success(f"Sessions reset daily at {hour_now}:00")+ elif mode == "none":+ print_info("Sessions will never auto-reset. Context is managed only by compression.")+ print_warning("Long conversations will grow in cost. Use /reset manually when needed.")- print_info("━" * 50)+ save_config(config)# =============================================================================@@ -2143,10 +727,8 @@ def setup_tools(config: dict, first_install: bool = False):Both `hermes setup tools` and `hermes tools` use the same flow:platform selection → toolset toggles → provider/API key configuration.-- Args:- first_install: When True, uses the simplified first-install flow- (no platform menu, prompts for all unconfigured API keys).+ ``first_install`` selects the simplified first-install flow (no platform+ menu, prompts for all unconfigured API keys)."""from hermes_cli.tools_config import tools_command@@ -2158,6 +740,20 @@ def setup_tools(config: dict, first_install: bool = False):# =============================================================================+_SEND_CONSENT_EXPLAINER = (+ "",+ "Sending uploads each daily package to the Nous telemetry",+ "service. Packages carry your profile-scoped install ID, a",+ "stable random UUID that identifies this profile across days",+ "(it contains no personal information and is reset by deleting",+ "the shared-metrics directory). Only packages whose entire",+ "collection period falls inside a recorded consent window are",+ "ever sent — data from before you opt in, or from any gap",+ "while sending was off, stays on this machine. Sending can be",+ "turned off again at any time.",+)++def setup_telemetry(config: dict):"""Configure the local shared-metrics subscriber and optional sending."""print_header("Shared Metrics")@@ -2174,10 +770,7 @@ def setup_telemetry(config: dict):telemetry["shared_metrics"] = shared_metricscurrent = shared_metrics.get("enabled") is True- shared_metrics["enabled"] = prompt_yes_no(- "Enable local shared metrics?",- default=current,- )+ shared_metrics["enabled"] = prompt_yes_no("Enable local shared metrics?", default=current)if not shared_metrics["enabled"]:print_info("Local shared metrics disabled.")# Sending cannot outlive collection: leaving send=true here would be a@@ -2193,25 +786,13 @@ def setup_telemetry(config: dict):returnprint_success("Local shared metrics enabled.")- print_info("")- print_info("Sending uploads each daily package to the Nous telemetry")- print_info("service. Packages carry your profile-scoped install ID, a")- print_info("stable random UUID that identifies this profile across days")- print_info("(it contains no personal information and is reset by deleting")- print_info("the shared-metrics directory). Only packages whose entire")- print_info("collection period falls inside a recorded consent window are")- print_info("ever sent — data from before you opt in, or from any gap")- print_info("while sending was off, stays on this machine. Sending can be")- print_info("turned off again at any time.")- shared_metrics["send"] = prompt_yes_no(- "Send shared metrics to Nous?",- default=shared_metrics.get("send") is True,- )+ for line in _SEND_CONSENT_EXPLAINER:+ print_info(line)+ shared_metrics["send"] = prompt_yes_no("Send shared metrics to Nous?", default=shared_metrics.get("send") is True)+ _record_send_consent_change(enabled=shared_metrics["send"])if shared_metrics["send"]:- _record_send_consent_change(enabled=True)print_success("Sending shared metrics enabled.")else:- _record_send_consent_change(enabled=False)print_info("Sending shared metrics disabled (collection stays local).")@@ -2226,9 +807,7 @@ def _record_send_consent_change(*, enabled: bool) -> None:"""try:from hermes_cli.observability.shared_metrics import SharedMetricsStore- from hermes_cli.observability.shared_metrics_sender import (- reconcile_send_consent,- )+ from hermes_cli.observability.shared_metrics_sender import reconcile_send_consentfrom hermes_cli.sqlite_util import write_txnstore = SharedMetricsStore()@@ -2242,400 +821,52 @@ def _record_send_consent_change(*, enabled: bool) -> None:# =============================================================================-# Post-Migration Section Skip Logic-# =============================================================================---def _model_section_has_credentials(config: dict) -> bool:- """Return True when any known inference provider has usable credentials.-- Sources of truth:- * ``PROVIDER_REGISTRY`` in ``hermes_cli.auth`` — lists every supported- provider along with its ``api_key_env_vars``.- * ``active_provider`` in the auth store — covers OAuth device-code /- external-OAuth providers (Nous, Codex, Qwen, Gemini CLI, ...).- * The legacy OpenRouter aggregator env vars, which route generic- ``OPENAI_API_KEY`` / ``OPENROUTER_API_KEY`` values through OpenRouter.- """- try:- from hermes_cli.auth import get_active_provider- if get_active_provider():- return True- except Exception:- pass-- try:- from hermes_cli.auth import PROVIDER_REGISTRY- except Exception:- PROVIDER_REGISTRY = {} # type: ignore[assignment]-- def _has_key(pconfig) -> bool:- for env_var in pconfig.api_key_env_vars:- # CLAUDE_CODE_OAUTH_TOKEN is set by Claude Code itself, not by- # the user — mirrors is_provider_explicitly_configured in auth.py.- if env_var == "CLAUDE_CODE_OAUTH_TOKEN":- continue- if get_env_value(env_var):- return True- return False-- # Prefer the provider declared in config.yaml, avoids false positives- # from stray env vars (GH_TOKEN, etc.) when the user has already picked- # a different provider.- model_cfg = config.get("model") if isinstance(config, dict) else None- if isinstance(model_cfg, dict):- provider_id = (model_cfg.get("provider") or "").strip().lower()- if provider_id in PROVIDER_REGISTRY and _has_key(PROVIDER_REGISTRY[provider_id]):- return True- if provider_id == "openrouter":- for env_var in ("OPENROUTER_API_KEY", "OPENAI_API_KEY"):- if get_env_value(env_var):- return True-- # OpenRouter aggregator fallback (no provider declared in config).- for env_var in ("OPENROUTER_API_KEY", "OPENAI_API_KEY"):- if get_env_value(env_var):- return True-- for pid, pconfig in PROVIDER_REGISTRY.items():- # Skip copilot in auto-detect: GH_TOKEN / GITHUB_TOKEN are- # commonly set for git tooling. Mirrors resolve_provider in auth.py.- if pid == "copilot":- continue- if _has_key(pconfig):- return True- return False---def _gateway_platform_short_label(label: str) -> str:- """Strip trailing parenthetical qualifiers from a gateway platform label."""- base = label.split("(", 1)[0].strip()- return base or label---def _get_section_config_summary(config: dict, section_key: str) -> Optional[str]:- """Return a short summary if a setup section is already configured, else None.-- Used after OpenClaw migration to detect which sections can be skipped.- ``get_env_value`` is the module-level import from hermes_cli.config- so that test patches on ``setup_mod.get_env_value`` take effect.- """- if section_key == "model":- if not _model_section_has_credentials(config):- return None- model = config.get("model")- if isinstance(model, str) and model.strip():- return model.strip()- if isinstance(model, dict):- return str(model.get("default") or model.get("model") or "configured")- return "configured"-- elif section_key == "terminal":- backend = cfg_get(config, "terminal", "backend", default="local")- return f"backend: {backend}"-- elif section_key == "agent":- max_turns = cfg_get(config, "agent", "max_turns", default=90)- return f"max turns: {max_turns}"-- elif section_key == "gateway":- from hermes_cli.gateway import _all_platforms, _platform_status- # Count any non-empty status other than the "not configured" sentinel —- # platforms like WhatsApp ("enabled, not paired"), Matrix ("configured- # + E2EE"), and Signal ("partially configured") all indicate the user- # has already started setup and we shouldn't force the section to rerun.- configured = [- _gateway_platform_short_label(plat["label"])- for plat in _all_platforms()- if _platform_status(plat) and _platform_status(plat) != "not configured"- ]- if configured:- return ", ".join(configured)- return None # No platforms configured — section must run-- elif section_key == "tools":- tools = []- if get_env_value("ELEVENLABS_API_KEY"):- tools.append("TTS/ElevenLabs")- if get_env_value("BROWSERBASE_API_KEY"):- tools.append("Browser")- if get_env_value("FIRECRAWL_API_KEY"):- tools.append("Firecrawl")- if tools:- return ", ".join(tools)- return None-- return None---def _skip_configured_section(- config: dict, section_key: str, label: str-) -> bool:- """Show an already-configured section summary and offer to skip.-- Returns True if the user chose to skip, False if the section should run.- """- summary = _get_section_config_summary(config, section_key)- if not summary:- return False- print()- print_success(f" {label}: {summary}")- return not prompt_yes_no(f" Reconfigure {label.lower()}?", default=False)---# =============================================================================-# OpenClaw Migration+# Extracted sections (re-exported so callers and test patches keep resolving+# through hermes_cli.setup). These modules import this module lazily inside+# function bodies, so the top-level import here is cycle-free.# =============================================================================--_OPENCLAW_SCRIPT = (- get_optional_skills_dir(PROJECT_ROOT / "optional-skills")- / "migration"- / "openclaw-migration"- / "scripts"- / "openclaw_to_hermes.py"+from hermes_cli.setup_tts import ( # noqa: E402,F401+ _run_xai_oauth_login_from_setup,+ _setup_tts_provider,+ _xai_oauth_logged_in_for_setup,+ setup_tts,+)+from hermes_cli.setup_terminal import ( # noqa: E402,F401+ _prompt_vercel_sandbox_settings,+ _read_nearest_vercel_project,+ setup_terminal_backend,+)+from hermes_cli.setup_platforms import ( # noqa: E402,F401+ _TELEGRAM_BOT_TOKEN_RE,+ _profile_name_from_hermes_home,+ _setup_bluebubbles,+ _setup_qqbot,+ _setup_telegram,+ _setup_telegram_auto_result,+ _setup_webhooks,+ setup_gateway,+)+from hermes_cli.setup_summary import _print_setup_summary # noqa: E402,F401+from hermes_cli.setup_migration import ( # noqa: E402,F401+ _OPENCLAW_SCRIPT,+ _get_section_config_summary,+ _load_openclaw_migration_module,+ _model_section_has_credentials,+ _offer_openclaw_migration,+ _print_migration_preview,+ _skip_configured_section,+)+from hermes_cli.setup_quick import ( # noqa: E402,F401+ _blank_slate_minimal_toolsets,+ _blank_slate_minimize_config,+ _blank_slate_walkthrough,+ _print_macos_fda_tip,+ _run_blank_slate_setup,+ _run_first_time_quick_setup,+ _run_portal_one_shot,+ _run_quick_setup,)---def _load_openclaw_migration_module():- """Load the openclaw_to_hermes migration script as a module.-- Returns the loaded module, or None if the script can't be loaded.- """- if not _OPENCLAW_SCRIPT.exists():- return None-- spec = importlib.util.spec_from_file_location(- "openclaw_to_hermes", _OPENCLAW_SCRIPT- )- if spec is None or spec.loader is None:- return None-- mod = importlib.util.module_from_spec(spec)- # Register in sys.modules so @dataclass can resolve the module- # (Python 3.11+ requires this for dynamically loaded modules)- import sys as _sys- _sys.modules[spec.name] = mod- try:- spec.loader.exec_module(mod)- except Exception:- _sys.modules.pop(spec.name, None)- raise- return mod---# Item kinds that represent high-impact changes warranting explicit warnings.-# Gateway tokens/channels can hijack messaging platforms from the old agent.-# Config values may have different semantics between OpenClaw and Hermes.-# Instruction/context files (.md) can contain incompatible setup procedures.-_HIGH_IMPACT_KIND_KEYWORDS = {- "gateway": "⚠ Gateway/messaging — this will configure Hermes to use your OpenClaw messaging channels",- "telegram": "⚠ Telegram — this will point Hermes at your OpenClaw Telegram bot",- "slack": "⚠ Slack — this will point Hermes at your OpenClaw Slack workspace",- "discord": "⚠ Discord — this will point Hermes at your OpenClaw Discord bot",- "whatsapp": "⚠ WhatsApp — this will point Hermes at your OpenClaw WhatsApp connection",- "config": "⚠ Config values — OpenClaw settings may not map 1:1 to Hermes equivalents",- "soul": "⚠ Instruction file — may contain OpenClaw-specific setup/restart procedures",- "memory": "⚠ Memory/context file — may reference OpenClaw-specific infrastructure",- "context": "⚠ Context file — may contain OpenClaw-specific instructions",-}---def _print_migration_preview(report: dict):- """Print a detailed dry-run preview of what migration would do.-- Groups items by category and adds explicit warnings for high-impact- changes like gateway token takeover and config value differences.- """- items = report.get("items", [])- if not items:- print_info("Nothing to migrate.")- return-- migrated_items = [i for i in items if i.get("status") == "migrated"]- conflict_items = [i for i in items if i.get("status") == "conflict"]- skipped_items = [i for i in items if i.get("status") == "skipped"]-- warnings_shown = set()-- if migrated_items:- print(color(" Would import:", Colors.GREEN))- for item in migrated_items:- kind = item.get("kind", "unknown")- dest = item.get("destination", "")- if dest:- dest_short = str(dest).replace(str(Path.home()), "~")- print(f" {kind:<22s} → {dest_short}")- else:- print(f" {kind}")-- # Check for high-impact items and collect warnings- kind_lower = kind.lower()- dest_lower = str(dest).lower()- for keyword, warning in _HIGH_IMPACT_KIND_KEYWORDS.items():- if keyword in kind_lower or keyword in dest_lower:- warnings_shown.add(warning)- print()-- if conflict_items:- print(color(" Would overwrite (conflicts with existing Hermes config):", Colors.YELLOW))- for item in conflict_items:- kind = item.get("kind", "unknown")- reason = item.get("reason", "already exists")- print(f" {kind:<22s} {reason}")- print()-- if skipped_items:- print(color(" Would skip:", Colors.DIM))- for item in skipped_items:- kind = item.get("kind", "unknown")- reason = item.get("reason", "")- print(f" {kind:<22s} {reason}")- print()-- # Print collected warnings- if warnings_shown:- print(color(" ── Warnings ──", Colors.YELLOW))- for warning in sorted(warnings_shown):- print(color(f" {warning}", Colors.YELLOW))- print()- print(color(" Note: OpenClaw config values may have different semantics in Hermes.", Colors.YELLOW))- print(color(" For example, OpenClaw's tool_call_execution: \"auto\" ≠ Hermes's yolo mode.", Colors.YELLOW))- print(color(" Instruction files (.md) from OpenClaw may contain incompatible procedures.", Colors.YELLOW))- print()---def _offer_openclaw_migration(hermes_home: Path) -> bool:- """Detect ~/.openclaw and offer to migrate during first-time setup.-- Runs a dry-run first to show the user exactly what would be imported,- overwritten, or taken over. Only executes after explicit confirmation.-- Returns True if migration ran successfully, False otherwise.- """- openclaw_dir = Path.home() / ".openclaw"- if not openclaw_dir.is_dir():- return False-- if not _OPENCLAW_SCRIPT.exists():- return False-- print()- print_header("OpenClaw Installation Detected")- print_info(f"Found OpenClaw data at {openclaw_dir}")- print_info("Hermes can preview what would be imported before making any changes.")- print()-- if not prompt_yes_no("Would you like to see what can be imported?", default=True):- print_info(- "Skipping migration. You can run it later with: hermes claw migrate --dry-run"- )- return False-- # Ensure config.yaml exists before migration tries to read it- config_path = get_config_path()- if not config_path.exists():- save_config(load_config())-- # Load the migration module- try:- mod = _load_openclaw_migration_module()- if mod is None:- print_warning("Could not load migration script.")- return False- except Exception as e:- print_warning(f"Could not load migration script: {e}")- logger.debug("OpenClaw migration module load error", exc_info=True)- return False-- # ── Phase 1: Dry-run preview ──- try:- selected = mod.resolve_selected_options(None, None, preset="full")- dry_migrator = mod.Migrator(- source_root=openclaw_dir.resolve(),- target_root=hermes_home.resolve(),- execute=False, # dry-run — no files modified- workspace_target=None,- overwrite=True, # show everything including conflicts- migrate_secrets=True,- output_dir=None,- selected_options=selected,- preset_name="full",- )- preview_report = dry_migrator.migrate()- except Exception as e:- print_warning(f"Migration preview failed: {e}")- logger.debug("OpenClaw migration preview error", exc_info=True)- return False-- # Display the full preview- preview_summary = preview_report.get("summary", {})- preview_count = preview_summary.get("migrated", 0)-- if preview_count == 0:- print()- print_info("Nothing to import from OpenClaw.")- return False-- print()- print_header(f"Migration Preview — {preview_count} item(s) would be imported")- print_info("No changes have been made yet. Review the list below:")- print()- _print_migration_preview(preview_report)-- # ── Phase 2: Confirm and execute ──- if not prompt_yes_no("Proceed with migration?", default=False):- print_info(- "Migration cancelled. You can run it later with: hermes claw migrate"- )- print_info(- "Use --dry-run to preview again, or --preset minimal for a lighter import."- )- return False-- # Execute the migration — overwrite=False so existing Hermes configs are- # preserved. The user saw the preview; conflicts are skipped by default.- try:- migrator = mod.Migrator(- source_root=openclaw_dir.resolve(),- target_root=hermes_home.resolve(),- execute=True,- workspace_target=None,- overwrite=False, # preserve existing Hermes config- migrate_secrets=True,- output_dir=None,- selected_options=selected,- preset_name="full",- )- report = migrator.migrate()- except Exception as e:- print_warning(f"Migration failed: {e}")- logger.debug("OpenClaw migration error", exc_info=True)- return False-- # Print final summary- summary = report.get("summary", {})- migrated = summary.get("migrated", 0)- skipped = summary.get("skipped", 0)- conflicts = summary.get("conflict", 0)- errors = summary.get("error", 0)-- print()- if migrated:- print_success(f"Imported {migrated} item(s) from OpenClaw.")- if conflicts:- print_info(f"Skipped {conflicts} item(s) that already exist in Hermes (use hermes claw migrate --overwrite to force).")- if skipped:- print_info(f"Skipped {skipped} item(s) (not found or unchanged).")- if errors:- print_warning(f"{errors} item(s) had errors — check the migration report.")-- output_dir = report.get("output_dir")- if output_dir:- print_info(f"Full report saved to: {output_dir}")-- print_success("Migration complete! Continuing with setup...")- return True# =============================================================================@@ -2653,203 +884,101 @@ SETUP_SECTIONS = []-def _run_portal_one_shot(config: dict) -> None:- """One-shot Nous Portal setup — OAuth + model pick + provider + Tool Gateway.-- Wired into ``hermes setup --portal`` and ``hermes portal``. This is the- Nous-Portal slice of the first-time quick setup, collapsed into a single- shareable command so a brand-new user goes from zero to a fully working- Hermes session — model selected, provider set, and web/image/tts/browser- tools routed via their Portal sub — without being told to run- ``hermes setup`` and hunt for the quick-setup option.-- The login + model selection + provider switch + Tool Gateway opt-in are all- delegated to ``_model_flow_nous`` — the exact same flow quick setup uses- (``_run_first_time_quick_setup``) and the same one ``hermes model`` runs- when you pick Nous. Routing through it (instead of hand-rolling the auth +- provider write here) means ``hermes portal`` always offers a model picker,- and there is a single source of truth for the Nous onboarding steps.- """- from hermes_cli.config import load_config-- print()- print(- color(- "┌─────────────────────────────────────────────────────────┐",- Colors.MAGENTA,- )- )- print(color("│ ⚕ Hermes Setup — Nous Portal (one-shot) │", Colors.MAGENTA))- print(- color(- "└─────────────────────────────────────────────────────────┘",- Colors.MAGENTA,- )- )- print()- print_info(" One subscription, 300+ models, plus the Tool Gateway:")- print_info(" web search, image generation, TTS, browser automation")- print_info(" — all routed through your Nous Portal sub.")- print()- print_info(" Sign up: https://portal.nousresearch.com/manage-subscription")- print()+def run_setup_wizard(args):+ """Run setup with navigation control scoped to this invocation."""+ with _setup_navigation_scope():+ try:+ return _run_setup_wizard_impl(args)+ except _SetupCancelled:+ print()+ print_info("Setup cancelled. Remaining sections were not changed.")+ return None- # _model_flow_nous handles BOTH the logged-out path (device-code OAuth,- # which selects a model internally) and the already-logged-in path (curated- # Nous model picker), then offers the Tool Gateway opt-in and sets- # provider=nous via the login/model save. This is the same routine quick- # setup calls, so `hermes portal` == quick setup's Nous step.- try:- from hermes_cli.main import _model_flow_nous-- _model_flow_nous(config)- except (KeyboardInterrupt, EOFError, SystemExit):- # _login_nous raises SystemExit(130)/(1) on cancel/failure; the- # logged-out path inside _model_flow_nous catches it, but the- # expired-session re-login path only catches Exception, so a- # SystemExit there would otherwise escape and kill the whole CLI.- # Treat all of these as a graceful cancel/abort for the portal flow.- print()- print_info(" Setup cancelled.")- print_info(" You can retry later with `hermes portal`.")- return- except Exception as exc:- logger.debug("_model_flow_nous error during `hermes portal`: %s", exc)- print()- print_error(f" Nous Portal setup encountered an error: {exc}")- print_info(" You can retry later with `hermes portal`.")- return- # Re-sync the in-memory config from disk — _model_flow_nous (and the- # underlying login/model save) write via their own load/save cycle, so any- # later save_config(config) by a caller must not clobber those values.+def _backup_config_file(config_path: Path) -> Path | None:+ """Back up config.yaml before setup modifies it (#3522); None when absent or copy fails."""+ if not config_path.exists():+ return None+ from datetime import datetime as _dt+ backup_path = config_path.with_suffix(f".yaml.bak.{_dt.now().strftime('%Y%m%d_%H%M%S')}")try:- _refreshed = load_config()- if isinstance(_refreshed, dict):- config.clear()- config.update(_refreshed)+ import shutil+ shutil.copy2(config_path, backup_path)except Exception:- pass+ return None+ return backup_path- print()- print_success("Portal setup complete.")- print_info(" Run `hermes portal info` to inspect routing.")- print_info(" Run `hermes` to start chatting.")+def _run_setup_section(config: dict, section: str) -> None:+ """``hermes setup <section>``: run one SETUP_SECTIONS entry under the banner."""+ for key, label, func in SETUP_SECTIONS:+ if key == section:+ _print_banner(f"│ ⚕ Hermes Setup — {label:<34s} │")+ _run_setup_steps([(label, lambda setup_func=func: setup_func(config))])+ save_config(config)+ print()+ print_success(f"{label} configuration complete!")+ return-@contextmanager-def _setup_navigation_scope():- """Install and reliably restore the setup menu navigation context."""- from hermes_cli.curses_ui import (- reset_menu_navigation_handler,- set_menu_navigation_handler,- )+ print_error(f"Unknown setup section: {section}")+ print_info(f"Available sections: {', '.join(k for k, _, _ in SETUP_SECTIONS)}")- token = _SETUP_NAVIGATION.set(_SetupNavigationState())- menu_token = set_menu_navigation_handler(_handle_setup_menu_navigation)- try:- yield- finally:- reset_menu_navigation_handler(menu_token)- _SETUP_NAVIGATION.reset(token)+def _run_full_setup(config: dict, hermes_home, *, is_existing: bool, migration_ran: bool) -> None:+ """Full Setup — run all sections, honoring post-migration skips."""+ print_header("Configuration Location")+ print_info(f"Config file: {get_config_path()}")+ print_info(f"Secrets file: {get_env_path()}")+ print_info(f"Data folder: {hermes_home}")+ print_info(f"Install dir: {PROJECT_ROOT}")+ print()+ print_info("You can edit these files directly or use 'hermes config edit'")-def run_setup_wizard(args):- """Run setup with navigation control scoped to this invocation."""- with _setup_navigation_scope():- try:- return _run_setup_wizard_impl(args)- except _SetupCancelled:- print()- print_info("Setup cancelled. Remaining sections were not changed.")- return None+ if migration_ran:+ print()+ print_info("Settings were imported from OpenClaw.")+ print_info("Each section below will show what was imported — press Enter to keep,")+ print_info("or choose to reconfigure if needed.")+ # Agent Settings are no longer prompted. First installs get the recommended+ # defaults silently; existing installs keep theirs. Tune via `hermes setup agent`.+ if not is_existing:+ _apply_default_agent_settings(config)-def _run_setup_steps(- steps: list[tuple[str, Callable[[], None]]],-) -> None:- """Run setup sections with left-arrow navigation between choices.+ def _skip(key: str, label: str) -> bool:+ return migration_ran and _skip_configured_section(config, key, label)- Left arrow at a section's first choice returns to the previous section.- From a later, nested choice it replays earlier selections invisibly and- reopens only the immediately preceding prompt.- """- state = _SETUP_NAVIGATION.get()- section_index = 0- answers_by_section: dict[int, list[object]] = {}- replay_by_section: dict[int, list[object]] = {}- try:- while section_index < len(steps):- label, action = steps[section_index]- if state is not None:- state.section_index = section_index- state.prompt_index = 0- state.active_prompt_index = -1- state.resolved_choices = []- state.replay_choices = copy.deepcopy(- replay_by_section.pop(section_index, [])- )- try:- action()- except _SetupGoBack as navigation:- if state is not None:- answers_by_section[section_index] = copy.deepcopy(- state.resolved_choices- )- if navigation.prompt_index > 0:- previous_index = section_index- target_prompt = navigation.prompt_index - 1- replay_by_section[previous_index] = copy.deepcopy(- answers_by_section.get(previous_index, [])[:target_prompt]- )- else:- previous_index = max(0, section_index - 1)- previous_answers = answers_by_section.get(previous_index, [])- target_prompt = max(0, len(previous_answers) - 1)- replay_by_section[previous_index] = copy.deepcopy(- previous_answers[:target_prompt]- )- previous_label = steps[previous_index][0]- print()- if previous_index == section_index:- print_info(f"Returning to the previous choice in {label}...")- else:- print_info(f"Returning to {previous_label}...")- section_index = previous_index- continue- if state is not None:- answers_by_section[section_index] = copy.deepcopy(- state.resolved_choices- )- section_index += 1- finally:- if state is not None:- state.section_index = -1- state.prompt_index = 0- state.active_prompt_index = -1- state.resolved_choices = []- state.replay_choices = []+ def _model_step() -> None:+ if not _skip("model", "Model & Provider"):+ setup_model_provider(config)+ def _terminal_step() -> None:+ if not _skip("terminal", "Terminal Backend"):+ setup_terminal_backend(config)-def run_setup_action_with_navigation(- label: str,- action: Callable[[], None],- *,- cancelled_message: str = "Setup cancelled.",-) -> None:- """Run a setup-style menu flow with Escape and nested Left navigation.+ def _gateway_step() -> None:+ if not _skip("gateway", "Messaging Platforms"):+ setup_gateway(config)+ return- Shared commands such as ``hermes model`` use the same provider/model- pickers as the setup wizard, but run outside ``run_setup_wizard``. This- installs the setup navigation context for that standalone command and- reuses the same prompt replay state machine.- """- with _setup_navigation_scope():- try:- _run_setup_steps([(label, action)])- except _SetupCancelled:- print()- print_info(cancelled_message)+ # A migrated gateway section can be skipped, but its service still+ # needs to exist so imported platforms and cron jobs become active.+ from hermes_cli.gateway import ensure_gateway_service++ ensure_gateway_service(context="setup")++ def _tools_step() -> None:+ if not _skip("tools", "Tools"):+ setup_tools(config, first_install=not is_existing)++ _run_setup_steps(+ [+ ("Model & Provider", _model_step),+ ("Terminal Backend", _terminal_step),+ ("Messaging Platforms", _gateway_step),+ ("Tools", _tools_step),+ ]+ )def _run_setup_wizard_impl(args):@@ -2871,8 +1000,7 @@ def _run_setup_wizard_impl(args):returnensure_hermes_home()- reset_requested = bool(getattr(args, "reset", False))- if reset_requested:+ if bool(getattr(args, "reset", False)):save_config(copy.deepcopy(DEFAULT_CONFIG))print_success("Configuration reset to defaults.")@@ -2882,30 +1010,12 @@ def _run_setup_wizard_impl(args):config = load_config()hermes_home = get_hermes_home()- # Back up existing config before setup modifies it (#3522)config_path = get_config_path()- if config_path.exists():- from datetime import datetime as _dt- _backup_path = config_path.with_suffix(- f".yaml.bak.{_dt.now().strftime('%Y%m%d_%H%M%S')}"- )- try:- import shutil- shutil.copy2(config_path, _backup_path)- except Exception:- _backup_path = None- else:- _backup_path = None+ _backup_path = _backup_config_file(config_path)# Detect non-interactive environments (headless SSH, Docker, CI/CD)- non_interactive = getattr(args, 'non_interactive', False)- if not non_interactive and not is_interactive_stdin():- non_interactive = True-- if non_interactive:- print_noninteractive_setup_guidance(- "Running in a non-interactive environment (no TTY detected)."- )+ if getattr(args, 'non_interactive', False) or not is_interactive_stdin():+ print_noninteractive_setup_guidance("Running in a non-interactive environment (no TTY detected).")return# --portal: one-shot Nous Portal setup. Skips the rest of the wizard.@@ -2913,80 +1023,25 @@ def _run_setup_wizard_impl(args):_run_portal_one_shot(config)return- # Check if a specific section was requestedsection = getattr(args, "section", None)if section:- for key, label, func in SETUP_SECTIONS:- if key == section:- print()- print(- color(- "┌─────────────────────────────────────────────────────────┐",- Colors.MAGENTA,- )- )- print(color(f"│ ⚕ Hermes Setup — {label:<34s} │", Colors.MAGENTA))- print(- color(- "└─────────────────────────────────────────────────────────┘",- Colors.MAGENTA,- )- )- _run_setup_steps(- [(label, lambda setup_func=func: setup_func(config))]- )- save_config(config)- print()- print_success(f"{label} configuration complete!")- return-- print_error(f"Unknown setup section: {section}")- print_info(f"Available sections: {', '.join(k for k, _, _ in SETUP_SECTIONS)}")+ _run_setup_section(config, section)return# Check if this is an existing installation with a provider configuredfrom hermes_cli.auth import get_active_provider- active_provider = get_active_provider()is_existing = (bool(get_env_value("OPENROUTER_API_KEY"))or bool(get_env_value("OPENAI_BASE_URL"))- or active_provider is not None+ or get_active_provider() is not None)- print()- print(- color(- "┌─────────────────────────────────────────────────────────┐",- Colors.MAGENTA,- )- )- print(- color(- "│ ⚕ Hermes Agent Setup Wizard │", Colors.MAGENTA- )- )- print(- color(- "├─────────────────────────────────────────────────────────┤",- Colors.MAGENTA,- )- )- print(- color(- "│ Let's configure your Hermes Agent installation. │", Colors.MAGENTA- )- )- print(- color(- "│ Press Ctrl+C at any time to exit. │", Colors.MAGENTA- )- )- print(- color(- "└─────────────────────────────────────────────────────────┘",- Colors.MAGENTA,- )+ _print_banner(+ "│ ⚕ Hermes Agent Setup Wizard │",+ "├─────────────────────────────────────────────────────────┤",+ "│ Let's configure your Hermes Agent installation. │",+ "│ Press Ctrl+C at any time to exit. │",)migration_ran = False@@ -2998,9 +1053,7 @@ def _run_setup_wizard_impl(args):# missing items" flow (useful after a partial OpenClaw migration# or when a required API key got cleared).if quick_requested:- _run_setup_steps(- [("Quick Setup", lambda: _run_quick_setup(config, hermes_home))]- )+ _run_setup_steps([("Quick Setup", lambda: _run_quick_setup(config, hermes_home))])returnprint()@@ -3011,9 +1064,8 @@ def _run_setup_wizard_impl(args):print_info("")print_info("Tip: jump straight to a section with 'hermes setup model|terminal|")print_info(" gateway|tools|agent', or fill only missing items with --quick.")- # Fall through to the "Full Setup — run all sections" block below.- # --reconfigure is now the default on existing installs; the flag- # is preserved for backwards compatibility but is a no-op here.+ # --reconfigure is the default on existing installs; the flag is kept+ # for backwards compatibility and is a no-op here.else:# ── First-Time Setup ──print()@@ -3041,93 +1093,16 @@ def _run_setup_wizard_impl(args):if setup_mode == 0:_run_setup_steps(- [- (- "Quick Setup",- lambda: _run_first_time_quick_setup(- config, hermes_home, is_existing- ),- )- ]+ [("Quick Setup", lambda: _run_first_time_quick_setup(config, hermes_home, is_existing))])returnif setup_mode == 2:_run_setup_steps(- [- (- "Blank Slate",- lambda: _run_blank_slate_setup(- config, hermes_home, is_existing- ),- )- ]+ [("Blank Slate", lambda: _run_blank_slate_setup(config, hermes_home, is_existing))])return- # ── Full Setup — run all sections ──- print_header("Configuration Location")- print_info(f"Config file: {get_config_path()}")- print_info(f"Secrets file: {get_env_path()}")- print_info(f"Data folder: {hermes_home}")- print_info(f"Install dir: {PROJECT_ROOT}")- print()- print_info("You can edit these files directly or use 'hermes config edit'")-- if migration_ran:- print()- print_info("Settings were imported from OpenClaw.")- print_info("Each section below will show what was imported — press Enter to keep,")- print_info("or choose to reconfigure if needed.")-- # Section 3: Agent Settings — no longer prompted. First installs get the- # recommended defaults silently; existing installs keep whatever they have.- # Tune later with `hermes setup agent`.- if not is_existing:- _apply_default_agent_settings(config)-- def _model_step() -> None:- if not (- migration_ran- and _skip_configured_section(config, "model", "Model & Provider")- ):- setup_model_provider(config)-- def _terminal_step() -> None:- if not (- migration_ran- and _skip_configured_section(config, "terminal", "Terminal Backend")- ):- setup_terminal_backend(config)-- def _gateway_step() -> None:- if not (- migration_ran- and _skip_configured_section(config, "gateway", "Messaging Platforms")- ):- setup_gateway(config)- return-- # A migrated gateway section can be skipped, but its service still- # needs to exist so imported platforms and cron jobs become active.- from hermes_cli.gateway import ensure_gateway_service-- ensure_gateway_service(context="setup")-- def _tools_step() -> None:- if not (- migration_ran- and _skip_configured_section(config, "tools", "Tools")- ):- setup_tools(config, first_install=not is_existing)-- _run_setup_steps(- [- ("Model & Provider", _model_step),- ("Terminal Backend", _terminal_step),- ("Messaging Platforms", _gateway_step),- ("Tools", _tools_step),- ]- )+ _run_full_setup(config, hermes_home, is_existing=is_existing, migration_ran=migration_ran)# Save and show summarysave_config(config)@@ -3136,528 +1111,3 @@ def _run_setup_wizard_impl(args):print_info("If setup changed a value you customized, restore it with:")print_info(f" cp {_backup_path} {config_path}")_print_setup_summary(config, hermes_home)---def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):- """Streamlined first-time setup via Nous Portal: OAuth, model, terminal & messaging.-- Routes straight to the Nous Portal provider — runs the device-code OAuth- login, picks a Nous model, then configures the terminal backend and (optionally)- a messaging platform. Applies sensible defaults for everything else (agent- settings, tools); the user can customize later via ``hermes setup <section>``- or switch providers with ``hermes model``.- """- from hermes_cli.config import load_config-- # Step 1: Nous Portal — OAuth login + model selection.- # _model_flow_nous() handles both the logged-out path (device-code OAuth,- # which selects a model internally) and the already-logged-in path (curated- # Nous model picker). Provider is set to "nous" by the login/model save.- print()- print_header("Nous Portal")- print_info("One subscription, 300+ models, plus the Tool Gateway:")- print_info(" web search, image generation, TTS, browser automation.")- print_info("Sign up: https://portal.nousresearch.com/manage-subscription")- print()- try:- from hermes_cli.main import _model_flow_nous- _model_flow_nous(config)- except (KeyboardInterrupt, EOFError):- print()- print_info("Nous Portal setup cancelled.")- except Exception as exc:- logger.debug("_model_flow_nous error during quick setup: %s", exc)- print_warning(f"Nous Portal setup encountered an error: {exc}")- print_info("You can try again later with: hermes model")-- # Re-sync the wizard's config dict from disk — _model_flow_nous (and the- # underlying login/model save) write via their own load/save cycle, and the- # wizard's later save_config(config) must not clobber those values (#4172).- _refreshed = load_config()- config.clear()- config.update(_refreshed)-- # Step 2: Terminal Backend — where commands run is a core decision- setup_terminal_backend(config)-- # Step 3: Apply defaults for everything else- _apply_default_agent_settings(config)-- save_config(config)-- # Step 4: Offer messaging gateway setup- print()- gateway_choice = prompt_choice(- "Connect a messaging platform? (Telegram, Discord, etc.)",- [- "Set up messaging now (recommended)",- "Skip — set up later with 'hermes setup gateway'",- ],- 0,- )-- if gateway_choice == 0:- setup_gateway(config)- save_config(config)- else:- # Messaging skipped — still install/start the gateway service so cron- # jobs run and platforms come alive as soon as tokens are added later- # (e.g. via `hermes import` from another machine).- from hermes_cli.gateway import ensure_gateway_service- ensure_gateway_service(context="setup")-- print()- print_success("Setup complete! You're ready to go.")- print()- print_info(" Configure all settings: hermes setup")- if gateway_choice != 0:- print_info(" Connect Telegram/Discord: hermes setup gateway")- _print_macos_fda_tip()- print()-- _print_setup_summary(config, hermes_home)---def _print_macos_fda_tip() -> None:- """One-time macOS onboarding tip: a single Full Disk Access grant kills- every per-folder permission prompt, permanently (issue #52010 follow-up).-- Uses the same prompt-free probe as doctor's check_macos_full_disk_access- (the TCC db dir is FDA-gated but probing it never triggers a dialog).- Silent on non-macOS and when FDA is already granted or indeterminate.- """- if sys.platform != "darwin":- return- tcc_dir = Path.home() / "Library" / "Application Support" / "com.apple.TCC"- try:- os.listdir(tcc_dir)- return # already granted — nothing to teach- except PermissionError:- pass- except OSError:- return # indeterminate — don't nag- print()- print_info(" macOS tip: silence ALL folder permission prompts with one switch —")- print_info(" System Settings → Privacy & Security → Full Disk Access → enable")- print_info(" your terminal (and Hermes.app if you use Desktop), or run:")- print_info(" open \"x-apple.systempreferences:com.apple.preference"- ".security?Privacy_AllFiles\"")- print_info(" The grant is permanent — it survives every Hermes update.")---def _blank_slate_minimal_toolsets(config: dict):- """Write the minimal toolset state for a Blank Slate install.-- Only ``file``, ``terminal``, ``vision``, and ``skills`` are enabled.- Vision is part of- the core surface: ``read_file`` cannot read images and its own description- points at ``vision_analyze``, so an agent without it can't see screenshots- or image files at all. Skills stay on because the essential- ``hermes-agent`` skill (the agent's operating manual for driving,- configuring, and troubleshooting Hermes) is always seeded — without- ``skill_view`` it would be unloadable. Two layers enforce the selection:-- 1. ``platform_toolsets["cli"] = ["file", "skills", "terminal", "vision"]``- — an explicit list of- configurable keys, which the resolver treats as authoritative- (``has_explicit_config``) so default toolsets aren't re-expanded.- 2. ``agent.disabled_toolsets`` — a global hard-suppression list (applied last- in ``_get_platform_tools``, overriding every other path including the- non-configurable platform-toolset recovery that would otherwise re-add- toolsets like ``kanban``). We list every known toolset except the ones we- keep, guaranteeing a true blank slate regardless of platform/recovery- quirks. The user re-enables any of them later via ``hermes tools`` (which- rewrites ``platform_toolsets``) or by editing ``agent.disabled_toolsets``.- """- keep = {"file", "terminal", "vision", "skills"}- config.setdefault("platform_toolsets", {})["cli"] = sorted(keep)-- try:- from toolsets import TOOLSETS- from hermes_cli.tools_config import CONFIGURABLE_TOOLSETS, _get_plugin_toolset_keys-- all_keys = set()- all_keys.update(k for k, _, _ in CONFIGURABLE_TOOLSETS)- all_keys.update(_get_plugin_toolset_keys())- # Plain (non-composite) TOOLSETS entries — catches recovered toolsets- # like ``kanban`` that aren't in CONFIGURABLE_TOOLSETS but get re-added.- for k, tdef in TOOLSETS.items():- if k.startswith("hermes-"):- continue # platform composites — not user-facing toolsets- if isinstance(tdef, dict) and tdef.get("includes"):- continue # composite groupings, not leaf toolsets- if isinstance(tdef, dict) and tdef.get("posture"):- continue # posture toolsets (e.g. coding) are session-level- # selections made by agent/coding_context.py — not permanent- # user-facing disables. Adding them here causes model_tools- # to subtract their tools (terminal, read_file, …) from the- # minimal Blank Slate surface (#57315).- all_keys.add(k)-- disabled = sorted(all_keys - keep)- if disabled:- config.setdefault("agent", {})["disabled_toolsets"] = disabled- except Exception as exc:- logger.debug("blank-slate disabled_toolsets computation skipped: %s", exc)---def _blank_slate_minimize_config(config: dict):- """Turn OFF the optional config features for a Blank Slate install.-- Everything here is opt-in afterwards via ``hermes setup agent`` /- ``hermes config set``. We keep only what's needed to run.- """- config.setdefault("agent", {})["max_turns"] = 90-- # Compression off — minimal footprint; user opts in if they want long sessions.- config.setdefault("compression", {})["enabled"] = False-- # No automatic memory / user-profile capture.- mem = config.setdefault("memory", {})- mem["memory_enabled"] = False- mem["user_profile_enabled"] = False-- # No filesystem checkpoints, no smart model routing, no auto session reset.- config.setdefault("checkpoints", {})["enabled"] = False- config.setdefault("smart_model_routing", {})["enabled"] = False- config.setdefault("session_reset", {})["mode"] = "none"-- # Quiet, minimal display.- config.setdefault("display", {})["tool_progress"] = "all"---def _run_blank_slate_setup(config: dict, hermes_home, is_existing: bool):- """Blank Slate setup — start with everything off except the bare minimum.-- Forces only the essentials to run an agent (provider + model, the file and- terminal toolsets) and turns every other tool/skill/plugin/MCP/config- feature OFF. After applying that minimal baseline, the user chooses one of- two paths:-- 1. Start with everything disabled — finish now with the minimal agent.- 2. Walk through every configuration — opt each capability back in.-- Either way nothing is enabled that the user did not explicitly choose.- """-- print()- print_header("Blank Slate Setup")- print_info("Everything starts OFF. First we force-enable only what's required")- print_info("to run an agent, then you choose whether to stop there or walk")- print_info("through enabling more — opting in to exactly what you want.")- print_info("")- print_info("Forced on: Provider & Model, File Operations, Terminal, Vision, Skills.")- print_info("Everything else (web, browser, code exec, memory,")- print_info("delegation, cron, plugins, MCP, …) starts disabled. The")- print_info("essential `hermes-agent` skill is always kept so the agent")- print_info("can help you drive and configure Hermes itself.")- print()-- # ── Step 1: Provider & Model (REQUIRED — the agent cannot run without it) ──- print_header("Step 1 — Provider & Model (required)")- setup_model_provider(config)- save_config(config)-- # ── Step 2: Terminal backend (where commands run — a core decision) ──- print_header("Step 2 — Terminal Backend")- setup_terminal_backend(config)-- # ── Step 3: Lock in the minimal toolset + minimized config knobs ──- _blank_slate_minimal_toolsets(config)- _blank_slate_minimize_config(config)- save_config(config)- print()- print_success("Minimal baseline applied:")- print_info(" Toolsets: file, terminal, vision, skills (everything else off)")- print_info(" Compression, memory, checkpoints, smart routing: off")-- # ── The fork: stop here, or walk through enabling things ──- print()- print_header("How far do you want to go?")- path = prompt_choice(- "Your minimal agent is ready. What next?",- [- "Start with everything disabled — finish now (most minimal)",- "Walk through all configurations — opt in to tools, skills, plugins, MCP",- ],- 0,- )-- if path == 0:- save_config(config)- # Blank Slate means no bundled skills; record the opt-out so future- # `hermes update` runs don't re-inject them. Essential skills (the- # `hermes-agent` operating manual) are still seeded by the sync.- try:- from tools.skills_sync import set_bundled_skills_opt_out, sync_skills- set_bundled_skills_opt_out(True)- sync_skills(quiet=True)- except Exception as exc:- logger.debug("blank-slate skill opt-out error: %s", exc)- print()- print_success("Blank Slate setup complete — minimal agent ready.")- print_info("Enable anything later, on demand:")- print_info(" Enable tools: hermes tools")- print_info(" Seed skills: hermes skills opt-in --sync")- print_info(" Add MCP servers: hermes mcp add")- print_info(" Enable plugins: hermes plugins")- print_info(" Tune agent settings: hermes setup agent")- print()- _print_setup_summary(config, hermes_home)- return-- # ── Walkthrough path — opt in to each capability ──- _blank_slate_walkthrough(config, hermes_home)---def _blank_slate_walkthrough(config: dict, hermes_home):- """Opt-in walkthrough for Blank Slate: skills, tools, plugins, MCP, gateway."""- from hermes_cli.config import load_config-- # ── Bundled skills — default to NONE, offer to seed all ──- print()- print_header("Bundled Skills")- print_info("Blank Slate ships with NO bundled skills by default.")- seed_skills = prompt_yes_no(- "Seed the full bundled skill catalog? (No = start with zero skills)",- default=False,- )- try:- from tools.skills_sync import set_bundled_skills_opt_out, sync_skills- if seed_skills:- # Make sure no stale opt-out marker blocks the seed, then sync.- set_bundled_skills_opt_out(False)- result = sync_skills(quiet=True)- copied = len(result.get("copied", [])) if isinstance(result, dict) else 0- print_success(f"Seeded {copied} bundled skills.")- else:- set_bundled_skills_opt_out(True)- # Essential skills (the `hermes-agent` operating manual) are- # still seeded even for an opted-out profile.- sync_skills(quiet=True)- print_info("No skills seeded (except the essential `hermes-agent`")- print_info("skill). A .no-bundled-skills marker keeps future")- print_info("`hermes update` runs from re-injecting them. Opt back in any")- print_info("time with `hermes skills opt-in --sync`.")- except Exception as exc:- logger.debug("blank-slate skill handling error: %s", exc)- print_warning(f"Skill setup step encountered an error: {exc}")-- # ── Walk through enabling additional tools ──- print()- print_header("Tools")- print_info("Pick exactly which additional toolsets to turn on.")- print_info("(file and terminal are already on; leave the rest off if you want")- print_info(" the most minimal agent.)")- if prompt_yes_no("Open the tool selector to enable more tools?", default=False):- try:- from hermes_cli.tools_config import tools_command- tools_command(first_install=False, config=config)- # tools_command saves via its own load/save cycle — re-sync.- _refreshed = load_config()- config.clear()- config.update(_refreshed)- except Exception as exc:- logger.debug("blank-slate tools_command error: %s", exc)- print_warning(f"Tool selector encountered an error: {exc}")- else:- print_info("Keeping the minimal toolset. Add tools later with `hermes tools`.")-- # ── Built-in plugins (off unless chosen) ──- print()- print_header("Plugins")- if prompt_yes_no("Review and enable built-in plugins now?", default=False):- print_info("Manage plugins with `hermes plugins list` / `hermes plugins install`.")- else:- print_info("No plugins enabled. Add later with `hermes plugins`.")-- # ── MCP servers (off unless chosen) ──- print()- print_header("MCP Servers")- if prompt_yes_no("Add an MCP server now?", default=False):- print_info("Add servers with `hermes mcp add <name> --url ... | --command ...`.")- else:- print_info("No MCP servers configured. Add later with `hermes mcp add`.")-- # ── Optional messaging gateway ──- print()- if prompt_yes_no("Connect a messaging platform (Telegram, Discord, …)?", default=False):- setup_gateway(config)-- save_config(config)-- print()- print_success("Blank Slate setup complete — minimal agent ready.")- print_info(" Enable more tools: hermes tools")- print_info(" Seed skills: hermes skills opt-in --sync")- print_info(" Add MCP servers: hermes mcp add")- print_info(" Tune agent settings: hermes setup agent")- print()-- _print_setup_summary(config, hermes_home)---def _run_quick_setup(config: dict, hermes_home):- """Quick setup — only configure items that are missing."""- from hermes_cli.config import (- get_missing_env_vars,- get_missing_config_fields,- check_config_version,- )-- print()- print_header("Quick Setup — Missing Items Only")-- # Check what's missing- missing_required = [- v for v in get_missing_env_vars(required_only=False) if v.get("is_required")- ]- missing_optional = [- v for v in get_missing_env_vars(required_only=False) if not v.get("is_required")- ]- missing_config = get_missing_config_fields()- current_ver, latest_ver = check_config_version()-- has_anything_missing = (- missing_required- or missing_optional- or missing_config- or current_ver < latest_ver- )-- if not has_anything_missing:- print_success("Everything is configured! Nothing to do.")- print()- print_info("Run 'hermes setup' and choose 'Full Setup' to reconfigure,")- print_info("or pick a specific section from the menu.")- return-- # Handle missing required env vars- if missing_required:- print()- print_info(f"{len(missing_required)} required setting(s) missing:")- for var in missing_required:- print(f" • {var['name']}")- print()-- for var in missing_required:- print()- print(color(f" {var['name']}", Colors.CYAN))- print_info(f" {var.get('description', '')}")- if var.get("url"):- print_info(f" Get key at: {var['url']}")-- if var.get("password"):- value = prompt(f" {var.get('prompt', var['name'])}", password=True)- else:- value = prompt(f" {var.get('prompt', var['name'])}")-- if value:- save_env_value(var["name"], value)- print_success(f" Saved {var['name']}")- else:- print_warning(f" Skipped {var['name']}")-- # Split missing optional vars by category- missing_tools = [v for v in missing_optional if v.get("category") == "tool"]- missing_messaging = [- v- for v in missing_optional- if v.get("category") == "messaging" and not v.get("advanced")- ]-- # ── Tool API keys (checklist) ──- if missing_tools:- print()- print_header("Tool API Keys")-- checklist_labels = []- for var in missing_tools:- tools = var.get("tools", [])- tools_str = f" → {', '.join(tools[:2])}" if tools else ""- checklist_labels.append(f"{var.get('description', var['name'])}{tools_str}")-- selected_indices = prompt_checklist(- "Which tools would you like to configure?",- checklist_labels,- )-- for idx in selected_indices:- var = missing_tools[idx]- _prompt_api_key(var)-- # ── Messaging platforms (checklist then prompt for selected) ──- if missing_messaging:- print()- print_header("Messaging Platforms")- print_info("Connect Hermes to messaging apps to chat from anywhere.")- print_info("You can configure these later with 'hermes setup gateway'.")-- # Group by platform (preserving order)- platform_order = []- platforms = {}- for var in missing_messaging:- name = var["name"]- if "TELEGRAM" in name:- plat = "Telegram"- elif "DISCORD" in name:- plat = "Discord"- elif "SLACK" in name:- plat = "Slack"- else:- continue- if plat not in platforms:- platform_order.append(plat)- platforms.setdefault(plat, []).append(var)-- platform_labels = [- {- "Telegram": "📱 Telegram",- "Discord": "💬 Discord",- "Slack": "💼 Slack",- }.get(p, p)- for p in platform_order- ]-- selected_indices = prompt_checklist(- "Which platforms would you like to set up?",- platform_labels,- )-- for idx in selected_indices:- plat = platform_order[idx]- vars_list = platforms[plat]- emoji = {"Telegram": "📱", "Discord": "💬", "Slack": "💼"}.get(plat, "")- print()- print(color(f" ─── {emoji} {plat} ───", Colors.CYAN))- print()- for var in vars_list:- print_info(f" {var.get('description', '')}")- if var.get("url"):- print_info(f" {var['url']}")- if var.get("password"):- value = prompt(f" {var.get('prompt', var['name'])}", password=True)- else:- value = prompt(f" {var.get('prompt', var['name'])}")- if value:- save_env_value(var["name"], value)- print_success(" ✓ Saved")- else:- print_warning(" Skipped")- print()-- # Handle missing config fields- if missing_config:- print()- print_info(- f"Adding {len(missing_config)} new config option(s) with defaults..."- )- for field in missing_config:- print_success(f" Added {field['key']} = {field['default']}")-- # Update config version- config["_config_version"] = latest_ver- save_config(config)-- # Jump to summary- _print_setup_summary(config, hermes_home)diff --git a/hermes_cli/setup_migration.py b/hermes_cli/setup_migration.pynew file mode 100644index 00000000000..f21bd76fc81--- /dev/null+++ b/hermes_cli/setup_migration.py@@ -0,0 +1,365 @@+"""Post-migration section-skip logic and the OpenClaw first-run migration flow.++Extracted from hermes_cli/setup.py, which re-exports the names it still uses.+"""++import importlib.util+import logging+import sys+from functools import partial+from pathlib import Path+from typing import Optional++from hermes_constants import get_optional_skills_dir++logger = logging.getLogger("hermes_cli.setup")++PROJECT_ROOT = Path(__file__).parent.parent.resolve()+++# =============================================================================+# Post-Migration Section Skip Logic+# =============================================================================++_OPENROUTER_ENV_VARS = ("OPENROUTER_API_KEY", "OPENAI_API_KEY")+++def _model_section_has_credentials(config: dict) -> bool:+ """Return True when any known inference provider has usable credentials.++ Sources of truth: ``PROVIDER_REGISTRY`` in ``hermes_cli.auth`` (every provider with its+ ``api_key_env_vars``); ``active_provider`` in the auth store (OAuth device-code / external-OAuth+ providers: Nous, Codex, Qwen, Gemini CLI, ...); and the legacy OpenRouter aggregator env vars,+ which route generic ``OPENAI_API_KEY`` / ``OPENROUTER_API_KEY`` values through OpenRouter.+ """+ from hermes_cli.setup import get_env_value++ try:+ from hermes_cli.auth import get_active_provider+ if get_active_provider():+ return True+ except Exception:+ pass++ try:+ from hermes_cli.auth import PROVIDER_REGISTRY+ except Exception:+ PROVIDER_REGISTRY = {} # type: ignore[assignment]++ def _has_key(pconfig) -> bool:+ # CLAUDE_CODE_OAUTH_TOKEN is set by Claude Code itself, not by the user —+ # mirrors is_provider_explicitly_configured in auth.py.+ return any(get_env_value(v) for v in pconfig.api_key_env_vars if v != "CLAUDE_CODE_OAUTH_TOKEN")++ def _any_openrouter_key() -> bool:+ return any(get_env_value(v) for v in _OPENROUTER_ENV_VARS)++ # Prefer the provider declared in config.yaml, avoids false positives from stray+ # env vars (GH_TOKEN, etc.) when the user has already picked a different provider.+ model_cfg = config.get("model") if isinstance(config, dict) else None+ if isinstance(model_cfg, dict):+ provider_id = (model_cfg.get("provider") or "").strip().lower()+ if provider_id in PROVIDER_REGISTRY and _has_key(PROVIDER_REGISTRY[provider_id]):+ return True+ if provider_id == "openrouter" and _any_openrouter_key():+ return True++ # OpenRouter aggregator fallback (no provider declared in config).+ if _any_openrouter_key():+ return True++ # Skip copilot in auto-detect: GH_TOKEN / GITHUB_TOKEN are commonly set for+ # git tooling. Mirrors resolve_provider in auth.py.+ return any(_has_key(pconfig) for pid, pconfig in PROVIDER_REGISTRY.items() if pid != "copilot")+++def _gateway_platform_short_label(label: str) -> str:+ """Strip trailing parenthetical qualifiers from a gateway platform label."""+ return label.split("(", 1)[0].strip() or label+++def _model_summary(config: dict) -> Optional[str]:+ if not _model_section_has_credentials(config):+ return None+ model = config.get("model")+ if isinstance(model, str) and model.strip():+ return model.strip()+ if isinstance(model, dict):+ return str(model.get("default") or model.get("model") or "configured")+ return "configured"+++def _cfg_summary(config: dict, section: str, key: str, default, prefix: str) -> str:+ from hermes_cli.setup import cfg_get+ return f"{prefix}{cfg_get(config, section, key, default=default)}"+++def _gateway_summary(config: dict) -> Optional[str]:+ from hermes_cli.gateway import _all_platforms, _platform_status+ # Count any non-empty status other than the "not configured" sentinel — platforms like+ # WhatsApp ("enabled, not paired"), Matrix ("configured + E2EE"), and Signal ("partially+ # configured") all indicate the user has already started setup and we shouldn't force+ # the section to rerun. No platforms configured -> None -> section must run.+ configured = [+ _gateway_platform_short_label(plat["label"])+ for plat in _all_platforms()+ if _platform_status(plat) and _platform_status(plat) != "not configured"+ ]+ return ", ".join(configured) if configured else None+++_TOOL_ENV_LABELS = (+ ("ELEVENLABS_API_KEY", "TTS/ElevenLabs"),+ ("BROWSERBASE_API_KEY", "Browser"),+ ("FIRECRAWL_API_KEY", "Firecrawl"),+)+++def _tools_summary(config: dict) -> Optional[str]:+ from hermes_cli.setup import get_env_value+ tools = [label for env_var, label in _TOOL_ENV_LABELS if get_env_value(env_var)]+ return ", ".join(tools) if tools else None+++_SECTION_SUMMARIES = {+ "model": _model_summary,+ "terminal": partial(_cfg_summary, section="terminal", key="backend", default="local", prefix="backend: "),+ "agent": partial(_cfg_summary, section="agent", key="max_turns", default=90, prefix="max turns: "),+ "gateway": _gateway_summary,+ "tools": _tools_summary,+}+++def _get_section_config_summary(config: dict, section_key: str) -> Optional[str]:+ """Return a short summary if a setup section is already configured, else None.++ Used after OpenClaw migration to detect which sections can be skipped. ``get_env_value`` is+ reached through hermes_cli.setup so that test patches on ``setup_mod.get_env_value`` apply.+ """+ summarize = _SECTION_SUMMARIES.get(section_key)+ return summarize(config) if summarize else None+++def _skip_configured_section(config: dict, section_key: str, label: str) -> bool:+ """Show an already-configured section summary and offer to skip.++ Returns True if the user chose to skip, False if the section should run.+ """+ from hermes_cli.setup import print_success, prompt_yes_no+ summary = _get_section_config_summary(config, section_key)+ if not summary:+ return False+ print()+ print_success(f" {label}: {summary}")+ return not prompt_yes_no(f" Reconfigure {label.lower()}?", default=False)+++# =============================================================================+# OpenClaw Migration+# =============================================================================++_OPENCLAW_SCRIPT = (+ get_optional_skills_dir(PROJECT_ROOT / "optional-skills")+ / "migration" / "openclaw-migration" / "scripts" / "openclaw_to_hermes.py"+)+++def _load_openclaw_migration_module():+ """Load the openclaw_to_hermes migration script as a module; None if it can't be loaded."""+ from hermes_cli.setup import _OPENCLAW_SCRIPT+ if not _OPENCLAW_SCRIPT.exists():+ return None+ spec = importlib.util.spec_from_file_location("openclaw_to_hermes", _OPENCLAW_SCRIPT)+ if spec is None or spec.loader is None:+ return None+ mod = importlib.util.module_from_spec(spec)+ # Register in sys.modules so @dataclass can resolve the module+ # (Python 3.11+ requires this for dynamically loaded modules)+ sys.modules[spec.name] = mod+ try:+ spec.loader.exec_module(mod)+ except Exception:+ sys.modules.pop(spec.name, None)+ raise+ return mod+++# Item kinds that represent high-impact changes warranting explicit warnings.+# Gateway tokens/channels can hijack messaging platforms from the old agent.+# Config values may have different semantics between OpenClaw and Hermes.+# Instruction/context files (.md) can contain incompatible setup procedures.+_HIGH_IMPACT_KIND_KEYWORDS = {+ "gateway": "⚠ Gateway/messaging — this will configure Hermes to use your OpenClaw messaging channels",+ "telegram": "⚠ Telegram — this will point Hermes at your OpenClaw Telegram bot",+ "slack": "⚠ Slack — this will point Hermes at your OpenClaw Slack workspace",+ "discord": "⚠ Discord — this will point Hermes at your OpenClaw Discord bot",+ "whatsapp": "⚠ WhatsApp — this will point Hermes at your OpenClaw WhatsApp connection",+ "config": "⚠ Config values — OpenClaw settings may not map 1:1 to Hermes equivalents",+ "soul": "⚠ Instruction file — may contain OpenClaw-specific setup/restart procedures",+ "memory": "⚠ Memory/context file — may reference OpenClaw-specific infrastructure",+ "context": "⚠ Context file — may contain OpenClaw-specific instructions",+}++_MIGRATION_WARNING_NOTES = (+ " Note: OpenClaw config values may have different semantics in Hermes.",+ " For example, OpenClaw's tool_call_execution: \"auto\" ≠ Hermes's yolo mode.",+ " Instruction files (.md) from OpenClaw may contain incompatible procedures.",+)+++def _migrated_row(item: dict, kind: str) -> str:+ dest = item.get("destination", "")+ if dest:+ return f" {kind:<22s} → {str(dest).replace(str(Path.home()), '~')}"+ return f" {kind}"+++def _reason_row(default_reason: str, item: dict, kind: str) -> str:+ return f" {kind:<22s} {item.get('reason', default_reason)}"+++def _print_migration_preview(report: dict):+ """Print a detailed dry-run preview of what migration would do.++ Groups items by status and adds explicit warnings for high-impact changes like+ gateway token takeover and config value differences.+ """+ from hermes_cli.setup import Colors, color, print_info+ items = report.get("items", [])+ if not items:+ print_info("Nothing to migrate.")+ return++ groups = (+ ("migrated", " Would import:", Colors.GREEN, _migrated_row),+ ("conflict", " Would overwrite (conflicts with existing Hermes config):", Colors.YELLOW,+ partial(_reason_row, "already exists")),+ ("skipped", " Would skip:", Colors.DIM, partial(_reason_row, "")),+ )+ warnings_shown = set()+ for status, header, col, row in groups:+ group = [i for i in items if i.get("status") == status]+ if not group:+ continue+ print(color(header, col))+ for item in group:+ kind = item.get("kind", "unknown")+ print(row(item, kind))+ if status == "migrated": # collect warnings for high-impact items+ kind_lower, dest_lower = kind.lower(), str(item.get("destination", "")).lower()+ warnings_shown.update(+ w for kw, w in _HIGH_IMPACT_KIND_KEYWORDS.items() if kw in kind_lower or kw in dest_lower+ )+ print()++ if warnings_shown:+ print(color(" ── Warnings ──", Colors.YELLOW))+ for warning in sorted(warnings_shown):+ print(color(f" {warning}", Colors.YELLOW))+ print()+ for line in _MIGRATION_WARNING_NOTES:+ print(color(line, Colors.YELLOW))+ print()+++def _run_migrator(mod, openclaw_dir: Path, hermes_home: Path, selected, *, execute: bool, overwrite: bool):+ """Run a Migrator with the fixed first-time-setup options and return its report."""+ return mod.Migrator(+ source_root=openclaw_dir.resolve(), target_root=hermes_home.resolve(), execute=execute,+ workspace_target=None, overwrite=overwrite, migrate_secrets=True, output_dir=None,+ selected_options=selected, preset_name="full",+ ).migrate()+++def _offer_openclaw_migration(hermes_home: Path) -> bool:+ """Detect ~/.openclaw and offer to migrate during first-time setup.++ Runs a dry-run first to show the user exactly what would be imported, overwritten, or+ taken over. Only executes after explicit confirmation. Returns True if migration ran+ successfully, False otherwise.+ """+ from hermes_cli.setup import (+ _OPENCLAW_SCRIPT, get_config_path, load_config, print_header, print_info,+ print_success, print_warning, prompt_yes_no, save_config,+ )+ openclaw_dir = Path.home() / ".openclaw"+ if not openclaw_dir.is_dir() or not _OPENCLAW_SCRIPT.exists():+ return False++ print()+ print_header("OpenClaw Installation Detected")+ print_info(f"Found OpenClaw data at {openclaw_dir}")+ print_info("Hermes can preview what would be imported before making any changes.")+ print()+ if not prompt_yes_no("Would you like to see what can be imported?", default=True):+ print_info("Skipping migration. You can run it later with: hermes claw migrate --dry-run")+ return False++ # Ensure config.yaml exists before migration tries to read it+ if not get_config_path().exists():+ save_config(load_config())++ try:+ mod = _load_openclaw_migration_module()+ if mod is None:+ print_warning("Could not load migration script.")+ return False+ except Exception as e:+ print_warning(f"Could not load migration script: {e}")+ logger.debug("OpenClaw migration module load error", exc_info=True)+ return False++ # ── Phase 1: Dry-run preview (overwrite=True shows everything, including conflicts) ──+ try:+ selected = mod.resolve_selected_options(None, None, preset="full")+ preview_report = _run_migrator(mod, openclaw_dir, hermes_home, selected, execute=False, overwrite=True)+ except Exception as e:+ print_warning(f"Migration preview failed: {e}")+ logger.debug("OpenClaw migration preview error", exc_info=True)+ return False++ preview_count = preview_report.get("summary", {}).get("migrated", 0)+ if preview_count == 0:+ print()+ print_info("Nothing to import from OpenClaw.")+ return False+ print()+ print_header(f"Migration Preview — {preview_count} item(s) would be imported")+ print_info("No changes have been made yet. Review the list below:")+ print()+ _print_migration_preview(preview_report)++ # ── Phase 2: Confirm and execute ──+ if not prompt_yes_no("Proceed with migration?", default=False):+ print_info("Migration cancelled. You can run it later with: hermes claw migrate")+ print_info("Use --dry-run to preview again, or --preset minimal for a lighter import.")+ return False++ # overwrite=False so existing Hermes configs are preserved. The user saw the+ # preview; conflicts are skipped by default.+ try:+ report = _run_migrator(mod, openclaw_dir, hermes_home, selected, execute=True, overwrite=False)+ except Exception as e:+ print_warning(f"Migration failed: {e}")+ logger.debug("OpenClaw migration error", exc_info=True)+ return False++ summary = report.get("summary", {})+ migrated, skipped = summary.get("migrated", 0), summary.get("skipped", 0)+ conflicts, errors = summary.get("conflict", 0), summary.get("error", 0)+ print()+ for count, printer, text in (+ (migrated, print_success, f"Imported {migrated} item(s) from OpenClaw."),+ (conflicts, print_info,+ f"Skipped {conflicts} item(s) that already exist in Hermes (use hermes claw migrate --overwrite to force)."),+ (skipped, print_info, f"Skipped {skipped} item(s) (not found or unchanged)."),+ (errors, print_warning, f"{errors} item(s) had errors — check the migration report."),+ ):+ if count:+ printer(text)++ output_dir = report.get("output_dir")+ if output_dir:+ print_info(f"Full report saved to: {output_dir}")+ print_success("Migration complete! Continuing with setup...")+ return Truediff --git a/hermes_cli/setup_platforms.py b/hermes_cli/setup_platforms.pynew file mode 100644index 00000000000..6eecb617762--- /dev/null+++ b/hermes_cli/setup_platforms.py@@ -0,0 +1,433 @@+"""Messaging-platform setup wizards (Telegram, BlueBubbles, QQ Bot, webhooks) and the+``hermes setup gateway`` flow. Extracted from hermes_cli/setup.py; setup.py re-exports+the public names, and tests monkeypatch prompt/print/env helpers on hermes_cli.setup."""++import logging+import re+from pathlib import Path++logger = logging.getLogger("hermes_cli.setup")++_TELEGRAM_BOT_TOKEN_RE = re.compile(r"^\d+:[A-Za-z0-9_-]{30,}$")+++def _is_valid_telegram_bot_token(token: str) -> bool:+ return bool(_TELEGRAM_BOT_TOKEN_RE.match(token))+++def _info(*lines: str | None) -> None:+ """print_info each line in order; ``None`` emits a bare blank ``print()``."""+ from hermes_cli.setup import print_info++ for line in lines:+ print() if line is None else print_info(line)+++def _profile_name_from_hermes_home(hermes_home) -> str | None:+ """Return the active profile name when HERMES_HOME is a profile dir."""+ if hermes_home.parent.name == "profiles":+ return hermes_home.name+ return None+++def _setup_telegram_auto_result():+ """Attempt automatic Telegram bot creation via managed QR onboarding."""+ from hermes_cli.setup import get_hermes_home++ try:+ from hermes_cli.telegram_managed_bot import auto_setup_telegram_bot_result+ except ImportError:+ return None++ profile_name: str | None = None+ try:+ profile_name = _profile_name_from_hermes_home(Path(get_hermes_home()))+ except Exception:+ pass+ return auto_setup_telegram_bot_result(profile_name=profile_name)+++def _declines_reconfigure(env_var: str, label: str, question: str) -> bool:+ """True when ``env_var`` is already set and the user does NOT want to reconfigure."""+ from hermes_cli.setup import get_env_value, print_info, prompt_yes_no++ if not get_env_value(env_var):+ return False+ print_info(f"{label}: already configured")+ return not prompt_yes_no(question, False)+++def _save_if_set(env_var: str, value: str) -> None:+ from hermes_cli.setup import save_env_value++ if value:+ save_env_value(env_var, value)+++def _save_allowlist(env_var: str, users: str, success_msg: str) -> None:+ """Strip spaces, persist the allowlist, and confirm."""+ from hermes_cli.setup import print_success, save_env_value++ save_env_value(env_var, users.replace(" ", ""))+ print_success(success_msg)+++def _save_port(env_var: str, value: str, default: str) -> None:+ """Persist ``value`` as an int port; warn (keeping ``default``) when it isn't one."""+ from hermes_cli.setup import print_success, print_warning, save_env_value++ if not value:+ return+ try:+ save_env_value(env_var, str(int(value)))+ print_success(f"Webhook port set to {value}")+ except ValueError:+ print_warning(f"Invalid port number, using default {default}")+++def _prompt_telegram_bot_token() -> str | None:+ from hermes_cli.setup import print_error, print_info, prompt++ print_info("Create a bot via @BotFather on Telegram")+ while True:+ token = prompt("Telegram bot token", password=True)+ if not token:+ return None+ if not _is_valid_telegram_bot_token(token):+ print_error("Invalid token format. Expected: <numeric_id>:<alphanumeric_hash> "+ "(e.g., 123456789:ABCdefGHI-jklMNOpqrSTUvwxYZ)")+ continue+ return token+++def _telegram_allowlist_nudge() -> None:+ """Existing config kept as-is: warn when it has no user allowlist."""+ from hermes_cli.setup import get_env_value, print_info, prompt, prompt_yes_no++ if get_env_value("TELEGRAM_ALLOWED_USERS"):+ return+ print_info("⚠️ Telegram has no user allowlist - anyone can use your bot!")+ if prompt_yes_no("Add allowed users now?", True):+ print_info(" To find your Telegram user ID: message @userinfobot")+ allowed_users = prompt("Allowed user IDs (comma-separated)")+ if allowed_users:+ _save_allowlist("TELEGRAM_ALLOWED_USERS", allowed_users, "Telegram allowlist configured")+++def _obtain_telegram_token():+ """Return (token, setup_result); auto flow first when chosen, else manual paste."""+ from hermes_cli.setup import print_error, prompt++ _info("How would you like to create your Telegram bot?", None,+ " [1] Automatic (recommended)",+ " Scan a QR code → confirm in Telegram → done.",+ " No token copy-paste needed.", None,+ " [2] Manual",+ " Create a bot via @BotFather yourself and paste the token.", None)++ choice = prompt("Choice [1/2]", default="1")+ token = None+ setup_result = None++ if choice.strip() == "1":+ setup_result = _setup_telegram_auto_result()+ if setup_result:+ token = setup_result.token+ if not _is_valid_telegram_bot_token(token):+ print_error("Automatic setup returned an invalid Telegram bot token.")+ token = None+ setup_result = None+ if not token:+ _info(None, "Falling back to manual setup...", None)++ if not token:+ token = _prompt_telegram_bot_token()+ return token, setup_result+++def _setup_telegram():+ """Configure Telegram bot credentials and allowlist."""+ from hermes_cli.setup import print_header, print_info, print_success, prompt, prompt_yes_no+ from hermes_cli.setup import save_env_value++ print_header("Telegram")+ if _declines_reconfigure("TELEGRAM_BOT_TOKEN", "Telegram", "Reconfigure Telegram?"):+ _telegram_allowlist_nudge()+ return++ token, setup_result = _obtain_telegram_token()+ if not token:+ return++ save_env_value("TELEGRAM_BOT_TOKEN", token)+ print_success("Telegram token saved")++ _info(None, "🔒 Security: Restrict who can use your bot",+ " To find your Telegram user ID:",+ " 1. Message @userinfobot on Telegram",+ " 2. It will reply with your numeric ID (e.g., 123456789)", None)++ open_access_q = "Allowed user IDs (comma-separated, leave empty for open access)"+ detected_user_id = getattr(setup_result, "owner_user_id", None)+ if detected_user_id:+ detected_id = str(detected_user_id)+ print_success(f"Detected your Telegram user ID: {detected_id}")+ if prompt_yes_no("Allow this Telegram account to use the bot?", True):+ extra = prompt("Additional allowed user IDs (comma-separated, optional)")+ ids = [detected_id]+ for uid in extra.replace(" ", "").split(","):+ if uid and uid not in ids:+ ids.append(uid)+ allowed_users = ",".join(ids)+ else:+ allowed_users = prompt(open_access_q)+ else:+ allowed_users = prompt(open_access_q)++ if allowed_users:+ allowed_users = allowed_users.replace(" ", "")+ save_env_value("TELEGRAM_ALLOWED_USERS", allowed_users)+ print_success("Telegram allowlist configured - only listed users can use the bot")+ else:+ print_info("⚠️ No allowlist set - anyone who finds your bot can use it!")++ _info(None, "📬 Home Channel: where Hermes delivers cron job results,",+ " cross-platform messages, and notifications.",+ " For Telegram DMs, this is your user ID (same as above).")++ first_user_id = allowed_users.split(",")[0].strip() if allowed_users else ""+ if first_user_id:+ if prompt_yes_no(f"Use your user ID ({first_user_id}) as the home channel?", True):+ save_env_value("TELEGRAM_HOME_CHANNEL", first_user_id)+ print_success(f"Telegram home channel set to {first_user_id}")+ else:+ q = "Home channel ID (or leave empty to set later with /set-home in Telegram)"+ _save_if_set("TELEGRAM_HOME_CHANNEL", prompt(q))+ else:+ print_info(" You can also set this later by typing /set-home in your Telegram chat.")+ _save_if_set("TELEGRAM_HOME_CHANNEL", prompt("Home channel ID (leave empty to set later)"))+++# _setup_slack/_write_slack_manifest_and_instruct and _setup_matrix live in their plugins+# (plugins/platforms/{slack,matrix}/adapter.py::interactive_setup, via setup_fn). #41112 #3823.+++def _setup_bluebubbles():+ """Configure BlueBubbles iMessage gateway."""+ from hermes_cli.setup import print_header, print_info, print_success, print_warning, prompt+ from hermes_cli.setup import prompt_yes_no, save_env_value++ print_header("BlueBubbles (iMessage)")+ if _declines_reconfigure("BLUEBUBBLES_SERVER_URL", "BlueBubbles", "Reconfigure BlueBubbles?"):+ return++ _info("Connects Hermes to iMessage via BlueBubbles — a free, open-source",+ "macOS server that bridges iMessage to any device.",+ " Requires a Mac running BlueBubbles Server v1.0.0+",+ " Download: https://bluebubbles.app/", None,+ "In BlueBubbles Server → Settings → API, note your Server URL and Password.", None)++ server_url = prompt("BlueBubbles server URL (e.g. http://192.168.1.10:1234)")+ if not server_url:+ print_warning("Server URL is required — skipping BlueBubbles setup")+ return+ save_env_value("BLUEBUBBLES_SERVER_URL", server_url.rstrip("/"))++ password = prompt("BlueBubbles server password", password=True)+ if not password:+ print_warning("Password is required — skipping BlueBubbles setup")+ return+ save_env_value("BLUEBUBBLES_PASSWORD", password)+ print_success("BlueBubbles credentials saved")++ _info(None, "🔒 Security: Restrict who can message your bot",+ " Use iMessage addresses: email ([email protected]) or phone (+15551234567)", None)+ allowed_users = prompt("Allowed iMessage addresses (comma-separated, leave empty for open access)")+ if allowed_users:+ _save_allowlist("BLUEBUBBLES_ALLOWED_USERS", allowed_users, "BlueBubbles allowlist configured")+ else:+ print_info("⚠️ No allowlist set — anyone who can iMessage you can use the bot!")++ _info(None, "📬 Home Channel: phone or email for cron job delivery and notifications.",+ " You can also set this later with /set-home in your iMessage chat.")+ _save_if_set("BLUEBUBBLES_HOME_CHANNEL", prompt("Home channel address (leave empty to set later)"))++ _info(None, "Advanced settings (defaults are fine for most setups):")+ if prompt_yes_no("Configure webhook listener settings?", False):+ _save_port("BLUEBUBBLES_WEBHOOK_PORT", prompt("Webhook listener port (default: 8645)"), "8645")++ _info(None, "Requires the BlueBubbles Private API helper for typing indicators,",+ "read receipts, and tapback reactions. Basic messaging works without it.",+ " Install: https://docs.bluebubbles.app/helper-bundle/installation")+++def _setup_qqbot():+ """Configure QQ Bot (Official API v2) via gateway setup."""+ from hermes_cli.gateway import _setup_qqbot as _gateway_setup_qqbot+ _gateway_setup_qqbot()+++def _setup_webhooks():+ """Configure webhook integration."""+ from hermes_cli.setup import print_header, print_success, print_warning, prompt, save_env_value++ print_header("Webhooks")+ if _declines_reconfigure("WEBHOOK_ENABLED", "Webhooks", "Reconfigure webhooks?"):+ return++ print()+ print_warning("⚠ Webhook and SMS platforms require exposing gateway ports to the")+ print_warning(" internet. For security, run the gateway in a sandboxed environment")+ print_warning(" (Docker, VM, etc.) to limit blast radius from prompt injection.")+ print()+ _info(" Full guide: https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/", None)++ _save_port("WEBHOOK_PORT", prompt("Webhook port (default 8644)"), "8644")++ secret = prompt("Global HMAC secret (shared across all routes)", password=True)+ if secret:+ save_env_value("WEBHOOK_SECRET", secret)+ print_success("Webhook secret saved")+ else:+ print_warning("No secret set — you must configure per-route secrets in config.yaml")++ save_env_value("WEBHOOK_ENABLED", "true")+ print()+ print_success("Webhooks enabled! Next steps:")+ from hermes_constants import display_hermes_home as _dhh+ _info(f" 1. Define webhook routes in {_dhh()}/config.yaml",+ " 2. Point your service (GitHub, GitLab, etc.) at:",+ " http://your-server:8644/webhooks/<route-name>", None,+ " Route configuration guide:",+ " https://hermes-agent.nousresearch.com/docs/user-guide/messaging/webhooks/#configuring-routes",+ None,+ # Printed twice upstream; kept verbatim for output parity.+ " Open config in your editor: hermes config edit",+ " Open config in your editor: hermes config edit")+++# ── Gateway ──++# (platform label, credential env var, home-channel env vars — any one satisfies)+_HOME_CHANNEL_CHECKS = (+ ("Telegram", "TELEGRAM_BOT_TOKEN", ("TELEGRAM_HOME_CHANNEL",)),+ ("Discord", "DISCORD_BOT_TOKEN", ("DISCORD_HOME_CHANNEL",)),+ ("Slack", "SLACK_BOT_TOKEN", ("SLACK_HOME_CHANNEL",)),+ ("BlueBubbles", "BLUEBUBBLES_SERVER_URL", ("BLUEBUBBLES_HOME_CHANNEL",)),+ ("QQBot", "QQ_APP_ID", ("QQBOT_HOME_CHANNEL", "QQ_HOME_CHANNEL")),+)+++def _is_progress(status: str) -> bool:+ """A platform counts as configured unless its status says otherwise."""+ s = status.lower()+ return not (s == "not configured" or s.startswith("partially") or s.startswith("plugin disabled"))+++def _warn_missing_home_channels() -> None:+ """Platforms with a token but no home channel."""+ from hermes_cli.setup import get_env_value, print_warning++ missing_home = [+ plat for plat, token_var, home_vars in _HOME_CHANNEL_CHECKS+ if get_env_value(token_var) and not any(get_env_value(v) for v in home_vars)+ ]+ if not missing_home:+ return+ print()+ print_warning(f"No home channel set for: {', '.join(missing_home)}")+ _info(" Without a home channel, cron jobs and cross-platform",+ " messages can't be delivered to those platforms.",+ " Set one later with /set-home in your chat, or:",+ *(f" hermes config set {plat.upper()}_HOME_CHANNEL <channel_id>" for plat in missing_home))+++def _restart_running_gateway(any_messaging: bool, supports_systemd: bool) -> None:+ """Already running: only offer a restart when this setup pass may have changed+ platform config — a restart interrupts any active session, so it stays behind a+ prompt."""+ from hermes_cli.setup import print_error, prompt_yes_no+ from hermes_cli.gateway import (+ systemd_restart, launchd_restart, UserSystemdUnavailableError, SystemScopeRequiresRootError,+ _system_scope_wizard_would_need_root, _print_system_scope_remediation,+ )+ import platform as _platform++ if supports_systemd and _system_scope_wizard_would_need_root():+ _print_system_scope_remediation("restart")+ return+ if not (any_messaging and prompt_yes_no(" Restart the gateway to pick up changes?", True)):+ return+ try:+ if supports_systemd:+ systemd_restart()+ elif _platform.system() == "Darwin":+ launchd_restart()+ elif _platform.system() == "Windows":+ from hermes_cli import gateway_windows+ gateway_windows.restart()+ except UserSystemdUnavailableError as e:+ print_error(" Restart failed — user systemd not reachable:")+ for line in str(e).splitlines():+ print(f" {line}")+ except SystemScopeRequiresRootError as e:+ # Defense in depth: the pre-check above should have caught this, but a race+ # (unit file appearing mid-run) could still land here. Previously this exited+ # the whole wizard via sys.exit(1).+ print_error(f" Restart failed: {e}")+ _print_system_scope_remediation("restart")+ except Exception as e:+ print_error(f" Restart failed: {e}")+++def setup_gateway(config: dict):+ """Configure messaging platform integrations."""+ from hermes_cli.setup import print_header, print_info, print_success, prompt_checklist+ from hermes_cli.gateway import _all_platforms, _platform_status, _configure_platform++ print_header("Messaging Platforms")+ _info("Connect to messaging platforms to chat with Hermes from anywhere.",+ "Toggle with Space, confirm with Enter.", None)++ platforms = _all_platforms()++ # Build checklist, pre-selecting already-configured platforms.+ statuses = [_platform_status(plat) for plat in platforms]+ items = [f"{plat['emoji']} {plat['label']} ({status})" for plat, status in zip(platforms, statuses)]+ pre_selected = [i for i, status in enumerate(statuses) if status == "configured"]+ selected = prompt_checklist("Select platforms to configure:", items, pre_selected)++ if not selected:+ print_info("No platforms selected. Run 'hermes setup gateway' later to configure.")+ for idx in selected or ():+ _configure_platform(platforms[idx])++ # Count any platform (built-in or plugin) the user configured during this setup+ # pass — reuses ``_platform_status`` so plugin platforms like IRC are picked up+ # without another hard-coded env-var list.+ any_messaging = any(_is_progress(_platform_status(p)) for p in _all_platforms())+ if any_messaging:+ print()+ print_info("━" * 50)+ print_success("Messaging platforms configured!")+ _warn_missing_home_channels()++ # ── Gateway Service Setup ──+ # Runs UNCONDITIONALLY — even with zero platforms configured. A gateway without+ # platforms is a supported mode (cron scheduler keeps running, and adapters come up+ # automatically once tokens are added later, e.g. via `hermes import` or+ # `hermes setup gateway`). Gating this on messaging config was the bug that left+ # install-then-import machines with registered cron jobs and restored bot tokens+ # but no process to serve them.+ from hermes_cli.gateway import _is_service_running, supports_systemd_services, ensure_gateway_service++ supports_systemd = supports_systemd_services()++ print()+ if _is_service_running():+ _restart_running_gateway(any_messaging, supports_systemd)+ else:+ # Not running: install (if needed) and start, no questions asked.+ ensure_gateway_service(context="setup")++ print_info("━" * 50)diff --git a/hermes_cli/setup_quick.py b/hermes_cli/setup_quick.pynew file mode 100644index 00000000000..a239bff9a39--- /dev/null+++ b/hermes_cli/setup_quick.py@@ -0,0 +1,530 @@+"""Streamlined setup flows extracted from hermes_cli/setup.py: the Nous Portal+one-shot (`hermes portal`), first-time quick setup, Blank Slate setup and the+`--quick` missing-items pass. Names from setup.py are imported lazily per+function so test patches on ``hermes_cli.setup`` take effect."""++import logging+import os+import sys+from pathlib import Path++logger = logging.getLogger("hermes_cli.setup")++# (env-var name substring, platform label, emoji) — order matters: first match wins.+_MESSAGING_PLATFORMS = (+ ("TELEGRAM", "Telegram", "📱"), ("DISCORD", "Discord", "💬"), ("SLACK", "Slack", "💼"),+)+++def _reload_config_into(config: dict) -> None:+ """Re-sync the in-memory config dict from disk after a sub-flow that saved+ via its own load/save cycle, so a later save_config(config) can't clobber it."""+ from hermes_cli.setup import load_config++ _refreshed = load_config()+ config.clear()+ config.update(_refreshed)+++def _prompt_env_var(var: dict):+ """Prompt for one env-var value (masked when the var is a secret)."""+ from hermes_cli.setup import prompt++ return prompt(f" {var.get('prompt', var['name'])}", password=bool(var.get("password")))+++def _run_portal_one_shot(config: dict) -> None:+ """One-shot Nous Portal setup — OAuth + model pick + provider + Tool Gateway.++ Wired into ``hermes setup --portal`` and ``hermes portal``: the Nous-Portal slice+ of first-time quick setup as one shareable command. Login, model selection,+ provider switch and Tool Gateway opt-in are all delegated to ``_model_flow_nous``+ — the same flow ``_run_first_time_quick_setup`` and ``hermes model`` use for Nous —+ so there is a single source of truth and ``hermes portal`` always offers a picker.+ """+ from hermes_cli.setup import Colors, color, load_config, print_error, print_info, print_success++ print()+ print(color("┌─────────────────────────────────────────────────────────┐", Colors.MAGENTA))+ print(color("│ ⚕ Hermes Setup — Nous Portal (one-shot) │", Colors.MAGENTA))+ print(color("└─────────────────────────────────────────────────────────┘", Colors.MAGENTA))+ print()+ print_info(" One subscription, 300+ models, plus the Tool Gateway:")+ print_info(" web search, image generation, TTS, browser automation")+ print_info(" — all routed through your Nous Portal sub.")+ print()+ print_info(" Sign up: https://portal.nousresearch.com/manage-subscription")+ print()++ # Handles both the logged-out path (device-code OAuth, selects a model) and the+ # logged-in path (curated picker), then Tool Gateway opt-in; sets provider=nous.+ try:+ from hermes_cli.main import _model_flow_nous++ _model_flow_nous(config)+ except (KeyboardInterrupt, EOFError, SystemExit):+ # _login_nous raises SystemExit(130)/(1) on cancel/failure; the expired-+ # session re-login path inside _model_flow_nous only catches Exception,+ # so a SystemExit there would otherwise escape and kill the whole CLI.+ print()+ print_info(" Setup cancelled.")+ print_info(" You can retry later with `hermes portal`.")+ return+ except Exception as exc:+ logger.debug("_model_flow_nous error during `hermes portal`: %s", exc)+ print()+ print_error(f" Nous Portal setup encountered an error: {exc}")+ print_info(" You can retry later with `hermes portal`.")+ return++ # Re-sync from disk — _model_flow_nous writes via its own load/save cycle, so+ # a later save_config(config) by a caller must not clobber those values.+ try:+ _refreshed = load_config()+ if isinstance(_refreshed, dict):+ config.clear()+ config.update(_refreshed)+ except Exception:+ pass++ print()+ print_success("Portal setup complete.")+ print_info(" Run `hermes portal info` to inspect routing.")+ print_info(" Run `hermes` to start chatting.")+++def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):+ """Streamlined first-time setup via Nous Portal: OAuth, model, terminal & messaging.++ Everything else gets sensible defaults; customize later via ``hermes setup+ <section>`` or switch providers with ``hermes model``.+ """+ from hermes_cli.setup import (+ _apply_default_agent_settings, _print_macos_fda_tip, _print_setup_summary, print_header,+ print_info, print_success, print_warning, prompt_choice, save_config, setup_gateway,+ setup_terminal_backend,+ )++ # Step 1: Nous Portal — OAuth login + model selection (provider set to "nous" by the save).+ print()+ print_header("Nous Portal")+ print_info("One subscription, 300+ models, plus the Tool Gateway:")+ print_info(" web search, image generation, TTS, browser automation.")+ print_info("Sign up: https://portal.nousresearch.com/manage-subscription")+ print()+ try:+ from hermes_cli.main import _model_flow_nous+ _model_flow_nous(config)+ except (KeyboardInterrupt, EOFError):+ print()+ print_info("Nous Portal setup cancelled.")+ except Exception as exc:+ logger.debug("_model_flow_nous error during quick setup: %s", exc)+ print_warning(f"Nous Portal setup encountered an error: {exc}")+ print_info("You can try again later with: hermes model")++ # The wizard's later save_config(config) must not clobber the login/model save (#4172).+ _reload_config_into(config)++ # Step 2: Terminal Backend; Step 3: defaults for everything else.+ setup_terminal_backend(config)+ _apply_default_agent_settings(config)+ save_config(config)++ # Step 4: Offer messaging gateway setup+ print()+ gateway_choice = prompt_choice("Connect a messaging platform? (Telegram, Discord, etc.)", [+ "Set up messaging now (recommended)", "Skip — set up later with 'hermes setup gateway'",+ ], 0)++ if gateway_choice == 0:+ setup_gateway(config)+ save_config(config)+ else:+ # Messaging skipped — still install/start the gateway service so cron+ # jobs run and platforms come alive as soon as tokens are added later+ # (e.g. via `hermes import` from another machine).+ from hermes_cli.gateway import ensure_gateway_service+ ensure_gateway_service(context="setup")++ print()+ print_success("Setup complete! You're ready to go.")+ print()+ print_info(" Configure all settings: hermes setup")+ if gateway_choice != 0:+ print_info(" Connect Telegram/Discord: hermes setup gateway")+ _print_macos_fda_tip()+ print()++ _print_setup_summary(config, hermes_home)+++def _print_macos_fda_tip() -> None:+ """One-time macOS onboarding tip: a single Full Disk Access grant kills+ every per-folder permission prompt, permanently (issue #52010 follow-up).++ Uses the same prompt-free probe as doctor's check_macos_full_disk_access+ (the TCC db dir is FDA-gated but probing it never triggers a dialog).+ Silent on non-macOS and when FDA is already granted or indeterminate.+ """+ from hermes_cli.setup import print_info++ if sys.platform != "darwin":+ return+ tcc_dir = Path.home() / "Library" / "Application Support" / "com.apple.TCC"+ try:+ os.listdir(tcc_dir)+ return # already granted — nothing to teach+ except PermissionError:+ pass+ except OSError:+ return # indeterminate — don't nag+ print()+ print_info(" macOS tip: silence ALL folder permission prompts with one switch —")+ print_info(" System Settings → Privacy & Security → Full Disk Access → enable")+ print_info(" your terminal (and Hermes.app if you use Desktop), or run:")+ print_info(" open \"x-apple.systempreferences:com.apple.preference"+ ".security?Privacy_AllFiles\"")+ print_info(" The grant is permanent — it survives every Hermes update.")+++def _blank_slate_minimal_toolsets(config: dict):+ """Write the minimal toolset state for a Blank Slate install.++ Only ``file``, ``terminal``, ``vision`` and ``skills`` stay on: ``read_file``+ can't read images (it points at ``vision_analyze``), and the always-seeded+ ``hermes-agent`` skill needs ``skill_view``. Two layers enforce the selection:+ 1. ``platform_toolsets["cli"]`` — an explicit configurable-key list the resolver+ treats as authoritative (``has_explicit_config``), so defaults aren't re-expanded.+ 2. ``agent.disabled_toolsets`` — a global hard-suppression list applied last in+ ``_get_platform_tools``, overriding even the non-configurable platform-toolset+ recovery that would re-add e.g. ``kanban``. Users re-enable via ``hermes tools``+ (rewrites ``platform_toolsets``) or by editing ``agent.disabled_toolsets``.+ """+ keep = {"file", "terminal", "vision", "skills"}+ config.setdefault("platform_toolsets", {})["cli"] = sorted(keep)++ try:+ from toolsets import TOOLSETS+ from hermes_cli.tools_config import CONFIGURABLE_TOOLSETS, _get_plugin_toolset_keys++ all_keys = {k for k, _, _ in CONFIGURABLE_TOOLSETS}+ all_keys.update(_get_plugin_toolset_keys())+ # Plain TOOLSETS entries catch recovered toolsets like ``kanban``. Skip+ # "hermes-*" platform composites, "includes" groupings, and posture toolsets+ # (session-level picks by agent/coding_context.py — disabling them would make+ # model_tools subtract terminal/read_file from the minimal surface, #57315).+ for k, tdef in TOOLSETS.items():+ if k.startswith("hermes-"):+ continue+ if isinstance(tdef, dict) and (tdef.get("includes") or tdef.get("posture")):+ continue+ all_keys.add(k)++ disabled = sorted(all_keys - keep)+ if disabled:+ config.setdefault("agent", {})["disabled_toolsets"] = disabled+ except Exception as exc:+ logger.debug("blank-slate disabled_toolsets computation skipped: %s", exc)+++def _blank_slate_minimize_config(config: dict):+ """Turn OFF the optional config features (compression, memory/profile capture,+ checkpoints, smart routing, auto session reset; quiet display). All opt-in+ afterwards via ``hermes setup agent`` / ``hermes config set``."""+ config.setdefault("agent", {})["max_turns"] = 90+ config.setdefault("compression", {})["enabled"] = False+ mem = config.setdefault("memory", {})+ mem["memory_enabled"] = False+ mem["user_profile_enabled"] = False+ config.setdefault("checkpoints", {})["enabled"] = False+ config.setdefault("smart_model_routing", {})["enabled"] = False+ config.setdefault("session_reset", {})["mode"] = "none"+ config.setdefault("display", {})["tool_progress"] = "all"+++def _run_blank_slate_setup(config: dict, hermes_home, is_existing: bool):+ """Blank Slate setup — essentials only (provider/model, file + terminal), everything+ else OFF; then either finish now or walk through opting capabilities back in.+ Nothing is enabled that the user did not explicitly choose."""+ from hermes_cli.setup import (+ _blank_slate_minimal_toolsets, _blank_slate_minimize_config, _blank_slate_walkthrough,+ _print_setup_summary, print_header, print_info, print_success, prompt_choice, save_config,+ setup_model_provider, setup_terminal_backend,+ )++ print()+ print_header("Blank Slate Setup")+ print_info("Everything starts OFF. First we force-enable only what's required")+ print_info("to run an agent, then you choose whether to stop there or walk")+ print_info("through enabling more — opting in to exactly what you want.")+ print_info("")+ print_info("Forced on: Provider & Model, File Operations, Terminal, Vision, Skills.")+ print_info("Everything else (web, browser, code exec, memory,")+ print_info("delegation, cron, plugins, MCP, …) starts disabled. The")+ print_info("essential `hermes-agent` skill is always kept so the agent")+ print_info("can help you drive and configure Hermes itself.")+ print()++ # Step 1: Provider & Model (REQUIRED — the agent cannot run without it)+ print_header("Step 1 — Provider & Model (required)")+ setup_model_provider(config)+ save_config(config)++ # Step 2: Terminal backend (where commands run — a core decision)+ print_header("Step 2 — Terminal Backend")+ setup_terminal_backend(config)++ # Step 3: Lock in the minimal toolset + minimized config knobs+ _blank_slate_minimal_toolsets(config)+ _blank_slate_minimize_config(config)+ save_config(config)+ print()+ print_success("Minimal baseline applied:")+ print_info(" Toolsets: file, terminal, vision, skills (everything else off)")+ print_info(" Compression, memory, checkpoints, smart routing: off")++ # The fork: stop here, or walk through enabling things+ print()+ print_header("How far do you want to go?")+ path = prompt_choice("Your minimal agent is ready. What next?", [+ "Start with everything disabled — finish now (most minimal)",+ "Walk through all configurations — opt in to tools, skills, plugins, MCP",+ ], 0)++ if path == 0:+ save_config(config)+ # Blank Slate means no bundled skills; record the opt-out so future+ # `hermes update` runs don't re-inject them. Essential skills (the+ # `hermes-agent` operating manual) are still seeded by the sync.+ try:+ from tools.skills_sync import set_bundled_skills_opt_out, sync_skills+ set_bundled_skills_opt_out(True)+ sync_skills(quiet=True)+ except Exception as exc:+ logger.debug("blank-slate skill opt-out error: %s", exc)+ print()+ print_success("Blank Slate setup complete — minimal agent ready.")+ print_info("Enable anything later, on demand:")+ print_info(" Enable tools: hermes tools")+ print_info(" Seed skills: hermes skills opt-in --sync")+ print_info(" Add MCP servers: hermes mcp add")+ print_info(" Enable plugins: hermes plugins")+ print_info(" Tune agent settings: hermes setup agent")+ print()+ _print_setup_summary(config, hermes_home)+ return++ _blank_slate_walkthrough(config, hermes_home)+++def _blank_slate_walkthrough(config: dict, hermes_home):+ """Opt-in walkthrough for Blank Slate: skills, tools, plugins, MCP, gateway."""+ from hermes_cli.setup import (+ _print_setup_summary, print_header, print_info, print_success, print_warning,+ prompt_yes_no, save_config, setup_gateway,+ )++ # Bundled skills — default to NONE, offer to seed all+ print()+ print_header("Bundled Skills")+ print_info("Blank Slate ships with NO bundled skills by default.")+ seed_skills = prompt_yes_no(+ "Seed the full bundled skill catalog? (No = start with zero skills)", default=False+ )+ try:+ from tools.skills_sync import set_bundled_skills_opt_out, sync_skills+ if seed_skills:+ # Make sure no stale opt-out marker blocks the seed, then sync.+ set_bundled_skills_opt_out(False)+ result = sync_skills(quiet=True)+ copied = len(result.get("copied", [])) if isinstance(result, dict) else 0+ print_success(f"Seeded {copied} bundled skills.")+ else:+ set_bundled_skills_opt_out(True)+ # Essential skills (`hermes-agent`) are still seeded for an opted-out profile.+ sync_skills(quiet=True)+ print_info("No skills seeded (except the essential `hermes-agent`")+ print_info("skill). A .no-bundled-skills marker keeps future")+ print_info("`hermes update` runs from re-injecting them. Opt back in any")+ print_info("time with `hermes skills opt-in --sync`.")+ except Exception as exc:+ logger.debug("blank-slate skill handling error: %s", exc)+ print_warning(f"Skill setup step encountered an error: {exc}")++ # Walk through enabling additional tools+ print()+ print_header("Tools")+ print_info("Pick exactly which additional toolsets to turn on.")+ print_info("(file and terminal are already on; leave the rest off if you want")+ print_info(" the most minimal agent.)")+ if prompt_yes_no("Open the tool selector to enable more tools?", default=False):+ try:+ from hermes_cli.tools_config import tools_command+ tools_command(first_install=False, config=config)+ _reload_config_into(config) # tools_command saves via its own load/save cycle+ except Exception as exc:+ logger.debug("blank-slate tools_command error: %s", exc)+ print_warning(f"Tool selector encountered an error: {exc}")+ else:+ print_info("Keeping the minimal toolset. Add tools later with `hermes tools`.")++ # Built-in plugins (off unless chosen)+ print()+ print_header("Plugins")+ if prompt_yes_no("Review and enable built-in plugins now?", default=False):+ print_info("Manage plugins with `hermes plugins list` / `hermes plugins install`.")+ else:+ print_info("No plugins enabled. Add later with `hermes plugins`.")++ # MCP servers (off unless chosen)+ print()+ print_header("MCP Servers")+ if prompt_yes_no("Add an MCP server now?", default=False):+ print_info("Add servers with `hermes mcp add <name> --url ... | --command ...`.")+ else:+ print_info("No MCP servers configured. Add later with `hermes mcp add`.")++ # Optional messaging gateway+ print()+ if prompt_yes_no("Connect a messaging platform (Telegram, Discord, …)?", default=False):+ setup_gateway(config)++ save_config(config)++ print()+ print_success("Blank Slate setup complete — minimal agent ready.")+ print_info(" Enable more tools: hermes tools")+ print_info(" Seed skills: hermes skills opt-in --sync")+ print_info(" Add MCP servers: hermes mcp add")+ print_info(" Tune agent settings: hermes setup agent")+ print()++ _print_setup_summary(config, hermes_home)+++def _run_quick_setup(config: dict, hermes_home):+ """Quick setup — only configure items that are missing."""+ from hermes_cli.setup import (+ Colors, _print_setup_summary, _prompt_api_key, color, print_header, print_info,+ print_success, print_warning, prompt_checklist, save_config, save_env_value,+ )+ from hermes_cli.config import (+ get_missing_env_vars, get_missing_config_fields, check_config_version,+ )++ print()+ print_header("Quick Setup — Missing Items Only")++ # Check what's missing+ missing_required = [v for v in get_missing_env_vars(required_only=False) if v.get("is_required")]+ missing_optional = [+ v for v in get_missing_env_vars(required_only=False) if not v.get("is_required")+ ]+ missing_config = get_missing_config_fields()+ current_ver, latest_ver = check_config_version()++ if not (missing_required or missing_optional or missing_config or current_ver < latest_ver):+ print_success("Everything is configured! Nothing to do.")+ print()+ print_info("Run 'hermes setup' and choose 'Full Setup' to reconfigure,")+ print_info("or pick a specific section from the menu.")+ return++ # Handle missing required env vars+ if missing_required:+ print()+ print_info(f"{len(missing_required)} required setting(s) missing:")+ for var in missing_required:+ print(f" • {var['name']}")+ print()++ for var in missing_required:+ print()+ print(color(f" {var['name']}", Colors.CYAN))+ print_info(f" {var.get('description', '')}")+ if var.get("url"):+ print_info(f" Get key at: {var['url']}")++ value = _prompt_env_var(var)+ if value:+ save_env_value(var["name"], value)+ print_success(f" Saved {var['name']}")+ else:+ print_warning(f" Skipped {var['name']}")++ # Split missing optional vars by category+ missing_tools = [v for v in missing_optional if v.get("category") == "tool"]+ missing_messaging = [+ v for v in missing_optional if v.get("category") == "messaging" and not v.get("advanced")+ ]++ # Tool API keys (checklist)+ if missing_tools:+ print()+ print_header("Tool API Keys")++ checklist_labels = []+ for var in missing_tools:+ tools = var.get("tools", [])+ tools_str = f" → {', '.join(tools[:2])}" if tools else ""+ checklist_labels.append(f"{var.get('description', var['name'])}{tools_str}")++ for idx in prompt_checklist("Which tools would you like to configure?", checklist_labels):+ _prompt_api_key(missing_tools[idx])++ # Messaging platforms (checklist then prompt for selected)+ if missing_messaging:+ print()+ print_header("Messaging Platforms")+ print_info("Connect Hermes to messaging apps to chat from anywhere.")+ print_info("You can configure these later with 'hermes setup gateway'.")++ # Group by platform (preserving order); vars matching no platform are dropped.+ platform_order = []+ platforms = {}+ emojis = {}+ for var in missing_messaging:+ for needle, plat, emoji in _MESSAGING_PLATFORMS:+ if needle in var["name"]:+ break+ else:+ continue+ if plat not in platforms:+ platform_order.append(plat)+ emojis[plat] = emoji+ platforms.setdefault(plat, []).append(var)++ platform_labels = [f"{emojis[p]} {p}" for p in platform_order]+ selected_indices = prompt_checklist(+ "Which platforms would you like to set up?", platform_labels+ )++ for idx in selected_indices:+ plat = platform_order[idx]+ print()+ print(color(f" ─── {emojis[plat]} {plat} ───", Colors.CYAN))+ print()+ for var in platforms[plat]:+ print_info(f" {var.get('description', '')}")+ if var.get("url"):+ print_info(f" {var['url']}")+ value = _prompt_env_var(var)+ if value:+ save_env_value(var["name"], value)+ print_success(" ✓ Saved")+ else:+ print_warning(" Skipped")+ print()++ # Handle missing config fields+ if missing_config:+ print()+ print_info(f"Adding {len(missing_config)} new config option(s) with defaults...")+ for field in missing_config:+ print_success(f" Added {field['key']} = {field['default']}")++ config["_config_version"] = latest_ver+ save_config(config)++ _print_setup_summary(config, hermes_home)diff --git a/hermes_cli/setup_summary.py b/hermes_cli/setup_summary.pynew file mode 100644index 00000000000..d09c2eaf43a--- /dev/null+++ b/hermes_cli/setup_summary.py@@ -0,0 +1,342 @@+"""Setup-completion summary (tool availability + "Setup Complete!" banner).++Extracted from hermes_cli/setup.py. Names originating in setup.py are imported lazily+inside function bodies so test patches on ``hermes_cli.setup.<name>`` take effect.+"""++import logging++logger = logging.getLogger("hermes_cli.setup")++# provider -> (label, env vars: any one set means available; empty = always).+# Local engines are (label, module, hint) and must be importable.+_TTS_SUMMARY_ROWS = {+ "elevenlabs": ("ElevenLabs", ("ELEVENLABS_API_KEY",)),+ "openai": ("OpenAI", ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY")),+ "minimax": ("MiniMax", ("MINIMAX_API_KEY",)),+ "mistral": ("Mistral Voxtral", ("MISTRAL_API_KEY",)),+ "gemini": ("Google Gemini", ("GEMINI_API_KEY", "GOOGLE_API_KEY")),+ "neutts": ("NeuTTS", "neutts", "run 'hermes setup tts'"),+ "kittentts": ("KittenTTS", "kittentts", "run 'hermes setup tts'"),+}+_TTS_SUMMARY_DEFAULT = ("Edge TTS", ())+_STT_SUMMARY_ROWS = {+ "openai": ("OpenAI", ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY")),+ "groq": ("Groq Whisper", ("GROQ_API_KEY",)),+ "elevenlabs": ("ElevenLabs Scribe", ("ELEVENLABS_API_KEY",)),+ "xai": ("xAI", ()),+ "deepinfra": ("DeepInfra", ("DEEPINFRA_API_KEY",)),+}+_STT_SUMMARY_DEFAULT = ("Local Whisper", "faster_whisper", "run 'hermes tools' → Speech-to-Text")++# Browser "missing" hint keyed by the configured provider; anything else gets the generic hint.+_BROWSER_MISSING_HINTS = {+ "Browserbase": "npm install -g agent-browser and set BROWSERBASE_API_KEY/BROWSERBASE_PROJECT_ID",+ "Browser Use": "npm install -g agent-browser and set BROWSER_USE_API_KEY",+ "Camofox": "CAMOFOX_URL",+ "Local browser": "npm install -g agent-browser && agent-browser install --with-deps",+}+_BROWSER_MISSING_DEFAULT = "npm install -g agent-browser, set CAMOFOX_URL, or configure Browser Use or Browserbase"++_DONE_BANNER = (+ "┌─────────────────────────────────────────────────────────┐",+ "│ ✓ Setup Complete! │",+ "└─────────────────────────────────────────────────────────┘",+)+# (command, description) rows; the description carries its own alignment padding.+_EDIT_WIZARD_ROWS = (+ ("hermes setup", " Re-run the full wizard"),+ ("hermes setup model", " Change model/provider"),+ ("hermes setup terminal", " Change terminal backend"),+ ("hermes setup gateway", " Configure messaging"),+ ("hermes setup tools", " Configure tool providers"),+)+_EDIT_CONFIG_ROWS = (+ ("hermes config", " View current settings"),+ ("hermes config edit", " Open config in your editor"),+ ("hermes config set <key> <value>", ""),+)+_READY_ROWS = (+ ("hermes", " Start chatting"),+ ("hermes gateway", " Start messaging gateway"),+ ("hermes doctor", " Check for issues"),+)+++def _voice_provider_status(kind: str, provider: str, rows: dict, default: tuple) -> tuple:+ """Summary row for a TTS/STT provider. A keyed provider whose key is missing+ falls through to the default row, matching the runtime fallback."""+ from hermes_cli.setup import get_env_value, _module_installed++ row = rows.get(provider, default)+ if isinstance(row[1], tuple) and row[1] and not any(get_env_value(v) for v in row[1]):+ row = default+ if isinstance(row[1], tuple):+ return (f"{kind} ({row[0]})", True, None)+ label, module, hint = row+ if _module_installed(module):+ return (f"{kind} ({label}{' local' if kind == 'Text-to-Speech' else ''})", True, None)+ return (f"{kind} ({label} — not installed)", False, hint)+++# ---- tool_status row builders: each takes (config, subscription_features) and returns+# a (name, available, hint) row or None (row omitted). Evaluated in _TOOL_ROW_BUILDERS order.++def _vision_row(config, feats):+ # Use the same runtime resolver as the actual vision tools.+ try:+ from agent.auxiliary_client import get_available_vision_backends++ _vision_backends = get_available_vision_backends()+ except Exception:+ _vision_backends = []+ if _vision_backends:+ return ("Vision (image analysis)", True, None)+ return ("Vision (image analysis)", False, "run 'hermes setup' to configure")+++def _web_row(config, feats):+ # Web tools (Exa, Parallel, Firecrawl, Tavily, or Keenable)+ web = feats.web+ if web.managed_by_nous:+ return ("Web Search & Extract (Nous subscription)", True, None)+ if web.available:+ label = f"Web Search & Extract ({web.current_provider})" if web.current_provider else "Web Search & Extract"+ return (label, True, None)+ return ("Web Search & Extract", False, "EXA_API_KEY, PARALLEL_API_KEY, FIRECRAWL_API_KEY/FIRECRAWL_API_URL, TAVILY_API_KEY, KEENABLE_API_KEY, or SEARXNG_URL")+++def _browser_row(config, feats):+ # Browser tools (local Chromium, Camofox, Browserbase, Browser Use, or Firecrawl)+ browser_provider = feats.browser.current_provider+ if feats.browser.managed_by_nous:+ return ("Browser Automation (Nous Browser Use)", True, None)+ if feats.browser.available:+ label = f"Browser Automation ({browser_provider})" if browser_provider else "Browser Automation"+ return (label, True, None)+ return ("Browser Automation", False, _BROWSER_MISSING_HINTS.get(browser_provider, _BROWSER_MISSING_DEFAULT))+++def _image_gen_row(config, feats):+ # FAL (direct or via Nous), or any plugin-registered provider (OpenAI, etc.)+ if feats.image_gen.managed_by_nous:+ return ("Image Generation (Nous subscription)", True, None)+ if feats.image_gen.available:+ return ("Image Generation", True, None)+ # Probe plugin-registered providers so OpenAI-only setups don't show as "missing FAL_KEY".+ _img_backend = None+ try:+ from agent.image_gen_registry import list_providers+ from hermes_cli.plugins import _ensure_plugins_discovered++ _ensure_plugins_discovered()+ for _p in list_providers():+ if _p.name == "fal":+ continue+ try:+ if _p.is_available():+ _img_backend = _p.display_name+ break+ except Exception:+ continue+ except Exception:+ pass+ if _img_backend:+ return (f"Image Generation ({_img_backend})", True, None)+ return ("Image Generation", False, "FAL_KEY or OPENAI_API_KEY")+++def _video_gen_row(config, feats):+ # Opt-in via `hermes tools` → Video Generation. Only show the row when a plugin reports+ # available so we don't badger users who don't care about video gen with a "missing" line.+ if feats.video_gen.managed_by_nous:+ return ("Video Generation (FAL via Nous subscription)", True, None)+ try:+ from agent.video_gen_registry import list_providers as _list_video_providers+ from hermes_cli.plugins import _ensure_plugins_discovered as _ensure_plugins+ _ensure_plugins()+ _video_backend = None+ for _vp in _list_video_providers():+ try:+ if _vp.is_available():+ _video_backend = _vp.display_name+ break+ except Exception:+ continue+ except Exception:+ _video_backend = None+ return (f"Video Generation ({_video_backend})", True, None) if _video_backend else None+++def _tts_row(config, feats):+ # Configured provider, gated on its key (or local install)+ from hermes_cli.setup import cfg_get++ tts_provider = cfg_get(config, "tts", "provider", default="edge")+ if feats.tts.managed_by_nous:+ return ("Text-to-Speech (OpenAI via Nous subscription)", True, None)+ return _voice_provider_status("Text-to-Speech", tts_provider, _TTS_SUMMARY_ROWS, _TTS_SUMMARY_DEFAULT)+++def _stt_row(config, feats):+ from hermes_cli.setup import cfg_get++ stt_provider = cfg_get(config, "stt", "provider", default="local") or "local"+ _stt_feature = feats.features.get("stt")+ if _stt_feature is not None and _stt_feature.managed_by_nous:+ return ("Speech-to-Text (OpenAI via Nous subscription)", True, None)+ return _voice_provider_status("Speech-to-Text", stt_provider, _STT_SUMMARY_ROWS, _STT_SUMMARY_DEFAULT)+++def _modal_row(config, feats):+ from hermes_cli.setup import cfg_get, managed_nous_tools_enabled++ if feats.modal.managed_by_nous:+ return ("Modal Execution (Nous subscription)", True, None)+ if cfg_get(config, "terminal", "backend") == "modal":+ if feats.modal.direct_override:+ return ("Modal Execution (direct Modal)", True, None)+ return ("Modal Execution", False, "run 'hermes setup terminal'")+ if managed_nous_tools_enabled() and feats.nous_auth_present:+ return ("Modal Execution (optional via Nous subscription)", True, None)+ return None+++def _home_assistant_row(config, feats):+ from hermes_cli.setup import get_env_value++ return ("Smart Home (Home Assistant)", True, None) if get_env_value("HASS_TOKEN") else None+++def _spotify_row(config, feats):+ # OAuth via hermes auth spotify — check auth.json, not env vars+ try:+ from hermes_cli.auth import get_provider_auth_state+ _spotify_state = get_provider_auth_state("spotify") or {}+ if _spotify_state.get("access_token") or _spotify_state.get("refresh_token"):+ return ("Spotify (PKCE OAuth)", True, None)+ except Exception:+ pass+ return None+++def _skills_hub_row(config, feats):+ from hermes_cli.setup import get_env_value++ if get_env_value("GITHUB_TOKEN"):+ return ("Skills Hub (GitHub)", True, None)+ return ("Skills Hub (GitHub)", False, "GITHUB_TOKEN")+++def _always_on_rows(config, feats):+ # Terminal (system deps met), task planning (in-memory), skills (bundled + user-created).+ return [+ ("Terminal/Commands", True, None),+ ("Task Planning (todo)", True, None),+ ("Skills (view, create, edit)", True, None),+ ]+++_TOOL_ROW_BUILDERS = (+ _vision_row, _web_row, _browser_row, _image_gen_row, _video_gen_row, _tts_row, _stt_row,+ _modal_row, _home_assistant_row, _spotify_row, _skills_hub_row, _always_on_rows,+)+++def _print_cmd_rows(rows):+ """Print (command, description) rows as ' <green cmd><desc>'."""+ from hermes_cli.setup import Colors, color++ for cmd, desc in rows:+ print(f" {color(cmd, Colors.GREEN)}{desc}")+++def _print_section_header(title):+ from hermes_cli.setup import Colors, color++ print(color("─" * 60, Colors.DIM))+ print()+ print(color(title, Colors.CYAN, Colors.BOLD))+ print()+++def _print_setup_summary(config: dict, hermes_home):+ """Print the setup completion summary."""+ from hermes_cli.setup import (+ print_header, print_info, print_warning, get_config_path, get_env_path,+ get_nous_subscription_features, Colors, color,+ )++ # Provider readiness — the one thing setup absolutely must produce. Previously a user+ # could cancel the API-key prompt mid-wizard (Enter → "Cancelled."), watch the wizard+ # continue through Terminal/Gateway/Tools, and exit "successfully" with NO working model —+ # believing they were set up. Say so loudly instead (consumer-onboarding audit finding #7).+ try:+ from hermes_cli.auth import resolve_provider++ resolve_provider()+ _provider_ready = True+ except Exception:+ _provider_ready = False+ if not _provider_ready:+ print()+ print_warning("No inference provider is configured — Hermes cannot chat yet.")+ print_info(" Finish this one step with either of:")+ print_info(" hermes model (pick any provider/model)")+ print_info(" hermes setup --portal (Nous Portal OAuth, no API key)")++ print()+ print_header("Tool Availability Summary")++ tool_status = []+ subscription_features = get_nous_subscription_features(config)+ for build in _TOOL_ROW_BUILDERS:+ row = build(config, subscription_features)+ if isinstance(row, list):+ tool_status.extend(row)+ elif row is not None:+ tool_status.append(row)++ available_count = sum(1 for _, avail, _ in tool_status if avail)+ print_info(f"{available_count}/{len(tool_status)} tool categories available:")+ print()+ for name, available, missing_var in tool_status:+ if available:+ print(f" {color('✓', Colors.GREEN)} {name}")+ else:+ print(f" {color('✗', Colors.RED)} {name} {color(f'(missing {missing_var})', Colors.DIM)}")+ print()++ if any(not avail for _, avail, _ in tool_status):+ print_warning("Some tools are disabled. Run 'hermes setup tools' to configure them,")+ from hermes_constants import display_hermes_home as _dhh+ print_warning(f"or edit {_dhh()}/.env directly to add the missing API keys.")+ print()++ print()+ for line in _DONE_BANNER:+ print(color(line, Colors.GREEN))+ print()++ from hermes_constants import display_hermes_home as _dhh+ print(color(f"📁 All your files are in {_dhh()}/:", Colors.CYAN, Colors.BOLD))+ print()+ print(f" {color('Settings:', Colors.YELLOW)} {get_config_path()}")+ print(f" {color('API Keys:', Colors.YELLOW)} {get_env_path()}")+ print(f" {color('Data:', Colors.YELLOW)} {hermes_home}/cron/, sessions/, logs/")+ print()++ _print_section_header("📝 To edit your configuration:")+ _print_cmd_rows(_EDIT_WIZARD_ROWS)+ print()+ _print_cmd_rows(_EDIT_CONFIG_ROWS)+ print(" Set a specific value")+ print()+ print(" Or edit the files directly:")+ print(f" {color(f'nano {get_config_path()}', Colors.DIM)}")+ print(f" {color(f'nano {get_env_path()}', Colors.DIM)}")+ print()++ _print_section_header("🚀 Ready to go!")+ _print_cmd_rows(_READY_ROWS)+ print()diff --git a/hermes_cli/setup_terminal.py b/hermes_cli/setup_terminal.pynew file mode 100644index 00000000000..b3eefac544c--- /dev/null+++ b/hermes_cli/setup_terminal.py@@ -0,0 +1,418 @@+"""Terminal-backend setup wizard (local/docker/singularity/modal/daytona/vercel/ssh/plugin).++Extracted from hermes_cli/setup.py; setup.py re-exports the public entry points.+"""++import json+import logging+import os+import shutil+import sys+from pathlib import Path++logger = logging.getLogger("hermes_cli.setup")++_SANDBOX_IMAGE = "nikolaik/python-nodejs:python3.11-nodejs20"+++def _prompt_vercel_sandbox_settings(config: dict):+ """Prompt for Vercel Sandbox settings without exposing unsupported disk sizing."""+ from hermes_cli.setup import (+ get_env_value, print_info, print_warning, prompt, remove_env_value, save_env_value,+ )++ terminal = config.setdefault("terminal", {})+ print()+ print_info("Vercel Sandbox settings:")+ print_info(" Filesystem persistence uses Vercel snapshots.")+ print_info(" Snapshots restore files only; live processes do not continue after sandbox recreation.")++ from tools.terminal_tool import _SUPPORTED_VERCEL_RUNTIMES++ current_runtime = terminal.get("vercel_runtime") or "node24"+ supported_label = ", ".join(_SUPPORTED_VERCEL_RUNTIMES)+ runtime = prompt(f" Runtime ({supported_label})", current_runtime).strip() or current_runtime+ if runtime not in _SUPPORTED_VERCEL_RUNTIMES:+ print_warning(f"Unsupported Vercel runtime '{runtime}', keeping {current_runtime}.")+ runtime = current_runtime if current_runtime in _SUPPORTED_VERCEL_RUNTIMES else "node24"+ terminal["vercel_runtime"] = runtime+ save_env_value("TERMINAL_VERCEL_RUNTIME", runtime)++ persist_label = "yes" if terminal.get("container_persistent", True) else "no"+ answer = prompt(" Persist filesystem with snapshots? (yes/no)", persist_label)+ terminal["container_persistent"] = answer.lower() in {"yes", "true", "y", "1"}++ # (key, prompt label, default, parser) — unparseable input leaves the value untouched.+ for key, label, default, parse in (+ ("container_cpu", " CPU cores", 1, float),+ ("container_memory", " Memory in MB (5120 = 5GB)", 5120, int),+ ):+ try:+ terminal[key] = parse(prompt(label, str(terminal.get(key, default))))+ except ValueError:+ pass++ if terminal.get("container_disk", 51200) not in {0, 51200}:+ print_warning(+ "Vercel Sandbox does not support custom disk sizing; resetting container_disk to 51200."+ )+ terminal["container_disk"] = 51200++ print()+ print_info("Vercel authentication:")+ print_info(" Use a long-lived Vercel access token plus project/team IDs.")+ linked = _read_nearest_vercel_project()+ if linked:+ print_info(" Found defaults in nearest .vercel/project.json.")++ remove_env_value("VERCEL_OIDC_TOKEN")+ token = prompt(" Vercel access token", get_env_value("VERCEL_TOKEN") or "", password=True)+ project = prompt(+ " Vercel project ID", get_env_value("VERCEL_PROJECT_ID") or linked.get("projectId", "")+ )+ team = prompt(" Vercel team ID", get_env_value("VERCEL_TEAM_ID") or linked.get("orgId", ""))+ for env_var, value in (("VERCEL_TOKEN", token), ("VERCEL_PROJECT_ID", project), ("VERCEL_TEAM_ID", team)):+ if value:+ save_env_value(env_var, value)+++def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]:+ """Read project/team defaults from the nearest Vercel link file."""+ current = (start or Path.cwd()).resolve()+ if current.is_file():+ current = current.parent+ for directory in (current, *current.parents):+ project_file = directory / ".vercel" / "project.json"+ if not project_file.exists():+ continue+ try:+ data = json.loads(project_file.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ return {}+ if not isinstance(data, dict):+ return {}+ return {+ key: value+ for key, value in {"projectId": data.get("projectId"), "orgId": data.get("orgId")}.items()+ if isinstance(value, str) and value.strip()+ }+ return {}+++def _prompt_secret_env(label: str, env_var: str, *, confirm_msg: str = "") -> None:+ """Prompt for a secret and persist it to .env when non-empty."""+ from hermes_cli.setup import print_success, prompt, save_env_value++ value = prompt(label, password=True)+ if value:+ save_env_value(env_var, value)+ if confirm_msg:+ print_success(confirm_msg)+++def _ensure_sdk(package: str, manual_hint: str, *, show_stderr: bool = False) -> None:+ """Import *package*; if missing, install it via the venv pip helper."""+ from hermes_cli.setup import print_info, print_success, print_warning++ try:+ __import__(package)+ except ImportError:+ print_info(f"Installing {package} SDK...")+ from hermes_cli.tools_config import _pip_install++ result = _pip_install([package])+ if result.returncode == 0:+ print_success(f"{package} SDK installed")+ else:+ print_warning(f"Install failed — run manually: {manual_hint}")+ if show_stderr and result.stderr:+ print_info(f" Error: {result.stderr.strip().splitlines()[-1]}")+++def _setup_backend_local(config: dict) -> None:+ from hermes_cli.setup import print_info, print_success++ print_success("Terminal backend: Local")+ print_info("Commands run directly on this machine.")+ # Gateway working directory defaults to home; sudo stays off. Both are+ # configurable later via `hermes setup terminal` / config.yaml.+ config["terminal"].setdefault("cwd", str(Path.home()))+++def _setup_backend_docker(config: dict) -> None:+ from hermes_cli.setup import print_info, print_success, print_warning, prompt_yes_no++ print_success("Terminal backend: Docker")+ docker_bin = shutil.which("docker")+ if not docker_bin:+ print_warning("Docker not found in PATH!")+ print_info("Install Docker: https://docs.docker.com/get-docker/")+ else:+ print_info(f"Docker found: {docker_bin}")++ # Image and resource limits use defaults; tune via `hermes setup terminal`.+ config["terminal"].setdefault("docker_image", _SANDBOX_IMAGE)+ print()+ print_info("Docker sandboxes can be protected with the egress credential firewall.")+ print_info(+ "It routes sandbox traffic through iron-proxy so containers receive "+ "proxy tokens instead of real API keys."+ )+ print_info(" Docker only for now; Modal, SSH, Daytona, and Singularity are not wired yet.")+ if prompt_yes_no(" Enable egress firewall for Docker sandboxes?", False):+ proxy_cfg = config.setdefault("proxy", {})+ proxy_cfg["enabled"] = True+ proxy_cfg.setdefault("enforce_on_docker", True)+ print_success("Egress firewall enabled in config")+ print_info("Run `hermes egress setup` then `hermes egress start` to mint tokens and launch the proxy.")+ else:+ print_info("Skipping egress firewall. You can enable it later with `hermes egress setup`.")+++def _setup_backend_singularity(config: dict) -> None:+ from hermes_cli.setup import print_info, print_success, print_warning++ print_success("Terminal backend: Singularity/Apptainer")+ sing_bin = shutil.which("apptainer") or shutil.which("singularity")+ if not sing_bin:+ print_warning("Singularity/Apptainer not found in PATH!")+ print_info("Install: https://apptainer.org/docs/admin/main/installation.html")+ else:+ print_info(f"Found: {sing_bin}")+ # Image and resource limits use defaults; tune via `hermes setup terminal`.+ config["terminal"].setdefault("singularity_image", "docker://nikolaik/python-nodejs:python3.11-nodejs20")+++def _setup_backend_modal(config: dict) -> None:+ from hermes_cli.setup import (+ cfg_get, get_env_value, get_nous_subscription_features, managed_nous_tools_enabled,+ print_info, print_success, prompt_choice, prompt_yes_no,+ )++ print_success("Terminal backend: Modal")+ print_info("Serverless cloud sandboxes. Each session gets its own container.")+ from tools.managed_tool_gateway import is_managed_tool_gateway_ready+ from tools.tool_backend_helpers import normalize_modal_mode++ managed_modal_available = bool(+ managed_nous_tools_enabled()+ and get_nous_subscription_features(config).nous_auth_present+ and is_managed_tool_gateway_ready("modal")+ )+ modal_mode = normalize_modal_mode(cfg_get(config, "terminal", "modal_mode"))+ use_managed_modal = False+ if managed_modal_available:+ if modal_mode == "managed":+ default_modal_idx = 0+ elif modal_mode == "direct":+ default_modal_idx = 1+ else:+ default_modal_idx = 1 if get_env_value("MODAL_TOKEN_ID") else 0+ modal_mode_idx = prompt_choice(+ "Select how Modal execution should be billed:",+ ["Use my Nous subscription", "Use my own Modal account"], default_modal_idx,+ )+ use_managed_modal = modal_mode_idx == 0++ if use_managed_modal:+ config["terminal"]["modal_mode"] = "managed"+ print_info("Modal execution will use the managed Nous gateway and bill to your subscription.")+ if get_env_value("MODAL_TOKEN_ID") or get_env_value("MODAL_TOKEN_SECRET"):+ print_info("Direct Modal credentials are still configured, but this backend is pinned to managed mode.")+ return++ config["terminal"]["modal_mode"] = "direct"+ print_info("Requires a Modal account: https://modal.com")+ _ensure_sdk("modal", "uv pip install modal")+ print()+ print_info("Modal authentication:")+ print_info(" Get your token at: https://modal.com/settings")+ if get_env_value("MODAL_TOKEN_ID"):+ print_info(" Modal token: already configured")+ if not prompt_yes_no(" Update Modal credentials?", False):+ return+ _prompt_secret_env(" Modal Token ID", "MODAL_TOKEN_ID")+ _prompt_secret_env(" Modal Token Secret", "MODAL_TOKEN_SECRET")+++def _setup_backend_daytona(config: dict) -> None:+ from hermes_cli.setup import get_env_value, print_info, print_success, prompt_yes_no++ print_success("Terminal backend: Daytona")+ print_info("Persistent cloud development environments.")+ print_info("Each session gets a dedicated sandbox with filesystem persistence.")+ print_info("Sign up at: https://daytona.io")+ _ensure_sdk("daytona", "uv pip install daytona", show_stderr=True)+ print()+ if get_env_value("DAYTONA_API_KEY"):+ print_info(" Daytona API key: already configured")+ if prompt_yes_no(" Update API key?", False):+ _prompt_secret_env(" Daytona API key", "DAYTONA_API_KEY", confirm_msg=" Updated")+ else:+ _prompt_secret_env(" Daytona API key", "DAYTONA_API_KEY", confirm_msg=" Configured")+ # Image and resource limits use defaults; tune via `hermes setup terminal`.+ config["terminal"].setdefault("daytona_image", _SANDBOX_IMAGE)+++def _setup_backend_vercel(config: dict) -> None:+ from hermes_cli.setup import print_info, print_success, print_warning++ print_success("Terminal backend: Vercel Sandbox")+ print_info("Cloud microVM sandboxes with snapshot-backed filesystem persistence.")+ print_info("Requires the optional SDK: pip install 'hermes-agent[vercel]'")+ try:+ __import__("vercel")+ except ImportError:+ print_info("Installing vercel SDK...")+ import subprocess++ # Managed uv first: $HERMES_HOME/bin is never on PATH, so a bare which()+ # misses the uv Hermes installed; bootstrapping one mid-wizard is fine,+ # and a `uv venv` venv may not even have pip.+ from hermes_cli.managed_uv import ensure_uv++ uv_bin = ensure_uv()+ cmd = [uv_bin, "pip", "install", "--python", sys.executable, "vercel"] if uv_bin else [+ sys.executable, "-m", "pip", "install", "vercel"]+ result = subprocess.run(cmd, capture_output=True, text=True)+ if result.returncode == 0:+ print_success("vercel SDK installed")+ else:+ print_warning("Install failed — run manually: pip install 'hermes-agent[vercel]'")+ if result.stderr:+ print_info(f" Error: {result.stderr.strip().splitlines()[-1]}")+ _prompt_vercel_sandbox_settings(config)+++def _setup_backend_ssh(config: dict) -> None:+ from hermes_cli.setup import (+ get_env_value, print_info, print_success, print_warning, prompt, prompt_yes_no, save_env_value,+ )++ print_success("Terminal backend: SSH")+ print_info("Run commands on a remote machine via SSH.")++ # (label, env var, fallback default when .env is empty); the port is only saved when not 22.+ fields = (+ (" SSH host (hostname or IP)", "TERMINAL_SSH_HOST", ""),+ (" SSH user", "TERMINAL_SSH_USER", os.getenv("USER", "")),+ (" SSH port", "TERMINAL_SSH_PORT", "22"),+ (" SSH private key path", "TERMINAL_SSH_KEY", str(Path.home() / ".ssh" / "id_rsa")),+ )+ values = []+ for label, env_var, default in fields:+ value = prompt(label, (get_env_value(env_var) or "") or default)+ values.append(value)+ if value and (env_var != "TERMINAL_SSH_PORT" or value != "22"):+ save_env_value(env_var, value)+ host, user, port, ssh_key = values++ if host and prompt_yes_no(" Test SSH connection?", True):+ print_info(" Testing connection...")+ import subprocess++ ssh_cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5"]+ if ssh_key:+ ssh_cmd.extend(["-i", ssh_key])+ if port and port != "22":+ ssh_cmd.extend(["-p", port])+ ssh_cmd += [f"{user}@{host}" if user else host, "echo ok"]+ result = subprocess.run(ssh_cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=10)+ if result.returncode == 0:+ print_success(" SSH connection successful!")+ else:+ print_warning(f" SSH connection failed: {result.stderr.strip()}")+ print_info(" Check your SSH key and host settings.")+++def _setup_backend_plugin(config: dict, backend: str) -> None:+ from hermes_cli.setup import print_info, print_success, print_warning++ try:+ from agent.terminal_env_registry import get_provider++ provider = get_provider(backend)+ print_success(f"Terminal backend: {provider.display_name}")+ for line in provider.setup_instructions():+ print_info(line)+ provider.post_setup()+ except Exception as exc:+ print_warning(f"Backend plugin setup hook failed: {exc}")+++_BUILTIN_TERMINAL_BACKENDS = [+ ("local", "Local - run directly on this machine (default)"),+ ("docker", "Docker - isolated container with configurable resources"),+ ("modal", "Modal - serverless cloud sandbox"),+ ("ssh", "SSH - run on a remote machine"),+ ("daytona", "Daytona - persistent cloud development environment"),+ ("vercel_sandbox", "Vercel Sandbox - cloud microVM with snapshot filesystem persistence"),+]+_TERMINAL_BACKEND_SETUP = {+ "local": _setup_backend_local, "docker": _setup_backend_docker, "singularity": _setup_backend_singularity,+ "modal": _setup_backend_modal, "daytona": _setup_backend_daytona, "vercel_sandbox": _setup_backend_vercel,+ "ssh": _setup_backend_ssh,+}+++def setup_terminal_backend(config: dict):+ """Configure the terminal execution backend."""+ from hermes_cli.setup import (+ _DOCS_BASE, cfg_get, print_header, print_info, print_success, prompt_choice, save_config, save_env_value,+ )+ import platform as _platform++ print_header("Terminal Backend")+ print_info("Choose where Hermes runs shell commands and code.")+ print_info("This affects tool execution, file access, and isolation.")+ print_info(f" Guide: {_DOCS_BASE}/user-guide/configuration#terminal-backend-configuration")+ print()++ current_backend = cfg_get(config, "terminal", "backend", default="local")+ backends = list(_BUILTIN_TERMINAL_BACKENDS)+ if _platform.system() == "Linux":+ backends.append(("singularity", "Singularity/Apptainer - HPC-friendly container"))++ # Plugin-registered terminal backends (standalone plugin repos under+ # ~/.hermes/plugins/). Fail-soft: a broken plugin must not take the wizard down.+ plugin_backend_names = []+ try:+ from hermes_cli.plugins import discover_plugins++ discover_plugins() # idempotent — plugin state may not be loaded yet+ from agent.terminal_env_registry import list_providers++ for provider in list_providers():+ pname = provider.name.strip().lower()+ backends.append((pname, f"{provider.display_name} - {provider.description}"))+ plugin_backend_names.append(pname)+ except Exception:+ pass++ keep_current_idx = len(backends)+ terminal_choices = [label for _, label in backends] + [f"Keep current ({current_backend})"]+ terminal_idx = prompt_choice("Select terminal backend:", terminal_choices, keep_current_idx)+ if terminal_idx == keep_current_idx:+ print_info(f"Keeping current backend: {current_backend}")+ return+ selected_backend = backends[terminal_idx][0] if 0 <= terminal_idx < len(backends) else None++ config.setdefault("terminal", {})["backend"] = selected_backend+ # Plugin names shadow only the ssh built-in (dispatch order of the original chain).+ handler = _TERMINAL_BACKEND_SETUP.get(selected_backend)+ if handler is not None and (selected_backend != "ssh" or selected_backend not in plugin_backend_names):+ handler(config)+ elif selected_backend in plugin_backend_names:+ _setup_backend_plugin(config, selected_backend)++ # config.yaml is the source of truth, but terminal_tool reads TERMINAL_ENV+ # from .env — keep them in sync.+ save_env_value("TERMINAL_ENV", selected_backend)+ if selected_backend == "modal":+ save_env_value("TERMINAL_MODAL_MODE", config["terminal"].get("modal_mode", "auto"))+ if selected_backend == "vercel_sandbox":+ save_env_value("TERMINAL_VERCEL_RUNTIME", config["terminal"].get("vercel_runtime", "node24"))+ save_config(config)+ print()+ print_success(f"Terminal backend set to: {selected_backend}")+diff --git a/hermes_cli/setup_tts.py b/hermes_cli/setup_tts.pynew file mode 100644index 00000000000..a074bfd689c--- /dev/null+++ b/hermes_cli/setup_tts.py@@ -0,0 +1,337 @@+"""Text-to-speech provider setup (provider picker, API-key prompts, local engine installs, xAI OAuth).++Extracted from hermes_cli/setup.py; setup.py re-exports the public entry points.+"""++import logging+import shutil+import subprocess+import sys++logger = logging.getLogger("hermes_cli.setup")+++def _check_espeak_ng() -> bool:+ """Check if espeak-ng is installed."""+ return shutil.which("espeak-ng") is not None or shutil.which("espeak") is not None+++def _pip_install_tts_package(name: str, pip_args: list, manual_cmd: str) -> bool:+ """Install a local TTS engine through the canonical uv → pip → ensurepip+ ladder so pip-less venvs (Ubuntu 25.10 ``python -m venv``, ``uv venv``) work."""+ from hermes_cli.setup import print_error, print_info, print_success+ from hermes_cli.tools_config import _pip_install++ try:+ result = _pip_install(pip_args, timeout=300)+ except Exception as e:+ print_error(f"Failed to install {name}: {e}")+ print_info(f"Try manually: {manual_cmd}")+ return False+ if result.returncode == 0:+ print_success(f"{name} installed successfully")+ return True+ err = (result.stderr or "").strip()+ print_error(f"Failed to install {name}: {err[:300] if err else 'install failed'}")+ print_info(f"Try manually: {manual_cmd}")+ return False+++# sys.platform -> (manual install hint, install command); anything else uses "linux".+_ESPEAK_INSTALL = {+ "darwin": ("Install with: brew install espeak-ng", ["brew", "install", "espeak-ng"]),+ "win32": ("Install with: choco install espeak-ng", ["choco", "install", "espeak-ng", "-y"]),+ "linux": ("Install with: sudo apt install espeak-ng", ["sudo", "apt", "install", "-y", "espeak-ng"]),+}+++def _install_neutts_deps() -> bool:+ """Install NeuTTS dependencies with user approval. Returns True on success."""+ from hermes_cli.setup import print_info, print_success, print_warning, prompt_yes_no++ if not _check_espeak_ng():+ hint, install_cmd = _ESPEAK_INSTALL.get(sys.platform, _ESPEAK_INSTALL["linux"])+ print()+ print_warning("NeuTTS requires espeak-ng for phonemization.")+ print_info(hint)+ print()+ if prompt_yes_no("Install espeak-ng now?", True):+ try:+ subprocess.run(install_cmd, check=True)+ print_success("espeak-ng installed")+ except (subprocess.CalledProcessError, FileNotFoundError) as e:+ print_warning(f"Could not install espeak-ng automatically: {e}")+ print_info("Please install it manually and re-run setup.")+ return False+ else:+ print_warning("espeak-ng is required for NeuTTS. Install it manually before using NeuTTS.")++ print()+ print_info("Installing neutts Python package...")+ print_info("This will also download the TTS model (~300MB) on first use.")+ print()+ return _pip_install_tts_package("neutts", ["-U", "neutts[all]", "--quiet"], "uv pip install -U 'neutts[all]'")+++def _install_kittentts_deps() -> bool:+ """Install KittenTTS dependencies with user approval. Returns True on success."""+ from hermes_cli.setup import print_info++ wheel_url = (+ "https://github.com/KittenML/KittenTTS/releases/download/"+ "0.8.1/kittentts-0.8.1-py3-none-any.whl"+ )+ print()+ print_info("Installing kittentts Python package (~25-80MB model downloaded on first use)...")+ print()+ return _pip_install_tts_package(+ "kittentts", ["-U", wheel_url, "soundfile", "--quiet"], f"uv pip install -U '{wheel_url}' soundfile",+ )+++def _xai_oauth_logged_in_for_setup() -> bool:+ """True iff xAI Grok OAuth credentials are already stored locally.++ Lets TTS / STT setup skip the API-key prompt for users who logged in+ through ``hermes model`` -> xAI Grok OAuth (SuperGrok / Premium+).+ """+ try:+ from hermes_cli.auth import get_xai_oauth_auth_status++ return bool(get_xai_oauth_auth_status().get("logged_in"))+ except Exception:+ return False+++def _run_xai_oauth_login_from_setup() -> bool:+ """Run the xAI Grok OAuth device-code login from inside the setup wizard.++ Saves OAuth tokens only. Does **not** switch the active inference+ provider or rewrite ``model.provider`` — callers (TTS setup, tools+ config) only need credentials for side tools.++ Returns True on success, False on any failure (the caller falls back+ to whatever the user picked next, e.g. Edge TTS).+ """+ from hermes_cli.setup import print_info, print_warning++ try:+ from hermes_cli.auth import (+ _is_remote_session, _save_xai_oauth_tokens, _xai_oauth_device_code_login,+ unsuppress_credential_source,+ )+ except Exception as exc:+ print_warning(f"xAI Grok OAuth helpers unavailable: {exc}")+ return False++ open_browser = not _is_remote_session()+ print()+ print_info("Signing in to xAI Grok OAuth (SuperGrok / Premium+)...")+ try:+ creds = _xai_oauth_device_code_login(open_browser=open_browser)+ _save_xai_oauth_tokens(+ creds["tokens"], discovery=creds.get("discovery"), redirect_uri=creds.get("redirect_uri", ""),+ last_refresh=creds.get("last_refresh"), auth_mode="oauth_device_code", set_active=False,+ )+ # Mirror model/dashboard re-login: clear device_code suppression so+ # the pool can seed from the singleton after a prior `auth remove`.+ unsuppress_credential_source("xai-oauth", "device_code")+ return True+ except Exception as exc:+ print_warning(f"xAI Grok OAuth login failed: {exc}")+ return False+++_TTS_PROVIDER_LABELS = {+ "edge": "Edge TTS", "elevenlabs": "ElevenLabs", "openai": "OpenAI TTS", "xai": "xAI TTS",+ "minimax": "MiniMax TTS", "mistral": "Mistral Voxtral TTS", "gemini": "Google Gemini TTS",+ "neutts": "NeuTTS", "kittentts": "KittenTTS",+}+_TTS_PROVIDER_CHOICES = [+ ("edge", "Edge TTS (free, cloud-based, no setup needed)"),+ ("elevenlabs", "ElevenLabs (premium quality, needs API key)"),+ ("openai", "OpenAI TTS (good quality, needs API key)"),+ ("xai", "xAI TTS (Grok voices — OAuth login or API key)"),+ ("minimax", "MiniMax TTS (high quality with voice cloning, needs API key)"),+ ("mistral", "Mistral Voxtral TTS (multilingual, native Opus, needs API key)"),+ ("gemini", "Google Gemini TTS (30 prebuilt voices, prompt-controllable, needs API key)"),+ ("neutts", "NeuTTS (local on-device, free, ~300MB model download)"),+ ("kittentts", "KittenTTS (local on-device, free, lightweight ~25-80MB ONNX)"),+]+# provider -> (env vars that satisfy it, env var to save, prompt, success line, pre-prompt hint)+_TTS_API_KEY_PROVIDERS = {+ "elevenlabs": (("ELEVENLABS_API_KEY",), "ELEVENLABS_API_KEY", "ElevenLabs API key", "ElevenLabs API key saved", ""),+ "openai": (+ ("VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"), "VOICE_TOOLS_OPENAI_KEY",+ "OpenAI API key for TTS", "OpenAI TTS API key saved", "",+ ),+ "minimax": (("MINIMAX_API_KEY",), "MINIMAX_API_KEY", "MiniMax API key for TTS", "MiniMax TTS API key saved", ""),+ "mistral": (("MISTRAL_API_KEY",), "MISTRAL_API_KEY", "Mistral API key for TTS", "Mistral TTS API key saved", ""),+ "gemini": (+ ("GEMINI_API_KEY", "GOOGLE_API_KEY"), "GEMINI_API_KEY", "Gemini API key for TTS", "Gemini TTS API key saved",+ "Get a free API key at https://aistudio.google.com/app/apikey",+ ),+}+# provider -> (module, display name, requirement lines, install question, installer)+_TTS_LOCAL_PROVIDERS = {+ "neutts": (+ "neutts", "NeuTTS",+ ("NeuTTS requires:", " • Python package: neutts (~50MB install + ~300MB model on first use)",+ " • System package: espeak-ng (phonemizer)"),+ "Install NeuTTS dependencies now?", _install_neutts_deps,+ ),+ "kittentts": (+ "kittentts", "KittenTTS",+ ("KittenTTS is lightweight (~25-80MB, CPU-only, no API key required).",+ "Voices: Jasper, Bella, Luna, Bruno, Rosie, Hugo, Kiki, Leo"),+ "Install KittenTTS now?", _install_kittentts_deps,+ ),+}+++def _tts_api_key_step(selected: str) -> str:+ """Ensure the key for an API-key TTS provider exists; fall back to edge otherwise."""+ from hermes_cli.setup import get_env_value, print_info, print_success, print_warning, prompt, save_env_value++ env_vars, save_var, prompt_label, saved_msg, hint = _TTS_API_KEY_PROVIDERS[selected]+ if any(get_env_value(v) for v in env_vars):+ return selected+ print()+ if hint:+ print_info(hint)+ api_key = prompt(prompt_label, password=True)+ if api_key:+ save_env_value(save_var, api_key)+ print_success(saved_msg)+ return selected+ print_warning("No API key provided. Falling back to Edge TTS.")+ return "edge"+++def _tts_local_install_step(selected: str) -> str:+ """Offer to install a local TTS engine; fall back to edge if declined/failed."""+ from hermes_cli.setup import _module_installed, print_info, print_success, print_warning, prompt_yes_no++ module, name, lines, question, installer = _TTS_LOCAL_PROVIDERS[selected]+ if _module_installed(module):+ print_success(f"{name} is already installed")+ return selected+ print()+ for line in lines:+ print_info(line)+ print()+ if not prompt_yes_no(question, True):+ print_info(f"Skipping install. Set tts.provider to '{selected}' after installing manually.")+ return "edge"+ if not installer():+ print_warning(f"{name} installation incomplete. Falling back to Edge TTS.")+ return "edge"+ return selected+++def _tts_xai_step(config: dict) -> str:+ """xAI TTS auth. Order: existing OAuth tokens (free for SuperGrok) > existing+ XAI_API_KEY > offer both paths — xAI TTS works with OAuth bearer tokens too."""+ from hermes_cli.setup import (+ _run_xai_oauth_login_from_setup, _xai_oauth_logged_in_for_setup, get_env_value, print_success,+ print_warning, prompt, prompt_choice, save_env_value,+ )++ selected = "xai"+ if _xai_oauth_logged_in_for_setup():+ print_success("xAI TTS will use your xAI Grok OAuth (SuperGrok / Premium+) credentials")+ elif get_env_value("XAI_API_KEY"):+ print_success("xAI TTS will use your existing XAI_API_KEY")+ else:+ print()+ choice_idx = prompt_choice(+ "How do you want xAI TTS to authenticate?",+ choices=[+ "Sign in with xAI Grok OAuth (SuperGrok / Premium+) — browser login",+ "Paste an xAI API key (console.x.ai)", "Skip → fallback to Edge TTS",+ ],+ default=0,+ )+ if choice_idx == 0:+ if _run_xai_oauth_login_from_setup():+ print_success("Logged in — xAI TTS will use these OAuth credentials")+ else:+ print_warning("xAI Grok OAuth login did not complete. Falling back to Edge TTS.")+ selected = "edge"+ elif choice_idx == 1:+ api_key = prompt("xAI API key for TTS", password=True)+ if api_key:+ save_env_value("XAI_API_KEY", api_key)+ print_success("xAI TTS API key saved")+ else:+ from hermes_constants import display_hermes_home as _dhh+ print_warning(+ "No xAI API key provided for TTS. Configure XAI_API_KEY "+ f"via hermes setup model or {_dhh()}/.env to use xAI TTS. "+ "Falling back to Edge TTS."+ )+ selected = "edge"+ else:+ print_warning("xAI TTS skipped. Falling back to Edge TTS.")+ selected = "edge"++ if selected == "xai":+ print()+ voice_id = prompt("xAI voice_id (Enter for 'eve', or paste a custom voice ID)")+ if voice_id and voice_id.strip():+ config.setdefault("tts", {}).setdefault("xai", {})["voice_id"] = voice_id.strip()+ print_success(f"xAI voice_id set to: {voice_id.strip()}")+ return selected+++def _setup_tts_provider(config: dict):+ """Interactive TTS provider selection with install flow for local engines."""+ from hermes_cli.setup import (+ get_env_value, get_nous_subscription_features, managed_nous_tools_enabled, print_header, print_info,+ print_success, print_warning, prompt_choice, save_config,+ )++ current_provider = config.get("tts", {}).get("provider", "edge")+ current_label = _TTS_PROVIDER_LABELS.get(current_provider, current_provider)++ print()+ print_header("Text-to-Speech Provider (optional)")+ print_info(f"Current: {current_label}")+ print()++ options = list(_TTS_PROVIDER_CHOICES)+ if managed_nous_tools_enabled() and get_nous_subscription_features(config).nous_auth_present:+ options.insert(0, ("nous-openai", "Nous Subscription (managed OpenAI TTS, billed to your subscription)"))+ choices = [label for _, label in options] + [f"Keep current ({current_label})"]+ keep_current_idx = len(choices) - 1+ idx = prompt_choice("Select TTS provider:", choices, keep_current_idx)+ if idx == keep_current_idx:+ return++ selected = options[idx][0]+ selected_via_nous = selected == "nous-openai"+ if selected_via_nous:+ selected = "openai"+ print_info("OpenAI TTS will use the managed Nous gateway and bill to your subscription.")+ if get_env_value("VOICE_TOOLS_OPENAI_KEY") or get_env_value("OPENAI_API_KEY"):+ print_warning(+ "Direct OpenAI credentials are still configured and may take precedence until removed from ~/.hermes/.env."+ )++ if selected in _TTS_LOCAL_PROVIDERS:+ selected = _tts_local_install_step(selected)+ elif selected in _TTS_API_KEY_PROVIDERS and not selected_via_nous:+ selected = _tts_api_key_step(selected)+ elif selected == "xai":+ selected = _tts_xai_step(config)++ config.setdefault("tts", {})["provider"] = selected+ save_config(config)+ print_success(f"TTS provider set to: {_TTS_PROVIDER_LABELS.get(selected, selected)}")+++def setup_tts(config: dict):+ """Standalone TTS setup (for 'hermes setup tts')."""+ _setup_tts_provider(config)++