client.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. """Gateway-side RPC client for a remote meet node: one short-lived sync WebSocket per call, so
  2. non-async tool handlers need no persistent connection. ``websockets`` is imported lazily."""
  3. from __future__ import annotations
  4. from typing import Any, Dict, Optional
  5. from plugins.google_meet.node import protocol as _proto
  6. class NodeClient:
  7. """Thin synchronous WS client matching the server's request surface."""
  8. def __init__(self, url: str, token: str, timeout: float = 10.0) -> None:
  9. if not isinstance(url, str) or not url:
  10. raise ValueError("url must be a non-empty string")
  11. if not isinstance(token, str) or not token:
  12. raise ValueError("token must be a non-empty string")
  13. self.url = url
  14. self.token = token
  15. self.timeout = float(timeout)
  16. def _rpc(self, type: str, payload: dict[str, Any]) -> dict[str, Any]:
  17. """Send one request, return its payload dict; RuntimeError on error envelope / id mismatch."""
  18. try:
  19. from websockets.sync.client import connect # type: ignore
  20. except ImportError as exc:
  21. raise RuntimeError("NodeClient requires the 'websockets' package. "
  22. "Install it with: pip install websockets") from exc
  23. req = _proto.make_request(type, self.token, payload)
  24. with connect(self.url, open_timeout=self.timeout, close_timeout=self.timeout) as ws:
  25. ws.send(_proto.encode(req))
  26. resp = _proto.decode(ws.recv(timeout=self.timeout))
  27. if resp.get("type") == "error":
  28. raise RuntimeError(f"node error: {resp.get('error', '<unknown>')}")
  29. if resp.get("id") != req["id"]:
  30. raise RuntimeError(f"response id mismatch: sent {req['id']}, got {resp.get('id')!r}")
  31. payload_out = resp.get("payload")
  32. if not isinstance(payload_out, dict): # pong envelopes also carry a dict payload
  33. raise RuntimeError("response missing payload dict")
  34. return payload_out
  35. def start_bot(self, url: str, guest_name: str = "Hermes Agent", duration: Optional[str] = None,
  36. headed: bool = False, mode: str = "transcribe") -> dict[str, Any]:
  37. payload: dict[str, Any] = {"url": url, "guest_name": guest_name, "headed": bool(headed), "mode": mode}
  38. if duration is not None:
  39. payload["duration"] = duration
  40. return self._rpc("start_bot", payload)
  41. def stop(self) -> dict[str, Any]:
  42. return self._rpc("stop", {})
  43. def status(self) -> dict[str, Any]:
  44. return self._rpc("status", {})
  45. def transcript(self, last: Optional[int] = None) -> dict[str, Any]:
  46. return self._rpc("transcript", {} if last is None else {"last": int(last)})
  47. def say(self, text: str) -> dict[str, Any]:
  48. return self._rpc("say", {"text": str(text)})
  49. def ping(self) -> dict[str, Any]:
  50. return self._rpc("ping", {})