plugin_messages.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. """Where ``PluginContext.post_message`` lands: the conversation the calling plugin code works for.
  2. The route is never chosen by the plugin. It is the session whose key is bound in the calling context
  3. (a tool or hook in its turn, its slash command, a hook fired for it), resolved here on the gateway loop:
  4. * a messaging chat posts through the adapter that answers it (``adapter.send``) and edits through
  5. ``adapter.edit_message``; an adapter without edit support, or a refused edit, gets a fresh send and
  6. the handle follows the new message;
  7. * a local CLI/TUI/Desktop session has no transport of its own (``LocalSessionAdapter.send`` is a no-op),
  8. so the text goes to its viewers as a keyed ``notification.show``; an edit re-publishes the same key,
  9. which Desktop and the Ink TUI replace in place (the classic CLI queues each as a line for its next
  10. turn end).
  11. """
  12. from __future__ import annotations
  13. import logging
  14. import uuid
  15. from contextlib import contextmanager
  16. from contextvars import ContextVar
  17. from dataclasses import dataclass
  18. from typing import Any, Iterator, Optional
  19. from gateway.config import Platform
  20. logger = logging.getLogger(__name__)
  21. @dataclass
  22. class PostTarget:
  23. """A resolved conversation: a messaging ``adapter`` + ``chat_id``, or a local session's ``live``."""
  24. platform: str
  25. chat_id: str
  26. adapter: Any = None
  27. metadata: Optional[dict] = None
  28. live: Any = None
  29. notice_key: str = ""
  30. def _err(code: str, detail: str = "") -> dict:
  31. return {"ok": False, "error": code, **({"detail": detail} if detail else {})}
  32. def _fit(adapter: Any, chat_id: str, text: str) -> str:
  33. """Clamp *text* to the adapter's per-chat message limit (ellipsis), never split it."""
  34. try:
  35. limit = int(adapter.max_message_length_for_chat(chat_id))
  36. measure = adapter.message_len_fn_for_chat(chat_id)
  37. except (AttributeError, TypeError, ValueError): # an adapter not built on BasePlatformAdapter
  38. limit, measure = 4096, len
  39. if limit <= 0 or measure(text) <= limit:
  40. return text
  41. cut = text
  42. while cut and measure(cut + "…") > limit:
  43. cut = cut[: -max(1, measure(cut + "…") - limit)]
  44. return cut + "…"
  45. def _supports_edit(adapter: Any) -> bool:
  46. from gateway.platforms.base import BasePlatformAdapter
  47. if getattr(adapter, "SUPPORTS_MESSAGE_EDITING", True) is False:
  48. return False
  49. return getattr(type(adapter), "edit_message", None) is not BasePlatformAdapter.edit_message
  50. # The live inbound source of a call the gateway dispatches before its session is stored (a plugin
  51. # command that is the chat's first message), receiving-bot provenance included. Task-local, so the
  52. # executor thread a sync handler runs on inherits it and a concurrent chat never sees it.
  53. _LIVE_SOURCE: ContextVar = ContextVar("plugin_message_live_source", default=None)
  54. @contextmanager
  55. def bind_live_source(source) -> Iterator[None]:
  56. token = _LIVE_SOURCE.set(source)
  57. try:
  58. yield
  59. finally:
  60. _LIVE_SOURCE.reset(token)
  61. def bound_route():
  62. """The live source bound in THIS context (read on the caller's thread: the gateway loop runs the
  63. send in its own context), or ``None``."""
  64. return _LIVE_SOURCE.get()
  65. def resolve(runner, *, session_key: str, route, plugin_home, plugin_id: str):
  66. """``(PostTarget, None)`` for the session *session_key* names, or ``(None, error dict)``. *route*
  67. is the live source the gateway bound for this call, used only while the session is not stored."""
  68. entry = runner.session_store.lookup_by_session_key(session_key)
  69. if entry is not None and entry.origin is not None:
  70. from gateway.session_identity import replace_source
  71. source = replace_source(runner._restored_source(entry))
  72. elif route is not None and runner._session_key_for_source(route) == session_key:
  73. source = route
  74. else:
  75. return None, _err("no_conversation", f"session {session_key!r} is not known to this gateway")
  76. if source.platform == Platform.LOCAL:
  77. live = runner._plugin_local_session(source, session_key, plugin_home=plugin_home, plugin_id=plugin_id)
  78. if live is None:
  79. return None, _err("no_conversation", "the local session is not live in this plugin's profile")
  80. key = f"plugin-message:{plugin_id}:{uuid.uuid4().hex[:12]}"
  81. return PostTarget(platform="local", chat_id=source.chat_id, live=live, notice_key=key), None
  82. if not runner._plugin_messaging_session_owned(session_key, plugin_home=plugin_home, plugin_id=plugin_id):
  83. return None, _err("no_conversation", "the session belongs to another profile")
  84. adapter = runner._delivery_adapter_for(source)
  85. if adapter is None:
  86. return None, _err("adapter_unavailable", f"no connected {source.platform.value} adapter answers this chat")
  87. try:
  88. metadata = runner._thread_metadata_for_source(source)
  89. except Exception: # thread routing is optional: post to the chat itself
  90. logger.debug("plugin_message: no thread metadata for %s", source.platform.value, exc_info=True)
  91. metadata = None
  92. return PostTarget(platform=source.platform.value, chat_id=str(source.chat_id), adapter=adapter,
  93. metadata=metadata), None
  94. def _publish_local(target: PostTarget, text: str) -> dict:
  95. delivered = target.live.event_stream.publish(target.chat_id, {
  96. "text": text, "level": "info", "kind": "sticky", "key": target.notice_key, "id": target.notice_key,
  97. }, event_type="notification.show")
  98. return {"ok": True, "message_id": target.notice_key, "delivered": bool(delivered)}
  99. async def _send(target: PostTarget, text: str) -> dict:
  100. # Never the turn's answer: a relay stream open for the reply must not be sealed with it.
  101. metadata = {**(target.metadata or {}), "_interim_send": True}
  102. result = await target.adapter.send(target.chat_id, _fit(target.adapter, target.chat_id, text),
  103. metadata=metadata)
  104. if not getattr(result, "success", False):
  105. return _err("send_failed", str(getattr(result, "error", "") or "")[:512])
  106. return {"ok": True, "message_id": str(result.message_id) if result.message_id is not None else None}
  107. async def post(target: PostTarget, text: str, *, plugin_id: str) -> dict:
  108. """First message of a handle."""
  109. try:
  110. result = _publish_local(target, text) if target.live is not None else await _send(target, text)
  111. except Exception as exc: # adapter boundary: the plugin gets a result, never the raise
  112. logger.warning("plugin_message plugin=%s op=post send raised", plugin_id, exc_info=True)
  113. result = _err("send_failed", str(exc)[:512])
  114. logger.info("plugin_message plugin=%s op=post platform=%s chat=%s ok=%s message_id=%s%s", plugin_id,
  115. target.platform, target.chat_id, result.get("ok"), result.get("message_id"),
  116. "" if result.get("ok") else f" error={result.get('error')}")
  117. return result
  118. async def edit(target: PostTarget, message_id: Optional[str], text: str, *, plugin_id: str) -> dict:
  119. """Edit *message_id* in place; a surface that cannot edit gets a fresh message (``fallback``)."""
  120. result: dict
  121. try:
  122. if target.live is not None:
  123. result = {**_publish_local(target, text), "edited": True}
  124. elif message_id and _supports_edit(target.adapter):
  125. try:
  126. sent = await target.adapter.edit_message(target.chat_id, message_id,
  127. _fit(target.adapter, target.chat_id, text))
  128. edited, edit_error = bool(getattr(sent, "success", False)), str(getattr(sent, "error", "") or "")
  129. except Exception as exc: # a raised edit falls back like a refused one
  130. logger.debug("plugin_message plugin=%s edit_message raised", plugin_id, exc_info=True)
  131. sent, edited, edit_error = None, False, str(exc) or type(exc).__name__
  132. if edited:
  133. result = {"ok": True, "message_id": str(sent.message_id or message_id), "edited": True}
  134. else:
  135. result = {**await _send(target, text), "edited": False, "fallback": True,
  136. "edit_error": edit_error[:256]}
  137. else:
  138. result = {**await _send(target, text), "edited": False, "fallback": True}
  139. except Exception as exc: # adapter boundary, as in post()
  140. logger.warning("plugin_message plugin=%s op=edit raised", plugin_id, exc_info=True)
  141. result = _err("edit_failed", str(exc)[:512])
  142. logger.info("plugin_message plugin=%s op=edit platform=%s chat=%s ok=%s edited=%s message_id=%s%s",
  143. plugin_id, target.platform, target.chat_id, result.get("ok"), result.get("edited", False),
  144. result.get("message_id"), "" if result.get("ok") else f" error={result.get('error')}")
  145. return result