Skip to content

The agent that grows with you

refactor(plugins): AST-neutral layout compaction of loader, chronos, disk-cleanup, google_meet

Tekniumfc46eabcf516
diff --git a/plugins/context_engine/__init__.py b/plugins/context_engine/__init__.py
index e70e428d5ef..12e2f4b7c3a 100644
--- a/plugins/context_engine/__init__.py
+++ b/plugins/context_engine/__init__.py
@@ -25,10 +25,8 @@ def discover_context_engines() -> List[Tuple[str, str, bool]]:
(
child.name,
_loader.read_plugin_description(child),
- _loader.probe_availability(lambda c=child: _load_engine_from_dir(c)),
- )
- for child in _loader.iter_plugin_dirs(_CONTEXT_ENGINE_PLUGINS_DIR)
- ]
+ _loader.probe_availability(lambda c=child: _load_engine_from_dir(c)))
+ for child in _loader.iter_plugin_dirs(_CONTEXT_ENGINE_PLUGINS_DIR)]
def load_context_engine(name: str) -> Optional["ContextEngine"]: # noqa: F821
@@ -38,8 +36,7 @@ def load_context_engine(name: str) -> Optional["ContextEngine"]: # noqa: F821
logger.debug("Context engine '%s' not found in %s", name, _CONTEXT_ENGINE_PLUGINS_DIR)
return None
return _loader.load_named(
- name, engine_dir, _load_engine_from_dir,
- kind="Context engine", noun="engine", logger=logger,
+ name, engine_dir, _load_engine_from_dir, kind="Context engine", noun="engine", logger=logger
)
@@ -50,14 +47,12 @@ def _load_engine_from_dir(engine_dir: Path) -> Optional["ContextEngine"]: # noq
name = engine_dir.name
mod = _loader.load_plugin_module(
f"plugins.context_engine.{name}", engine_dir,
- parents=("plugins", "plugins.context_engine"), logger=logger,
- )
+ parents=("plugins", "plugins.context_engine"), logger=logger)
if mod is None:
return None
return _loader.instance_from_module(
mod, collector=_EngineCollector(engine_name=name), collected_attr="engine",
- base_cls=ContextEngine, name=name, logger=logger,
- )
+ base_cls=ContextEngine, name=name, logger=logger)
class _EngineCollector(_loader.NoopPluginContext):
@@ -77,8 +72,7 @@ class _EngineCollector(_loader.NoopPluginContext):
if not clean:
logger.warning(
"Context engine '%s' tried to register a command with an empty name.",
- self._engine_name,
- )
+ self._engine_name)
return
conflict = "Context engine '%s' tried to register command '/%s' which %s Skipping."
@@ -100,11 +94,9 @@ class _EngineCollector(_loader.NoopPluginContext):
"handler": handler,
"description": description or "Context engine command",
"plugin": f"context-engine:{self._engine_name}",
- "args_hint": (args_hint or "").strip(),
- }
+ "args_hint": (args_hint or "").strip()}
self._registered_commands.append(clean)
logger.debug("Context engine '%s' registered command: /%s", self._engine_name, clean)
except Exception as exc:
logger.debug(
- "Context engine '%s' could not register /%s: %s", self._engine_name, clean, exc,
- )
+ "Context engine '%s' could not register /%s: %s", self._engine_name, clean, exc)
diff --git a/plugins/cron_providers/__init__.py b/plugins/cron_providers/__init__.py
index 47dceb11cc4..799ebfd38e7 100644
--- a/plugins/cron_providers/__init__.py
+++ b/plugins/cron_providers/__init__.py
@@ -71,10 +71,8 @@ def discover_cron_schedulers() -> List[Tuple[str, str, bool]]:
(
name,
_loader.read_plugin_description(child),
- _loader.probe_availability(lambda c=child: _load_provider_from_dir(c)),
- )
- for name, child in _iter_provider_dirs()
- ]
+ _loader.probe_availability(lambda c=child: _load_provider_from_dir(c)))
+ for name, child in _iter_provider_dirs()]
def load_cron_scheduler(name: str) -> Optional["CronScheduler"]: # noqa: F821
@@ -85,8 +83,7 @@ def load_cron_scheduler(name: str) -> Optional["CronScheduler"]: # noqa: F821
return None
return _loader.load_named(
name, provider_dir, _load_provider_from_dir,
- kind="Cron provider", noun="provider", logger=logger,
- )
+ kind="Cron provider", noun="provider", logger=logger)
def _load_provider_from_dir(provider_dir: Path) -> Optional["CronScheduler"]: # noqa: F821
@@ -100,14 +97,12 @@ def _load_provider_from_dir(provider_dir: Path) -> Optional["CronScheduler"]: #
module_name, provider_dir,
parents=("plugins", "plugins.cron_providers"),
logger=logger,
- synthetic_namespace=None if is_bundled else _USER_NAMESPACE,
- )
+ synthetic_namespace=None if is_bundled else _USER_NAMESPACE)
if mod is None:
return None
return _loader.instance_from_module(
mod, collector=_ProviderCollector(), collected_attr="provider",
- base_cls=CronScheduler, name=name, logger=logger,
- )
+ base_cls=CronScheduler, name=name, logger=logger)
class _ProviderCollector(_loader.NoopPluginContext):
diff --git a/plugins/cron_providers/chronos/__init__.py b/plugins/cron_providers/chronos/__init__.py
index 3ae5d820f61..b5ce44bdd28 100644
--- a/plugins/cron_providers/chronos/__init__.py
+++ b/plugins/cron_providers/chronos/__init__.py
@@ -100,8 +100,7 @@ class ChronosCronScheduler(CronScheduler):
job_id=job_id,
fire_at=fire_at,
agent_callback_url=str(_cfg("cron", "chronos", "callback_url") or ""),
- dedup_key=f"{job_id}:{fire_at}",
- )
+ dedup_key=f"{job_id}:{fire_at}")
with self._lock:
self._armed[job_id] = fire_at
@@ -129,8 +128,7 @@ class ChronosCronScheduler(CronScheduler):
observed = {
item["job_id"]: item.get("fire_at", "")
for item in self._get_client().list_armed()
- if item.get("job_id")
- }
+ if item.get("job_id")}
with self._lock:
self._armed.update(observed)
return observed
@@ -145,8 +143,7 @@ class ChronosCronScheduler(CronScheduler):
desired: Dict[str, str] = {
j["id"]: j["next_run_at"]
for j in load_jobs()
- if j.get("enabled") and j.get("next_run_at") and j.get("state") != "paused"
- }
+ if j.get("enabled") and j.get("next_run_at") and j.get("state") != "paused"}
observed = self._list_armed()
for job_id, fire_at in desired.items():
@@ -167,16 +164,10 @@ class ChronosCronScheduler(CronScheduler):
# admission, duplicate detection, and cancel-aware drain on the fire webhook.
def fire_claimed(
- self,
- claimed_job: dict,
- *,
- adapters: Any = None,
- loop: Any = None,
- cancel_event: Any = None,
+ self, claimed_job: dict, *, adapters: Any = None, loop: Any = None, cancel_event: Any = None
) -> bool:
ran = super().fire_claimed(
- claimed_job, adapters=adapters, loop=loop, cancel_event=cancel_event,
- )
+ claimed_job, adapters=adapters, loop=loop, cancel_event=cancel_event)
if ran:
from cron.jobs import get_job
job_id = claimed_job["id"]
diff --git a/plugins/cron_providers/chronos/_nas_client.py b/plugins/cron_providers/chronos/_nas_client.py
index 2707bbc447c..4d6fa34a2d3 100644
--- a/plugins/cron_providers/chronos/_nas_client.py
+++ b/plugins/cron_providers/chronos/_nas_client.py
@@ -33,8 +33,7 @@ class NasCronClient:
from hermes_cli.auth import resolve_nous_access_token
return {
"Authorization": f"Bearer {resolve_nous_access_token()}",
- "Content-Type": "application/json",
- }
+ "Content-Type": "application/json"}
def _request(self, method: str, path: str, **kwargs: Any) -> Dict[str, Any]:
"""Issue one request; raise NasCronClientError on transport error or non-2xx."""
@@ -43,14 +42,12 @@ class NasCronClient:
try:
resp = requests.request(
method, f"{self.portal_url}{path}",
- headers=self._headers(), timeout=self.timeout_seconds, **kwargs,
- )
+ headers=self._headers(), timeout=self.timeout_seconds, **kwargs)
except Exception as e:
raise NasCronClientError(f"{method} {path} failed: {e}") from e
if resp.status_code // 100 != 2:
raise NasCronClientError(
- f"{method} {path} returned {resp.status_code}: {resp.text[:200]}"
- )
+ f"{method} {path} returned {resp.status_code}: {resp.text[:200]}")
try:
return resp.json() if resp.content else {}
except Exception:
@@ -67,8 +64,7 @@ class NasCronClient:
"job_id": job_id,
"fire_at": fire_at,
"agent_callback_url": agent_callback_url,
- "dedup_key": dedup_key,
- })
+ "dedup_key": dedup_key})
def cancel(self, *, job_id: str) -> Dict[str, Any]:
"""Cancel any armed one-shot for ``job_id``."""
diff --git a/plugins/cron_providers/chronos/verify.py b/plugins/cron_providers/chronos/verify.py
index db2981d365d..67ae20ec6f1 100644
--- a/plugins/cron_providers/chronos/verify.py
+++ b/plugins/cron_providers/chronos/verify.py
@@ -38,9 +38,7 @@ def _get_jwk_client(jwks_url: str) -> Any:
# Explicit Accept + User-Agent: the portal WAF 403s the default urllib fingerprint.
client = PyJWKClient(
- jwks_url,
- headers={"Accept": "application/json", "User-Agent": "HermesAgent/1.0"},
- )
+ jwks_url, headers={"Accept": "application/json", "User-Agent": "HermesAgent/1.0"})
_JWK_CLIENTS[jwks_url] = client
return client
@@ -51,8 +49,7 @@ def verify_nas_fire_token(
expected_audience: str,
jwks_or_key: Optional[str] = None,
issuer: Optional[str] = None,
- leeway_seconds: int = 30,
-) -> Optional[Dict[str, Any]]:
+ leeway_seconds: int = 30) -> Optional[Dict[str, Any]]:
"""Verify a NAS-minted cron-fire JWT; return decoded claims or None (never raises).
Checks asymmetric signature (JWKS URL or inline PEM; symmetric secrets rejected since
@@ -79,8 +76,7 @@ def verify_nas_fire_token(
algorithms=["RS256", "RS384", "RS512", "ES256", "ES384"],
audience=expected_audience,
leeway=leeway_seconds,
- options={"require": ["exp", "aud"]},
- )
+ options={"require": ["exp", "aud"]})
if issuer:
decode_kwargs["issuer"] = issuer
claims = jwt.decode(token, signing_key, **decode_kwargs)
diff --git a/plugins/disk-cleanup/__init__.py b/plugins/disk-cleanup/__init__.py
index 1384a8df57f..44938f3287c 100644
--- a/plugins/disk-cleanup/__init__.py
+++ b/plugins/disk-cleanup/__init__.py
@@ -63,8 +63,7 @@ def _extract_paths_from_terminal(args: Dict[str, Any], result: str) -> Set[str]:
_PATH_EXTRACTORS: Dict[str, Callable[[Dict[str, Any], str], Set[str]]] = {
"write_file": _extract_path_arg,
"patch": _extract_path_arg,
- "terminal": _extract_paths_from_terminal,
-}
+ "terminal": _extract_paths_from_terminal}
# --- Hooks ------------------------------------------------------------------
@@ -76,8 +75,7 @@ def _on_post_tool_call(
task_id: str = "",
session_id: str = "",
tool_call_id: str = "",
- **_: Any,
-) -> None:
+ **_: Any) -> None:
"""Auto-track ephemeral files created by recent tool calls. Best-effort, never raises."""
extractor = _PATH_EXTRACTORS.get(tool_name)
if not isinstance(args, dict) or extractor is None:
@@ -96,11 +94,7 @@ def _on_post_tool_call(
def _on_session_end(
- session_id: str = "",
- completed: bool = True,
- interrupted: bool = False,
- **_: Any,
-) -> None:
+ session_id: str = "", completed: bool = True, interrupted: bool = False, **_: Any) -> None:
"""Run quick cleanup if any test files were tracked during this turn."""
# Drain the session bucket plus every task-scoped bucket: subagents record
# into their own task_id buckets and should be cleaned up at session end too.
@@ -119,8 +113,7 @@ def _on_session_end(
if summary["deleted"] or summary["empty_dirs"]:
dg._log(
f"AUTO_QUICK (session_end): deleted={summary['deleted']} "
- f"dirs={summary['empty_dirs']} freed={dg.fmt_size(summary['freed'])}"
- )
+ f"dirs={summary['empty_dirs']} freed={dg.fmt_size(summary['freed'])}")
# --- Slash command ----------------------------------------------------------
@@ -146,8 +139,7 @@ Test files are auto-tracked on write_file / terminal and auto-cleaned at session
def _fmt_summary(summary: Dict[str, Any]) -> str:
base = (
f"[disk-cleanup] Cleaned {summary['deleted']} files + "
- f"{summary['empty_dirs']} empty dirs, freed {dg.fmt_size(summary['freed'])}."
- )
+ f"{summary['empty_dirs']} empty dirs, freed {dg.fmt_size(summary['freed'])}.")
if summary.get("errors"):
base += f"\n {len(summary['errors'])} error(s); see cleanup.log."
return base
@@ -197,8 +189,7 @@ def _cmd_forget(argv: List[str]) -> str:
n = dg.forget(argv[1])
return (
f"Removed {n} tracking entr{'y' if n == 1 else 'ies'} for {argv[1]}."
- if n else f"Not found in tracking: {argv[1]}"
- )
+ if n else f"Not found in tracking: {argv[1]}")
_SUBCOMMANDS: Dict[str, Callable[[List[str]], str]] = {
@@ -207,8 +198,7 @@ _SUBCOMMANDS: Dict[str, Callable[[List[str]], str]] = {
"quick": lambda argv: _fmt_summary(dg.quick()),
"deep": _cmd_deep,
"track": _cmd_track,
- "forget": _cmd_forget,
-}
+ "forget": _cmd_forget}
def _handle_slash(raw_args: str) -> Optional[str]:
@@ -227,5 +217,4 @@ def register(ctx) -> None:
ctx.register_command(
"disk-cleanup",
handler=_handle_slash,
- description="Track and clean up ephemeral Hermes session files.",
- )
+ description="Track and clean up ephemeral Hermes session files.")
diff --git a/plugins/disk-cleanup/disk_cleanup.py b/plugins/disk-cleanup/disk_cleanup.py
index 66b6126e811..884c5aecb2c 100755
--- a/plugins/disk-cleanup/disk_cleanup.py
+++ b/plugins/disk-cleanup/disk_cleanup.py
@@ -107,9 +107,7 @@ def save_tracked(tracked: List[Dict[str, Any]]) -> None:
# --- Categories / protected trees -------------------------------------------
ALLOWED_CATEGORIES = {
- "temp", "test", "research", "download",
- "chrome-profile", "cron-output", "other",
-}
+ "temp", "test", "research", "download", "chrome-profile", "cron-output", "other"}
# Top-level HERMES_HOME dirs whose empty subdirs are never swept. The last row
# is user-authored project trees (patches/, projects/, ...) β€” never sweep inside.
@@ -117,13 +115,10 @@ _EMPTY_DIR_PROTECTED_TOP_LEVEL = frozenset({
"logs", "memories", "sessions", "cron", "cronjobs",
"cache", "skills", "plugins", "disk-cleanup", "optional-skills",
"hermes-agent", "backups", "profiles", ".worktrees",
- "patches", "projects", "skins", "themes", "contributors",
-})
+ "patches", "projects", "skins", "themes", "contributors"})
_EMPTY_DIR_SWEEP_PRUNE_DIRS = frozenset({
- ".git", "node_modules", "venv", ".venv",
- "site-packages", "__pycache__",
-})
+ ".git", "node_modules", "venv", ".venv", "site-packages", "__pycache__"})
# Top-level entries under HERMES_HOME that guess_category() never auto-tracks:
# state dir, logs, memory, sessions, config/secrets, and user-authored project
@@ -133,8 +128,7 @@ _NEVER_TRACK_TOP_LEVEL = frozenset({
"skills", "plugins", ".env", "USER.md", "MEMORY.md", "SOUL.md",
"auth.json", "hermes-agent",
"patches", "projects", "skins", "themes", "contributors",
- "profiles", "backups", "optional-skills",
-})
+ "profiles", "backups", "optional-skills"})
# Defense-in-depth for quick(): exact cron control-plane paths never deleted,
# regardless of stored category (guards stale tracked.json entries).
@@ -155,8 +149,7 @@ def _is_protected_cron_path(p: Path) -> bool:
for parent in ("cron", "cronjobs"):
base = hermes_home / parent
_PROTECTED_CRON_PATHS.update(
- str(x) for x in (base, base / "output", base / "jobs.json", base / ".tick.lock")
- )
+ str(x) for x in (base, base / "output", base / "jobs.json", base / ".tick.lock"))
return str(p.resolve()) in _PROTECTED_CRON_PATHS
@@ -193,8 +186,7 @@ def track(path_str: str, category: str, silent: bool = False) -> bool:
"path": str(path),
"timestamp": datetime.now(timezone.utc).isoformat(),
"category": category,
- "size": size,
- })
+ "size": size})
save_tracked(tracked)
_log(f"TRACKED: {path} ({category}, {fmt_size(size)})")
if not silent:
diff --git a/plugins/google_meet/__init__.py b/plugins/google_meet/__init__.py
index 48af371dc0b..faacddedf1a 100644
--- a/plugins/google_meet/__init__.py
+++ b/plugins/google_meet/__init__.py
@@ -20,8 +20,7 @@ from plugins.google_meet.cli import meet_command as _meet_command
from plugins.google_meet.tools import (
MEET_JOIN_SCHEMA, MEET_LEAVE_SCHEMA, MEET_SAY_SCHEMA, MEET_STATUS_SCHEMA, MEET_TRANSCRIPT_SCHEMA,
check_meet_requirements, handle_meet_join, handle_meet_leave, handle_meet_say, handle_meet_status,
- handle_meet_transcript,
-)
+ handle_meet_transcript)
logger = logging.getLogger(__name__)
@@ -31,8 +30,7 @@ _TOOLS = (
("meet_status", MEET_STATUS_SCHEMA, handle_meet_status, "🟒"),
("meet_transcript", MEET_TRANSCRIPT_SCHEMA, handle_meet_transcript, "πŸ“"),
("meet_leave", MEET_LEAVE_SCHEMA, handle_meet_leave, "πŸ‘‹"),
- ("meet_say", MEET_SAY_SCHEMA, handle_meet_say, "πŸ—£οΈ"),
-)
+ ("meet_say", MEET_SAY_SCHEMA, handle_meet_say, "πŸ—£οΈ"))
def _on_session_end(**kwargs) -> None:
@@ -68,8 +66,6 @@ def register(ctx) -> None:
handler_fn=_meet_command,
description=(
"Let the hermes agent join a Google Meet call and scrape live "
- "captions into a transcript. See: hermes meet setup"
- ),
- )
+ "captions into a transcript. See: hermes meet setup"))
ctx.register_hook("on_session_end", _on_session_end)
diff --git a/plugins/google_meet/audio_bridge.py b/plugins/google_meet/audio_bridge.py
index 4919580aa9a..ad3b7046db8 100644
--- a/plugins/google_meet/audio_bridge.py
+++ b/plugins/google_meet/audio_bridge.py
@@ -27,8 +27,7 @@ def _pactl(*args: str, check: bool) -> subprocess.CompletedProcess:
check=check,
capture_output=True,
text=True, encoding='utf-8', errors='replace',
- stdin=subprocess.DEVNULL,
- )
+ stdin=subprocess.DEVNULL)
class AudioBridge:
@@ -95,8 +94,7 @@ class AudioBridge:
try:
sink_out = _pactl(
"load-module", "module-null-sink", f"sink_name={sink_name}",
- "sink_properties=device.description=HermesMeetSink", check=True,
- )
+ "sink_properties=device.description=HermesMeetSink", check=True)
except FileNotFoundError as exc:
raise RuntimeError("pactl not found β€” install PulseAudio/pipewire-pulse") from exc
except subprocess.CalledProcessError as exc:
@@ -106,8 +104,7 @@ class AudioBridge:
try:
src_out = _pactl(
"load-module", "module-virtual-source", f"source_name={src_name}",
- f"master={sink_name}.monitor", check=True,
- )
+ f"master={sink_name}.monitor", check=True)
except subprocess.CalledProcessError as exc:
# Roll back the null-sink we just created so we don't leak it.
_pactl("unload-module", str(sink_mod_id), check=False)
@@ -120,8 +117,7 @@ class AudioBridge:
out = subprocess.check_output(
["system_profiler", "SPAudioDataType"],
text=True, encoding='utf-8', errors='replace',
- stderr=subprocess.STDOUT,
- )
+ stderr=subprocess.STDOUT)
except FileNotFoundError as exc:
raise RuntimeError("system_profiler not found (macOS-only command)") from exc
except subprocess.CalledProcessError as exc:
@@ -130,8 +126,7 @@ class AudioBridge:
if "BlackHole" not in out:
raise RuntimeError(
"BlackHole virtual audio device not installed. "
- "Install via: brew install blackhole-2ch"
- )
+ "Install via: brew install blackhole-2ch")
return self._finish("darwin", _BLACKHOLE_DEVICE, _BLACKHOLE_DEVICE, [])
@staticmethod
diff --git a/plugins/google_meet/cli.py b/plugins/google_meet/cli.py
index 72807b57934..c8b7a22e94b 100644
--- a/plugins/google_meet/cli.py
+++ b/plugins/google_meet/cli.py
@@ -36,9 +36,7 @@ def register_cli(subparser: argparse.ArgumentParser) -> None:
subs.add_parser("setup", help="Preflight: playwright, chromium, auth")
inst_p = subs.add_parser(
- "install",
- help="Install prerequisites (pip deps, Chromium, platform audio tools)",
- )
+ "install", help="Install prerequisites (pip deps, Chromium, platform audio tools)")
inst_p.add_argument(
"--realtime", action="store_true",
help="Also install realtime audio tools (pulseaudio-utils on Linux, BlackHole+ffmpeg on macOS). Uses sudo/brew, prompts before invoking either.",
@@ -57,12 +55,9 @@ def register_cli(subparser: argparse.ArgumentParser) -> None:
join_p.add_argument("--headed", action="store_true", help="show browser")
join_p.add_argument(
"--mode", choices=("transcribe", "realtime"), default="transcribe",
- help="transcribe (default, listen-only) or realtime (speak via OpenAI Realtime)"
- )
+ help="transcribe (default, listen-only) or realtime (speak via OpenAI Realtime)")
join_p.add_argument(
- "--node", default=None,
- help="remote node name, or 'auto' to use the sole registered node"
- )
+ "--node", default=None, help="remote node name, or 'auto' to use the sole registered node")
subs.add_parser("status", help="Print current Meet bot state")
@@ -76,9 +71,7 @@ def register_cli(subparser: argparse.ArgumentParser) -> None:
subs.add_parser("stop", help="Leave the current meeting")
node_p = subs.add_parser(
- "node",
- help="Manage remote meet node hosts (run/list/approve/remove/status/ping)",
- )
+ "node", help="Manage remote meet node hosts (run/list/approve/remove/status/ping)")
try:
from plugins.google_meet.node.cli import register_cli as _register_node_cli
_register_node_cli(node_p)
@@ -105,19 +98,16 @@ def _cmd_node(args: argparse.Namespace) -> int:
_DISPATCH = {
"setup": lambda a: _cmd_setup(),
"install": lambda a: _cmd_install(
- realtime=bool(getattr(a, "realtime", False)), assume_yes=bool(getattr(a, "yes", False)),
- ),
+ realtime=bool(getattr(a, "realtime", False)), assume_yes=bool(getattr(a, "yes", False))),
"auth": lambda a: _cmd_auth(),
"join": lambda a: _cmd_join(
url=a.url, guest_name=a.guest_name, duration=a.duration, headed=a.headed,
- mode=getattr(a, "mode", "transcribe"), node=getattr(a, "node", None),
- ),
+ mode=getattr(a, "mode", "transcribe"), node=getattr(a, "node", None)),
"status": lambda a: _print_result(pm.status()),
"transcript": lambda a: _cmd_transcript(last=a.last),
"say": lambda a: _cmd_say(text=a.text, node=getattr(a, "node", None)),
"stop": lambda a: _print_result(pm.stop(reason="hermes meet stop")),
- "node": _cmd_node,
-}
+ "node": _cmd_node}
def meet_command(args: argparse.Namespace) -> int:
@@ -167,8 +157,7 @@ def _cmd_setup() -> int:
auth_path = _auth_state_path()
print(
" google auth : "
- + (f"ok ({auth_path})" if auth_path.is_file() else "not saved β€” run: hermes meet auth")
- )
+ + (f"ok ({auth_path})" if auth_path.is_file() else "not saved β€” run: hermes meet auth"))
print()
all_ok = system_ok and pw_ok and chromium_ok
@@ -245,8 +234,7 @@ def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
try:
out = subprocess.check_output(
["system_profiler", "SPAudioDataType"], text=True, encoding='utf-8', errors='replace',
- stdin=subprocess.DEVNULL,
- )
+ stdin=subprocess.DEVNULL)
have_bh = "BlackHole" in out
except Exception:
pass
@@ -256,8 +244,7 @@ def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
elif not shutil.which("brew"):
print(
" missing: " + ", ".join(needs) + "\n"
- " install Homebrew first (https://brew.sh) or install the packages manually."
- )
+ " install Homebrew first (https://brew.sh) or install the packages manually.")
else:
_install_pkgs(f" install via brew: {' '.join(needs)}?", ["brew", "install", *needs],
" brew install failed β€” install them manually")
@@ -265,8 +252,7 @@ def _cmd_install(*, realtime: bool, assume_yes: bool) -> int:
"\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."
- )
+ " hermes will not switch your default input for you.")
print("\ndone. verify with: hermes meet setup")
return 0
@@ -279,8 +265,7 @@ def _cmd_auth() -> int:
except ImportError:
print(
"playwright is not installed. run:\n"
- " pip install playwright && python -m playwright install chromium"
- )
+ " pip install playwright && python -m playwright install chromium")
return 1
path = _auth_state_path()
@@ -337,20 +322,17 @@ def _cmd_join(
duration: Optional[str],
headed: bool,
mode: str = "transcribe",
- node: Optional[str] = None,
-) -> int:
+ node: Optional[str] = None) -> int:
if not _is_safe_meet_url(url):
print(f"refusing: not a meet.google.com URL: {url}")
return 2
if node:
return _remote(node, "start_bot", lambda c: c.start_bot(
- url=url, guest_name=guest_name, duration=duration, headed=headed, mode=mode,
- ))
+ url=url, guest_name=guest_name, duration=duration, headed=headed, mode=mode))
auth = _auth_state_path()
return _print_result(pm.start(
url=url, headed=headed, guest_name=guest_name, duration=duration,
- auth_state=str(auth) if auth.is_file() else None, mode=mode,
- ))
+ auth_state=str(auth) if auth.is_file() else None, mode=mode))
def _cmd_say(text: str, node: Optional[str] = None) -> int:
diff --git a/plugins/google_meet/meet_bot.py b/plugins/google_meet/meet_bot.py
index af89a00a647..a9852e29412 100644
--- a/plugins/google_meet/meet_bot.py
+++ b/plugins/google_meet/meet_bot.py
@@ -35,8 +35,7 @@ MEET_URL_RE = re.compile(
r"[a-z0-9]{3,}-[a-z0-9]{3,}-[a-z0-9]{3,}"
r"|lookup/[^/?#]+"
r"|new"
- r")(?:[/?#].*)?$"
-)
+ r")(?:[/?#].*)?$")
# Filenames the bot reads/writes in ``HERMES_MEET_OUT_DIR``.
SAY_QUEUE_FILENAME = "say_queue.jsonl"
@@ -78,8 +77,7 @@ _STATUS_FIELDS = (
("realtime", "realtime", False), ("realtimeReady", "realtime_ready", False),
("realtimeDevice", "realtime_device", None), ("audioBytesOut", "audio_bytes_out", 0),
("lastAudioOutAt", "last_audio_out_at", None), ("lastBargeInAt", "last_barge_in_at", None),
- ("leaveReason", "leave_reason", None),
-)
+ ("leaveReason", "leave_reason", None))
class _BotState:
@@ -188,13 +186,11 @@ _CAPTION_OBSERVER_JS = r"""
# is too brittle to rely on.
_ENABLE_CAPTIONS_JS = (
"(() => { document.body.dispatchEvent(new KeyboardEvent('keydown', "
- "{ key: 'c', code: 'KeyC', keyCode: 67, which: 67, bubbles: true })); return true; })();"
-)
+ "{ key: 'c', code: 'KeyC', keyCode: 67, which: 67, bubbles: true })); return true; })();")
_LEAVE_CALL_JS = (
"() => { const b = document.querySelector('button[aria-label*=\"eave call\"]');"
- " if (b) b.click(); }"
-)
+ " if (b) b.click(); }")
# True once we're clearly past the lobby: leave button, caption region
# (only once our observer is installed) or participant list visible.
@@ -257,8 +253,7 @@ def _start_pcm_pump(rt: dict, bridge_info: dict, pcm_path: Path, state: "_BotSta
return
try:
rt["pcm_pump"] = subprocess.Popen(
- cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- )
+ cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
state.set(error=missing)
except Exception as e:
@@ -283,8 +278,7 @@ def _start_realtime_speaker(rt: dict, cfg: "_BotConfig", stop_flag: dict, state:
try:
session = RealtimeSession(
api_key=cfg.realtime_api_key, model=cfg.realtime_model, voice=cfg.realtime_voice,
- instructions=cfg.realtime_instructions, audio_sink_path=pcm_path, sample_rate=24000,
- )
+ instructions=cfg.realtime_instructions, audio_sink_path=pcm_path, sample_rate=24000)
session.connect()
except Exception as e:
state.set(error=f"realtime connect failed: {e}")
@@ -292,8 +286,7 @@ def _start_realtime_speaker(rt: dict, cfg: "_BotConfig", stop_flag: dict, state:
rt["session"] = session
speaker = RealtimeSpeaker(
- session=session, queue_path=queue_path, processed_path=cfg.out_dir / "say_processed.jsonl",
- )
+ session=session, queue_path=queue_path, processed_path=cfg.out_dir / "say_processed.jsonl")
def _speaker_loop():
try:
@@ -315,8 +308,7 @@ def _mac_audio_device_index(device_name: str) -> str:
try:
out = subprocess.run(
["ffmpeg", "-f", "avfoundation", "-list_devices", "true", "-i", ""],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10,
- )
+ capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10)
except Exception:
return "0"
needle = device_name.strip().lower()
@@ -392,8 +384,7 @@ def _config_from_env() -> _BotConfig:
realtime_model=env("HERMES_MEET_REALTIME_MODEL", "gpt-realtime"),
realtime_voice=env("HERMES_MEET_REALTIME_VOICE", "alloy"),
realtime_instructions=env("HERMES_MEET_REALTIME_INSTRUCTIONS", ""),
- lobby_timeout=float(env("HERMES_MEET_LOBBY_TIMEOUT", "300")),
- )
+ lobby_timeout=float(env("HERMES_MEET_LOBBY_TIMEOUT", "300")))
def _join(page, cfg: _BotConfig, state: _BotState) -> None:
@@ -440,8 +431,7 @@ def _drain_loop(page, cfg: _BotConfig, state: _BotState, rt: dict, stop_flag: di
waited = int(lobby_deadline - state.join_attempted_at) if state.join_attempted_at else 0
state.set(
error=f"lobby timeout β€” host never admitted the bot within {waited}s",
- leave_reason="lobby_timeout",
- )
+ leave_reason="lobby_timeout")
return
elif _probe(page, _DENIED_PROBE_JS):
state.set(error="host denied admission", leave_reason="denied")
@@ -469,8 +459,7 @@ def _drain_loop(page, cfg: _BotConfig, state: _BotState, rt: dict, stop_flag: di
if rt["session"] is not None:
state.set(
audio_bytes_out=rt["session"].audio_bytes_out,
- last_audio_out_at=rt["session"].last_audio_out_at,
- )
+ last_audio_out_at=rt["session"].last_audio_out_at)
time.sleep(1.0)
@@ -480,8 +469,7 @@ def run_bot() -> int:
if not _is_safe_meet_url(cfg.url):
sys.stderr.write(
"google_meet bot: refusing to launch β€” HERMES_MEET_URL must be a "
- "meet.google.com URL. got: %r\n" % cfg.url
- )
+ "meet.google.com URL. got: %r\n" % cfg.url)
return 2
if cfg.out_dir is None:
sys.stderr.write("google_meet bot: HERMES_MEET_OUT_DIR is required\n")
@@ -511,8 +499,7 @@ def run_bot() -> int:
state.set(error=f"playwright not installed: {e}", exited=True)
sys.stderr.write(
"google_meet bot: playwright is not installed. Run "
- "`pip install playwright && python -m playwright install chromium`\n"
- )
+ "`pip install playwright && python -m playwright install chromium`\n")
if rt["bridge"]:
rt["bridge"].teardown()
return 3
@@ -533,10 +520,8 @@ def run_bot() -> int:
"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"],
- }
+ "(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)
diff --git a/plugins/google_meet/node/__init__.py b/plugins/google_meet/node/__init__.py
index 9cbccaf438f..91c6677a610 100644
--- a/plugins/google_meet/node/__init__.py
+++ b/plugins/google_meet/node/__init__.py
@@ -14,12 +14,10 @@ from __future__ import annotations
from plugins.google_meet.node import protocol
from plugins.google_meet.node.client import NodeClient
from plugins.google_meet.node.protocol import ( # noqa: F401
- VALID_REQUEST_TYPES, decode, encode, make_error, make_request, make_response, validate_request,
-)
+ VALID_REQUEST_TYPES, decode, encode, make_error, make_request, make_response, validate_request)
from plugins.google_meet.node.registry import NodeRegistry
from plugins.google_meet.node.server import NodeServer
__all__ = [
"NodeClient", "NodeServer", "NodeRegistry", "protocol", "make_request", "make_response",
- "make_error", "encode", "decode", "validate_request", "VALID_REQUEST_TYPES",
-]
+ "make_error", "encode", "decode", "validate_request", "VALID_REQUEST_TYPES"]
diff --git a/plugins/google_meet/node/cli.py b/plugins/google_meet/node/cli.py
index 6553797ba4c..14ab77c5238 100644
--- a/plugins/google_meet/node/cli.py
+++ b/plugins/google_meet/node/cli.py
@@ -97,8 +97,7 @@ _COMMANDS = {
"approve": _cmd_approve,
"remove": _cmd_remove,
"status": _cmd_ping,
- "ping": _cmd_ping,
-}
+ "ping": _cmd_ping}
def node_command(args: argparse.Namespace) -> int:
diff --git a/plugins/google_meet/node/client.py b/plugins/google_meet/node/client.py
index 840f7253ad0..93ce8db7d61 100644
--- a/plugins/google_meet/node/client.py
+++ b/plugins/google_meet/node/client.py
@@ -54,8 +54,7 @@ class NodeClient:
guest_name: str = "Hermes Agent",
duration: Optional[str] = None,
headed: bool = False,
- mode: str = "transcribe",
- ) -> Dict[str, Any]:
+ mode: str = "transcribe") -> Dict[str, Any]:
payload: Dict[str, Any] = {"url": url, "guest_name": guest_name, "headed": bool(headed), "mode": mode}
if duration is not None:
payload["duration"] = duration
diff --git a/plugins/google_meet/node/server.py b/plugins/google_meet/node/server.py
index 632e2ba03e4..9c1c9e80e32 100644
--- a/plugins/google_meet/node/server.py
+++ b/plugins/google_meet/node/server.py
@@ -65,8 +65,7 @@ _RPC = {
"stop": lambda p, pm: pm.stop(reason=p.get("reason", "requested")),
"status": lambda p, pm: pm.status(),
"transcript": lambda p, pm: pm.transcript(last=p.get("last")),
- "say": _rpc_say,
-}
+ "say": _rpc_say}
class NodeServer:
@@ -77,14 +76,12 @@ class NodeServer:
host: str = "127.0.0.1",
port: int = 18789,
token_path: Optional[Path] = None,
- display_name: str = "hermes-meet-node",
- ) -> None:
+ display_name: str = "hermes-meet-node") -> None:
self.host = host
self.port = port
self.display_name = display_name
self.token_path = Path(token_path) if token_path is not None else (
- Path(get_hermes_home()) / "workspace" / "meetings" / "node_token.json"
- )
+ Path(get_hermes_home()) / "workspace" / "meetings" / "node_token.json")
self._token: Optional[str] = None
def ensure_token(self) -> str:
diff --git a/plugins/google_meet/process_manager.py b/plugins/google_meet/process_manager.py
index b28a80b2f12..1625ad47200 100644
--- a/plugins/google_meet/process_manager.py
+++ b/plugins/google_meet/process_manager.py
@@ -77,8 +77,7 @@ def start(
realtime_model: Optional[str] = None,
realtime_voice: Optional[str] = None,
realtime_instructions: Optional[str] = None,
- realtime_api_key: Optional[str] = None,
-) -> Dict[str, Any]:
+ realtime_api_key: Optional[str] = None) -> Dict[str, Any]:
"""Spawn the meet_bot subprocess for *url*, stopping any running bot first
(single-active-meeting semantics). Returns a dict summarizing the bot."""
from plugins.google_meet.meet_bot import _is_safe_meet_url, _meeting_id_from_url
@@ -109,8 +108,7 @@ def start(
(mode, "HERMES_MEET_MODE"), # bot defaults to transcribe when unset (v1 behavior)
(realtime_model, "HERMES_MEET_REALTIME_MODEL"),
(realtime_voice, "HERMES_MEET_REALTIME_VOICE"),
- (realtime_instructions, "HERMES_MEET_REALTIME_INSTRUCTIONS"),
- ):
+ (realtime_instructions, "HERMES_MEET_REALTIME_INSTRUCTIONS")):
if value:
env[var] = value
# Resolve the realtime key at SPAWN time, in the parent, where the profile
@@ -131,8 +129,7 @@ def start(
proc = subprocess.Popen(
[sys.executable, "-m", "plugins.google_meet.meet_bot"],
stdin=subprocess.DEVNULL, stdout=log_fh, stderr=subprocess.STDOUT,
- env=env, start_new_session=True, close_fds=True,
- )
+ env=env, start_new_session=True, close_fds=True)
record = {
"pid": proc.pid, "meeting_id": meeting_id, "out_dir": str(out), "url": url,
@@ -156,8 +153,7 @@ def status() -> Dict[str, Any]:
"url": active.get("url"),
"startedAt": active.get("started_at"),
"outDir": active.get("out_dir"),
- **(read_json(Path(active.get("out_dir", "")) / "status.json") or {}),
- }
+ **(read_json(Path(active.get("out_dir", "")) / "status.json") or {})}
def transcript(last: Optional[int] = None) -> Dict[str, Any]:
@@ -174,8 +170,7 @@ def transcript(last: Optional[int] = None) -> Dict[str, Any]:
"meetingId": active.get("meeting_id"),
"lines": all_lines[-last:] if last else all_lines,
"total": len(all_lines),
- "path": str(tp),
- }
+ "path": str(tp)}
def enqueue_say(text: str) -> Dict[str, Any]:
@@ -234,5 +229,4 @@ def stop(*, reason: str = "requested") -> Dict[str, Any]:
"ok": True,
"reason": reason,
"meetingId": active.get("meeting_id"),
- "transcriptPath": str(Path(out_dir) / "transcript.txt") if out_dir else None,
- }
+ "transcriptPath": str(Path(out_dir) / "transcript.txt") if out_dir else None}
diff --git a/plugins/google_meet/realtime/openai_client.py b/plugins/google_meet/realtime/openai_client.py
index fac4e2b9b86..e8c95235204 100644
--- a/plugins/google_meet/realtime/openai_client.py
+++ b/plugins/google_meet/realtime/openai_client.py
@@ -43,8 +43,7 @@ class RealtimeSession:
voice: str = "alloy",
instructions: str = "",
audio_sink_path: Optional[Path] = None,
- sample_rate: int = 24000,
- ) -> None:
+ sample_rate: int = 24000) -> None:
self.api_key = api_key
self.model = model
self.voice = voice
@@ -81,9 +80,7 @@ class RealtimeSession:
"instructions": self.instructions,
"modalities": ["audio", "text"],
"output_audio_format": "pcm16",
- "input_audio_format": "pcm16",
- },
- })
+ "input_audio_format": "pcm16"}})
def close(self) -> None:
if self._ws is not None:
@@ -186,10 +183,7 @@ class RealtimeSpeaker:
"""
def __init__(
- self,
- session: RealtimeSession,
- queue_path: Path,
- processed_path: Optional[Path] = None,
+ self, session: RealtimeSession, queue_path: Path, processed_path: Optional[Path] = None
) -> None:
self.session = session
self.queue_path = Path(queue_path)
diff --git a/plugins/plugin_loader.py b/plugins/plugin_loader.py
index bd36eb80943..95264760642 100644
--- a/plugins/plugin_loader.py
+++ b/plugins/plugin_loader.py
@@ -45,8 +45,7 @@ def iter_plugin_dirs(root: Path) -> List[Path]:
child for child in sorted(root.iterdir())
if child.is_dir()
and not child.name.startswith(("_", "."))
- and (child / "__init__.py").exists()
- ]
+ and (child / "__init__.py").exists()]
def read_plugin_description(plugin_dir: Path) -> str:
@@ -66,8 +65,7 @@ def read_plugin_description(plugin_dir: Path) -> str:
def _new_module(name: str, file: Path, search_locations: Optional[List[str]] = None) -> Optional[Any]:
"""spec -> module -> sys.modules[name] (NOT executed); None if no spec."""
spec = importlib.util.spec_from_file_location(
- name, str(file), submodule_search_locations=search_locations
- )
+ name, str(file), submodule_search_locations=search_locations)
if not spec:
return None
mod = importlib.util.module_from_spec(spec)
@@ -98,8 +96,7 @@ def load_plugin_module(
*,
parents: Tuple[str, ...],
logger: logging.Logger,
- synthetic_namespace: Optional[str] = None,
-) -> Optional[Any]:
+ synthetic_namespace: Optional[str] = None) -> Optional[Any]:
"""Import ``plugin_dir/__init__.py`` as *module_name* (reusing sys.modules when loaded).
Order matters: parent packages first (relative imports need them), then sibling
@@ -167,8 +164,7 @@ def instance_from_module(
collected_attr: str,
base_cls: type,
name: str,
- logger: logging.Logger,
-) -> Optional[Any]:
+ logger: logging.Logger) -> Optional[Any]:
"""Extract the provider instance: ``register(ctx)`` first, then any ``base_cls`` subclass."""
if hasattr(mod, "register"):
try:
@@ -196,8 +192,7 @@ def load_named(
*,
kind: str,
noun: str,
- logger: logging.Logger,
-) -> Optional[Any]:
+ logger: logging.Logger) -> Optional[Any]:
"""Shared body of ``load_<kind>(name)``: load from *plugin_dir*, warn + None on failure."""
try:
instance = load_from_dir(plugin_dir)