The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): setup_terminal/tts/summary/telegram share secret-prompt, xai-path, poll-tick helpers
Teknium7f379193695a
diff --git a/hermes_cli/setup_summary.py b/hermes_cli/setup_summary.pyindex 934597d52db..14e7d082fc2 100644--- a/hermes_cli/setup_summary.py+++ b/hermes_cli/setup_summary.py@@ -77,7 +77,6 @@ def _first_available_plugin_provider(registry: str, skip: str = None):try:import importlibfrom hermes_cli.plugins import _ensure_plugins_discovered-_ensure_plugins_discovered()for provider in importlib.import_module(f"agent.{registry}").list_providers():if provider.name == skip:@@ -99,7 +98,6 @@ 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-ok = bool(get_available_vision_backends())except Exception:ok = False@@ -150,18 +148,18 @@ def _video_gen_row(config, feats):def _tts_row(config, feats):# Configured provider, gated on its key (or local install)- tts_provider = _setup.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)+ provider = _setup.cfg_get(config, "tts", "provider", default="edge")+ return _voice_provider_status("Text-to-Speech", provider, _TTS_SUMMARY_ROWS, _TTS_SUMMARY_DEFAULT)def _stt_row(config, feats):- stt_provider = _setup.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:+ 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)+ provider = _setup.cfg_get(config, "stt", "provider", default="local") or "local"+ return _voice_provider_status("Speech-to-Text", provider, _STT_SUMMARY_ROWS, _STT_SUMMARY_DEFAULT)def _modal_row(config, feats):@@ -184,8 +182,8 @@ def _spotify_row(config, feats):# OAuth via hermes auth spotify β check auth.json, not env varstry: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"):+ state = get_provider_auth_state("spotify") or {}+ if state.get("access_token") or state.get("refresh_token"):return ("Spotify (PKCE OAuth)", True, None)except Exception:pass@@ -228,7 +226,6 @@ def _print_setup_summary(config: dict, hermes_home):# prompt mid-wizard used to exit "successfully" with NO working model; say so loudly.try:from hermes_cli.auth import resolve_provider-resolve_provider()except Exception:print()@@ -244,7 +241,7 @@ def _print_setup_summary(config: dict, hermes_home):subscription_features = _setup.get_nous_subscription_features(config)for build in _TOOL_ROW_BUILDERS:row = build(config, subscription_features)- tool_status.extend(row if isinstance(row, list) else [row] if row is not None else [])+ tool_status.extend(row if isinstance(row, list) else [] if row is None else [row])available_count = sum(1 for _, avail, _ in tool_status if avail)_setup._info(f"{available_count}/{len(tool_status)} tool categories available:", None)@@ -267,9 +264,9 @@ def _print_setup_summary(config: dict, hermes_home):print()print(_setup.color(f"π All your files are in {_dhh()}/:", _setup.Colors.CYAN, _setup.Colors.BOLD))print()- print(f" {_setup.color('Settings:', _setup.Colors.YELLOW)} {_setup.get_config_path()}")- print(f" {_setup.color('API Keys:', _setup.Colors.YELLOW)} {_setup.get_env_path()}")- print(f" {_setup.color('Data:', _setup.Colors.YELLOW)} {hermes_home}/cron/, sessions/, logs/")+ for label, value in (("Settings:", f" {_setup.get_config_path()}"), ("API Keys:", f" {_setup.get_env_path()}"),+ ("Data:", f" {hermes_home}/cron/, sessions/, logs/")):+ print(f" {_setup.color(label, _setup.Colors.YELLOW)}{value}")print()_print_section_header("π To edit your configuration:")@@ -279,8 +276,8 @@ def _print_setup_summary(config: dict, hermes_home):print(" Set a specific value")print()print(" Or edit the files directly:")- print(f" {_setup.color(f'nano {_setup.get_config_path()}', _setup.Colors.DIM)}")- print(f" {_setup.color(f'nano {_setup.get_env_path()}', _setup.Colors.DIM)}")+ for path in (_setup.get_config_path(), _setup.get_env_path()):+ print(f" {_setup.color(f'nano {path}', _setup.Colors.DIM)}")print()_print_section_header("π Ready to go!")diff --git a/hermes_cli/setup_terminal.py b/hermes_cli/setup_terminal.pyindex 676f6f32182..8b136a4273f 100644--- a/hermes_cli/setup_terminal.py+++ b/hermes_cli/setup_terminal.py@@ -80,9 +80,8 @@ def _read_nearest_vercel_project(start: Path | None = None) -> dict[str, str]: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 {key: data[key] for key in ("projectId", "orgId")+ if isinstance(data.get(key), str) and data[key].strip()}return {}@@ -95,6 +94,14 @@ def _prompt_secret_env(label: str, env_var: str, *, confirm_msg: str = "") -> No_setup.print_success(confirm_msg)+def _existing_secret_keeps(env_var: str, label: str, question: str) -> bool:+ """True when ``env_var`` is already set and the user declines to update it."""+ if not _setup.get_env_value(env_var):+ return False+ _setup.print_info(f" {label}: already configured")+ return not _setup.prompt_yes_no(question, False)++def _pip_install_vercel(package):"""uv when Hermes has one ($HERMES_HOME/bin is never on PATH, so which() misses it andbootstrapping mid-wizard is fine), else pip β a `uv venv` venv may not even have pip."""@@ -198,10 +205,8 @@ def _setup_backend_modal(config: dict) -> None:_setup.print_info("Requires a Modal account: https://modal.com")_ensure_sdk("modal", "uv pip install modal")_setup._info(None, "Modal authentication:", " Get your token at: https://modal.com/settings")- if _setup.get_env_value("MODAL_TOKEN_ID"):- _setup.print_info(" Modal token: already configured")- if not _setup.prompt_yes_no(" Update Modal credentials?", False):- return+ if _existing_secret_keeps("MODAL_TOKEN_ID", "Modal token", " Update Modal credentials?"):+ return_prompt_secret_env(" Modal Token ID", "MODAL_TOKEN_ID")_prompt_secret_env(" Modal Token Secret", "MODAL_TOKEN_SECRET")@@ -213,12 +218,9 @@ def _setup_backend_daytona(config: dict) -> None:"Sign up at: https://daytona.io")_ensure_sdk("daytona", "uv pip install daytona", show_stderr=True)print()- if _setup.get_env_value("DAYTONA_API_KEY"):- _setup.print_info(" Daytona API key: already configured")- if _setup.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")+ had_key = bool(_setup.get_env_value("DAYTONA_API_KEY"))+ if not _existing_secret_keeps("DAYTONA_API_KEY", "Daytona API key", " Update API key?"):+ _prompt_secret_env(" Daytona API key", "DAYTONA_API_KEY", confirm_msg=" Updated" if had_key else " Configured")config["terminal"].setdefault("daytona_image", _SANDBOX_IMAGE)@@ -251,13 +253,8 @@ def _setup_backend_ssh(config: dict) -> None:if host and _setup.prompt_yes_no(" Test SSH connection?", True):_setup.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"]+ ssh_cmd = ["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=5", *(["-i", ssh_key] if ssh_key else []),+ *(["-p", port] if port and port != "22" else []), f"{user}@{host}" if user else host, "echo ok"]result = subprocess.run(ssh_cmd, timeout=10, **_RUN_KW)if result.returncode == 0:_setup.print_success(" SSH connection successful!")@@ -269,7 +266,6 @@ def _setup_backend_ssh(config: dict) -> None:def _setup_backend_plugin(config: dict, backend: str) -> None:try:from agent.terminal_env_registry import get_provider-provider = get_provider(backend)_setup.print_success(f"Terminal backend: {provider.display_name}")for line in provider.setup_instructions():@@ -314,10 +310,8 @@ def setup_terminal_backend(config: dict):plugin_backend_names = []try:from hermes_cli.plugins import discover_plugins-discover_plugins() # idempotent β plugin state may not be loaded yetfrom 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}"))@@ -325,10 +319,9 @@ def setup_terminal_backend(config: dict):except Exception:pass- keep_current_idx = len(backends)terminal_choices = [label for _, label in backends] + [f"Keep current ({current_backend})"]- terminal_idx = _setup.prompt_choice("Select terminal backend:", terminal_choices, keep_current_idx)- if terminal_idx == keep_current_idx:+ terminal_idx = _setup.prompt_choice("Select terminal backend:", terminal_choices, len(backends))+ if terminal_idx == len(backends):_setup.print_info(f"Keeping current backend: {current_backend}")returnselected_backend = backends[terminal_idx][0] if 0 <= terminal_idx < len(backends) else Nonediff --git a/hermes_cli/setup_tts.py b/hermes_cli/setup_tts.pyindex eda2ba48d75..598ab78de48 100644--- a/hermes_cli/setup_tts.py+++ b/hermes_cli/setup_tts.py@@ -67,8 +67,7 @@ def _install_kittentts_deps() -> bool:wheel_url = "https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl"_setup._info(None, "Installing kittentts Python package (~25-80MB model downloaded on first use)...", None)return _pip_install_tts_package(- "kittentts", ["-U", wheel_url, "soundfile", "--quiet"], f"uv pip install -U '{wheel_url}' soundfile",- )+ "kittentts", ["-U", wheel_url, "soundfile", "--quiet"], f"uv pip install -U '{wheel_url}' soundfile")def _xai_oauth_logged_in_for_setup() -> bool:@@ -76,7 +75,6 @@ def _xai_oauth_logged_in_for_setup() -> bool:API-key prompt for users who logged in via ``hermes model`` -> xAI Grok OAuth."""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@@ -185,6 +183,24 @@ def _tts_local_install_step(selected: str) -> str:return selected+def _xai_oauth_path():+ if _setup._run_xai_oauth_login_from_setup():+ _setup.print_success("Logged in β xAI TTS will use these OAuth credentials")+ return None+ return "xAI Grok OAuth login did not complete. Falling back to Edge TTS."+++def _xai_api_key_path():+ api_key = _setup.prompt("xAI API key for TTS", password=True)+ if api_key:+ _setup.save_env_value("XAI_API_KEY", api_key)+ _setup.print_success("xAI TTS API key saved")+ return None+ from hermes_constants import display_hermes_home as _dhh+ return ("No xAI API key provided for TTS. Configure XAI_API_KEY via hermes setup model "+ f"or {_dhh()}/.env to use xAI TTS. Falling back to Edge TTS.")++def _tts_xai_step(config: dict) -> str:"""xAI TTS auth. Order: existing OAuth tokens (free for SuperGrok) > existingXAI_API_KEY > offer both paths β xAI TTS works with OAuth bearer tokens too."""@@ -199,23 +215,9 @@ def _tts_xai_step(config: dict) -> str: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)- fallback = None # warning printed when xAI auth did not happen; result is then "edge"- if choice_idx == 0:- if _setup._run_xai_oauth_login_from_setup():- _setup.print_success("Logged in β xAI TTS will use these OAuth credentials")- else:- fallback = "xAI Grok OAuth login did not complete. Falling back to Edge TTS."- elif choice_idx == 1:- api_key = _setup.prompt("xAI API key for TTS", password=True)- if api_key:- _setup.save_env_value("XAI_API_KEY", api_key)- _setup.print_success("xAI TTS API key saved")- else:- from hermes_constants import display_hermes_home as _dhh- fallback = ("No xAI API key provided for TTS. Configure XAI_API_KEY via hermes setup model "- f"or {_dhh()}/.env to use xAI TTS. Falling back to Edge TTS.")- else:- fallback = "xAI TTS skipped. Falling back to Edge TTS."+ # Each path returns the fallback warning (result is then "edge") or None on success.+ fallback = (_xai_oauth_path, _xai_api_key_path, lambda: "xAI TTS skipped. Falling back to Edge TTS.")[+ choice_idx if choice_idx in (0, 1) else 2]()if fallback:_setup.print_warning(fallback)return "edge"@@ -248,17 +250,15 @@ def _setup_tts_provider(config: dict):returnselected = options[idx][0]- selected_via_nous = selected == "nous-openai"- if selected_via_nous:+ if selected == "nous-openai":selected = "openai"_setup.print_info("OpenAI TTS will use the managed Nous gateway and bill to your subscription.")if _setup.get_env_value("VOICE_TOOLS_OPENAI_KEY") or _setup.get_env_value("OPENAI_API_KEY"):_setup.print_warning("Direct OpenAI credentials are still configured and may take precedence "- "until removed from ~/.hermes/.env.")-- if selected in _TTS_LOCAL_PROVIDERS:+ "until removed from ~/.hermes/.env.")+ elif selected in _TTS_LOCAL_PROVIDERS:selected = _tts_local_install_step(selected)- elif selected in _TTS_API_KEY_PROVIDERS and not selected_via_nous:+ elif selected in _TTS_API_KEY_PROVIDERS:selected = _tts_api_key_step(selected)elif selected == "xai":selected = _tts_xai_step(config)diff --git a/hermes_cli/telegram_managed_bot.py b/hermes_cli/telegram_managed_bot.pyindex 44551067d5e..e1e248f925c 100644--- a/hermes_cli/telegram_managed_bot.py+++ b/hermes_cli/telegram_managed_bot.py@@ -150,10 +150,14 @@ def _try_poll(api_url: str | None, pairing: TelegramPairing) -> TelegramBotSetupdef poll_for_setup_result(api_url: str | None, pairing: TelegramPairing, timeout: float = DEFAULT_POLL_TIMEOUT,- interval: float = POLL_INTERVAL) -> Optional[TelegramBotSetupResult]:- """Poll the pairing API until setup metadata is available or timeout."""- deadline = time.monotonic() + timeout+ interval: float = POLL_INTERVAL, on_tick=None) -> Optional[TelegramBotSetupResult]:+ """Poll the pairing API until setup metadata is available or timeout. ``on_tick(elapsed_s)``+ runs before each attempt (progress display)."""+ start = time.monotonic()+ deadline = start + timeoutwhile time.monotonic() < deadline:+ if on_tick:+ on_tick(time.monotonic() - start)if result := _try_poll(api_url, pairing):return resulttime.sleep(interval)@@ -172,8 +176,8 @@ def auto_setup_telegram_bot_result(sys.stdout.flush()pairing = create_pairing(resolved_api_url)if not pairing:- print(" β Could not reach the Hermes Telegram onboarding service.")- print(" Try the manual setup instead, or check your network.")+ print(" β Could not reach the Hermes Telegram onboarding service.\n"+ " Try the manual setup instead, or check your network.")return Noneprint(" β Pairing created")@@ -181,28 +185,26 @@ def auto_setup_telegram_bot_result(sys.stdout.flush()print("\n Scan this QR code with your phone, or open the link below:\n")print_qr_code(pairing.qr_payload, include_link=False)- print(f"\n Link: {pairing.deep_link}\n")- print(" When Telegram opens, tap 'Create Bot' to confirm.")- print(" (You can edit the bot display name before confirming)\n")+ print(f"\n Link: {pairing.deep_link}\n"+ " When Telegram opens, tap 'Create Bot' to confirm.\n"+ " (You can edit the bot display name before confirming)\n")spinner_chars = "β β β Ήβ Έβ Όβ ΄β ¦β §β β "- start = time.monotonic()- deadline = start + poll_timeout- idx = 0- while time.monotonic() < deadline:- char = spinner_chars[idx % len(spinner_chars)]- remaining = max(0, int(poll_timeout - int(time.monotonic() - start)))+ ticks = iter(range(1 << 30))++ def spin(elapsed: float) -> None:+ char = spinner_chars[next(ticks) % len(spinner_chars)]+ remaining = max(0, int(poll_timeout - int(elapsed)))sys.stdout.write(f"\r {char} Waiting for bot creation... ({remaining}s remaining) ")sys.stdout.flush()- idx += 1- if result := _try_poll(resolved_api_url, pairing):- sys.stdout.write("\r β Bot created successfully! \n")- sys.stdout.flush()- return result- time.sleep(POLL_INTERVAL)+ result = poll_for_setup_result(resolved_api_url, pairing, poll_timeout, POLL_INTERVAL, on_tick=spin)+ if result:+ sys.stdout.write("\r β Bot created successfully! \n")+ sys.stdout.flush()+ return resultsys.stdout.write("\r β Timed out waiting for bot creation. \n")sys.stdout.flush()- print(" The bot may still be created β check Telegram.")- print(" You can paste the token manually below, or re-run setup.")+ print(" The bot may still be created β check Telegram.\n"+ " You can paste the token manually below, or re-run setup.")return None