hooks.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. """Event hook system: fires handlers at gateway lifecycle points.
  2. Hooks live in ~/.hermes/hooks/<name>/ with HOOK.yaml (name, description, events) and
  3. handler.py (``def handle(event_type, context)``, sync or async); errors never block
  4. the pipeline. Events: gateway:startup, session:start/end/reset, agent:start,
  5. agent:step (each tool-loop turn), agent:end, command:* (wildcard). agent:* context:
  6. platform, user_id, chat_id, thread_id ("" outside a thread), chat_type
  7. ("dm"|"group"|"forum"|""), session_id, message (500 chars); agent:end adds response,
  8. model, provider. Forum follow-ups pass ``message_thread_id=int(thread_id)``.
  9. """
  10. import asyncio
  11. import importlib.util
  12. import sys
  13. import threading
  14. from pathlib import Path
  15. from typing import Any, Callable, Dict, List, Optional
  16. import hermes_yaml as yaml
  17. from hermes_cli.config import get_hermes_home
  18. from hermes_constants import hermes_home_key
  19. HOOKS_DIR = get_hermes_home() / "hooks"
  20. _HOOKS_DIR_AT_IMPORT = HOOKS_DIR
  21. def _resolve_hooks_dir() -> Path:
  22. """Active profile's hooks dir at call time: the patched ``HOOKS_DIR`` when a test changed it,
  23. else ``get_hermes_home()/hooks``. The import-time constant is the LAUNCH profile's; under
  24. ``gateway.multiplex_profiles`` every served profile has its own ``hooks/``, and a registry
  25. loaded from the launch home would run the default profile's handlers (arbitrary Python) on
  26. every other profile's messages, responses and user ids."""
  27. configured = Path(HOOKS_DIR)
  28. return configured if configured != _HOOKS_DIR_AT_IMPORT else get_hermes_home() / "hooks"
  29. def _skip(name: str, reason: str) -> None:
  30. print(f"[hooks] Skipping {name}: {reason}", flush=True)
  31. def _load_hook_dir(hook_dir: Path) -> Optional[tuple]:
  32. """``(name, events, handle_fn, description)`` for a valid hook dir, else None (reason printed)."""
  33. manifest_path, handler_path = hook_dir / "HOOK.yaml", hook_dir / "handler.py"
  34. if not manifest_path.exists() or not handler_path.exists():
  35. return None
  36. manifest = yaml.safe_load(manifest_path.read_text(encoding="utf-8-sig"))
  37. if not manifest or not isinstance(manifest, dict):
  38. return _skip(hook_dir.name, "invalid HOOK.yaml")
  39. hook_name = manifest.get("name", hook_dir.name)
  40. events = manifest.get("events", [])
  41. if not events:
  42. return _skip(hook_name, "no events declared")
  43. # Register in sys.modules BEFORE exec_module so Pydantic/dataclass forward references
  44. # (``from __future__ import annotations``) resolve; otherwise a handler declaring a
  45. # BaseModel fails at first dispatch with "TypeAdapter ... is not fully defined".
  46. module_name = f"hermes_hook_{hook_name}"
  47. spec = importlib.util.spec_from_file_location(module_name, handler_path)
  48. if spec is None or spec.loader is None:
  49. return _skip(hook_name, "could not load handler.py")
  50. module = importlib.util.module_from_spec(spec)
  51. sys.modules[module_name] = module
  52. try:
  53. spec.loader.exec_module(module)
  54. except Exception:
  55. sys.modules.pop(module_name, None)
  56. raise
  57. handle_fn = getattr(module, "handle", None)
  58. if handle_fn is None:
  59. return _skip(hook_name, "no 'handle' function found")
  60. return hook_name, events, handle_fn, manifest.get("description", "")
  61. class HookRegistry:
  62. """Discovers, loads, and fires event hooks."""
  63. def __init__(self):
  64. self._handlers: dict[str, list[Callable]] = {} # event_type -> handlers
  65. self._loaded_hooks: list[dict] = [] # metadata for listing
  66. @property
  67. def loaded_hooks(self) -> list[dict]:
  68. return list(self._loaded_hooks)
  69. def _register_builtin_hooks(self) -> None:
  70. """Extension point for always-on built-in hooks; currently none shipped."""
  71. def discover_and_load(self) -> None:
  72. """Register built-in hooks, then load every valid hook dir under the active profile's ``hooks/``."""
  73. self._register_builtin_hooks()
  74. hooks_dir = _resolve_hooks_dir()
  75. if not hooks_dir.exists():
  76. return
  77. for hook_dir in sorted(hooks_dir.iterdir()):
  78. if not hook_dir.is_dir():
  79. continue
  80. try:
  81. loaded = _load_hook_dir(hook_dir)
  82. except Exception as e:
  83. print(f"[hooks] Error loading hook {hook_dir.name}: {e}", flush=True)
  84. continue
  85. if loaded is None:
  86. continue
  87. hook_name, events, handle_fn, description = loaded
  88. for event in events:
  89. self._handlers.setdefault(event, []).append(handle_fn)
  90. self._loaded_hooks.append(
  91. {"name": hook_name, "description": description, "events": events, "path": str(hook_dir)}
  92. )
  93. print(f"[hooks] Loaded hook '{hook_name}' for events: {events}", flush=True)
  94. def _resolve_handlers(self, event_type: str) -> list[Callable]:
  95. """Exact-match handlers first, then ``<base>:*`` wildcards. A bare base type
  96. ("agent") does NOT fire for "agent:start" — only exact matches and explicit wildcards."""
  97. handlers = list(self._handlers.get(event_type, []))
  98. if ":" in event_type:
  99. handlers.extend(self._handlers.get(f"{event_type.split(':')[0]}:*", []))
  100. return handlers
  101. async def emit(self, event_type: str, context: Optional[dict[str, Any]] = None) -> None:
  102. """Fire all handlers for an event, discarding return values."""
  103. await self.emit_collect(event_type, context)
  104. async def emit_collect(self, event_type: str, context: Optional[dict[str, Any]] = None) -> list[Any]:
  105. """Fire handlers and return their non-None return values in order (decision-style
  106. hooks, e.g. ``command:<name>`` policies). A failing handler is logged, not fatal."""
  107. if context is None:
  108. context = {}
  109. results: list[Any] = []
  110. for fn in self._resolve_handlers(event_type):
  111. try:
  112. result = fn(event_type, context)
  113. result = await result if asyncio.iscoroutine(result) else result # sync or async handlers
  114. if result is not None:
  115. results.append(result)
  116. except Exception as e:
  117. print(f"[hooks] Error in handler for '{event_type}': {e}", flush=True)
  118. return results
  119. class ProfileHookRegistries:
  120. """``HookRegistry`` per served profile home, picked at emit time from the active HERMES_HOME.
  121. The gateway holds ONE of these. Every hook emit already runs inside the routed profile's
  122. ``_profile_runtime_scope`` (message handlers, /new, turn wiring), so resolving the registry by
  123. ``get_hermes_home()`` there gives each profile its own ``hooks/`` and keeps the default
  124. profile's handlers from seeing other profiles' messages. Each home's registry is loaded on its
  125. first emit, i.e. inside that profile's scope (handler imports see its HERMES_HOME); multiplexing off
  126. means a single entry for the launch home, i.e. exactly the old behaviour.
  127. """
  128. def __init__(self):
  129. self._by_home: dict[str, HookRegistry] = {}
  130. self._lock = threading.Lock()
  131. def _active(self) -> HookRegistry:
  132. key = hermes_home_key(get_hermes_home())
  133. registry = self._by_home.get(key)
  134. if registry is None:
  135. with self._lock:
  136. registry = self._by_home.get(key)
  137. if registry is None:
  138. registry = HookRegistry()
  139. registry.discover_and_load()
  140. self._by_home[key] = registry
  141. return registry
  142. @property
  143. def loaded_hooks(self) -> list[dict]:
  144. return self._active().loaded_hooks
  145. def discover_and_load(self) -> None:
  146. """Load the active home's hooks now (startup, or a secondary profile's scoped startup)."""
  147. self._active()
  148. async def emit(self, event_type: str, context: Optional[dict[str, Any]] = None) -> None:
  149. await self._active().emit(event_type, context)
  150. async def emit_collect(self, event_type: str, context: Optional[dict[str, Any]] = None) -> list[Any]:
  151. return await self._active().emit_collect(event_type, context)