plugin_messages.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. """``PluginContext.post_message``: one message in the current conversation, editable in place.
  2. The conversation is the session bound in the calling context (a tool or hook running in its turn,
  3. its slash command, a hook fired for it): the plugin never names a chat, so it cannot reach another
  4. one. Outside any session (a timer, a plugin thread, cron, a process with no live gateway) the call
  5. is refused with a result, never an exception. Routing and the edit fallback live in
  6. ``gateway/plugin_messages.py``; this side only hands work to the gateway loop and back.
  7. """
  8. from __future__ import annotations
  9. import asyncio
  10. import concurrent.futures
  11. import logging
  12. from typing import Any, Optional
  13. logger = logging.getLogger("hermes_cli.plugins")
  14. _TIMEOUT_S = 30.0
  15. def _err(code: str, detail: str = "") -> dict[str, Any]:
  16. return {"ok": False, "error": code, **({"detail": detail} if detail else {})}
  17. class PluginMessage:
  18. """Handle for one posted message. ``ok`` / ``message_id`` / ``error`` describe the last
  19. operation; ``edit(text)`` replaces the text in place (or posts anew where the surface cannot
  20. edit, and the handle then follows the new message). A refused post returns a handle whose
  21. edits are refused the same way. Operations stay ordered: one the gateway has not finished
  22. (``error == "timeout"``, ``pending`` set) is waited for before the next runs, and its outcome
  23. still lands on the handle, so a slow post never leaves an orphan message behind a dead handle."""
  24. def __init__(self, plugin_id: str, target: Any, result: dict[str, Any]):
  25. self._plugin_id, self._target = plugin_id, target
  26. self.result = result
  27. self.message_id: Optional[str] = result.get("message_id")
  28. self._pending: Optional[concurrent.futures.Future] = None
  29. @property
  30. def ok(self) -> bool:
  31. return bool(self.result.get("ok"))
  32. @property
  33. def error(self) -> Optional[str]:
  34. return self.result.get("error")
  35. @property
  36. def pending(self) -> bool:
  37. return self._pending is not None and not self._pending.done()
  38. def __repr__(self) -> str:
  39. return f"<PluginMessage ok={self.ok} message_id={self.message_id!r} error={self.error!r}>"
  40. def _adopt(self, other: PluginMessage) -> None:
  41. self._target, self.result, self.message_id = other._target, other.result, other.message_id
  42. def _refused(self) -> Optional[dict[str, Any]]:
  43. if self._target is None:
  44. return _err(self.error or "no_conversation", self.result.get("detail", ""))
  45. return None
  46. def _settle(self, result: dict[str, Any]) -> dict[str, Any]:
  47. self.result = result
  48. if result.get("ok") and result.get("message_id"):
  49. self.message_id = result["message_id"]
  50. return result
  51. async def _edit(self, text: str) -> dict[str, Any]:
  52. refused = self._refused()
  53. if refused is not None:
  54. return refused
  55. from gateway import plugin_messages
  56. return self._settle(await plugin_messages.edit(self._target, self.message_id, str(text),
  57. plugin_id=self._plugin_id))
  58. async def aedit(self, text: str) -> dict[str, Any]:
  59. """``edit`` for code already running on the gateway's event loop (async hooks/commands)."""
  60. if self.pending:
  61. await asyncio.wrap_future(self._pending)
  62. return await self._edit(text)
  63. def edit(self, text: str) -> dict[str, Any]:
  64. """Replace the message text: ``{"ok", "message_id", "edited", ["fallback"]}``. Thread-safe."""
  65. if _on_gateway_loop(): # never block the loop the pending operation needs
  66. return _err("on_event_loop", "called from the gateway event loop: use await handle.aedit(...)")
  67. if self.pending:
  68. try:
  69. self._pending.result(_TIMEOUT_S)
  70. except concurrent.futures.TimeoutError:
  71. return _err("timeout", "the previous operation on this message has not finished")
  72. except Exception: # its own outcome is already on the handle
  73. logger.debug("plugin_message: previous operation failed", exc_info=True)
  74. refused = self._refused()
  75. if refused is not None:
  76. return refused
  77. return _run_on_gateway_loop(self._edit(text), self)
  78. def _gateway_loop():
  79. try:
  80. from gateway.run import _gateway_runner_ref
  81. runner = _gateway_runner_ref()
  82. except ImportError:
  83. runner = None
  84. loop = getattr(runner, "_gateway_loop", None)
  85. if runner is None or not getattr(runner, "_running", False) or loop is None or loop.is_closed():
  86. return None, None
  87. return runner, loop
  88. def _on_gateway_loop() -> bool:
  89. _runner, loop = _gateway_loop()
  90. try:
  91. return loop is not None and asyncio.get_running_loop() is loop
  92. except RuntimeError:
  93. return False
  94. def _run_on_gateway_loop(coro, handle: PluginMessage) -> dict[str, Any]:
  95. """Run *coro* on the gateway loop and wait up to ``_TIMEOUT_S``; past that it keeps running as
  96. the handle's pending operation (its result still lands on the handle)."""
  97. _runner, loop = _gateway_loop()
  98. if loop is None:
  99. coro.close()
  100. return _err("gateway_unavailable", "no live gateway is running in this process")
  101. if _on_gateway_loop():
  102. coro.close()
  103. return _err("on_event_loop", "called from the gateway event loop: use the async form (await ...)")
  104. future = asyncio.run_coroutine_threadsafe(coro, loop)
  105. handle._pending = future
  106. try:
  107. return future.result(_TIMEOUT_S)
  108. except concurrent.futures.TimeoutError:
  109. result = _err("timeout", f"the gateway did not answer within {_TIMEOUT_S:.0f}s; the operation "
  110. "is still running and its result will land on this handle")
  111. handle.result = result
  112. return result
  113. except Exception as exc: # the plugin gets a result, never the raise
  114. logger.warning("plugin_message: gateway hand-off failed", exc_info=True)
  115. return _err("send_failed", str(exc)[:512])
  116. _NO_SESSION = ("no session is bound in the calling context (a tool call, slash command or hook "
  117. "fired for a session)")
  118. async def _post_for(ctx: Any, text: str, session_key: str, route: Any) -> PluginMessage:
  119. plugin_id = ctx.plugin_id
  120. runner, _loop = _gateway_loop()
  121. result: dict[str, Any]
  122. if not session_key:
  123. result = _err("no_conversation", _NO_SESSION)
  124. elif runner is None:
  125. result = _err("gateway_unavailable", "no live gateway is running in this process")
  126. else:
  127. from gateway import plugin_messages
  128. # The session store read is disk-bound: keep it off the gateway loop.
  129. target, refusal = await asyncio.to_thread(plugin_messages.resolve, runner, session_key=session_key,
  130. route=route, plugin_home=ctx._manager.home_path, plugin_id=plugin_id)
  131. if target is None:
  132. result = refusal or _err("no_conversation")
  133. else:
  134. result = await plugin_messages.post(target, str(text), plugin_id=plugin_id)
  135. if result.get("ok"):
  136. return PluginMessage(plugin_id, target, result)
  137. logger.info("plugin_message plugin=%s op=post refused: %s", plugin_id, result.get("error"))
  138. return PluginMessage(plugin_id, None, result)
  139. async def apost(ctx: Any, text: str) -> PluginMessage:
  140. """``post`` for code already running on the gateway's event loop (async hooks/commands)."""
  141. from gateway.plugin_messages import bound_route
  142. from gateway.session_context import bound_session_key
  143. return await _post_for(ctx, text, bound_session_key(), bound_route())
  144. def post(ctx: Any, text: str) -> PluginMessage:
  145. """Post *text* to the calling session from a tool handler or hook on a worker thread. The session
  146. is read here, on the caller's own context, then the send runs on the gateway loop."""
  147. from gateway.session_context import bound_session_key
  148. session_key = bound_session_key()
  149. if not session_key:
  150. return PluginMessage(ctx.plugin_id, None, _err("no_conversation", _NO_SESSION))
  151. from gateway.plugin_messages import bound_route
  152. route = bound_route()
  153. handle = PluginMessage(ctx.plugin_id, None, _err("timeout"))
  154. async def _post() -> dict[str, Any]:
  155. handle._adopt(await _post_for(ctx, text, session_key, route))
  156. return handle.result
  157. result = _run_on_gateway_loop(_post(), handle)
  158. if handle._target is None and not handle.pending:
  159. handle.result = result
  160. return handle