telegram_topic_transfer.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Opt-in root-DM -> fresh topic transfer for Telegram ``/topic`` mode (``dm_topic_auto_transfer``).
  2. Off by default: a root-DM message keeps the v0.22 lobby recovery and is answered in the user's
  3. most recently bound topic (#136567). With the key on, the runner's transfer hook creates a new
  4. topic and the message (and its reply) move there before session keying; if creating the topic
  5. fails, the hook answers with the lobby-recovery topic instead (#139136).
  6. """
  7. from __future__ import annotations
  8. import logging
  9. from typing import Any, Awaitable, Callable, Optional
  10. from gateway.platforms.base import coerce_plaintext_gateway_command
  11. from gateway.platforms.event import MessageEvent
  12. from gateway.session_identity import replace_source
  13. logger = logging.getLogger(__name__)
  14. # ``(thread_id, created)``: ``created`` = a fresh topic; otherwise the lobby-recovery fallback topic.
  15. TopicTransferFn = Callable[[Any], Awaitable[Optional[tuple[str, bool]]]]
  16. async def apply_root_dm_topic_transfer(adapter: Any, event: MessageEvent) -> None:
  17. """Rewrite ``event.source`` onto the topic the transfer hook picks; no-op when it declines.
  18. Runs at adapter ingress, before session keying, so the turn, its session and its reply all use
  19. the new topic. Commands, internal wakes, routed events and non-DM traffic are never moved.
  20. """
  21. transfer: Optional[TopicTransferFn] = getattr(adapter, "_topic_transfer_fn", None)
  22. source = getattr(event, "source", None)
  23. if transfer is None or source is None or getattr(source, "chat_type", None) != "dm":
  24. return
  25. if getattr(event, "allow_gateway_control", False):
  26. coerce_plaintext_gateway_command(event) # "restart gateway" is a lobby command too (idempotent)
  27. if getattr(event, "internal", False) or event.get_command():
  28. return
  29. if str((event.metadata or {}).get("gateway_session_key") or "").strip():
  30. return
  31. if adapter._is_sender_authorized(source.user_id, source.chat_type, source.chat_id) is False:
  32. return
  33. try:
  34. decided = await transfer(source)
  35. except Exception:
  36. logger.debug("telegram topic transfer hook failed", exc_info=True)
  37. return
  38. if not decided:
  39. return
  40. thread_id, created = decided
  41. if not created:
  42. event.source = replace_source(source, thread_id=str(thread_id))
  43. return
  44. # The root-DM message lives outside the new topic, so it cannot anchor the reply there: an empty
  45. # override plus no source.message_id sends the first reply by message_thread_id alone.
  46. event.source = replace_source(source, thread_id=str(thread_id), message_id=None)
  47. event.reply_anchor_override = ""