event.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. """Inbound message event types shared by every gateway platform adapter.
  2. A leaf module: adapters, helpers and the runner import it, so it must not import from
  3. gateway.platforms.*.
  4. """
  5. import re
  6. import unicodedata
  7. from dataclasses import dataclass, field
  8. from datetime import datetime
  9. from enum import Enum
  10. from typing import Any, Dict, List, Optional
  11. from gateway.session import SessionSource
  12. # Desktop attachment reference tags prepended by buildContextText before the
  13. # user's visible text (e.g. "@image:/tmp/foo.png\n\n/moa ask something").
  14. # Strip these when detecting slash commands so a media-ref prefix does not hide
  15. # a slash token from MessageEvent.is_command() / get_command().
  16. # The pattern matches to end-of-line (not just whitespace-bounded) to handle
  17. # Windows paths that may contain spaces (e.g. "C:\Users\John Doe\image.png").
  18. _ATTACHMENT_REF_RE = re.compile(r"^(?:@(?:image|file|url):[^\n]+\n?)+", re.IGNORECASE)
  19. _MAX_FILENAME_CHARS = 255
  20. def clean_attachment_filename(name: object) -> str:
  21. """An untrusted attachment filename reduced to a display-safe basename; ``""`` when unusable.
  22. Directory parts (either separator), control and format characters (CR/LF, NUL, bidi
  23. overrides) are dropped and the length is capped with the extension kept. Never a storage
  24. path: callers keep their own random cache names."""
  25. if not isinstance(name, str):
  26. return ""
  27. base = name.replace("\\", "/").rsplit("/", 1)[-1]
  28. base = "".join(ch for ch in base if unicodedata.category(ch) not in {"Cc", "Cf"}).strip()
  29. if base in {"", ".", ".."}:
  30. return ""
  31. if len(base) > _MAX_FILENAME_CHARS:
  32. stem, dot, ext = base.rpartition(".")
  33. keep = f"{dot}{ext}" if stem and len(ext) <= 16 else ""
  34. base = base[: _MAX_FILENAME_CHARS - len(keep)] + keep
  35. return base
  36. class MessageType(Enum):
  37. """Types of incoming messages."""
  38. TEXT = "text"
  39. LOCATION = "location"
  40. PHOTO = "photo"
  41. VIDEO = "video"
  42. AUDIO = "audio"
  43. VOICE = "voice"
  44. DOCUMENT = "document"
  45. STICKER = "sticker"
  46. COMMAND = "command" # /command style
  47. class ProcessingOutcome(Enum):
  48. """Result classification for message-processing lifecycle hooks."""
  49. SUCCESS = "success"
  50. FAILURE = "failure"
  51. CANCELLED = "cancelled"
  52. @dataclass
  53. class MessageEvent:
  54. """Incoming message from a platform — the normalized shape all adapters produce."""
  55. text: str
  56. message_type: MessageType = MessageType.TEXT
  57. # Author, mirrored from ``source`` for per-message prompt builders; None for non-IM sources.
  58. user_id: Optional[str] = None
  59. user_name: Optional[str] = None
  60. # None only in isolated unit tests; production always sets it. Typing it Optional
  61. # exposes ~60 unguarded ``.source.<attr>`` reads, so that is a separate change.
  62. source: SessionSource = None
  63. raw_message: Any = None
  64. message_id: Optional[str] = None
  65. # Delivery-ledger identity for the final send, when it differs from ``message_id``. A queued
  66. # (/queue) chain answers the LAST message of the chain, so its final send has to be ledgered
  67. # under that message's id. Keyed on the opening event's id instead, two chained turns carrying
  68. # the same text collide on one obligation id and the earlier turn's row is overwritten (a
  69. # refused first reply then reads as delivered). Reply routing is unaffected: the reply anchor
  70. # still comes from this event.
  71. ledger_message_id: Optional[str] = None
  72. # Reply anchor for the final send when the answer is to a DIFFERENT message than the one that
  73. # opened the turn: a successful busy redirect turns the running turn onto the redirecting
  74. # message, so its reply must quote that message (#115001). ``_reply_anchor_for_event``
  75. # honours this over ``message_id``; None = derive from the event as usual.
  76. reply_anchor_override: Optional[str] = None
  77. # Platform update id (Telegram ``update_id``): ``/restart`` records it so the new gateway
  78. # advances past it even if PTB's shutdown ACK times out.
  79. platform_update_id: Optional[int] = None
  80. # Media attachments: local file paths (for vision tool access)
  81. media_urls: list[str] = field(default_factory=list)
  82. media_types: list[str] = field(default_factory=list)
  83. # Per-attachment text-inlining contract; None = legacy "text/* already inlined into ``text``".
  84. media_text_inlined: list[Optional[bool]] = field(default_factory=list)
  85. reply_to_message_id: Optional[str] = None
  86. reply_to_text: Optional[str] = None # Text of the replied-to message (for context injection)
  87. reply_to_author_id: Optional[str] = None
  88. reply_to_author_name: Optional[str] = None
  89. reply_to_is_own_message: bool = False # True when the user replied to this bot/assistant's message
  90. # Structured interactive-prompt reply (relay only): {prompt_id, option_id, label?,
  91. # prompt_message_id?}; routed to the approval/slash-confirm/clarify resolvers BEFORE dispatch.
  92. prompt_response: Optional[dict[str, Any]] = None
  93. # Auto-loaded skill(s) for topic/channel bindings; a single name or ordered list.
  94. auto_skill: Optional[str | list[str]] = None
  95. # Per-channel ephemeral system prompt; applied at API call time, never persisted to transcript.
  96. channel_prompt: Optional[str] = None
  97. # History-backfilled channel context (missed under require_mention); kept out of ``text`` so
  98. # run.py's sender-prefix logic sees only the trigger message.
  99. channel_context: Optional[str] = None
  100. # Set for synthetic events (e.g. background-process notifications) that must bypass user authorization.
  101. internal: bool = False
  102. # Free-form per-event metadata (e.g. ``whatsapp_from_owner=True``); plugins must ``.get()``.
  103. metadata: dict[str, Any] = field(default_factory=dict)
  104. timestamp: datetime = field(default_factory=datetime.now)
  105. # May this event resolve gateway commands / control prompts? Proactive plugin events set False
  106. # so untrusted payload text stays conversational. New fields append after it (positional compat).
  107. allow_gateway_control: bool = True
  108. # Was this message addressed to this bot? False lets a bare silence marker stand (the adapter
  109. # knows the message was meant for someone else); None means unknown and keeps the visible
  110. # fallback, like True.
  111. reply_expected: Optional[bool] = None
  112. # Set for synthetic turns that carry no channel inputs of their own (goal continuation,
  113. # heartbeat due-prompts, /goal resume) so the turn reuses the session's pinned channel
  114. # prompt/parent instead of overwriting it with this event's own None (#126109). Independent
  115. # of ``internal``: these events still go through user authorization. Appended after
  116. # ``reply_expected`` for positional compat (see the field-order rule above).
  117. inherit_channel_pin: bool = False
  118. # Identity of one edit of a message (Telegram: its ``update_id``). An edit re-sends its message's own
  119. # ``message_id`` with new text, so native admission keys it apart from the original send.
  120. # Appended for positional compat (see the field-order rule above).
  121. edit_revision: Optional[str] = None
  122. # Original filename per attachment, parallel to ``media_urls`` like ``media_types`` ("" =
  123. # unknown). For adapters whose ``media_urls`` are random cache names (relay); the name is
  124. # display data only, never a path. Appended for positional compat.
  125. media_filenames: list[str] = field(default_factory=list)
  126. # Process-local admission receipt, never routing metadata or execution acknowledgement.
  127. _gateway_accepted: bool = field(default=False, init=False, repr=False, compare=False)
  128. # Set when ``admit_internal_event`` hands its producer a receipt before any drain began. The
  129. # producer will not retry, so a restart drain runs this event instead of refusing it at the
  130. # drain gate or discarding it as a queued follow-up (#138123).
  131. _admitted_before_drain: bool = field(default=False, init=False, repr=False, compare=False)
  132. # Run-owned final presentation snapshot; never deserialized from ingress metadata.
  133. _notification_reply_muted: Optional[bool] = field(default=None, init=False, repr=False, compare=False)
  134. def absorb_reply_expected(self, other: "MessageEvent") -> None:
  135. """One turn now answers *other* too: an addressed message wins, then an unknown one."""
  136. if self.reply_expected is not True and other.reply_expected is not False:
  137. self.reply_expected = other.reply_expected
  138. def extend_media(self, other: "MessageEvent") -> None:
  139. """Append *other*'s attachments (urls, types and original names) to this event's. Names are
  140. padded with ``""`` on either side so each stays on its own attachment; events without names
  141. (native adapters keep the name in the cache path) leave ``media_filenames`` untouched."""
  142. if self.media_filenames or other.media_filenames:
  143. def pad(msg: "MessageEvent") -> list[str]:
  144. return (list(msg.media_filenames) + [""] * len(msg.media_urls))[: len(msg.media_urls)]
  145. self.media_filenames = pad(self) + pad(other)
  146. self.media_urls.extend(other.media_urls)
  147. self.media_types.extend(other.media_types)
  148. def _command_text(self) -> str:
  149. """Return the message text with leading Desktop attachment refs stripped.
  150. Desktop's buildContextText prepends ``@image:<path>``, ``@file:<path>``,
  151. or ``@url:<url>`` tags before the user's visible text. Stripping these
  152. lets is_command / get_command / get_command_args work correctly even
  153. when the payload is prefixed with one or more media refs.
  154. """
  155. return _ATTACHMENT_REF_RE.sub("", (self.text or "").lstrip()).lstrip()
  156. def is_command(self) -> bool:
  157. """Check if this is a command message (e.g., /new, /reset)."""
  158. return self.allow_gateway_control and self._command_text().startswith("/")
  159. def get_command(self) -> Optional[str]:
  160. """Extract command name if this is a command message."""
  161. if not self.is_command():
  162. return None
  163. raw = self._command_text().split(maxsplit=1)[0][1:].lower().split("@", 1)[0]
  164. # Reject file paths: valid command names never contain /
  165. return None if "/" in raw else raw
  166. def get_command_args(self) -> str:
  167. """Get the arguments after a command."""
  168. if not self.is_command():
  169. return self.text
  170. parts = self._command_text().lstrip().split(maxsplit=1)
  171. args = parts[1] if len(parts) > 1 else ""
  172. # iOS auto-corrects -- to — (em dash) and - to – (en dash)
  173. return args.replace("\u2014\u2014", "--").replace("\u2014", "--").replace("\u2013", "-")