cli.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. """CLI commands for the google_meet plugin (``hermes meet <subcommand>``).
  2. setup / install — preflight and install prerequisites
  3. auth — open a browser to sign into Google, save storage state
  4. join <url> — join a Meet URL (locally or on a remote node)
  5. status / transcript / say / stop — drive the active bot
  6. node — remote node host management (see node/cli.py)
  7. """
  8. from __future__ import annotations
  9. import argparse
  10. import contextlib
  11. import importlib.util
  12. import json
  13. import platform
  14. import shutil
  15. import subprocess
  16. import sys
  17. from pathlib import Path
  18. from typing import Optional
  19. from hermes_cli.browser_runtime import chromium_executable
  20. from hermes_constants import get_hermes_home
  21. from plugins.google_meet import process_manager as pm
  22. from plugins.google_meet.meet_bot import _is_safe_meet_url
  23. from plugins.google_meet.node.cli import node_command, register_cli as _register_node_cli
  24. from plugins.google_meet.tools import resolve_node
  25. def _auth_state_path() -> Path:
  26. return Path(get_hermes_home()) / "workspace" / "meetings" / "auth.json"
  27. # ``hermes meet <sub>`` in help order.
  28. _SUBCOMMAND_HELP = (
  29. ("setup", "Preflight: playwright, chromium, auth"),
  30. ("install", "Install prerequisites (Python dependencies, Chromium, platform audio tools)"),
  31. ("auth", "Sign in to Google and save session state"),
  32. ("join", "Join a Meet URL"),
  33. ("status", "Print current Meet bot state"),
  34. ("transcript", "Print the scraped transcript"),
  35. ("say", "Speak text in an active realtime meeting"),
  36. ("stop", "Leave the current meeting"),
  37. ("node", "Manage remote meet node hosts (run/list/approve/remove/status/ping)"))
  38. def register_cli(subparser: argparse.ArgumentParser) -> None:
  39. """Build the ``hermes meet`` argparse tree (called at plugin load time)."""
  40. subs = subparser.add_subparsers(dest="meet_command")
  41. p = {name: subs.add_parser(name, help=help_) for name, help_ in _SUBCOMMAND_HELP}
  42. p["install"].add_argument("--realtime", action="store_true",
  43. help="Also install realtime audio tools (pulseaudio-utils on Linux, BlackHole+ffmpeg on macOS). Uses sudo/brew, prompts before invoking either.")
  44. p["install"].add_argument("--yes", "-y", action="store_true",
  45. help="Answer yes to all prompts (use with care; will run sudo apt-get or brew without asking).")
  46. p["join"].add_argument("url", help="https://meet.google.com/...")
  47. p["join"].add_argument("--guest-name", default="Hermes Agent")
  48. p["join"].add_argument("--duration", default=None, help="e.g. 30m, 2h, 90s")
  49. p["join"].add_argument("--headed", action="store_true", help="show browser")
  50. p["join"].add_argument("--mode", choices=("transcribe", "realtime"), default="transcribe",
  51. help="transcribe (default, listen-only) or realtime (speak via OpenAI Realtime)")
  52. p["join"].add_argument("--node", default=None,
  53. help="remote node name, or 'auto' to use the sole registered node")
  54. p["transcript"].add_argument("--last", type=int, default=None)
  55. p["say"].add_argument("text", help="what to say")
  56. p["say"].add_argument("--node", default=None)
  57. _register_node_cli(p["node"])
  58. subparser.set_defaults(func=meet_command)
  59. _DISPATCH = {
  60. "setup": lambda a: _cmd_setup(),
  61. "install": lambda a: _cmd_install(realtime=bool(a.realtime), assume_yes=bool(a.yes)),
  62. "auth": lambda a: _cmd_auth(),
  63. "join": lambda a: _cmd_join(url=a.url, guest_name=a.guest_name, duration=a.duration, headed=a.headed,
  64. mode=a.mode, node=a.node),
  65. "status": lambda a: _print_result(pm.status()),
  66. "transcript": lambda a: _cmd_transcript(last=a.last),
  67. "say": lambda a: _cmd_say(text=a.text, node=a.node),
  68. "stop": lambda a: _print_result(pm.stop(reason="hermes meet stop")),
  69. "node": node_command} # node subparsers are required=True, so a sub-command is always present
  70. def meet_command(args: argparse.Namespace) -> int:
  71. sub = args.meet_command
  72. if not sub:
  73. print("usage: hermes meet {setup,auth,join,status,transcript,say,stop,node}")
  74. return 2
  75. handler = _DISPATCH.get(sub)
  76. if handler is None:
  77. print(f"unknown subcommand: {sub}")
  78. return 2
  79. return handler(args)
  80. def _cmd_setup() -> int:
  81. print("google_meet preflight\n---------------------")
  82. system = platform.system()
  83. system_ok = system in {"Linux", "Darwin"}
  84. print(f" platform : {system} [{'ok' if system_ok else 'unsupported'}]")
  85. pw_ok = importlib.util.find_spec("playwright") is not None
  86. print(" playwright : " + ("installed" if pw_ok else "NOT installed — run: hermes meet install"))
  87. chromium_ok, chromium_msg = False, "unknown"
  88. if pw_ok:
  89. try:
  90. from playwright.sync_api import sync_playwright
  91. with sync_playwright() as p:
  92. exe = chromium_executable() or p.chromium.executable_path
  93. chromium_ok = bool(exe and Path(exe).exists())
  94. chromium_msg = f"ok ({exe})" if chromium_ok else "not installed — run: hermes meet install"
  95. except Exception as e:
  96. chromium_msg = f"probe failed: {e}"
  97. print(f" chromium : {chromium_msg}")
  98. auth_path = _auth_state_path()
  99. print(" google auth : " + (f"ok ({auth_path})" if auth_path.is_file() else "not saved — run: hermes meet auth"))
  100. print()
  101. all_ok = system_ok and pw_ok and chromium_ok
  102. print("ready. Join a meeting: hermes meet join https://meet.google.com/abc-defg-hij" if all_ok
  103. else "not ready yet — fix the items above.")
  104. return 0 if all_ok else 1
  105. def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
  106. """PM dependencies + Chromium; ``--realtime`` adds platform audio tools.
  107. Prompts before system package-manager invocations unless ``--yes``."""
  108. system = platform.system()
  109. if system not in {"Linux", "Darwin"}:
  110. print(f"google_meet install: {system} is not supported (linux/macos only)")
  111. return 1
  112. def _install_pkgs(prompt: str, cmd: list[str], fail_msg: str) -> None:
  113. """Confirm (unless --yes) then run a package-manager command, reporting failure."""
  114. try:
  115. ok = assume_yes or input(f"{prompt} [y/N] ").strip().lower() in {"y", "yes"}
  116. except EOFError:
  117. ok = False
  118. if not ok:
  119. print(" skipped (you can run it manually later)")
  120. return
  121. print(f" $ {' '.join(cmd)}")
  122. # sudo/brew may prompt on the tty; the user explicitly confirmed above.
  123. if subprocess.run(cmd, check=False, stdin=None).returncode != 0:
  124. print(fail_msg)
  125. print("google_meet install\n-------------------")
  126. print("\n[1/3] Python dependencies (google-meet extra)")
  127. try:
  128. import pm as package_manager
  129. package_manager.sync_venv(["google-meet"], explicit=True)
  130. except Exception as exc:
  131. print(f" dependency install failed: {exc}")
  132. return 1
  133. print("\n[2/3] PM-managed Chromium")
  134. try:
  135. package_manager.ensure("chromium", explicit=True)
  136. except Exception as exc:
  137. print(f" Chromium install failed: {exc}")
  138. return 1
  139. if not realtime:
  140. print("\n[3/3] skipped (pass --realtime to install audio tooling too)")
  141. else:
  142. print("\n[3/3] realtime audio deps")
  143. if system == "Linux":
  144. if shutil.which("paplay") and shutil.which("pactl"):
  145. print(" pulseaudio-utils already installed.")
  146. else:
  147. _install_pkgs(" install pulseaudio-utils? this runs `sudo apt-get install -y pulseaudio-utils`",
  148. ["sudo", "apt-get", "install", "-y", "pulseaudio-utils"],
  149. " apt install failed — install pulseaudio-utils manually")
  150. elif system == "Darwin":
  151. try:
  152. have_bh = "BlackHole" in subprocess.check_output(
  153. ["system_profiler", "SPAudioDataType"], text=True, encoding='utf-8', errors='replace',
  154. stdin=subprocess.DEVNULL)
  155. except Exception:
  156. have_bh = False
  157. needs = [pkg for pkg, have in (("blackhole-2ch", have_bh), ("ffmpeg", shutil.which("ffmpeg"))) if not have]
  158. if not needs:
  159. print(" BlackHole and ffmpeg already installed.")
  160. elif not shutil.which("brew"):
  161. print(" missing: " + ", ".join(needs) + "\n"
  162. " install Homebrew first (https://brew.sh) or install the packages manually.")
  163. else:
  164. _install_pkgs(f" install via brew: {' '.join(needs)}?", ["brew", "install", *needs],
  165. " brew install failed — install them manually")
  166. print("\n NOTE: macOS does not auto-route audio. Open\n System Settings → Sound → "
  167. "Input\n and select 'BlackHole 2ch' before starting a realtime meeting.\n "
  168. "hermes will not switch your default input for you.")
  169. print("\ndone. verify with: hermes meet setup")
  170. return 0
  171. def _cmd_auth() -> int:
  172. """Open a headed Chromium, let the user sign in, save storage_state."""
  173. try:
  174. from playwright.sync_api import sync_playwright
  175. except ImportError:
  176. print("playwright is not installed. Run: hermes meet install")
  177. return 1
  178. path = _auth_state_path()
  179. path.parent.mkdir(parents=True, exist_ok=True)
  180. print("opening Chromium — sign in to Google, then return here and press Enter.\n"
  181. f"saving storage state to: {path}")
  182. try:
  183. with sync_playwright() as pw:
  184. browser = pw.chromium.launch(
  185. channel="chromium", executable_path=chromium_executable(), headless=False,
  186. )
  187. context = browser.new_context()
  188. context.new_page().goto("https://accounts.google.com/", wait_until="domcontentloaded")
  189. with contextlib.suppress(EOFError):
  190. input("press Enter after you've signed in ... ")
  191. context.storage_state(path=str(path))
  192. browser.close()
  193. except Exception as e:
  194. print(f"auth failed: {e}")
  195. return 1
  196. print("saved. you can now run: hermes meet join <url>")
  197. return 0
  198. def _print_result(res: dict) -> int:
  199. print(json.dumps(res, indent=2))
  200. return 0 if res.get("ok") else 1
  201. def _remote(node: str, op: str, call) -> int:
  202. """Run *call(client)* against the registered node *node* and print the result."""
  203. try:
  204. client, name = resolve_node(node)
  205. except ImportError as e:
  206. print(f"node module unavailable: {e}")
  207. return 1
  208. if client is None:
  209. print(f"no registered node matches {node!r}")
  210. return 1
  211. try:
  212. res = call(client)
  213. except Exception as e:
  214. print(f"remote {op} failed: {e}")
  215. return 1
  216. return _print_result({"node": name, **res})
  217. def _cmd_join(url: str, *, guest_name: str, duration: Optional[str], headed: bool,
  218. mode: str = "transcribe", node: Optional[str] = None) -> int:
  219. if not _is_safe_meet_url(url):
  220. print(f"refusing: not a meet.google.com URL: {url}")
  221. return 2
  222. if node:
  223. return _remote(node, "start_bot", lambda c: c.start_bot(
  224. url=url, guest_name=guest_name, duration=duration, headed=headed, mode=mode))
  225. auth = _auth_state_path()
  226. return _print_result(pm.start(url=url, headed=headed, guest_name=guest_name, duration=duration,
  227. auth_state=str(auth) if auth.is_file() else None, mode=mode))
  228. def _cmd_say(text: str, node: Optional[str] = None) -> int:
  229. if not (text or "").strip():
  230. print("refusing: empty text")
  231. return 2
  232. if node:
  233. return _remote(node, "say", lambda c: c.say(text))
  234. return _print_result(pm.enqueue_say(text))
  235. def _cmd_transcript(last: Optional[int]) -> int:
  236. res = pm.transcript(last=last)
  237. if not res.get("ok"):
  238. return _print_result(res)
  239. for ln in res.get("lines", []):
  240. print(ln)
  241. return 0
  242. if __name__ == "__main__": # pragma: no cover
  243. parser = argparse.ArgumentParser(prog="hermes meet")
  244. register_cli(parser)
  245. sys.exit(meet_command(parser.parse_args()))