server.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """Remote node server — hosts the Meet bot on another machine (``hermes meet node run``).
  2. WebSocket endpoint accepting token-signed RPC requests dispatched to ``process_manager``.
  3. Token: 32 hex chars minted on first boot, persisted at ``$HERMES_HOME/workspace/meetings/
  4. node_token.json`` so approved gateways survive restarts; the operator copies it to the gateway
  5. via ``hermes meet node approve <name> <url> <token>``. ``websockets`` is imported lazily.
  6. """
  7. from __future__ import annotations
  8. import asyncio
  9. import contextlib
  10. import json
  11. import secrets
  12. import time
  13. from pathlib import Path
  14. from typing import Any, Dict, Optional
  15. from hermes_constants import get_hermes_home
  16. from plugins.google_meet._jsonfile import read_json, say_queue_lock
  17. from utils import atomic_json_write
  18. from plugins.google_meet.node import protocol as _proto
  19. _START_BOT_KEYS = ("url", "guest_name", "duration", "headed", "auth_state", "session_id", "out_dir")
  20. class _RpcError(Exception):
  21. """Handler-level protocol error; sent verbatim as an error envelope."""
  22. def _rpc_start_bot(payload: dict[str, Any], pm) -> dict[str, Any]:
  23. # Whitelist kwargs we pass through to pm.start.
  24. kwargs = {k: payload[k] for k in _START_BOT_KEYS if k in payload}
  25. if "url" not in kwargs:
  26. raise _RpcError("missing 'url' in payload")
  27. return pm.start(**kwargs)
  28. def _rpc_say(payload: dict[str, Any], pm) -> dict[str, Any]:
  29. # The bot-side consumer only exists in realtime mode: ok=True means "enqueued", not "spoken".
  30. text = payload.get("text", "")
  31. active = pm._read_active()
  32. enqueued = False
  33. if active and active.get("out_dir"):
  34. with contextlib.suppress(OSError):
  35. queue = Path(active["out_dir"]) / "say_queue.jsonl"
  36. queue.parent.mkdir(parents=True, exist_ok=True)
  37. with say_queue_lock(queue), queue.open("a", encoding="utf-8") as fh:
  38. fh.write(json.dumps({"text": text, "ts": time.time()}) + "\n")
  39. enqueued = True
  40. return {"ok": True, "enqueued": enqueued, "text": text}
  41. # request type → fn(payload, pm) returning the response payload.
  42. _RPC = {
  43. "start_bot": _rpc_start_bot,
  44. "stop": lambda p, pm: pm.stop(reason=p.get("reason", "requested")),
  45. "status": lambda p, pm: pm.status(),
  46. "transcript": lambda p, pm: pm.transcript(last=p.get("last")),
  47. "say": _rpc_say}
  48. class NodeServer:
  49. """WebSocket server that executes meet bot RPCs locally."""
  50. def __init__(self, host: str = "127.0.0.1", port: int = 18789, token_path: Optional[Path] = None,
  51. display_name: str = "hermes-meet-node") -> None:
  52. self.host = host
  53. self.port = port
  54. self.display_name = display_name
  55. self.token_path = Path(token_path) if token_path is not None else (
  56. Path(get_hermes_home()) / "workspace" / "meetings" / "node_token.json")
  57. self._token: Optional[str] = None
  58. def ensure_token(self) -> str:
  59. """Return the persisted shared secret, generating one on first use."""
  60. if self._token:
  61. return self._token
  62. data = read_json(self.token_path)
  63. tok = data.get("token") if isinstance(data, dict) else None
  64. if not (isinstance(tok, str) and tok):
  65. tok = secrets.token_hex(16) # 32 hex chars
  66. # Owner-only: the token grants full RPC access to the meet bot.
  67. atomic_json_write(self.token_path, {"token": tok, "generated_at": time.time()}, mode=0o600)
  68. self._token = tok
  69. return tok
  70. async def _handle_request(self, msg: dict[str, Any]) -> dict[str, Any]:
  71. """Validate + dispatch one decoded request; always returns an envelope, never raises.
  72. Envelope ``error`` is for auth/protocol failures and pm crashes; pm's own ``ok``/``error``
  73. results travel inside a normal response payload."""
  74. ok, reason = _proto.validate_request(msg, self.ensure_token())
  75. if not ok:
  76. return _proto.make_error(str(msg.get("id") or ""), reason)
  77. req_id, t = msg["id"], msg["type"]
  78. if t == "ping":
  79. return {"type": "pong", "id": req_id,
  80. "payload": {"display_name": self.display_name, "ts": time.time()}}
  81. handler = _RPC.get(t)
  82. if handler is None:
  83. return _proto.make_error(req_id, f"unhandled type: {t!r}")
  84. # Import lazily so test mocks can monkeypatch freely.
  85. from plugins.google_meet import process_manager as pm
  86. try:
  87. return _proto.make_response(req_id, handler(msg["payload"], pm))
  88. except _RpcError as exc:
  89. return _proto.make_error(req_id, str(exc))
  90. except Exception as exc:
  91. return _proto.make_error(req_id, f"{type(exc).__name__}: {exc}")
  92. async def serve(self) -> None:
  93. """Run the WebSocket server until cancelled (wrap in ``asyncio.run``)."""
  94. try:
  95. import websockets # type: ignore
  96. except ImportError as exc:
  97. raise RuntimeError("NodeServer.serve requires the 'websockets' package. "
  98. "Install it with: pip install websockets") from exc
  99. self.ensure_token()
  100. async def _handler(ws):
  101. async for raw in ws:
  102. try:
  103. msg = _proto.decode(raw)
  104. except ValueError as exc:
  105. await ws.send(_proto.encode(_proto.make_error("", f"decode: {exc}")))
  106. continue
  107. await ws.send(_proto.encode(await self._handle_request(msg)))
  108. async with websockets.serve(_handler, self.host, self.port):
  109. await asyncio.Future() # run until cancelled