gateway_setup_wizard.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. """Gateway platform setup wizard (hermes gateway setup): platform registry/status table, per-platform setup prompts, service offer.
  2. Extracted from ``hermes_cli/gateway.py``. Bodies read facade helpers through ``_gw()`` (late
  3. binding on ``hermes_cli.gateway``) so the seams tests and callers patch on the facade keep
  4. intercepting the moved code.
  5. """
  6. from __future__ import annotations
  7. import shutil
  8. import subprocess
  9. import sys
  10. def _gw():
  11. from hermes_cli import gateway # late: the facade imports this module
  12. return gateway
  13. # Built-in per-platform setup config (env vars, instructions, prompts). Telegram, WhatsApp, Email,
  14. # SMS, etc. live in plugins/platforms/<name>/ and are discovered via the platform registry.
  15. _PLATFORMS = [
  16. {
  17. "key": "mattermost", "label": "Mattermost", "emoji": "💬", "token_var": "MATTERMOST_TOKEN",
  18. "setup_instructions": [
  19. "1. In Mattermost: Integrations → Bot Accounts → Add Bot Account",
  20. " (System Console → Integrations → Bot Accounts must be enabled)",
  21. "2. Give it a username (e.g. hermes) and copy the bot token",
  22. "3. Works with any self-hosted Mattermost instance — enter your server URL",
  23. "4. Find your user ID (the profile dialog does not show it):",
  24. " Admins: System Console → User Management → Users → open your user.",
  25. " Anyone: while logged in, open <server>/api/v4/users/me in a browser tab.",
  26. " With the bot token: GET <server>/api/v4/users/username/<your-username>.",
  27. " Copy the \"id\" field. /users/me with the bot token returns the bot's ID.",
  28. " ⚠ This is NOT your username — it's a 26-character alphanumeric ID.",
  29. "5. To get a channel ID: click the channel name → View Info → copy the ID",
  30. ],
  31. "vars": [
  32. {"name": "MATTERMOST_URL", "prompt": "Server URL (e.g. https://mm.example.com)",
  33. "password": False, "help": "Your Mattermost server URL. Works with any self-hosted instance."},
  34. {"name": "MATTERMOST_TOKEN", "prompt": "Bot token", "password": True,
  35. "help": "Paste the bot token from step 2 above."},
  36. {"name": "MATTERMOST_ALLOWED_USERS", "prompt": "Allowed user IDs (comma-separated)",
  37. "password": False, "is_allowlist": True,
  38. "help": "Your user ID from step 4 above (26 characters, not your @username)."},
  39. {"name": "MATTERMOST_HOME_CHANNEL",
  40. "prompt": "Home channel ID (for cron/notification delivery, or empty to set later with /set-home)",
  41. "password": False, "help": "Channel ID where Hermes delivers cron results and notifications."},
  42. {"name": "MATTERMOST_REPLY_MODE",
  43. "prompt": "Reply mode — 'off' for flat messages, 'thread' for threaded replies (default: off)",
  44. "password": False,
  45. "help": "off = flat channel messages, thread = replies nest under your message."},
  46. ],
  47. },
  48. ]
  49. def _all_platforms() -> list[dict]:
  50. """Built-in ``_PLATFORMS`` plus registry plugin platforms (same dict shape, source in
  51. ``_registry_entry``). Plugins are discovered here (idempotent) so the setup menu works without a
  52. running gateway; user-installed ones still need ``plugins.enabled`` (untrusted code). Matrix is
  53. hidden on Windows: python-olm has no wheel or native build (use WSL)."""
  54. try:
  55. from hermes_cli.plugins import discover_plugins
  56. discover_plugins()
  57. except Exception as e:
  58. _gw().logger.debug("plugin discovery failed during platform enumeration: %s", e)
  59. hide_matrix = sys.platform == "win32"
  60. platforms = [dict(p) for p in _gw()._PLATFORMS if not (hide_matrix and p.get("key") == "matrix")]
  61. by_key = {p["key"]: p for p in platforms}
  62. try:
  63. from gateway.platform_registry import platform_registry
  64. except Exception:
  65. return platforms
  66. for entry in platform_registry.all_entries():
  67. if entry.name in by_key or (hide_matrix and entry.name == "matrix"):
  68. continue
  69. platforms.append({
  70. "key": entry.name, "label": entry.label, "emoji": entry.emoji,
  71. "token_var": entry.required_env[0] if entry.required_env else "",
  72. "install_hint": entry.install_hint, "_registry_entry": entry,
  73. })
  74. return platforms
  75. def _platform_status(platform: dict) -> str:
  76. """Plain-text status string; uncolored because ANSI codes break curses menu width math."""
  77. entry = platform.get("_registry_entry")
  78. if entry is not None:
  79. # Prefer is_connected (env + config.yaml) over check_fn (a coarse deps gate). Never fall back
  80. # to check_fn when is_connected returned False, or "SDK installed" would override "no token".
  81. try:
  82. if entry.is_connected is not None:
  83. from gateway.config import PlatformConfig
  84. configured = bool(entry.is_connected(PlatformConfig(enabled=True)))
  85. else:
  86. configured = bool(entry.check_fn())
  87. except Exception:
  88. configured = False
  89. return "configured" if configured else "not configured"
  90. token_var = platform.get("token_var", "")
  91. if not token_var:
  92. return "not configured"
  93. return "configured" if _gw().get_env_value(token_var) else "not configured"
  94. def _set_platform_unauthorized_dm_behavior(platform_key: str, behavior: str) -> None:
  95. """Persist a platform-specific unauthorized-DM policy in config.yaml."""
  96. _gw().write_platform_config_field(platform_key, "unauthorized_dm_behavior", behavior, raw=True)
  97. def print_setup_header(title: str) -> None:
  98. print()
  99. print(_gw().color(f" ─── {title} Setup ───", _gw().Colors.CYAN))
  100. def confirm_reconfigure(label: str, *env_vars: str) -> bool:
  101. """False when ``label`` is already configured (all ``env_vars`` set) and the user declines."""
  102. if all(_gw().get_env_value(v) for v in env_vars):
  103. print()
  104. _gw().print_success(f"{label} is already configured.")
  105. return _gw().prompt_yes_no(f" Reconfigure {label}?", False)
  106. return True
  107. def offer_home_channel(home_var: str, user_id: str, what: str) -> None:
  108. """Offer to persist ``user_id`` as ``home_var`` (e.g. "your Telegram user ID")."""
  109. if _gw().prompt_yes_no(f" Use {what} ({user_id}) as the home channel?", True):
  110. _gw().save_env_value(home_var, user_id)
  111. _gw().print_success(f" Home channel set to {user_id}")
  112. def save_env_values(**values: str) -> None:
  113. for name, value in values.items():
  114. _gw().save_env_value(name, value)
  115. def prompt_csv(prompt_text: str, default: str) -> str:
  116. """Comma-separated ID prompt with whitespace stripped."""
  117. return _gw().prompt(prompt_text, default, password=False).replace(" ", "")
  118. # (default index, *choices) for the no-allowlist access prompt, keyed by is_email.
  119. _UNAUTHORIZED_ACCESS_CHOICES = {
  120. True: (3,
  121. "Enable open access (any email sender can message the bot)",
  122. "Use DM pairing (unknown email senders receive a pairing code)",
  123. "Politely decline unknown senders (one-time message, then silence)",
  124. "Keep unknown senders silent"),
  125. False: (1,
  126. "Enable open access (anyone can message the bot)",
  127. "Use DM pairing (unknown users request access, you approve with 'hermes pairing approve')",
  128. "Politely decline unknown senders (one-time message, then silence)",
  129. "Skip for now (bot will deny all users until configured)"),
  130. }
  131. def _prompt_unauthorized_access(platform_key: str) -> None:
  132. """No allowlist was given — ask open access vs DM pairing vs decline vs skip/silent, and persist."""
  133. is_email = platform_key == "email"
  134. print()
  135. default_idx, *access_choices = _UNAUTHORIZED_ACCESS_CHOICES[is_email]
  136. access_idx = _gw().prompt_choice(" How should unauthorized users be handled?", access_choices, default_idx)
  137. if access_idx == 0:
  138. _gw().save_env_value("EMAIL_ALLOW_ALL_USERS" if is_email else "GATEWAY_ALLOW_ALL_USERS", "true")
  139. _gw().print_warning(" Open access enabled — anyone can use your bot!")
  140. elif access_idx == 1:
  141. if is_email:
  142. _set_platform_unauthorized_dm_behavior("email", "pair")
  143. _gw().print_success(" DM pairing mode — users will receive a code to request access.")
  144. _gw().print_info(" Approve with: hermes pairing approve <platform> <code>")
  145. elif access_idx == 2:
  146. _set_platform_unauthorized_dm_behavior(platform_key, "decline")
  147. _gw().print_success(" Unknown senders get one polite decline, then silence (unauthorized_dm_behavior: decline).")
  148. elif is_email:
  149. _gw().print_success(" Unknown email senders will be ignored.")
  150. else:
  151. _gw().print_info(" Skipped — configure later with 'hermes gateway setup'")
  152. def _telegram_auto_setup(token_var: str) -> tuple[bool, object]:
  153. """Offer the managed-bot QR flow. Returns (token_saved, owner_user_id)."""
  154. print()
  155. _gw()._print_info_lines(
  156. " Telegram can be configured automatically with a managed bot:",
  157. " [1] Automatic (scan QR → confirm in Telegram → done)", " [2] Manual BotFather token",
  158. )
  159. if _gw().prompt(" Choice [1/2]", default="1").strip() != "1":
  160. return False, None
  161. try:
  162. from hermes_cli.telegram_managed_bot import (
  163. auto_setup_telegram_bot_result, is_valid_telegram_bot_token,
  164. )
  165. except ImportError:
  166. _gw().print_warning(" Automatic setup is unavailable in this install.")
  167. return False, None
  168. result = auto_setup_telegram_bot_result()
  169. if result and is_valid_telegram_bot_token(result.token):
  170. _gw().save_env_value(token_var, result.token)
  171. _gw().print_success(" Saved TELEGRAM_BOT_TOKEN")
  172. return True, result.owner_user_id
  173. if result:
  174. _gw().print_warning(" Automatic setup returned an invalid Telegram token.")
  175. print()
  176. _gw().print_info(" Falling back to manual setup...")
  177. return False, None
  178. def _clean_discord_ids(cleaned: str) -> str:
  179. """Strip common Discord prefixes (user:123, <@123>, <@!123>) from a comma-separated list."""
  180. parts = []
  181. for uid in cleaned.split(","):
  182. uid = uid.strip()
  183. if uid.startswith("<@") and uid.endswith(">"):
  184. uid = uid.lstrip("<@!").rstrip(">")
  185. if uid.lower().startswith("user:"):
  186. uid = uid[5:]
  187. if uid:
  188. parts.append(uid)
  189. return ",".join(parts)
  190. def _prompt_allowlist_var(var: dict, platform_key: str, auto_owner_user_id) -> str | None:
  191. """Allowlist prompt for one var; returns the saved value or None (open-access prompt shown)."""
  192. if "TELEGRAM" in var["name"] and auto_owner_user_id:
  193. detected_id = str(auto_owner_user_id)
  194. _gw().print_success(f" Detected your Telegram user ID: {detected_id}")
  195. if _gw().prompt_yes_no(" Allow this Telegram account to use the bot?", True):
  196. extra = _gw().prompt(" Additional allowed user IDs (comma-separated, optional)", password=False)
  197. ids = [detected_id]
  198. for uid in extra.replace(" ", "").split(","):
  199. if uid and uid not in ids:
  200. ids.append(uid)
  201. cleaned = ",".join(ids)
  202. _gw().save_env_value(var["name"], cleaned)
  203. _gw().print_success(" Saved — only these users can interact with the bot.")
  204. return cleaned
  205. _gw()._print_info_lines(
  206. " The gateway DENIES all users by default for security.",
  207. " Enter user IDs to create an allowlist, or leave empty",
  208. " and you'll be asked about open access next.",
  209. )
  210. value = _gw().prompt(f" {var['prompt']}", password=False)
  211. if not value:
  212. _prompt_unauthorized_access(platform_key)
  213. return None
  214. cleaned = value.replace(" ", "")
  215. if "DISCORD" in var["name"]:
  216. cleaned = _clean_discord_ids(cleaned)
  217. _gw().save_env_value(var["name"], cleaned)
  218. _gw().print_success(" Saved — only these users can interact with the bot.")
  219. return cleaned
  220. def _setup_standard_platform(platform: dict):
  221. """Interactive setup for Telegram, Discord, or Slack."""
  222. from hermes_cli.setup_hidden_env import is_setup_hidden_env as _is_setup_hidden_env
  223. emoji, label, token_var = platform["emoji"], platform["label"], platform["token_var"]
  224. print_setup_header(f"{emoji} {label}")
  225. instructions = platform.get("setup_instructions")
  226. if instructions:
  227. print()
  228. _gw()._print_info_lines(*(f" {line}" for line in instructions))
  229. if not confirm_reconfigure(label, token_var):
  230. return
  231. auto_token_saved, auto_owner_user_id = False, None
  232. if platform.get("key") == "telegram":
  233. auto_token_saved, auto_owner_user_id = _telegram_auto_setup(token_var)
  234. allowed_val_set = None # Track if user set an allowlist (for home channel offer)
  235. # Skip knobs the setup forms hide (home channel, reply mode, proxy...): they're self-configuring.
  236. setup_vars = [
  237. v for v in platform["vars"]
  238. if v["name"] == token_var or v.get("is_allowlist") or not _is_setup_hidden_env(v["name"])
  239. ]
  240. for var in setup_vars:
  241. print()
  242. _gw().print_info(f" {var['help']}")
  243. existing = _gw().get_env_value(var["name"])
  244. if existing and var["name"] != token_var:
  245. _gw().print_info(f" Current: {existing}")
  246. if auto_token_saved and var["name"] == token_var:
  247. _gw().print_info(" Token saved by automatic setup.")
  248. continue
  249. if var.get("is_allowlist"):
  250. saved = _prompt_allowlist_var(var, platform.get("key"), auto_owner_user_id)
  251. if saved is not None:
  252. allowed_val_set = saved
  253. continue
  254. value = _gw().prompt(f" {var['prompt']}", password=var.get("password", False))
  255. if value:
  256. _gw().save_env_value(var["name"], value)
  257. _gw().print_success(f" Saved {var['name']}")
  258. elif var["name"] == token_var:
  259. _gw().print_warning(f" Skipped — {label} won't work without this.")
  260. return
  261. else:
  262. _gw().print_info(" Skipped (can configure later)")
  263. # Offer the first allowlisted user ID as home channel when none is set (Telegram DMs).
  264. home_var = f"{label.upper()}_HOME_CHANNEL"
  265. home_val = _gw().get_env_value(home_var)
  266. if allowed_val_set and not home_val and label == "Telegram":
  267. first_id = allowed_val_set.split(",")[0].strip()
  268. if first_id:
  269. offer_home_channel(home_var, first_id, "your user ID")
  270. print()
  271. _gw().print_success(f"{emoji} {label} configured!")
  272. def _builtin_setup_fn(key: str):
  273. """Resolve a built-in platform's setup function; late-bound to dodge the hermes_cli.setup cycle."""
  274. from hermes_cli import setup as _s
  275. return {
  276. # telegram/discord/slack/whatsapp/dingtalk/feishu/wecom setup_fns come from their plugins.
  277. "webhooks": _gw().setup_platforms._setup_webhooks,
  278. }.get(key)
  279. def _configure_platform(platform: dict) -> None:
  280. """Plugin ``setup_fn`` -> built-in by key -> ``_setup_standard_platform`` (``vars``) -> env-var hint.
  281. Bundled plugins auto-load; user plugins must already be in ``plugins.enabled``."""
  282. entry = platform.get("_registry_entry")
  283. fn = entry.setup_fn if entry is not None else None
  284. if fn is None:
  285. fn = _builtin_setup_fn(platform["key"])
  286. if fn is not None:
  287. fn()
  288. return
  289. if platform.get("vars"):
  290. _gw()._setup_standard_platform(platform)
  291. return
  292. label = platform.get("label", platform["key"])
  293. print_setup_header(f"{platform.get('emoji', '🔌')} {label}")
  294. required = entry.required_env if entry else []
  295. if required:
  296. _gw().print_info(f" Set these env vars in ~/.hermes/.env: {', '.join(required)}")
  297. else:
  298. _gw().print_info(f" Configure {label} in config.yaml under gateway.platforms.{platform['key']}")
  299. if platform.get("install_hint"):
  300. _gw().print_info(f" {platform['install_hint']}")
  301. def _wizard_offer_service_action(action: str, question: str, failed_label: str, **kwargs) -> None:
  302. """Wizard start/restart prompt; prints remediation instead when system scope would need root."""
  303. if _gw().supports_systemd_services() and _gw()._system_scope_wizard_would_need_root():
  304. _gw()._print_system_scope_remediation(action)
  305. elif _gw().prompt_yes_no(question, True):
  306. _gw()._setup_service_action(action, failed_label=failed_label, **kwargs)
  307. def _setup_service_action(
  308. action: str, *, failed_label: str, windows: bool = True, system: bool = False
  309. ) -> None:
  310. """Run a wizard service start/restart, printing remediation instead of raising. ``windows=False``
  311. skips Windows (pre-platform status block never offers it); ``system`` is a fresh install's scope."""
  312. try:
  313. backend = _gw()._service_backend(windows=windows)
  314. if backend is not None:
  315. _gw()._service_call(backend, action, None if action == "restart" else system)
  316. elif action == "restart" and windows:
  317. _gw().stop_profile_gateway()
  318. _gw().print_info("Start manually: hermes gateway")
  319. except _gw().UserSystemdUnavailableError as e:
  320. _gw().print_error(f" {failed_label} — user systemd not reachable:")
  321. _gw()._print_indented(str(e))
  322. except _gw().SystemScopeRequiresRootError as e:
  323. # Defense in depth: the wizard's root pre-check should have caught this.
  324. _gw().print_error(f" {failed_label}: {e}")
  325. _gw()._print_system_scope_remediation(action)
  326. except subprocess.CalledProcessError as e:
  327. _gw().print_error(f" {failed_label}: {e}")
  328. _WIZARD_BANNER = (
  329. "┌─────────────────────────────────────────────────────────┐",
  330. "│ ☤ Gateway Setup │",
  331. "├─────────────────────────────────────────────────────────┤",
  332. "│ Configure messaging platforms and the gateway service. │",
  333. "│ Press Ctrl+C at any time to exit. │",
  334. "└─────────────────────────────────────────────────────────┘",
  335. )
  336. _WIZARD_BACKEND_LABELS = {"systemd": "systemd", "launchd": "launchd", "windows": "Scheduled Task"}
  337. # Post-setup guidance when no service backend applies, keyed by the fallthrough reason.
  338. _WIZARD_NO_SERVICE_LINES = {
  339. "wsl": (
  340. " WSL detected but systemd is not running.", " Run in foreground: hermes gateway run",
  341. " For persistence: tmux new -s hermes 'hermes gateway run'",
  342. " To enable systemd: add systemd=true to /etc/wsl.conf, then 'wsl --shutdown'",
  343. ),
  344. "termux": (
  345. " Termux does not use systemd/launchd services.", " Run in foreground: hermes gateway run",
  346. " Or start it manually in the background (best effort): nohup hermes gateway run >{home}/logs/gateway.log 2>&1 &",
  347. ),
  348. "unsupported": (
  349. " Service install not supported on this platform.", " Run in foreground: hermes gateway run",
  350. ),
  351. }
  352. def _wizard_service_status_block() -> None:
  353. """Pre-platform service status: warnings, then offer to start an installed-but-stopped service."""
  354. print()
  355. service_installed = _gw()._is_service_installed()
  356. service_running = _gw()._is_service_running()
  357. if _gw().supports_systemd_services() and _gw().has_conflicting_systemd_units():
  358. _gw().print_systemd_scope_conflict_warning()
  359. print()
  360. if _gw().supports_systemd_services() and _gw().has_legacy_hermes_units():
  361. _gw().print_legacy_unit_warning()
  362. print()
  363. if service_installed and service_running:
  364. _gw().print_success("Gateway service is installed and running.")
  365. elif service_installed:
  366. _gw().print_warning("Gateway service is installed but not running.")
  367. _wizard_offer_service_action("start", " Start it now?", "Failed to start", windows=False)
  368. else:
  369. _gw().print_info("Gateway service is not installed yet.")
  370. _gw().print_info("You'll be offered to install it after configuring platforms.")
  371. def _wizard_platform_loop() -> None:
  372. while True:
  373. print()
  374. _gw().print_header("Messaging Platforms")
  375. platforms = _gw()._all_platforms()
  376. menu_items = [f"{p['emoji']} {p['label']} ({_platform_status(p)})" for p in platforms] + ["Done"]
  377. choice = _gw().prompt_choice("Select a platform to configure:", menu_items, len(menu_items) - 1)
  378. if choice == len(platforms):
  379. break
  380. _gw()._configure_platform(platforms[choice])
  381. def _wizard_install_service(backend: str) -> None:
  382. """Fresh install from the wizard: ask start-now / start-on-login once, install, then start.
  383. The Windows installer owns its start decision (Scheduled Task and Startup-folder
  384. paths start the gateway themselves when start_now is true, and a UAC hand-off
  385. installs and starts in the elevated child), so the wizard forwards the answers
  386. and returns without a second start. Each install-intent question is asked exactly
  387. once per setup run."""
  388. wsl_note = " (note: services may not survive WSL restarts)" if _gw().is_wsl() else ""
  389. start_now = _gw().prompt_yes_no(" Start the gateway now?", True)
  390. start_on_login = _gw().prompt_yes_no(
  391. f" Start the gateway automatically on login/boot as a {_WIZARD_BACKEND_LABELS[backend]} service?"
  392. f"{wsl_note}",
  393. True,
  394. )
  395. if not (start_now or start_on_login):
  396. _gw().print_info(" Skipped start and auto-start setup.")
  397. _gw().print_info(" You can install later: hermes gateway install")
  398. if _gw().supports_systemd_services():
  399. _gw().print_info(" Or as a boot-time service: sudo hermes gateway install --system")
  400. _gw().print_info(" Or run in foreground: hermes gateway run")
  401. return
  402. try:
  403. installed_scope, did_install = None, True
  404. if backend == "systemd":
  405. installed_scope, did_install = _gw().install_linux_gateway_from_setup(
  406. force=False, enable_on_startup=start_on_login
  407. )
  408. elif backend == "launchd":
  409. _gw().launchd_install(force=False, start_now=start_now)
  410. else:
  411. _gw()._gw_windows().install(force=False, start_now=start_now, start_on_login=start_on_login)
  412. return
  413. print()
  414. if did_install and start_now:
  415. _gw()._setup_service_action("start", failed_label="Start failed", system=installed_scope == "system")
  416. except subprocess.CalledProcessError as e:
  417. _gw().print_error(f" Install failed: {e}")
  418. _gw().print_info(" You can try manually: hermes gateway install")
  419. except SystemExit:
  420. # The backend installers exit non-zero on a refused write (a unit pinning another home);
  421. # setup reports it and goes on rather than ending the wizard.
  422. _gw().print_warning(" Gateway service install did not complete.")
  423. _gw().print_info(" You can try manually: hermes gateway install")
  424. def _wizard_post_setup() -> None:
  425. """Offer to install/start/restart the gateway once at least one platform has progress."""
  426. print()
  427. print(_gw().color("─" * 58, _gw().Colors.DIM))
  428. if _gw()._served_profile_needs_no_service():
  429. return
  430. service_installed = _gw()._is_service_installed()
  431. service_running = _gw()._is_service_running()
  432. if service_running:
  433. _wizard_offer_service_action("restart", " Restart the gateway to pick up changes?", "Restart failed")
  434. elif service_installed:
  435. _wizard_offer_service_action("start", " Start the gateway service?", "Start failed")
  436. else:
  437. print()
  438. backend = _gw()._service_backend()
  439. if backend is not None:
  440. _gw()._wizard_install_service(backend)
  441. return
  442. if _gw().is_wsl():
  443. reason, home = "wsl", ""
  444. elif _gw().is_termux():
  445. from hermes_constants import display_hermes_home as _dhh
  446. reason, home = "termux", _dhh()
  447. else:
  448. reason, home = "unsupported", ""
  449. _gw()._print_info_lines(*(line.format(home=home) for line in _WIZARD_NO_SERVICE_LINES[reason]))
  450. def gateway_setup():
  451. """Interactive setup for messaging platforms + gateway service."""
  452. if _gw().is_managed():
  453. _gw().managed_error("run gateway setup")
  454. return
  455. print()
  456. for banner_line in _WIZARD_BANNER:
  457. print(_gw().color(banner_line, _gw().Colors.MAGENTA))
  458. _wizard_service_status_block()
  459. _wizard_platform_loop()
  460. # Meaningful progress on any platform; ``_platform_status`` already handles plugin dual states.
  461. def _is_progress(status: str) -> bool:
  462. s = status.lower()
  463. return not (s == "not configured" or s.startswith("partially") or s.startswith("plugin disabled"))
  464. if any(_is_progress(_gw()._platform_status(p)) for p in _gw()._all_platforms()):
  465. _gw()._wizard_post_setup()
  466. else:
  467. print()
  468. _gw().print_info("No platforms configured. Run 'hermes gateway setup' when ready.")
  469. print()