main_platform_setup.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. """Interactive messaging-platform setup wizards: WhatsApp (bridge + Cloud API), Slack manifest.
  2. Split out of ``hermes_cli/main.py``. Names that still live in main are imported lazily at call time.
  3. """
  4. import contextlib
  5. import shutil
  6. import subprocess
  7. import sys
  8. from hermes_cli.cli_output import line_input
  9. from hermes_cli.model_setup_flows_common import _say
  10. def _err(msg: str) -> None:
  11. print(msg, file=sys.stderr)
  12. def _yes_no(prompt: str) -> bool:
  13. """``[y/N]`` prompt; Ctrl-C/EOF counts as "no"."""
  14. try:
  15. response = input(prompt).strip()
  16. except (EOFError, KeyboardInterrupt):
  17. response = "n"
  18. return response.lower() in {"y", "yes"}
  19. def _whatsapp_choose_mode(get_env_value, save_env_value):
  20. """Step 1 of ``hermes whatsapp``: ``"bot"`` / ``"self-chat"``, or None when cancelled."""
  21. current_mode = get_env_value("WHATSAPP_MODE") or ""
  22. if current_mode:
  23. mode_label = "separate bot number" if current_mode == "bot" else "personal number (self-chat)"
  24. print(f"\n✓ Mode: {mode_label}")
  25. return current_mode
  26. _say("", "How will you use WhatsApp with Hermes?", "",
  27. " 1. Separate bot number (recommended)",
  28. " People message the bot's number directly — cleanest experience.",
  29. " Requires a second phone number with WhatsApp installed on a device.", "",
  30. " 2. Personal number (self-chat)",
  31. " You message yourself to talk to the agent.",
  32. " Quick to set up, but the UX is less intuitive.", "")
  33. try:
  34. choice = input(" Choose [1/2]: ").strip()
  35. except (EOFError, KeyboardInterrupt):
  36. print("\nSetup cancelled.")
  37. return None
  38. if choice == "1":
  39. save_env_value("WHATSAPP_MODE", "bot")
  40. _say(" ✓ Mode: separate bot number", "",
  41. " ┌─────────────────────────────────────────────────┐",
  42. " │ Getting a second number for the bot: │",
  43. " │ │",
  44. " │ Easiest: Install WhatsApp Business (free app) │",
  45. " │ on your phone with a second number: │",
  46. " │ • Dual-SIM: use your 2nd SIM slot │",
  47. " │ • Google Voice: free US number (voice.google) │",
  48. " │ • Prepaid SIM: $3-10, verify once │",
  49. " │ │",
  50. " │ WhatsApp Business runs alongside your personal │",
  51. " │ WhatsApp — no second phone needed. │",
  52. " └─────────────────────────────────────────────────┘")
  53. return "bot"
  54. save_env_value("WHATSAPP_MODE", "self-chat")
  55. print(" ✓ Mode: personal number (self-chat)")
  56. return "self-chat"
  57. def _whatsapp_allowed_users(wa_mode: str, get_env_value, save_env_value) -> None:
  58. """Step 3 of ``hermes whatsapp``: show / set WHATSAPP_ALLOWED_USERS."""
  59. current_users = get_env_value("WHATSAPP_ALLOWED_USERS") or ""
  60. if current_users:
  61. print(f"✓ Allowed users: {current_users}")
  62. if not _yes_no("\n Update allowed users? [y/N] "):
  63. return
  64. if wa_mode == "bot":
  65. phone = line_input(" Phone numbers that can message the bot (comma-separated): ").strip()
  66. else:
  67. phone = line_input(" Your phone number (e.g. 15551234567): ").strip()
  68. if phone:
  69. save_env_value("WHATSAPP_ALLOWED_USERS", phone.replace(" ", ""))
  70. print(f" ✓ Updated to: {phone}")
  71. return
  72. print()
  73. if wa_mode == "bot":
  74. print(" Who should be allowed to message the bot?")
  75. phone = line_input(" Phone numbers (comma-separated, or * for anyone): ").strip()
  76. else:
  77. phone = line_input(" Your phone number (e.g. 15551234567): ").strip()
  78. if phone:
  79. save_env_value("WHATSAPP_ALLOWED_USERS", phone.replace(" ", ""))
  80. print(f" ✓ Allowed users set: {phone}")
  81. else:
  82. print(" ⚠ No allowlist — the agent will respond to ALL incoming messages")
  83. def _whatsapp_install_bridge(bridge_dir) -> bool:
  84. """Step 4 of ``hermes whatsapp``: ``npm install`` the bridge when needed. False = stop."""
  85. from hermes_constants import find_node_executable, with_hermes_node_path
  86. if (bridge_dir / "node_modules").exists():
  87. print("✓ Bridge dependencies already installed")
  88. return True
  89. print("\n→ Installing WhatsApp bridge dependencies (this can take a few minutes)...")
  90. import pm
  91. npm = find_node_executable("npm")
  92. try:
  93. env = with_hermes_node_path()
  94. if npm is None:
  95. env = pm.ensure("npm", explicit=True).env
  96. installed = pm.installed_package("npm")
  97. if installed is None or installed.binary is None:
  98. raise pm.InstallError("npm", "npm binary is missing after preparation")
  99. npm = str(installed.binary)
  100. result = subprocess.run(
  101. [npm, "install", "--no-fund", "--no-audit", "--progress=false"],
  102. cwd=str(bridge_dir), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True,
  103. encoding="utf-8", errors="replace", env=env, check=False)
  104. except (pm.InstallError, OSError) as exc:
  105. print(f" ✗ Bridge dependency preparation failed: {exc}")
  106. return False
  107. except KeyboardInterrupt:
  108. print("\n ✗ Install cancelled")
  109. return False
  110. if result.returncode != 0:
  111. err = (result.stderr or "").strip()
  112. preview = "\n".join(err.splitlines()[-30:]) if err else "(no output)"
  113. _say(" ✗ npm install failed:", preview)
  114. return False
  115. print(" ✓ Dependencies installed")
  116. return True
  117. def cmd_whatsapp(args):
  118. """Set up WhatsApp: choose mode, configure, install bridge, pair via QR."""
  119. from hermes_cli.main import _require_tty, get_hermes_home
  120. _require_tty("whatsapp")
  121. from hermes_cli.config import get_env_value, save_env_value
  122. from hermes_constants import find_node_executable, with_hermes_node_path
  123. _say("", "☤ WhatsApp Setup", "=" * 50)
  124. wa_mode = _whatsapp_choose_mode(get_env_value, save_env_value)
  125. if wa_mode is None:
  126. return
  127. # WHATSAPP_ENABLED=true is deliberately NOT written here: an aborted wizard (Ctrl+C, failed npm
  128. # install, missed QR scan) would leave .env claiming WhatsApp is ready with no creds.json, and
  129. # every `hermes gateway` would pay a 30s bridge timeout + indefinite retries. Set only after
  130. # pairing succeeds; prior successful pairings stay enabled.
  131. print()
  132. if (get_env_value("WHATSAPP_ENABLED") or "").lower() == "true":
  133. print("✓ WhatsApp is already enabled")
  134. _whatsapp_allowed_users(wa_mode, get_env_value, save_env_value)
  135. from gateway.platforms.whatsapp_common import resolve_whatsapp_bridge_dir
  136. bridge_dir = resolve_whatsapp_bridge_dir()
  137. bridge_script = bridge_dir / "bridge.js"
  138. if not bridge_script.exists():
  139. print(f"\n✗ Bridge script not found at {bridge_script}")
  140. return
  141. if not _whatsapp_install_bridge(bridge_dir):
  142. return
  143. # Existing session: re-pair or keep.
  144. session_dir = get_hermes_home() / "whatsapp" / "session"
  145. session_dir.mkdir(parents=True, exist_ok=True)
  146. if (session_dir / "creds.json").exists():
  147. print("✓ Existing WhatsApp session found")
  148. if _yes_no("\n Re-pair? This will clear the existing session. [y/N] "):
  149. shutil.rmtree(session_dir, ignore_errors=True)
  150. session_dir.mkdir(parents=True, exist_ok=True)
  151. print(" ✓ Session cleared")
  152. else:
  153. # Older installs may have lost WHATSAPP_ENABLED; a kept pairing re-asserts it.
  154. if (get_env_value("WHATSAPP_ENABLED") or "").lower() != "true":
  155. save_env_value("WHATSAPP_ENABLED", "true")
  156. _say("\n✓ WhatsApp is configured and paired!", " Start the gateway with: hermes gateway")
  157. return
  158. # QR code pairing
  159. _say("", "─" * 50)
  160. if wa_mode == "bot":
  161. _say("📱 Open WhatsApp (or WhatsApp Business) on the", " phone with the BOT's number, then scan:")
  162. else:
  163. print("📱 Open WhatsApp on your phone, then scan:")
  164. _say("", " Settings → Linked Devices → Link a Device", "─" * 50, "")
  165. import pm
  166. node = find_node_executable("node")
  167. if node is None:
  168. try:
  169. pm.ensure("node", explicit=True)
  170. installed = pm.installed_package("node")
  171. if installed is None or installed.binary is None:
  172. raise pm.InstallError("node", "Node.js binary is missing after preparation")
  173. node = str(installed.binary)
  174. except pm.InstallError as exc:
  175. print(f" ✗ Node.js preparation failed: {exc}")
  176. return
  177. with contextlib.suppress(KeyboardInterrupt):
  178. subprocess.run(
  179. [node, str(bridge_script), "--pair-only", "--session", str(session_dir)],
  180. cwd=str(bridge_dir), env=with_hermes_node_path(), check=False)
  181. print()
  182. if not (session_dir / "creds.json").exists():
  183. print("⚠ Pairing may not have completed. Run 'hermes whatsapp' to try again.")
  184. return
  185. # Only enable WhatsApp now that pairing actually succeeded (see above).
  186. save_env_value("WHATSAPP_ENABLED", "true")
  187. _say("✓ WhatsApp paired successfully!", "")
  188. if wa_mode == "bot":
  189. _say(" Next steps:", " 1. Start the gateway: hermes gateway",
  190. " 2. Send a message to the bot's WhatsApp number",
  191. " 3. The agent will reply automatically", "",
  192. " Tip: Agent responses are prefixed with '☤ Hermes Agent'")
  193. else:
  194. _say(" Next steps:", " 1. Start the gateway: hermes gateway",
  195. " 2. Open WhatsApp → Message Yourself",
  196. " 3. Type a message — the agent will reply", "",
  197. " Tip: Agent responses are prefixed with '☤ Hermes Agent'",
  198. " so you can tell them apart from your own messages.")
  199. _say("", " Or install as a service: hermes gateway install")
  200. def cmd_whatsapp_cloud(args):
  201. """Set up WhatsApp Business Cloud API (official Meta integration) — complementary to the
  202. ``hermes whatsapp`` Baileys bridge wizard. See ``plugins/platforms/whatsapp_cloud/setup_wizard.py``."""
  203. from hermes_cli.main import _require_tty
  204. _require_tty("whatsapp-cloud")
  205. from plugins.platforms.whatsapp_cloud.setup_wizard import run_whatsapp_cloud_setup
  206. return run_whatsapp_cloud_setup()
  207. def cmd_slack(args):
  208. """``hermes slack <subcommand>``; ``manifest`` prints or writes a Slack app manifest with
  209. every gateway command registered as a first-class slash."""
  210. sub = getattr(args, "slack_command", None)
  211. if sub in {None, ""}:
  212. _err("usage: hermes slack <subcommand>\n"
  213. "\n"
  214. "subcommands:\n"
  215. " manifest Generate a Slack app manifest with every gateway\n"
  216. " command registered as a native slash\n"
  217. "\n"
  218. "Run `hermes slack manifest -h` for details.")
  219. return 1
  220. if sub == "manifest":
  221. from hermes_cli.slack_cli import slack_manifest_command
  222. status = slack_manifest_command(args)
  223. if status:
  224. raise SystemExit(status)
  225. return status
  226. _err(f"Unknown slack subcommand: {sub}")
  227. return 1