adapter_discord_interaction.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. """Forwarded Discord interaction -> ``MessageEvent`` normalization for the relay adapter.
  2. ``RelayAdapter`` mixes this in; the passthrough path (``_on_passthrough``) calls
  3. ``_discord_interaction_to_event`` for every connector-forwarded Discord interaction body and gives it
  4. the chat labels the text lane last carried (``_remember_discord_labels``).
  5. """
  6. from __future__ import annotations
  7. import asyncio
  8. import json
  9. import logging
  10. import re
  11. from gateway.config import Platform
  12. from gateway.platforms.event import MessageEvent, MessageType
  13. from gateway.session import SessionSource
  14. logger = logging.getLogger(__name__)
  15. # Connector promptCodec.decodePromptCallback id alphabet ([A-Za-z0-9_.-], <=32).
  16. _PROMPT_ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,32}$")
  17. class RelayDiscordInteractionMixin:
  18. """Decode connector-forwarded Discord interactions into normalized inbound events."""
  19. _DISCORD_LABELS_MAX = 2048
  20. def _capture_ingress_scope(self, event) -> None:
  21. """``_capture_scope`` for a connector-delivered event, on every Relay ingress path. A
  22. single-profile gateway serves the connector's profile route from its one profile, so once the
  23. stamp is kept for egress (persona attribution) it is cleared before admission, command
  24. dispatch or a passthrough turn. A bare adapter with no runner keeps it."""
  25. self._capture_scope(event)
  26. config = getattr(getattr(self._message_handler, '__self__', None), 'config', None)
  27. if config is not None and not getattr(config, 'multiplex_profiles', False):
  28. event.source.profile = None
  29. async def _remember_discord_labels(self, source) -> None:
  30. """Keep the text lane's Discord chat labels for the interaction lane: the pinned
  31. session-context prompt renders them, so a slash turn without them re-rendered the cached
  32. prefix and the next message rendered it back."""
  33. # A message carrying no labels is an observation too (a topic or name removed upstream):
  34. # the interaction must render what the text lane last rendered, not an older label.
  35. if getattr(source, "platform", None) != Platform.DISCORD or not source.chat_id:
  36. return
  37. key, labels = (str(source.scope_id or ""), str(source.chat_id)), (source.chat_name, source.chat_topic)
  38. self._discord_chat_labels[key] = labels
  39. self._evict_oldest(self._discord_chat_labels, self._DISCORD_LABELS_MAX)
  40. store = getattr(self, "_session_store", None)
  41. if store is None or self._discord_labels_recorded.get(key) == labels:
  42. return
  43. # Recorded when observed, so the interaction lane has them after a restart whatever order
  44. # the chat's sessions were created or reset in. Awaited before dispatch (the reader delivers
  45. # events one at a time, so records land in observation order) but off the loop: disk write.
  46. try:
  47. recorded = await asyncio.to_thread(store.record_chat_labels, source)
  48. except Exception:
  49. logger.debug("relay: Discord chat labels not recorded", exc_info=True)
  50. recorded = False
  51. if not recorded:
  52. # Not written (store fault, or no database handle right now): leave the key out so the
  53. # next message with these labels tries again.
  54. self._discord_labels_recorded.pop(key, None)
  55. return
  56. self._discord_labels_recorded[key] = labels
  57. self._evict_oldest(self._discord_labels_recorded, self._DISCORD_LABELS_MAX)
  58. async def _discord_chat_labels_for(self, scope: str, chat_id: str) -> tuple:
  59. """The text lane's last (chat_name, chat_topic) for a chat. After a restart (or eviction) the
  60. map is empty until the text lane speaks again, so ask the session store for what that lane
  61. last recorded; otherwise a first interaction re-renders the prompt the cache still holds."""
  62. key = (scope, chat_id)
  63. if key in self._discord_chat_labels:
  64. return self._discord_chat_labels[key]
  65. store = getattr(self, "_session_store", None)
  66. try:
  67. # Off the loop: the read takes the database's writer lock, which a write may be holding.
  68. recorded = (await asyncio.to_thread(store.chat_labels, Platform.DISCORD, scope, chat_id)
  69. if store is not None else None)
  70. except Exception:
  71. # Labels only keep the prompt cache warm; a store fault must not drop the interaction.
  72. # Not cached either: the next interaction asks the store again.
  73. logger.debug("relay: recorded Discord chat labels unreadable", exc_info=True)
  74. return (None, None)
  75. if recorded is not None:
  76. self._discord_labels_recorded[key] = recorded
  77. self._evict_oldest(self._discord_labels_recorded, self._DISCORD_LABELS_MAX)
  78. self._discord_chat_labels[key] = recorded or (None, None)
  79. self._evict_oldest(self._discord_chat_labels, self._DISCORD_LABELS_MAX)
  80. return self._discord_chat_labels[key]
  81. async def _on_passthrough(self, forward, buffer_id=None) -> None:
  82. """Handle a connector-forwarded passthrough request. The connector answered the
  83. provider's latency-critical ACK at the edge, verified the signature and vaulted
  84. any shared-identity credential; the agent later acts via the token-less
  85. ``send_follow_up`` path. A Discord interaction becomes a normalized
  86. ``MessageEvent`` on the SAME agent path as chat; other forwards are logged and
  87. dropped. NEVER raises: a malformed forward must not kill the read loop."""
  88. try:
  89. platform = getattr(forward, "platform", "") or ""
  90. if platform == "discord":
  91. event = self._discord_interaction_to_event(forward)
  92. if event is not None:
  93. self._capture_ingress_scope(event)
  94. # A prompt-token component press is consumed (same gate as _on_inbound).
  95. if await self._consume_prompt_response(event):
  96. return
  97. src = event.source
  98. src.chat_name, src.chat_topic = await self._discord_chat_labels_for(
  99. str(src.scope_id or ""), src.chat_id)
  100. from gateway.session_ingress_context import relay_passthrough_event
  101. with relay_passthrough_event(self._transport, forward, event):
  102. await self.handle_message(event)
  103. return
  104. logger.info(
  105. "relay passthrough_forward dropped (no handler): platform=%s method=%s path=%s",
  106. platform, getattr(forward, "method", "?"), getattr(forward, "path", "?"),
  107. )
  108. except Exception:
  109. logger.warning("relay passthrough_forward handling failed", exc_info=True)
  110. def _discord_interaction_to_event(self, forward):
  111. """Convert a forwarded Discord interaction body to a MessageEvent, or None for
  112. an unusable body (a PING is answered at the edge and never forwarded). The
  113. session source mirrors the connector's ``interactionSessionSource`` so the
  114. session key matches the one the follow-up capability was bound under."""
  115. try:
  116. payload = json.loads(bytes(getattr(forward, "body", b"")).decode("utf-8"))
  117. except Exception:
  118. return None
  119. if not isinstance(payload, dict):
  120. return None
  121. # type 2 = APPLICATION_COMMAND; 3 = MESSAGE_COMPONENT; 5 = MODAL_SUBMIT.
  122. itype = payload.get("type")
  123. data = payload.get("data") or {}
  124. message_type = MessageType.TEXT
  125. if itype == 2:
  126. # Normalize to a leading-slash command string ("/name arg…"), the
  127. # shape the dispatcher and the connector's Slack slash lane expect.
  128. text = ("/" + str(data.get("name") or "")).rstrip("/") or ""
  129. if text:
  130. parts = [text] + self._render_interaction_options(data.get("options"))
  131. text = " ".join(parts).strip()
  132. message_type = MessageType.COMMAND
  133. elif itype == 3:
  134. text = str(data.get("custom_id") or "")
  135. elif itype == 5:
  136. text = self._render_modal_submit(data)
  137. else:
  138. text = ""
  139. member = payload.get("member") or {}
  140. user = (member.get("user") if isinstance(member, dict) else None) or payload.get("user") or {}
  141. if not isinstance(user, dict):
  142. user = {}
  143. guild_id = payload.get("guild_id")
  144. # The text lane's user_display_name is the native author.display_name: guild nick, else
  145. # global name, else username. The interaction carries all three as of now, so derive the
  146. # same name from it; a remembered one would outlive a nickname change.
  147. user_name = next(
  148. (str(v) for v in ((member.get("nick") if isinstance(member, dict) else None),
  149. user.get("global_name"), user.get("username")) if v), None)
  150. chat_id = str(payload.get("channel_id") or "")
  151. # The text lane keys a message inside a thread on chat_type "thread" + thread_id (both session-key
  152. # fields), so an interaction sent there must carry the same or it lands in a per-user "group"
  153. # session beside the thread's. The partial channel object marks a thread by type (10 announcement,
  154. # 11 public, 12 private: what discord.py's Thread covers) and names the parent.
  155. channel = payload.get("channel") if isinstance(payload.get("channel"), dict) else {}
  156. is_thread = bool(guild_id) and channel.get("type") in (10, 11, 12)
  157. source = SessionSource(
  158. # The LOGICAL platform, not RELAY: session keys must match the connector's
  159. # capability binding (platform="discord"), /sethome must file under the
  160. # logical platform, and _capture_scope skips the generic "relay".
  161. platform=Platform.DISCORD,
  162. chat_id=chat_id,
  163. # "group", not "channel": both the connector's capability binding and the
  164. # native Discord adapter key guild channels as "group".
  165. chat_type="thread" if is_thread else ("group" if guild_id else "dm"),
  166. thread_id=chat_id if is_thread else None,
  167. parent_chat_id=str(channel["parent_id"]) if is_thread and channel.get("parent_id") else None,
  168. user_id=str(user["id"]) if user.get("id") else None,
  169. user_name=user_name,
  170. # chat_name / chat_topic: filled by _on_passthrough from what the text lane recorded.
  171. scope_id=str(guild_id) if guild_id else None,
  172. message_id=str(payload.get("id")) if payload.get("id") else None,
  173. # Same upstream-trust marker the relay text lane stamps. Set locally, never
  174. # read off the wire (engages /sethome's via_relay guard).
  175. delivered_via_upstream_relay=True,
  176. # Profile routing (multiplex mode), mirroring _event_from_wire.
  177. # The HERMES profile this interaction is routed to (multiplex mode) — mirrors _event_from_wire's
  178. # profile stamping for plain relayed messages (#60586). Without this, a Team-Gateway's Discord
  179. # slash-command/button/modal always fell back to the legacy agent:main namespace even when the
  180. # connector resolved a specific profile for it.
  181. profile=getattr(forward, "profile", None),
  182. )
  183. event = MessageEvent(text=text, message_type=message_type, source=source)
  184. if itype == 3:
  185. # A component press whose custom_id is a Hermes prompt token
  186. # (hp1:<prompt_id>:<option_id>) becomes a STRUCTURED prompt answer;
  187. # foreign custom_ids keep the best-effort TEXT shape.
  188. decoded = self._decode_prompt_token(text)
  189. if decoded:
  190. prompt_id, option_id = decoded
  191. msg = payload.get("message") or {}
  192. prompt_message_id = str(msg["id"]) if isinstance(msg, dict) and msg.get("id") else None
  193. event.prompt_response = {
  194. "prompt_id": prompt_id,
  195. "option_id": option_id,
  196. "prompt_message_id": prompt_message_id,
  197. }
  198. event.text = f"/{option_id}"
  199. event.message_type = MessageType.COMMAND
  200. return event
  201. @staticmethod
  202. def _decode_prompt_token(token: str):
  203. """Decode an hp1:<prompt_id>:<option_id> callback token, or None (mirrors the connector's promptCodec)."""
  204. parts = (token or "").split(":")
  205. if len(parts) != 3 or parts[0] != "hp1":
  206. return None
  207. if not _PROMPT_ID_RE.match(parts[1]) or not _PROMPT_ID_RE.match(parts[2]):
  208. return None
  209. return parts[1], parts[2]
  210. @staticmethod
  211. def _render_modal_submit(data) -> str:
  212. """A MODAL_SUBMIT as text: the modal's custom_id, then one ``input_id: value`` line per
  213. submitted input. Inputs sit in action rows (``components``) or labels (``component``);
  214. an empty optional input is left out."""
  215. lines = [str(data.get("custom_id") or "")]
  216. stack = list(reversed(data.get("components") or []))
  217. while stack:
  218. comp = stack.pop()
  219. if not isinstance(comp, dict):
  220. continue
  221. nested = comp.get("components") or ([comp["component"]] if comp.get("component") else [])
  222. stack.extend(reversed(nested if isinstance(nested, list) else []))
  223. value = comp.get("value", comp.get("values"))
  224. if isinstance(value, list):
  225. value = ", ".join(str(v) for v in value)
  226. if value is not None and str(value).strip():
  227. lines.append(f"{comp.get('custom_id') or ''}: {value}")
  228. return "\n".join(lines).strip()
  229. @staticmethod
  230. def _render_interaction_options(options) -> list:
  231. """Render Discord interaction options to text parts: scalars contribute their
  232. value (native ``f"/model {name}"`` shape); SUB_COMMAND (1) / SUB_COMMAND_GROUP
  233. (2) contribute their name then recurse into nested options."""
  234. parts: list = []
  235. if not isinstance(options, list):
  236. return parts
  237. for opt in options:
  238. if not isinstance(opt, dict):
  239. continue
  240. if opt.get("type") in (1, 2):
  241. sub_name = str(opt.get("name") or "").strip()
  242. if sub_name:
  243. parts.append(sub_name)
  244. parts.extend(RelayDiscordInteractionMixin._render_interaction_options(opt.get("options")))
  245. else:
  246. value = opt.get("value")
  247. if value is not None and str(value).strip():
  248. parts.append(str(value).strip())
  249. return parts