Files
Teknium d9028f3088 fix(gateway): on_session_open opens behind a hung one stay bounded; no consumer, no thread
Second independent review of #151120:

- P2: every open queued its own task behind its predecessor with no bound, so
  under `plugins.hook_callback_timeout: 0` a hung callback let every later open
  of that session pile up (41 pending tasks in the review's probe). Now at most
  one delivery runs and one queues per (profile, session); opens arriving while
  that one still queues join it and fire once after the running one, with the
  latest open's payload (an open is setup, so firing it once is enough). The
  first join logs one WARNING.
- P3: the delivery thread started before `has_hook('on_session_open')` was
  checked. The loop now asks `hook_known_unused` first, under the owning
  profile's home override: safe mode, or that profile's plugins already loaded
  with no callback for a hook no first-party observer handles, answers without
  discovering plugins or reading config, and no thread starts. A profile whose
  plugins are not loaded yet still goes to the thread, which discovers and
  checks `has_hook` off the loop as before.
2026-11-08 01:26:58 -08:00

116 lines
3.9 KiB
Python

"""Hermes lifecycle dispatch for first-party observers and plugins."""
from __future__ import annotations
import logging
from typing import Any, List
logger = logging.getLogger(__name__)
def _observe(hook_name: str, **kwargs: Any) -> None:
from agent.safe_worker_policy import safe_worker_enabled
if safe_worker_enabled():
return
try:
from hermes_cli.observability import observe_lifecycle
observe_lifecycle(hook_name, **kwargs)
except Exception:
logger.warning("Built-in observability hook failed", exc_info=True)
def _plugin_hooks(hook_name: str, **kwargs: Any) -> list[Any]:
from hermes_cli import plugins
return plugins.invoke_hook(hook_name, **kwargs)
def invoke_hook(hook_name: str, **kwargs: Any) -> list[Any]:
"""Notify first-party observers, then invoke compatibility plugin hooks."""
from agent.safe_worker_policy import safe_worker_enabled
if safe_worker_enabled():
return []
_observe(hook_name, **kwargs)
return _plugin_hooks(hook_name, **kwargs)
async def ainvoke_hook(hook_name: str, **kwargs: Any) -> list[Any]:
""":func:`invoke_hook` for callers on an event loop: same observers-then-plugins
composition, with ``async def`` plugin callbacks awaited on that loop."""
_observe(hook_name, **kwargs)
from hermes_cli import plugins
return await plugins.ainvoke_hook(hook_name, **kwargs)
def has_hook(hook_name: str) -> bool:
"""Return whether a first-party observer or plugin consumes a hook."""
from agent.safe_worker_policy import safe_worker_enabled
if safe_worker_enabled():
return False
try:
from hermes_cli.observability import handles_hook
if handles_hook(hook_name):
return True
except Exception:
logger.warning("Unable to inspect built-in observability hooks", exc_info=True)
from hermes_cli import plugins
return plugins.has_hook(hook_name)
def hook_known_unused(hook_name: str) -> bool:
"""True when nothing in the active profile can consume *hook_name*, decided without loading
plugins or reading config, so an event loop may ask before spending a thread on it: safe mode,
or this profile's plugins already loaded with none registered for a hook no first-party observer
handles. False means it may be consumed: ask :func:`has_hook` off the loop."""
from agent.safe_worker_policy import safe_worker_enabled
if safe_worker_enabled():
return True
from hermes_cli.observability.relay_shared_metrics import HANDLED_HOOKS
if hook_name in HANDLED_HOOKS:
return False
from hermes_cli import plugins
return plugins.hook_unused_nowait(hook_name)
def session_end_messages(results: Any) -> list[str]:
"""User-facing text from ``on_session_finalize`` results: a non-empty ``str`` or ``{"message": str}``.
Surfaces show these out-of-band (CLI print, TUI system line, gateway chat send) — never as a model
turn. ``on_session_end`` is per-turn and stays observer-only."""
messages: list[str] = []
for result in results or ():
text = result.get("message") if isinstance(result, dict) else result
if isinstance(text, str) and text.strip():
messages.append(text.strip())
return messages
def finalize_session(**kwargs: Any) -> list[Any]:
"""Notify observers and hard-close one core-owned Relay conversation."""
_observe("on_session_finalize", **kwargs)
session_id = str(kwargs.get("session_id") or "")
if session_id:
try:
from agent import relay_runtime
relay_runtime.SESSION_COORDINATOR.finalize_conversation(
profile_key=relay_runtime.current_profile_key(),
session_id=session_id,
)
except Exception:
logger.warning("Core Relay session finalization failed", exc_info=True)
return _plugin_hooks("on_session_finalize", **kwargs)