Skip to content

The agent that grows with you

refactor(plugins/google_meet,disk-cleanup): fold try/except into _quiet/suppress, hoist context args, repack schema strings (bytes unchanged)

Teknium5f70de0d5922
diff --git a/plugins/disk-cleanup/disk_cleanup.py b/plugins/disk-cleanup/disk_cleanup.py
index 15db509b495..28a2a4c2089 100755
--- a/plugins/disk-cleanup/disk_cleanup.py
+++ b/plugins/disk-cleanup/disk_cleanup.py
@@ -16,15 +16,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional, Tuple
-try:
- from hermes_constants import get_hermes_home
-except Exception: # pragma: no cover — plugin may load before constants resolves
- import os
-
- def get_hermes_home() -> Path: # type: ignore[no-redef]
- val = (os.environ.get("HERMES_HOME") or "").strip()
- return Path(val).resolve() if val else (Path.home() / ".hermes").resolve()
-
+from hermes_constants import get_hermes_home
logger = logging.getLogger(__name__)
@@ -47,14 +39,12 @@ def is_safe_path(path: Path) -> bool:
def _log(message: str) -> None:
"""Append to the audit log; never let it break the agent loop."""
- try:
+ with contextlib.suppress(OSError):
log_file = _state_file("cleanup.log")
log_file.parent.mkdir(parents=True, exist_ok=True)
ts = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
with open(log_file, "a", encoding="utf-8") as f:
f.write(f"[{ts}] {message}\n")
- except OSError:
- pass
def load_tracked() -> List[Dict[str, Any]]:
@@ -63,18 +53,14 @@ def load_tracked() -> List[Dict[str, Any]]:
tf.parent.mkdir(parents=True, exist_ok=True)
if not tf.exists():
return []
- try:
+ with contextlib.suppress(ValueError):
return json.loads(tf.read_text(encoding="utf-8"))
- except (json.JSONDecodeError, ValueError):
- pass
bak = tf.with_suffix(".json.bak")
if bak.exists():
- try:
+ with contextlib.suppress(Exception):
data = json.loads(bak.read_text(encoding="utf-8"))
_log("WARN: tracked.json corrupted — restored from .bak")
return data
- except Exception:
- pass
_log("WARN: tracked.json corrupted, no backup — starting fresh")
return []
@@ -221,8 +207,7 @@ _STALE_SKIP_NOTE = {"cron-output": "", "test": " — under protected tree"}
def dry_run() -> Tuple[List[Dict], List[Dict]]:
"""Return (auto_delete_list, needs_prompt_list) without touching files."""
- auto: List[Dict] = []
- prompt: List[Dict] = []
+ auto, prompt = [], []
for item, p, age in _live_items(load_tracked(), datetime.now(timezone.utc)):
cat = item["category"]
# Stale cron-output entries are skipped by quick(); omit them here too.
@@ -331,7 +316,7 @@ def guess_category(path: Path) -> Optional[str]:
"""Category label for *path*, or None if we shouldn't track it (``post_tool_call`` hook)."""
if not is_safe_path(path):
return None
- try:
+ with contextlib.suppress(ValueError): # not under HERMES_HOME (/tmp/hermes-*) — name rules only
rel = path.resolve().relative_to(get_hermes_home())
top = rel.parts[0] if rel.parts else ""
if top in _NEVER_TRACK_TOP_LEVEL:
@@ -342,7 +327,5 @@ def guess_category(path: Path) -> Optional[str]:
return "cron-output" if len(rel.parts) >= 3 and rel.parts[1] == "output" else None
if top == "cache":
return "temp"
- except ValueError:
- pass # not under HERMES_HOME (e.g. /tmp/hermes-*) — fall through to name rules
name = path.name
return "test" if name.startswith(_TEST_PATTERNS) or name.endswith(_TEST_SUFFIXES) else None
diff --git a/plugins/google_meet/cli.py b/plugins/google_meet/cli.py
index f2515609359..610750329e5 100644
--- a/plugins/google_meet/cli.py
+++ b/plugins/google_meet/cli.py
@@ -102,18 +102,14 @@ def _cmd_setup() -> int:
pw_ok = importlib.util.find_spec("playwright") is not None
print(" playwright : installed" if pw_ok
else " playwright : NOT installed — run: pip install playwright")
- chromium_ok = False
- chromium_msg = "unknown"
+ chromium_ok, chromium_msg = False, "unknown"
if pw_ok:
try:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
exe = p.chromium.executable_path
- if exe and Path(exe).exists():
- chromium_ok = True
- chromium_msg = f"ok ({exe})"
- else:
- chromium_msg = "not installed — run: python -m playwright install chromium"
+ chromium_ok = bool(exe and Path(exe).exists())
+ chromium_msg = f"ok ({exe})" if chromium_ok else "not installed — run: python -m playwright install chromium"
except Exception as e:
chromium_msg = f"probe failed: {e}"
print(f" chromium : {chromium_msg}")
@@ -162,9 +158,8 @@ def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
return 1
print("\n[2/3] python -m playwright install chromium")
try:
- res = subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=False,
- stdin=subprocess.DEVNULL)
- if res.returncode != 0:
+ if subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=False,
+ stdin=subprocess.DEVNULL).returncode != 0:
print(" playwright install failed (may already be installed)")
except Exception as e:
print(f" playwright install failed: {e}")
@@ -196,10 +191,9 @@ def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
else:
_install_pkgs(f" install via brew: {' '.join(needs)}?", ["brew", "install", *needs],
" brew install failed — install them manually")
- print("\n NOTE: macOS does not auto-route audio. Open\n"
- " System Settings → Sound → Input\n"
- " and select 'BlackHole 2ch' before starting a realtime meeting.\n"
- " hermes will not switch your default input for you.")
+ print("\n NOTE: macOS does not auto-route audio. Open\n System Settings → Sound → "
+ "Input\n and select 'BlackHole 2ch' before starting a realtime meeting.\n "
+ "hermes will not switch your default input for you.")
print("\ndone. verify with: hermes meet setup")
return 0
diff --git a/plugins/google_meet/meet_bot.py b/plugins/google_meet/meet_bot.py
index a9be4c364a3..a42e913ae9c 100644
--- a/plugins/google_meet/meet_bot.py
+++ b/plugins/google_meet/meet_bot.py
@@ -197,39 +197,31 @@ _DENIED_PROBE_JS = r"""
def _probe(page, js: str) -> bool:
"""Evaluate a boolean JS probe; conservative — False on any error."""
- try:
- return bool(page.evaluate(js))
- except Exception:
- return False
+ return bool(_quiet(page.evaluate, js))
def _visible(locator):
"""``locator.first`` if it exists and is visible, else None (swallows Playwright errors)."""
- try:
- first = locator.first
- return first if first.count() and first.is_visible() else None
- except Exception:
- return None
+ return _quiet(lambda: locator.first if locator.first.count() and locator.first.is_visible() else None)
def _start_pcm_pump(rt: dict, bridge_info: dict, pcm_path: Path, state: "_BotState") -> None:
"""Stream the growing ``speaker.pcm`` (24kHz s16le mono) into the device Chrome's fake mic reads."""
bridge_info = bridge_info or {}
platform_tag = bridge_info.get("platform")
+ target = bridge_info.get("write_target")
if platform_tag == "linux":
- sink = bridge_info.get("write_target") or "hermes_meet_sink"
cmd = ["paplay", "--raw", "--rate=24000", "--format=s16le", "--channels=1",
- f"--device={sink}", str(pcm_path)]
+ f"--device={target or 'hermes_meet_sink'}", str(pcm_path)]
missing = "paplay not found — install pulseaudio-utils for realtime on Linux"
elif platform_tag == "darwin":
# User must have BlackHole as default input; ffmpeg targets it by audiotoolbox index.
if not shutil.which("ffmpeg"):
state.set(error=_FFMPEG_MISSING)
return
- device_name = bridge_info.get("write_target") or "BlackHole 2ch"
cmd = ["ffmpeg", "-nostdin", "-hide_banner", "-loglevel", "error", "-re",
- "-f", "s16le", "-ar", "24000", "-ac", "1", "-i", str(pcm_path),
- "-f", "audiotoolbox", "-audio_device_index", _mac_audio_device_index(device_name), "-"]
+ "-f", "s16le", "-ar", "24000", "-ac", "1", "-i", str(pcm_path), "-f", "audiotoolbox",
+ "-audio_device_index", _mac_audio_device_index(target or "BlackHole 2ch"), "-"]
missing = _FFMPEG_MISSING
else:
return
@@ -251,8 +243,7 @@ def _start_realtime_speaker(rt: dict, cfg: "_BotConfig", stop_flag: dict, state:
except Exception as e:
state.set(error=f"realtime import failed: {e}")
return
- pcm_path = cfg.out_dir / "speaker.pcm"
- queue_path = cfg.out_dir / "say_queue.jsonl"
+ pcm_path, queue_path = cfg.out_dir / "speaker.pcm", cfg.out_dir / "say_queue.jsonl"
pcm_path.write_bytes(b"") # clean sink file per session
queue_path.touch() # so the speaker poller doesn't error on first iteration
try:
@@ -282,14 +273,10 @@ def _start_realtime_speaker(rt: dict, cfg: "_BotConfig", stop_flag: dict, state:
def _mac_audio_device_index(device_name: str) -> str:
"""ffmpeg ``-audio_device_index`` for *device_name* (case-insensitive; ``"0"`` if not found).
ffmpeg prints the avfoundation device table on stderr as ``[N] Name``."""
- try:
- out = subprocess.run(
- ["ffmpeg", "-f", "avfoundation", "-list_devices", "true", "-i", ""],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10)
- except Exception:
- return "0"
+ out = _quiet(subprocess.run, ["ffmpeg", "-f", "avfoundation", "-list_devices", "true", "-i", ""],
+ capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10)
needle = device_name.strip().lower()
- for line in (out.stderr or "").splitlines():
+ for line in (out.stderr if out else "").splitlines():
m = re.search(r"\[(\d+)\]\s+(.+)$", line)
if m and m.group(2).strip().lower() == needle:
return m.group(1)
@@ -317,11 +304,10 @@ def _teardown_realtime(rt: dict) -> None:
if rt.get("pcm_pump"):
_quiet(rt["pcm_pump"].terminate)
_quiet(rt["pcm_pump"].wait, timeout=3)
- if rt["speaker_thread"] is not None:
- _quiet(rt["speaker_thread"].join, timeout=5.0)
- for key, method in (("session", "close"), ("bridge", "teardown")):
- if rt[key]:
- _quiet(getattr(rt[key], method))
+ for key, method, kw in (("speaker_thread", "join", {"timeout": 5.0}), ("session", "close", {}),
+ ("bridge", "teardown", {})):
+ if rt[key] is not None:
+ _quiet(getattr(rt[key], method), **kw)
@dataclass
@@ -369,15 +355,10 @@ def _join(page, cfg: _BotConfig, state: _BotState) -> None:
_quiet(name_box.fill, cfg.guest_name, timeout=2_000)
for label in ("Join now", "Ask to join"):
btn = _visible(page.get_by_role("button", name=label, exact=False))
- if btn is None:
- continue
- try:
- btn.click(timeout=3_000)
- except Exception:
- continue
- if label == "Ask to join":
- state.set(lobby_waiting=True)
- break
+ if btn is not None and _quiet(lambda: (btn.click(timeout=3_000), True)):
+ if label == "Ask to join":
+ state.set(lobby_waiting=True)
+ break
def _drain_loop(page, cfg: _BotConfig, state: _BotState, rt: dict, stop_flag: dict) -> None:
@@ -405,9 +386,7 @@ def _drain_loop(page, cfg: _BotConfig, state: _BotState, rt: dict, stop_flag: di
return
try:
queued = page.evaluate("window.__hermesMeetDrain && window.__hermesMeetDrain()")
- for entry in queued if isinstance(queued, list) else ():
- if not isinstance(entry, dict):
- continue
+ for entry in (e for e in (queued if isinstance(queued, list) else ()) if isinstance(e, dict)):
speaker = str(entry.get("speaker", ""))
state.record_caption(speaker=speaker, text=str(entry.get("text", "")))
# Barge-in: a real human spoke while we may be generating audio.
@@ -424,6 +403,13 @@ def _drain_loop(page, cfg: _BotConfig, state: _BotState, rt: dict, stop_flag: di
time.sleep(1.0)
+_CONTEXT_ARGS = {
+ "viewport": {"width": 1280, "height": 800},
+ "user_agent": ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"),
+ "permissions": ["microphone", "camera"]}
+
+
def run_bot() -> int:
cfg = _config_from_env()
if not _is_safe_meet_url(cfg.url):
@@ -440,8 +426,7 @@ def run_bot() -> int:
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, lambda _sig, _frame: stop_flag.__setitem__("stop", True))
# Realtime resources in one dict so teardown works however we exit.
- rt = {"enabled": cfg.realtime, "bridge": None, "bridge_info": None, "session": None,
- "speaker_thread": None}
+ rt = dict(enabled=cfg.realtime, bridge=None, bridge_info=None, session=None, speaker_thread=None)
if rt["enabled"]:
_setup_realtime(rt, cfg.realtime_api_key, state)
try:
@@ -459,16 +444,12 @@ def run_bot() -> int:
elif rt["bridge_info"] and rt["bridge_info"].get("platform") == "linux":
# Playwright's launch() takes no env: set PULSE_SOURCE on ourselves so Chrome inherits it.
os.environ["PULSE_SOURCE"] = rt["bridge_info"].get("device_name", "")
+ context_args = dict(_CONTEXT_ARGS)
+ if cfg.auth_state and Path(cfg.auth_state).is_file():
+ context_args["storage_state"] = cfg.auth_state
try:
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=not cfg.headed, args=chrome_args)
- context_args = {
- "viewport": {"width": 1280, "height": 800},
- "user_agent": ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
- "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"),
- "permissions": ["microphone", "camera"]}
- if cfg.auth_state and Path(cfg.auth_state).is_file():
- context_args["storage_state"] = cfg.auth_state
context = browser.new_context(**context_args)
page = context.new_page()
try:
diff --git a/plugins/google_meet/tools.py b/plugins/google_meet/tools.py
index 5ed307f99b6..815419001b8 100644
--- a/plugins/google_meet/tools.py
+++ b/plugins/google_meet/tools.py
@@ -39,14 +39,11 @@ _NODE_PROP = {"type": "string"}
MEET_JOIN_SCHEMA: Dict[str, Any] = {
"name": "meet_join",
"description": (
- "Join a Google Meet call and start scraping live captions into a "
- "transcript file. Only meet.google.com URLs are accepted; no calendar "
- "scanning, no auto-dial. Spawns a headless Chromium subprocess that "
- "runs in parallel with the agent loop — returns immediately. Poll "
- "with meet_status and read captions with meet_transcript. Reminder "
- "to the agent: you should announce yourself in the meeting (there is "
- "no automatic consent announcement)."
- ),
+ "Join a Google Meet call and start scraping live captions into a transcript file. Only "
+ "meet.google.com URLs are accepted; no calendar scanning, no auto-dial. Spawns a headless "
+ "Chromium subprocess that runs in parallel with the agent loop — returns immediately. Poll "
+ "with meet_status and read captions with meet_transcript. Reminder to the agent: you "
+ "should announce yourself in the meeting (there is no automatic consent announcement)."),
"parameters": {
"type": "object",
"properties": {
@@ -56,8 +53,7 @@ MEET_JOIN_SCHEMA: Dict[str, Any] = {
"description": (
"transcribe (default): listen-only, scrape captions. "
"realtime: also enable agent speech via meet_say "
- "(requires OpenAI Realtime key + platform audio bridge)."),
- },
+ "(requires OpenAI Realtime key + platform audio bridge).")},
"guest_name": {
"type": "string",
"description": "Display name to use when joining as guest. Defaults to 'Hermes Agent'."},
@@ -71,26 +67,18 @@ MEET_JOIN_SCHEMA: Dict[str, Any] = {
"node": {
"type": "string",
"description": (
- "Name of a registered remote node to run the bot on "
- "(useful when the gateway runs on a headless Linux box "
- "but the user's Chrome with a signed-in Google profile "
- "lives on their Mac). Pass 'auto' to use the single "
- "registered node. Default: run locally. Nodes are "
- "approved via `hermes meet node approve`."),
- },
- },
+ "Name of a registered remote node to run the bot on (useful when the gateway "
+ "runs on a headless Linux box but the user's Chrome with a signed-in Google "
+ "profile lives on their Mac). Pass 'auto' to use the single registered node. "
+ "Default: run locally. Nodes are approved via `hermes meet node approve`.")}},
"required": ["url"],
- "additionalProperties": False,
- },
-}
+ "additionalProperties": False}}
MEET_STATUS_SCHEMA: Dict[str, Any] = {
"name": "meet_status",
"description": (
- "Report the current Meet session state — whether the bot is alive, "
- "has joined, is sitting in the lobby, number of transcript lines "
- "captured, and last-caption timestamp."
- ),
+ "Report the current Meet session state — whether the bot is alive, has joined, is sitting "
+ "in the lobby, number of transcript lines captured, and last-caption timestamp."),
"parameters": {"type": "object", "properties": {"node": _NODE_PROP}, "additionalProperties": False},
}
@@ -98,8 +86,7 @@ MEET_TRANSCRIPT_SCHEMA: Dict[str, Any] = {
"name": "meet_transcript",
"description": (
"Read the scraped transcript for the active Meet session. Returns "
- "full transcript unless 'last' is set, in which case returns the last N lines only."
- ),
+ "full transcript unless 'last' is set, in which case returns the last N lines only."),
"parameters": {
"type": "object",
"properties": {
@@ -108,39 +95,30 @@ MEET_TRANSCRIPT_SCHEMA: Dict[str, Any] = {
"description": ("Optional: return only the last N caption lines. Useful "
"for polling during a meeting without re-reading the whole transcript."),
"minimum": 1},
- "node": _NODE_PROP,
- },
- "additionalProperties": False,
- },
-}
+ "node": _NODE_PROP},
+ "additionalProperties": False}}
MEET_LEAVE_SCHEMA: Dict[str, Any] = {
"name": "meet_leave",
"description": (
- "Leave the active Meet call cleanly, stop caption scraping, and "
- "finalize the transcript file. Safe to call when no meeting is "
- "active — returns ok=false with a reason."
- ),
+ "Leave the active Meet call cleanly, stop caption scraping, and finalize the transcript "
+ "file. Safe to call when no meeting is active — returns ok=false with a reason."),
"parameters": {"type": "object", "properties": {"node": _NODE_PROP}, "additionalProperties": False},
}
MEET_SAY_SCHEMA: Dict[str, Any] = {
"name": "meet_say",
"description": (
- "Speak text into the active Meet call. Requires the active meeting "
- "to have been joined with mode='realtime'. The text is queued to "
- "the bot's OpenAI Realtime session; the generated audio is streamed "
- "into Chrome's fake microphone via a virtual audio device "
- "(PulseAudio null-sink on Linux, BlackHole on macOS). Returns "
- "immediately — the actual speech lags by a couple of seconds."
- ),
+ "Speak text into the active Meet call. Requires the active meeting to have been joined "
+ "with mode='realtime'. The text is queued to the bot's OpenAI Realtime session; the "
+ "generated audio is streamed into Chrome's fake microphone via a virtual audio device "
+ "(PulseAudio null-sink on Linux, BlackHole on macOS). Returns immediately — the actual "
+ "speech lags by a couple of seconds."),
"parameters": {
"type": "object",
"properties": {"text": {"type": "string", "description": "Text to speak."}, "node": _NODE_PROP},
"required": ["text"],
- "additionalProperties": False,
- },
-}
+ "additionalProperties": False}}
def _json(obj: Any) -> str: