plugins_injection.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """Host routing for ``PluginContext.inject_message``: classic CLI REPL, Ink TUI / desktop, messaging
  2. gateway (existing ``session_key`` or a new session at ``origin``)."""
  3. from __future__ import annotations
  4. import logging
  5. from collections.abc import Mapping
  6. from typing import Any, Optional
  7. logger = logging.getLogger("hermes_cli.plugins")
  8. def inject_plugin_message(
  9. ctx: Any, content: str, role: str, *, session_key: Optional[str],
  10. origin: Optional[Mapping[str, Any]],
  11. ) -> bool:
  12. manager = ctx._manager
  13. msg = content if role == "user" else f"[{role}] {content}"
  14. cli = manager._cli_ref
  15. # An origin names a messaging chat; the local REPL is never that chat.
  16. if cli is not None and origin is None:
  17. queue_ = cli._interrupt_queue if getattr(cli, "_agent_running", False) else cli._pending_input
  18. queue_.put(msg)
  19. return True
  20. if session_key and origin is not None:
  21. logger.warning("inject_message: pass session_key or origin, not both")
  22. return False
  23. # Neither: the live gateway picks the chat (gateway/plugin_keyless_inject.py) from the session this
  24. # call works for, read here on the caller's own context; no gateway keeps main's refusal.
  25. keyless = not session_key and origin is None
  26. if keyless and not manager.has_gateway_message_injector:
  27. logger.warning("inject_message: gateway mode requires an existing session_key or an origin")
  28. return False
  29. if origin is not None and not isinstance(origin, Mapping):
  30. logger.warning("inject_message: origin must be a mapping in the SessionSource.to_dict() shape")
  31. return False
  32. if not ctx._gateway_injection_allowed():
  33. logger.warning("inject_message: gateway injection denied for plugin %s; set "
  34. "plugins.entries.%s.allow_gateway_injection: true to allow it",
  35. ctx.plugin_id, ctx.plugin_id)
  36. return False
  37. # TUI/desktop host is a different slot. It accepts only when it owns this
  38. # session_key; a miss falls through so a co-resident messaging gateway
  39. # still receives its own keys. An exception fails closed — do not also
  40. # hand the same text to the gateway.
  41. if session_key and manager.has_tui_message_injector:
  42. try:
  43. if manager.inject_tui_message(session_key=session_key, content=msg, plugin_id=ctx.plugin_id):
  44. return True
  45. except Exception:
  46. logger.warning("inject_message: TUI scheduling failed for plugin %s", ctx.plugin_id, exc_info=True)
  47. return False
  48. if not manager.has_gateway_message_injector:
  49. logger.warning("inject_message: no live gateway is available")
  50. return False
  51. # The manager's immutable home is the plugin's profile: the gateway creates an origin's session
  52. # there or nowhere, and a keyed local session must belong to it (never the ambient HERMES_HOME
  53. # of whatever thread called us).
  54. if keyless:
  55. from gateway.session_context import bound_session_key
  56. target: dict[str, Any] = {"keyless": True, "calling_session_key": bound_session_key(),
  57. "plugin_home": manager.home_path}
  58. elif origin is None:
  59. target = {"session_key": session_key, "plugin_home": manager.home_path}
  60. else:
  61. target = {"origin": dict(origin), "plugin_home": manager.home_path}
  62. try:
  63. return bool(manager.inject_gateway_message(**target, content=msg, plugin_id=ctx.plugin_id))
  64. except Exception:
  65. logger.warning("inject_message: gateway scheduling failed for plugin %s", ctx.plugin_id, exc_info=True)
  66. return False