process_manager.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. """Subprocess lifecycle manager for the google_meet bot.
  2. One active meeting at a time, recorded in ``$HERMES_HOME/workspace/meetings/.active.json``
  3. (``pid, meeting_id, out_dir, url, started_at, session_id, log_path, mode``) so tool calls
  4. across turns can find the bot. The bot is a detached subprocess reached via files only
  5. (``<meeting-id>/status.json``, ``<meeting-id>/transcript.txt``), so the agent loop can't block.
  6. """
  7. from __future__ import annotations
  8. import contextlib
  9. import json
  10. import os
  11. import signal
  12. import subprocess
  13. import sys
  14. import time
  15. import uuid
  16. from pathlib import Path
  17. from typing import Any, Dict, Optional
  18. from hermes_constants import get_hermes_home
  19. from plugins.google_meet._jsonfile import say_queue_lock
  20. from utils import atomic_json_write
  21. def _root() -> Path:
  22. return Path(get_hermes_home()) / "workspace" / "meetings"
  23. def _active_file() -> Path:
  24. return _root() / ".active.json"
  25. def _read_active() -> Optional[dict[str, Any]]:
  26. p = _active_file()
  27. if not p.is_file():
  28. return None
  29. try:
  30. return json.loads(p.read_text(encoding="utf-8-sig"))
  31. except Exception:
  32. return None
  33. def _write_active(data: dict[str, Any]) -> None:
  34. atomic_json_write(_active_file(), data)
  35. def _pid_alive(pid: int) -> bool:
  36. # Not ``os.kill(pid, 0)``: on Windows that can kill the target (bpo-14484).
  37. from gateway.status import _pid_exists
  38. return bool(pid) and _pid_exists(pid)
  39. def _kill(pid: int, sig) -> None:
  40. with contextlib.suppress(ProcessLookupError):
  41. os.kill(pid, sig)
  42. _NO_ACTIVE = {"ok": False, "reason": "no active meeting"}
  43. def start(url: str, *, out_dir: Optional[Path] = None, headed: bool = False,
  44. auth_state: Optional[str] = None, guest_name: str = "Hermes Agent", duration: Optional[str] = None,
  45. session_id: Optional[str] = None, mode: str = "transcribe", realtime_model: Optional[str] = None,
  46. realtime_voice: Optional[str] = None, realtime_instructions: Optional[str] = None,
  47. realtime_api_key: Optional[str] = None) -> dict[str, Any]:
  48. """Spawn the meet_bot subprocess for *url*, stopping any running bot first (one active meeting)."""
  49. from plugins.google_meet.meet_bot import _is_safe_meet_url, _meeting_id_from_url
  50. if not _is_safe_meet_url(url):
  51. return {"ok": False, "error": "refusing: only https://meet.google.com/ URLs are allowed. got: " + repr(url)}
  52. if _pid_alive(int((_read_active() or {}).get("pid", 0))):
  53. stop(reason="replaced by new meet_join")
  54. meeting_id = _meeting_id_from_url(url)
  55. out = out_dir or (_root() / meeting_id)
  56. out.mkdir(parents=True, exist_ok=True)
  57. # Wipe stale files from a previous run of this meeting id.
  58. for name in ("transcript.txt", "status.json"):
  59. with contextlib.suppress(OSError):
  60. (out / name).unlink()
  61. env = {**os.environ, "HERMES_MEET_URL": url, "HERMES_MEET_OUT_DIR": str(out),
  62. "HERMES_MEET_GUEST_NAME": guest_name}
  63. for value, var in (
  64. (headed and "1", "HERMES_MEET_HEADED"),
  65. (auth_state, "HERMES_MEET_AUTH_STATE"),
  66. (duration, "HERMES_MEET_DURATION"),
  67. (mode, "HERMES_MEET_MODE"), # bot defaults to transcribe when unset (v1 behavior)
  68. (realtime_model, "HERMES_MEET_REALTIME_MODEL"),
  69. (realtime_voice, "HERMES_MEET_REALTIME_VOICE"),
  70. (realtime_instructions, "HERMES_MEET_REALTIME_INSTRUCTIONS")):
  71. if value:
  72. env[var] = value
  73. # Resolve the realtime key at SPAWN time in the parent, where the profile secret scope
  74. # (a contextvar) is installed; the detached child inherits env, not scope.
  75. if not realtime_api_key:
  76. from agent.secret_scope import get_secret
  77. realtime_api_key = get_secret("HERMES_MEET_REALTIME_KEY") or get_secret("OPENAI_API_KEY")
  78. if realtime_api_key:
  79. env["HERMES_MEET_REALTIME_KEY"] = realtime_api_key
  80. log_path = out / "bot.log"
  81. # Detach: stdout/stderr → log file, new session so parent signals don't propagate.
  82. with open(log_path, "ab", buffering=0) as log_fh:
  83. proc = subprocess.Popen([sys.executable, "-P", "-m", "plugins.google_meet.meet_bot"], stdin=subprocess.DEVNULL,
  84. # detached-spawn: ok — reached via files across turns, stopped by meet_leave (pid in .active.json)
  85. stdout=log_fh, stderr=subprocess.STDOUT, env=env, start_new_session=True,
  86. close_fds=True)
  87. record = {"pid": proc.pid, "meeting_id": meeting_id, "out_dir": str(out), "url": url,
  88. "started_at": time.time(), "session_id": session_id, "log_path": str(log_path), "mode": mode}
  89. _write_active(record)
  90. return {"ok": True, **record}
  91. def status() -> dict[str, Any]:
  92. """Return the current meeting state, or ``{"ok": False, "reason": ...}``."""
  93. active = _read_active()
  94. if not active:
  95. return dict(_NO_ACTIVE)
  96. pid = int(active.get("pid", 0))
  97. alive = _pid_alive(pid) if pid else False
  98. status_path = Path(active.get("out_dir", "")) / "status.json"
  99. bot_status: dict[str, Any] = {}
  100. if status_path.is_file():
  101. try:
  102. bot_status = json.loads(status_path.read_text(encoding="utf-8-sig"))
  103. except Exception:
  104. pass
  105. return {
  106. "ok": True,
  107. "alive": alive,
  108. "pid": pid,
  109. "meetingId": active.get("meeting_id"),
  110. "url": active.get("url"),
  111. "startedAt": active.get("started_at"),
  112. "outDir": active.get("out_dir"),
  113. **bot_status,
  114. }
  115. def transcript(last: Optional[int] = None) -> dict[str, Any]:
  116. """Read the current transcript file (empty result if the bot hasn't written one yet)."""
  117. active = _read_active()
  118. if not active:
  119. return dict(_NO_ACTIVE)
  120. tp = Path(active.get("out_dir", "")) / "transcript.txt"
  121. if not tp.is_file():
  122. return {
  123. "ok": True,
  124. "meetingId": active.get("meeting_id"),
  125. "lines": [],
  126. "total": 0,
  127. "path": str(tp),
  128. }
  129. text = tp.read_text(encoding="utf-8-sig", errors="replace")
  130. all_lines = [ln for ln in text.splitlines() if ln.strip()]
  131. return {"ok": True, "meetingId": active.get("meeting_id"),
  132. "lines": all_lines[-last:] if last else all_lines, "total": len(all_lines), "path": str(tp)}
  133. def enqueue_say(text: str) -> dict[str, Any]:
  134. """Append a ``say`` request to ``<out_dir>/say_queue.jsonl``.
  135. Refused when no meeting is active or the active bot is transcribe-only."""
  136. text = (text or "").strip()
  137. if not text:
  138. return {"ok": False, "reason": "text is required"}
  139. active = _read_active()
  140. if not active:
  141. return dict(_NO_ACTIVE)
  142. if active.get("mode") != "realtime":
  143. return {"ok": False, "reason": ("active meeting is in transcribe mode — pass mode='realtime' "
  144. "to meet_join to enable agent speech")}
  145. out_dir = Path(active.get("out_dir", ""))
  146. if not out_dir.is_dir():
  147. return {"ok": False, "reason": f"out_dir missing: {out_dir}"}
  148. queue_path = out_dir / "say_queue.jsonl"
  149. entry = {"id": uuid.uuid4().hex[:12], "text": text}
  150. with say_queue_lock(queue_path), queue_path.open("a", encoding="utf-8") as f:
  151. f.write(json.dumps(entry) + "\n")
  152. return {"ok": True, "meetingId": active.get("meeting_id"), "enqueued_id": entry["id"],
  153. "queue_path": str(queue_path)}
  154. def stop(*, reason: str = "requested") -> dict[str, Any]:
  155. """SIGTERM the active bot (SIGKILL after 10s), then clear the active pointer."""
  156. active = _read_active()
  157. if not active:
  158. return dict(_NO_ACTIVE)
  159. pid = int(active.get("pid", 0))
  160. out_dir = active.get("out_dir")
  161. if _pid_alive(pid):
  162. _kill(pid, signal.SIGTERM)
  163. for _ in range(20):
  164. if not _pid_alive(pid):
  165. break
  166. time.sleep(0.5)
  167. else:
  168. _kill(pid, signal.SIGKILL) # windows-footgun: ok — POSIX-only plugin (google_meet registers no-op on Windows; see __init__.py)
  169. _active_file().unlink(missing_ok=True)
  170. return {"ok": True, "reason": reason, "meetingId": active.get("meeting_id"),
  171. "transcriptPath": str(Path(out_dir) / "transcript.txt") if out_dir else None}