plugin_keyless_inject.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. """Where a key-less ``PluginContext.inject_message(text)`` goes when plugin code runs for the gateway.
  2. Before the one-gateway runtime each classic CLI loaded its own plugins, so a key-less inject meant that
  3. CLI's own chat. The gateway's copy of a plugin (or its plugin host's) serves every session of its
  4. profile, so the target is picked here, in order:
  5. 1. The local session the call is working for: the session bound in the calling context (its slash
  6. command, a hook fired for it, a tool or hook in its turn). Never a guess, however many are open.
  7. 2. No session in the calling context (a timer, the plugin's own thread): the one local session of the
  8. plugin's profile launched by the classic CLI (frozen policy source ``cli``) with a viewer attached.
  9. 3. Otherwise refused by name: nothing is injected anywhere.
  10. A calling context that is another profile's local session gets the keyed path's refusal naming the
  11. plugin's profile; any other one (a messaging chat) keeps main's refusal. A resolved target is
  12. committed like a keyed plugin inject under the session authority: a queued producer admission in that
  13. session's FIFO, run once, in order.
  14. """
  15. from __future__ import annotations
  16. import contextlib
  17. import logging
  18. from pathlib import Path
  19. import threading
  20. import time
  21. from gateway.config import Platform
  22. logger = logging.getLogger("gateway.run")
  23. # One refusal warning per (plugin, kind) per window: a plugin retrying on a timer must not flood the log.
  24. # (plugin, kind) -> when it last warned; a mark past the window is dropped at the next refusal.
  25. _WARN_WINDOW_S = 300.0
  26. _warned: dict[tuple[str, str], float] = {}
  27. _warned_lock = threading.Lock() # refusals run on plugin threads
  28. def _refuse(plugin_id: str, kind: str, detail: str) -> None:
  29. now = time.monotonic()
  30. with _warned_lock:
  31. for key in [key for key, at in _warned.items() if now - at >= _WARN_WINDOW_S]:
  32. del _warned[key]
  33. repeated = (plugin_id, kind) in _warned
  34. if not repeated:
  35. _warned[(plugin_id, kind)] = now
  36. if repeated:
  37. logger.debug("inject_message from plugin %s refused again: %s", plugin_id, detail)
  38. return
  39. logger.warning("inject_message from plugin %s has no session key and %s; nothing was injected. Pass "
  40. "session_key= (or origin=) to choose the chat.", plugin_id, detail)
  41. def _local(runner, live) -> bool:
  42. from gateway.session_local import authorize_local_source
  43. source = live.source
  44. return source is not None and source.platform == Platform.LOCAL and authorize_local_source(runner, source) is True
  45. def _launched_by_classic_cli(runner, live) -> bool:
  46. from gateway.session_policy import policy_for_source
  47. from hermes_state_runtime import RuntimeStoreError
  48. try:
  49. policy = policy_for_source(runner, live.source)
  50. except RuntimeStoreError:
  51. return False
  52. return policy is not None and policy.source == "cli"
  53. def resolve(runner, *, plugin_home, calling_session_key: str, plugin_id: str):
  54. """``(authority, live session)`` the key-less inject goes to, or ``None`` (logged). Runs on the
  55. plugin's calling thread so a refusal is the plugin's own ``False``; it only reads the authority's
  56. live map, never the store."""
  57. from gateway.session_authorities import all_authorities, authority_for_home
  58. authority = authority_for_home(runner, plugin_home) if plugin_home is not None else None
  59. if authority is None:
  60. _refuse(plugin_id, "unserved", f"its profile home {plugin_home} is not served by this gateway")
  61. return None
  62. sessions = list(authority.sessions.values())
  63. if calling_session_key:
  64. live = next((s for s in sessions if s.route == calling_session_key and _local(runner, s)), None)
  65. if live is None:
  66. if any(s.route == calling_session_key and s.source is not None and s.source.platform == Platform.LOCAL
  67. for other in all_authorities(runner) if other is not None and other is not authority
  68. for s in other.sessions.values()):
  69. # Another profile's local session: the keyed path's refusal, naming the plugin's profile.
  70. logger.warning("Plugin message injection refused: plugin=%s session=%s is not a live local session "
  71. "of the plugin's profile home %s", plugin_id, calling_session_key, plugin_home)
  72. return None
  73. # Main's answer for a key-less inject from a messaging chat's command, hook or tool.
  74. logger.warning("inject_message: gateway mode requires an existing session_key or an origin")
  75. return None
  76. return authority, live
  77. attached = [s for s in sessions if s.subscribers and _local(runner, s) and _launched_by_classic_cli(runner, s)]
  78. if len(attached) == 1:
  79. return authority, attached[0]
  80. if not attached:
  81. _refuse(plugin_id, "none", "no classic CLI session is attached in its profile")
  82. return None
  83. _refuse(plugin_id, "several", f"{len(attached)} classic CLI sessions are attached in its profile")
  84. return None
  85. async def admit(runner, authority, live, *, content: str, plugin_id: str) -> bool:
  86. """Commit the text to *live*'s durable FIFO through the keyed path's producer admission, under the
  87. plugin's profile (whose authority resolved it)."""
  88. from gateway.session_authorities import active_authority
  89. if not runner._plugin_injection_accepting():
  90. return False
  91. entry = await runner.async_session_store.lookup_by_session_key(live.route)
  92. if entry is None or not runner._plugin_injection_accepting():
  93. return False
  94. scope = contextlib.nullcontext()
  95. if getattr(getattr(runner, "config", None), "multiplex_profiles", False) is True:
  96. from gateway.run import _async_profile_runtime_scope
  97. scope = _async_profile_runtime_scope(Path(authority.profile_id))
  98. async with scope:
  99. if active_authority(runner) is not authority:
  100. return False
  101. return bool(await runner._admit_plugin_injection(
  102. runner._adapter_for_source(live.source), live.source, session_key=live.route,
  103. session_id=entry.session_id, content=content, plugin_id=plugin_id))