run_shutdown_session_end.py 4.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. """Session finalize dispatch and delivery of plugin ``on_session_finalize`` messages for GatewayRunner.
  2. Split out of ``gateway/run_shutdown.py``; bound onto ``GatewayRunner`` via ``GatewayShutdownMixin``.
  3. """
  4. from __future__ import annotations
  5. import asyncio
  6. import logging
  7. from typing import Any, List, Optional
  8. logger = logging.getLogger("gateway.run")
  9. class GatewaySessionEndMixin:
  10. """Bounded off-loop ``finalize_session`` plus out-of-band delivery of what plugins return."""
  11. async def _deliver_session_end_messages(
  12. self, messages: list[str], *, source: Any = None, session_key: Optional[str] = None,
  13. ) -> None:
  14. """Send plugin ``on_session_finalize`` text to the chat that owns the session — a plain adapter send,
  15. never an agent turn. No resolvable chat (or no adapter) → logged and dropped."""
  16. if not messages:
  17. return
  18. if source is None and session_key:
  19. target = await self._shutdown_notification_target(session_key)
  20. source = target[0] if target else None
  21. adapter = self._delivery_adapter_for(source) if source is not None else None
  22. if adapter is None:
  23. logger.info("Session-end plugin message(s) dropped: no chat for session %s", session_key)
  24. return
  25. metadata = self._thread_metadata_for_source(source)
  26. for message in messages:
  27. await self._send_notice_logged(
  28. adapter, str(source.chat_id), message, source.platform.value if source.platform else "",
  29. "Failed to send session-end plugin message to %s:%s: %s", metadata=metadata)
  30. async def _reset_session_off_loop(self, *, session_key: Optional[str] = None, **kwargs: Any) -> None:
  31. """Plugin ``on_session_reset`` off-loop under the profile owning ``session_key``, bounded like
  32. finalize: a viewer's ``/new`` resets its conversation on the owner (gateway/session_viewer_close)."""
  33. def _call() -> None:
  34. from hermes_cli.lifecycle import invoke_hook
  35. invoke_hook("on_session_reset", **kwargs)
  36. try:
  37. await asyncio.wait_for(
  38. self._run_housekeeping_in_executor(self._run_release_in_profile_scope, _call, (), session_key),
  39. timeout=self._FINALIZE_TIMEOUT_S,
  40. )
  41. except TimeoutError:
  42. logger.warning("Session reset hooks (%s) exceeded %ss; proceeding without blocking the event loop.",
  43. kwargs.get("old_session_id"), self._FINALIZE_TIMEOUT_S)
  44. except Exception:
  45. logger.debug("Session reset hooks (%s) failed", kwargs.get("old_session_id"), exc_info=True)
  46. async def _finalize_session_off_loop(
  47. self, *, session_id: Any, platform: str, reason: str, session_key: Optional[str] = None, **extra: Any,
  48. ) -> list[str]:
  49. """Run hermes_cli.lifecycle.finalize_session off-loop, bounded; on timeout the worker is left alone.
  50. ``session_key`` lets an unscoped caller (shutdown) enter the owning profile's scope: plugin
  51. ``on_session_finalize`` observers and the Relay coordinator (``current_profile_key``) resolve
  52. profile state at call time. Returns the plugins' user-facing messages (empty on timeout/error)."""
  53. messages: list[str] = []
  54. def _call() -> None:
  55. from hermes_cli.lifecycle import finalize_session, session_end_messages
  56. messages.extend(session_end_messages(
  57. finalize_session(session_id=session_id, platform=platform, reason=reason, **extra)))
  58. try:
  59. await asyncio.wait_for(
  60. self._run_housekeeping_in_executor(self._run_release_in_profile_scope, _call, (), session_key),
  61. timeout=self._FINALIZE_TIMEOUT_S,
  62. )
  63. except TimeoutError:
  64. logger.warning(
  65. "Session finalize hooks (%s, reason=%s) exceeded %ss; proceeding without blocking the event loop "
  66. "(the worker thread is left to finish on its own).", session_id, reason, self._FINALIZE_TIMEOUT_S,
  67. )
  68. except Exception:
  69. logger.debug("Session finalize hooks (%s, reason=%s) failed", session_id, reason, exc_info=True)
  70. return list(messages)