run_topics.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. """Telegram forum-topic and Discord auto-thread binding/rename methods for GatewayRunner (MRO mixin).
  2. ``gateway.run`` internals are imported lazily inside method bodies (import cycle), so
  3. ``patch("gateway.run.X")`` keeps intercepting them at call time."""
  4. from __future__ import annotations
  5. import asyncio
  6. import json
  7. import logging
  8. import re
  9. import time
  10. from contextlib import suppress
  11. from pathlib import Path
  12. from typing import TYPE_CHECKING, Optional, Tuple
  13. from agent.compaction_display import project_compaction_message_for_display
  14. from agent.i18n import t
  15. from gateway.config import Platform
  16. from gateway.platforms.base import _prefix_within_utf16_limit, utf16_len
  17. from gateway.platforms.event import MessageEvent
  18. from gateway.session import SessionSource
  19. from gateway.session_identity import replace_source
  20. from utils import is_truthy_value
  21. if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
  22. from gateway.run import GatewayRunner
  23. from gateway.run_turn_runner import TurnRunner
  24. # Log-record parity with the origin module.
  25. logger = logging.getLogger("gateway.run")
  26. def _topic_restore_steps() -> tuple:
  27. return (t("gateway.topic.restore_step_1"), t("gateway.topic.restore_step_2"))
  28. def _collapse_title(title: str) -> str:
  29. return re.sub(r"\s+", " ", str(title or "")).strip() or t("gateway.topic.default_title")
  30. class GatewayTopicThreadsMixin:
  31. """Telegram forum-topic and Discord auto-thread binding/rename methods for GatewayRunner."""
  32. # ── Telegram topic mode: predicates and keys ────────────────────────────────────────────
  33. @staticmethod
  34. def _telegram_topic_profile_name(source: SessionSource) -> str:
  35. """Profile namespace for topic-mode rows: the profile stamped on the routed event, never the
  36. process-global one (under multiplex that mis-attributes state across bots sharing state.db).
  37. See #76423.
  38. """
  39. return str(getattr(source, "profile", None) or "").strip() or "default"
  40. def _sync_session_db(self):
  41. """The sync SessionDB handle, or None. Only for callers that provably run off-loop."""
  42. session_db = getattr(self, "_session_db", None)
  43. return None if session_db is None else getattr(session_db, "_db", session_db)
  44. @staticmethod
  45. def _is_telegram_dm(source: SessionSource) -> bool:
  46. return source.platform == Platform.TELEGRAM and source.chat_type == "dm"
  47. def _telegram_topic_mode_enabled(self, source: SessionSource) -> bool:
  48. """Return whether Telegram DM topic mode is active for this chat."""
  49. session_db = self._sync_session_db() if self._is_telegram_dm(source) else None
  50. if session_db is None:
  51. return False
  52. try:
  53. raw = session_db.is_telegram_topic_mode_enabled(
  54. chat_id=str(source.chat_id), user_id=str(source.user_id),
  55. profile_name=self._telegram_topic_profile_name(source),
  56. )
  57. except Exception:
  58. logger.debug("Failed to read Telegram topic mode state", exc_info=True)
  59. return False
  60. # Only a real True enables topic mode; anything else (including MagicMock from test
  61. # fixtures that didn't opt in) means off for this chat.
  62. return raw is True
  63. def _is_telegram_topic_root_lobby(self, source: SessionSource) -> bool:
  64. """True for the main Telegram DM (or General topic) when topic mode has made it a lobby."""
  65. return (
  66. self._is_telegram_dm(source) and self._telegram_topic_mode_enabled(source)
  67. and str(source.thread_id or "") in self._TELEGRAM_GENERAL_TOPIC_IDS
  68. )
  69. def _is_telegram_topic_lane(self, source: SessionSource) -> bool:
  70. """True for a user-created Telegram private-chat topic lane. Never a conversation its chat
  71. moved past (gateway/session_detached.py): its turns neither heal nor rewrite the topic's
  72. binding, nor rename the topic, which belong to the chat's current conversation."""
  73. from gateway.session_detached import detached_route_of
  74. tid = str(source.thread_id or "")
  75. return (
  76. detached_route_of(source) is None
  77. and self._is_telegram_dm(source) and self._telegram_topic_mode_enabled(source)
  78. and bool(tid) and tid not in self._TELEGRAM_GENERAL_TOPIC_IDS
  79. )
  80. def _telegram_topic_cooldown_key(self, source: SessionSource) -> Optional[str]:
  81. """Cooldown key (profile, chat_id): profiles sharing a Telegram private chat_id under
  82. multiplex must not suppress each other's lobby reminders / capability hints.
  83. See #76423.
  84. """
  85. chat_id = str(source.chat_id or "")
  86. return f"{self._telegram_topic_profile_name(source)}:{chat_id}" if chat_id else None
  87. def _telegram_cooldown_elapsed(self, source: SessionSource, attr: str, cooldown_s: float) -> bool:
  88. """Per-(profile, chat) debounce: True (and stamp now) when the window has elapsed."""
  89. if not hasattr(self, attr):
  90. setattr(self, attr, {})
  91. key = self._telegram_topic_cooldown_key(source)
  92. if not key:
  93. return True
  94. stamps, now = getattr(self, attr), time.monotonic()
  95. if now - stamps.get(key, 0.0) < cooldown_s:
  96. return False
  97. stamps[key] = now
  98. return True
  99. def _should_send_telegram_lobby_reminder(self, source: SessionSource) -> bool:
  100. """Rate-limit root-DM lobby reminders to one per cooldown window, not one per prompt typed."""
  101. return self._telegram_cooldown_elapsed(source, "_telegram_lobby_reminder_ts", self._TELEGRAM_LOBBY_REMINDER_COOLDOWN_S)
  102. def _should_send_telegram_capability_hint(self, source: SessionSource) -> bool:
  103. """Rate-limit the BotFather Threads Settings screenshot (repeated /topic must not re-upload it)."""
  104. return self._telegram_cooldown_elapsed(source, "_telegram_capability_hint_ts", self._TELEGRAM_CAPABILITY_HINT_COOLDOWN_S)
  105. # ── Telegram topic mode: user-facing text ───────────────────────────────────────────────
  106. def _telegram_topic_root_lobby_message(self) -> str:
  107. return t("gateway.topic.root_lobby")
  108. def _telegram_topic_root_new_message(self) -> str:
  109. return t("gateway.topic.root_new")
  110. def _telegram_topic_new_header(self, source: SessionSource) -> Optional[str]:
  111. return t("gateway.topic.new_header") if self._is_telegram_topic_lane(source) else None
  112. def _telegram_topic_help_text(self) -> str:
  113. return t("gateway.topic.help")
  114. # ── Telegram topic bindings ─────────────────────────────────────────────────────────────
  115. def _record_telegram_topic_binding(self, source: SessionSource, session_entry) -> None:
  116. """Persist the Telegram topic -> Hermes session binding for topic lanes (off-loop)."""
  117. session_db = self._sync_session_db()
  118. if session_db is None or not source.chat_id or not source.thread_id:
  119. return
  120. session_db.bind_telegram_topic(
  121. chat_id=str(source.chat_id), thread_id=str(source.thread_id), user_id=str(source.user_id or ""),
  122. session_key=session_entry.session_key, session_id=session_entry.session_id,
  123. profile_name=self._telegram_topic_profile_name(source),
  124. )
  125. def _sync_telegram_topic_binding(self, source: SessionSource, session_entry, *, reason: str) -> None:
  126. """Update the topic binding to ``session_entry.session_id``: a stale binding after a mid-turn
  127. compression rotation reloads the oversized parent next message, retriggering compression.
  128. Telegram topic lanes persist a (chat_id, thread_id) -> session_id row so reopening a topic in a
  129. fresh process resumes the right Hermes session. See #20470, #29712, #33414.
  130. """
  131. if not self._is_telegram_topic_lane(source):
  132. return
  133. try:
  134. self._record_telegram_topic_binding(source, session_entry)
  135. except Exception:
  136. logger.debug("telegram topic binding refresh failed (%s)", reason, exc_info=True)
  137. def _recover_telegram_topic_thread_id(self, source: SessionSource) -> Optional[str]:
  138. """Adapter-ingress recovery hook (sync, called off-loop before session keying): lobby recovery,
  139. except when ``dm_topic_auto_transfer`` is on — then the root-DM source is left alone so
  140. ``_transfer_telegram_root_dm`` can open a fresh topic (and fall back to this recovery itself)."""
  141. if self._telegram_topic_auto_transfer_enabled(source):
  142. return None
  143. return self._recover_telegram_lobby_thread_id(source)
  144. def _recover_telegram_lobby_thread_id(self, source: SessionSource) -> Optional[str]:
  145. """Pin lobby-shaped topic-mode DM replies (missing ``message_thread_id`` or General) to the
  146. user's most-recent bound topic. Never rewrite a non-lobby, unbound thread id: a brand-new DM
  147. topic is also "unknown" until its first message is recorded. None = leave the source alone."""
  148. if (
  149. not self._is_telegram_dm(source) or not source.chat_id or not source.user_id
  150. or not self._telegram_topic_mode_enabled(source)
  151. ):
  152. return None
  153. inbound = str(source.thread_id or "")
  154. if inbound and inbound not in self._TELEGRAM_GENERAL_TOPIC_IDS:
  155. return None
  156. session_db = self._sync_session_db()
  157. if session_db is None:
  158. return None
  159. try:
  160. bindings = session_db.list_telegram_topic_bindings_for_chat(
  161. chat_id=str(source.chat_id), profile_name=self._telegram_topic_profile_name(source)
  162. )
  163. except Exception:
  164. logger.debug("topic-recover: read failed", exc_info=True)
  165. return None
  166. for b in bindings or (): # newest-first
  167. if str(b.get("user_id") or "") == str(source.user_id):
  168. recovered = str(b.get("thread_id") or "")
  169. return recovered if recovered and recovered != inbound else None
  170. return None
  171. def _telegram_dm_topic_auto_transfer_configured(self, source: SessionSource) -> bool:
  172. """The RECEIVING bot's ``extra.dm_topic_auto_transfer`` (default False): under multiplexing each
  173. bot owns its opt-in. Off keeps the v0.22 lobby recovery (#136567). No state.db read."""
  174. adapter = self._delivery_adapter_for(source)
  175. platform_cfg = getattr(adapter, "config", None) if adapter is not None else None
  176. return is_truthy_value((getattr(platform_cfg, "extra", None) or {}).get("dm_topic_auto_transfer"))
  177. def _telegram_topic_auto_transfer_enabled(self, source: SessionSource) -> bool:
  178. """The key is on and ``source`` is a ``/topic``-mode root DM (reads state.db: call off-loop)."""
  179. return self._telegram_dm_topic_auto_transfer_configured(source) and self._is_telegram_topic_root_lobby(source)
  180. async def _transfer_telegram_root_dm(self, source: SessionSource) -> Optional[tuple[str, bool]]:
  181. """Adapter-ingress transfer hook for an opted-in root-DM message (#139136).
  182. ``(thread_id, True)``: a fresh topic was created and the turn runs there. ``(thread_id, False)``:
  183. creating it failed, so the message falls back to lobby recovery (the last bound topic).
  184. ``None``: not applicable (key off, not a topic-mode root DM) or nothing to recover to.
  185. """
  186. if (not source.chat_id or not self._telegram_dm_topic_auto_transfer_configured(source)
  187. or not await asyncio.to_thread(self._is_telegram_topic_root_lobby, source)):
  188. return None
  189. adapter = self._delivery_adapter_for(source)
  190. create_topic = getattr(adapter, "_create_dm_topic", None) if adapter is not None else None
  191. thread_id = None
  192. if callable(create_topic):
  193. try:
  194. thread_id = await create_topic(int(source.chat_id), t("gateway.topic.default_title"))
  195. except Exception:
  196. logger.debug("Failed to auto-transfer Telegram root DM into a new topic", exc_info=True)
  197. if thread_id:
  198. logger.info("telegram topic auto-transfer: chat=%s user=%s root -> new topic %s",
  199. source.chat_id, source.user_id, thread_id)
  200. return str(thread_id), True
  201. recovered = await asyncio.to_thread(self._recover_telegram_lobby_thread_id, source)
  202. return (recovered, False) if recovered else None
  203. # ── Telegram topic mode: /topic activation helpers ──────────────────────────────────────
  204. async def _get_telegram_topic_capabilities(self, source: SessionSource) -> dict:
  205. """Read Telegram private-topic capability flags via Bot API getMe."""
  206. bot = getattr(self._delivery_adapter_for(source), "_bot", None)
  207. if bot is None or not hasattr(bot, "get_me"):
  208. return {"checked": False}
  209. try:
  210. me = await bot.get_me()
  211. except Exception:
  212. logger.debug("Failed to fetch Telegram getMe topic capabilities", exc_info=True)
  213. return {"checked": False}
  214. def _field(name: str):
  215. if hasattr(me, name):
  216. return getattr(me, name)
  217. api_kwargs = getattr(me, "api_kwargs", None)
  218. if isinstance(api_kwargs, dict) and name in api_kwargs:
  219. return api_kwargs[name]
  220. return me.get(name) if isinstance(me, dict) else None
  221. return {"checked": True, **{k: _field(k) for k in ("has_topics_enabled", "allows_users_to_create_topics")}}
  222. async def _ensure_telegram_system_topic(self, source: SessionSource) -> None:
  223. """Create/pin the managed System topic after /topic activation when possible."""
  224. adapter = self._delivery_adapter_for(source)
  225. create_topic = getattr(adapter, "_create_dm_topic", None) if adapter is not None and source.chat_id else None
  226. if not callable(create_topic):
  227. return
  228. try:
  229. thread_id = await create_topic(int(source.chat_id), t("gateway.topic.system_topic_name"))
  230. except Exception:
  231. logger.debug("Failed to create Telegram System topic", exc_info=True)
  232. return
  233. if not thread_id:
  234. return
  235. try:
  236. send_result = await adapter.send(
  237. source.chat_id, t("gateway.topic.system_topic_intro"), metadata={"thread_id": str(thread_id)},
  238. )
  239. message_id = getattr(send_result, "message_id", None)
  240. except Exception:
  241. logger.debug("Failed to send Telegram System topic intro", exc_info=True)
  242. return
  243. bot = getattr(adapter, "_bot", None)
  244. if not message_id or bot is None or not hasattr(bot, "pin_chat_message"):
  245. return
  246. try:
  247. await bot.pin_chat_message(chat_id=int(source.chat_id), message_id=int(message_id), disable_notification=True)
  248. except Exception:
  249. logger.debug("Failed to pin Telegram System topic intro", exc_info=True)
  250. async def _send_telegram_topic_setup_image(self, source: SessionSource) -> None:
  251. """Send the bundled BotFather Threads Settings screenshot when available."""
  252. adapter = self._delivery_adapter_for(source)
  253. image_path = Path(__file__).resolve().parent / "assets" / "telegram-botfather-threads-settings.jpg"
  254. if adapter is None or not source.chat_id or not hasattr(adapter, "send_image_file") or not image_path.exists():
  255. return
  256. try:
  257. await adapter.send_image_file(
  258. chat_id=source.chat_id, image_path=str(image_path), caption=t("gateway.topic.setup_image_caption"),
  259. metadata={"thread_id": str(source.thread_id)} if source.thread_id else None,
  260. )
  261. except Exception:
  262. logger.debug("Failed to send Telegram topic setup image", exc_info=True)
  263. # ── title sanitizers ────────────────────────────────────────────────────────────────────
  264. def _sanitize_telegram_topic_title(self, title: str) -> str:
  265. """Bot API-safe forum topic name: names are 1-128 chars; keep room for multi-byte titles."""
  266. cleaned = _collapse_title(title)
  267. return cleaned if len(cleaned) <= 120 else cleaned[:117].rstrip() + "..."
  268. def _sanitize_discord_thread_title(self, title: str) -> str:
  269. """Discord-safe thread title: the 100-char cap is measured in UTF-16 code units (emoji count
  270. double), so truncate with the UTF-16 helpers rather than Python code-point slices."""
  271. cleaned = _collapse_title(title)
  272. return cleaned if utf16_len(cleaned) <= 80 else _prefix_within_utf16_limit(cleaned, 77).rstrip() + "..."
  273. # ── Discord auto-thread lanes ───────────────────────────────────────────────────────────
  274. def _is_discord_auto_thread_lane(self, source: SessionSource) -> bool:
  275. """Return True only for Discord threads Hermes just auto-created."""
  276. return (
  277. source.platform == Platform.DISCORD and source.chat_type == "thread"
  278. and bool(getattr(source, "auto_thread_created", False)) and bool(source.thread_id)
  279. and bool(getattr(source, "auto_thread_initial_name", None))
  280. )
  281. def _recover_discord_auto_thread_source(self, source: SessionSource, session_key: str) -> SessionSource:
  282. """*source* with the auto-thread markers of the session's opening event, when that event
  283. created this same native Discord thread.
  284. Native Discord stamps the markers only on the opening event, so a later title retry on a
  285. rebuilt agent arrives unmarked. The routing entry's ``origin`` is that opening source and
  286. survives restarts. ``replace_source`` keeps the live transport owner and message id."""
  287. if (
  288. source.platform != Platform.DISCORD or source.chat_type != "thread" or not source.thread_id
  289. or source.delivered_via_upstream_relay or self._is_discord_auto_thread_lane(source)
  290. ):
  291. return source
  292. entry = self.session_store.lookup_by_session_key(session_key)
  293. if entry is None:
  294. return source
  295. def opens_this_thread(origin: Optional[SessionSource]) -> bool:
  296. return (
  297. origin is not None and str(origin.thread_id) == str(source.thread_id)
  298. and self._is_discord_auto_thread_lane(origin)
  299. )
  300. origin = entry.origin
  301. if not opens_this_thread(origin):
  302. # An entry rebuilt after a lost routing index holds an unmarked event, while the session
  303. # row keeps the opening origin until that entry's first peer refresh overwrites it.
  304. db = self.session_store._db_for_key(session_key)
  305. row = db.get_session(entry.session_id) if db is not None else None
  306. raw = (row or {}).get("origin_json")
  307. origin = None
  308. if raw:
  309. with suppress(ValueError, KeyError, TypeError): # malformed/legacy row: no recovery
  310. origin = SessionSource.from_dict(json.loads(raw))
  311. if not opens_this_thread(origin):
  312. return source
  313. return replace_source(
  314. source, auto_thread_created=True, auto_thread_initial_name=origin.auto_thread_initial_name,
  315. )
  316. def _is_relay_discord_channel_lane(self, source: SessionSource) -> bool:
  317. """Shape-only check: a relay-delivered Discord CHANNEL event whose reply the connector MAY
  318. auto-thread (title-turn registration gate). Deliberately does NOT consult the send-result
  319. cache — before delivery the feedback can't exist; the rename lane polls it at fire time."""
  320. return (
  321. source.platform == Platform.DISCORD and bool(source.chat_id) and not source.thread_id
  322. and source.chat_type in ("group", "channel")
  323. and getattr(source, "delivered_via_upstream_relay", False) is True
  324. )
  325. def _relay_auto_thread_info(self, source: SessionSource) -> Optional[tuple[str, str]]:
  326. """(thread_id, initial_name) when the RELAY connector auto-threaded our reply — the title-turn
  327. sibling of _is_discord_auto_thread_lane (whose markers only exist from turn 2 on; the title
  328. turn's source is the PARENT channel event).
  329. Preferred: the connector's per-message ``prospective_thread_id`` stamp (anchor message id ==
  330. the thread it will create), exact even when several auto-threads spawn from one channel;
  331. the connector's created-name guard enforces no-clobber. Fallback: the per-chat send-result
  332. cache (older connectors), which only ever renamed the FIRST thread.
  333. """
  334. from gateway.run import _as_thread_info
  335. if (
  336. source.platform != Platform.DISCORD or not source.chat_id
  337. or not getattr(source, "delivered_via_upstream_relay", False)
  338. ):
  339. return None
  340. prospective = getattr(source, "prospective_thread_id", None)
  341. if prospective:
  342. # Deterministic per-thread identity; the empty initial-name marker signals the caller
  343. # to rely on the connector-side no-clobber guard.
  344. return (str(prospective), "")
  345. info_fn = getattr(self._delivery_adapter_for(source), "auto_thread_info_for_chat", None)
  346. if not callable(info_fn):
  347. return None
  348. with suppress(Exception):
  349. return _as_thread_info(info_fn(str(source.chat_id)))
  350. return None
  351. async def _await_relay_auto_thread_info(self, source: SessionSource) -> Optional[tuple[str, str]]:
  352. """``_relay_auto_thread_info``, waited out until this turn delivers (the legacy send-result
  353. path can only answer once the reply is sent; the caller asks at title time, one turn early).
  354. The timeout is only a backstop for a turn that never sends: the turn's own inactivity limit."""
  355. from gateway.run import _as_thread_info, _float_env
  356. # The connector-stamped prospective id is known at ingest, so most sessions answer here.
  357. known = self._relay_auto_thread_info(source)
  358. if known is not None:
  359. return known
  360. wait_fn = getattr(self._delivery_adapter_for(source), "wait_for_auto_thread_info", None)
  361. if not callable(wait_fn) or not source.chat_id:
  362. return None
  363. # 0 means the operator disabled the turn limit; the backstop still needs one.
  364. timeout = _float_env("HERMES_AGENT_TIMEOUT", 1800) or 1800
  365. with suppress(Exception):
  366. return _as_thread_info(await wait_fn(str(source.chat_id), timeout))
  367. return None
  368. async def _rename_discord_auto_thread_for_session_title(
  369. self, source: SessionSource, session_id: str, title: str,
  370. relay_info: Optional[tuple[str, str]] = None,
  371. ) -> None:
  372. """Best-effort semantic rename of a newly auto-created Discord thread. ``relay_info`` is the
  373. connector's (thread_id, initial_name) feedback, supplied on the title turn where the source
  374. is the parent-channel event without auto-thread markers (see _relay_auto_thread_info)."""
  375. if relay_info is None and not await asyncio.to_thread(self._is_discord_auto_thread_lane, source):
  376. # Relay title turn with no feedback captured at schedule time: the title comes off the
  377. # user's opening message, so it beats the delivery that produces the connector's
  378. # send-result feedback by the whole length of the turn. None here = a true miss.
  379. if not self._is_relay_discord_channel_lane(source):
  380. return
  381. relay_info = await self._await_relay_auto_thread_info(source)
  382. if relay_info is None:
  383. return
  384. adapter = self._delivery_adapter_for(source) if getattr(self, "adapters", None) else None
  385. rename_thread = getattr(adapter, "rename_thread", None)
  386. if rename_thread is None:
  387. return
  388. relay = relay_info is not None
  389. target_thread_id = relay_info[0] if relay else str(source.thread_id)
  390. thread_name = self._sanitize_discord_thread_title(title)
  391. # Relay: ask the CONNECTOR to enforce the no-clobber guard from its own created-name memory —
  392. # the gateway can't reproduce the initial name byte-for-byte (normalization drift silently
  393. # declined every rename). Its egress guard resolves the tenant from caches keyed by the PARENT
  394. # channel chat_id, so pass it or the lookup misses. Native: the source IS the thread; guard on
  395. # the initial name.
  396. rename_kwargs = (
  397. {"prefer_connector_created": True, "parent_chat_id": str(source.chat_id) if source.chat_id else None}
  398. if relay else {"only_if_current_name": getattr(source, "auto_thread_initial_name", None)}
  399. )
  400. logger.info(
  401. "discord auto-thread rename: thread=%s lane=%s new_title=%r",
  402. target_thread_id, "relay" if relay else "native", thread_name,
  403. )
  404. try:
  405. renamed = await rename_thread(target_thread_id, thread_name, **rename_kwargs)
  406. logger.info("discord auto-thread rename result: thread=%s applied=%s", target_thread_id, bool(renamed))
  407. except TypeError:
  408. logger.warning(
  409. "Discord semantic thread rename raised TypeError (adapter=%s)", type(adapter).__name__, exc_info=True,
  410. )
  411. except Exception:
  412. logger.debug("Failed to rename Discord auto-thread for generated session title", exc_info=True)
  413. # ── title-thread → loop rename scheduling ───────────────────────────────────────────────
  414. def _schedule_rename_from_title_thread(self, source: SessionSource, make_coro, label: str) -> None:
  415. """Schedule a best-effort rename coroutine onto the gateway loop from the auto-title thread.
  416. The source is copied so the thread never shares the live dataclass with the loop; failures
  417. are logged at debug and never propagate."""
  418. from gateway.run import safe_schedule_threadsafe
  419. try:
  420. loop = asyncio.get_running_loop()
  421. except RuntimeError:
  422. loop = getattr(self, "_gateway_loop", None)
  423. if loop is None or loop.is_closed():
  424. return
  425. copied_source = source
  426. with suppress(Exception):
  427. # Keep the live transport owner and identity; multiplex routes may run under a
  428. # profile that does not own the Discord adapter/token.
  429. from gateway.session_identity import replace_source
  430. copied_source = replace_source(source)
  431. future = safe_schedule_threadsafe(
  432. make_coro(copied_source), loop, logger=logger, log_message=f"{label} failed to schedule",
  433. )
  434. def _log_rename_failure(fut) -> None:
  435. try:
  436. fut.result()
  437. except Exception:
  438. logger.debug("%s failed", label, exc_info=True)
  439. if future is not None:
  440. future.add_done_callback(_log_rename_failure)
  441. def _schedule_discord_semantic_thread_rename(self, source: SessionSource, session_id: str, title: str) -> None:
  442. """Schedule Discord auto-thread rename from the auto-title background thread."""
  443. if not title:
  444. return
  445. relay_info = None
  446. if not self._is_discord_auto_thread_lane(source):
  447. # Relay title turn: the source is the PARENT channel event (thread didn't exist at
  448. # ingest). The auto-title races the delivery that fills the send-result cache, so a
  449. # miss HERE is not a verdict: schedule whenever the SHAPE matches; the async rename
  450. # lane polls the cache (bounded wait) and no-ops on a true miss.
  451. relay_info = self._relay_auto_thread_info(source)
  452. if relay_info is None and not self._is_relay_discord_channel_lane(source):
  453. return
  454. self._schedule_rename_from_title_thread(
  455. source,
  456. lambda copied: self._rename_discord_auto_thread_for_session_title(
  457. copied, session_id, title, relay_info=relay_info
  458. ),
  459. "Discord semantic thread rename",
  460. )
  461. def _schedule_telegram_topic_title_rename(self, source: SessionSource, session_id: str, title: str) -> None:
  462. """Schedule a topic rename from the auto-title background thread."""
  463. if not title or not self._is_telegram_topic_lane(source) or self._telegram_topic_auto_rename_disabled(source):
  464. return
  465. self._schedule_rename_from_title_thread(
  466. source,
  467. lambda copied: self._rename_telegram_topic_for_session_title(copied, session_id, title),
  468. "Telegram topic title rename",
  469. )
  470. def _telegram_topic_auto_rename_disabled(self, source: SessionSource) -> bool:
  471. """``gateway.platforms.telegram.extra.disable_topic_auto_rename``; default False (auto-rename on)."""
  472. config = getattr(self, "config", None)
  473. platform_cfg = config.platforms.get(source.platform) if config and getattr(config, "platforms", None) else None
  474. if platform_cfg is None:
  475. return False
  476. return is_truthy_value((getattr(platform_cfg, "extra", None) or {}).get("disable_topic_auto_rename"))
  477. async def _rename_telegram_topic_for_session_title(self, source: SessionSource, session_id: str, title: str) -> None:
  478. """Best-effort rename of a Telegram DM topic when Hermes auto-titles a session."""
  479. if not await asyncio.to_thread(self._is_telegram_topic_lane, source) or not source.chat_id or not source.thread_id:
  480. return
  481. # Operator kill-switch, e.g. user-managed topics (ad-hoc Threaded Mode) that auto-rename
  482. # would keep overwriting.
  483. if self._telegram_topic_auto_rename_disabled(source):
  484. return
  485. # Skip operator-declared topics (extra.dm_topics): fixed names chosen by the operator;
  486. # auto-renaming would silently mutate operator config. Check the class, not the instance —
  487. # getattr() on a MagicMock auto-creates attributes, so every test double would match. Only
  488. # dict-shaped returns count; a bare MagicMock or other sentinel shouldn't.
  489. adapter = self._delivery_adapter_for(source)
  490. get_info = getattr(type(adapter), "_get_dm_topic_info", None) if adapter is not None else None
  491. if callable(get_info):
  492. try:
  493. operator_topic = get_info(adapter, str(source.chat_id), str(source.thread_id))
  494. except Exception:
  495. operator_topic = None
  496. if isinstance(operator_topic, dict):
  497. return
  498. session_db = getattr(self, "_session_db", None)
  499. if session_db is not None:
  500. try:
  501. binding = await session_db.get_telegram_topic_binding(
  502. chat_id=str(source.chat_id), thread_id=str(source.thread_id),
  503. profile_name=self._telegram_topic_profile_name(source),
  504. )
  505. if binding and str(binding.get("session_id") or "") != str(session_id):
  506. return
  507. except Exception:
  508. logger.debug("Failed to verify Telegram topic binding before rename", exc_info=True)
  509. return
  510. if adapter is None:
  511. return
  512. topic_name = self._sanitize_telegram_topic_title(title)
  513. try:
  514. rename_topic = getattr(adapter, "rename_dm_topic", None)
  515. if rename_topic is not None:
  516. await rename_topic(chat_id=str(source.chat_id), thread_id=str(source.thread_id), name=topic_name)
  517. return
  518. bot = getattr(adapter, "_bot", None)
  519. edit_forum_topic = getattr(bot, "edit_forum_topic", None) or getattr(bot, "editForumTopic", None)
  520. if edit_forum_topic is None:
  521. return
  522. try:
  523. await edit_forum_topic(chat_id=int(source.chat_id), message_thread_id=int(source.thread_id), name=topic_name)
  524. except (TypeError, ValueError):
  525. await edit_forum_topic(chat_id=source.chat_id, message_thread_id=source.thread_id, name=topic_name)
  526. except Exception:
  527. logger.debug("Failed to rename Telegram topic for auto-generated title", exc_info=True)
  528. # ── /topic command bodies ───────────────────────────────────────────────────────────────
  529. async def _disable_telegram_topic_mode_for_chat(self, source: SessionSource) -> str:
  530. """Cleanly disable topic mode for a chat via /topic off."""
  531. if not self._session_db:
  532. from hermes_state import format_session_db_unavailable
  533. return format_session_db_unavailable(prefix=t("gateway.shared.session_db_unavailable_prefix"))
  534. chat_id = str(source.chat_id or "")
  535. if not chat_id:
  536. return t("gateway.topic.no_chat_id")
  537. profile_name = self._telegram_topic_profile_name(source)
  538. currently_enabled = False
  539. with suppress(Exception):
  540. currently_enabled = await self._session_db.is_telegram_topic_mode_enabled(
  541. chat_id=chat_id, user_id=str(source.user_id or ""), profile_name=profile_name,
  542. )
  543. if not currently_enabled:
  544. return t("gateway.topic.mode_not_enabled")
  545. try:
  546. await self._session_db.disable_telegram_topic_mode(chat_id=chat_id, profile_name=profile_name)
  547. except Exception as exc:
  548. logger.exception("Failed to disable Telegram topic mode")
  549. return t("gateway.topic.disable_failed", error=exc)
  550. # Reset per-profile+chat debounce state so the next activation doesn't see a stale cooldown.
  551. # See #76423.
  552. cooldown_key = self._telegram_topic_cooldown_key(source)
  553. for attr in ("_telegram_lobby_reminder_ts", "_telegram_capability_hint_ts") if cooldown_key else ():
  554. store = getattr(self, attr, None)
  555. if isinstance(store, dict):
  556. store.pop(cooldown_key, None)
  557. return t("gateway.topic.mode_disabled")
  558. async def _telegram_topic_root_status_message(self, source: SessionSource) -> str:
  559. lines = [t("gateway.topic.status_enabled"), "", t("gateway.topic.status_how_to"), ""]
  560. try:
  561. sessions = await self._session_db.list_unlinked_telegram_sessions_for_user(
  562. chat_id=str(source.chat_id), user_id=str(source.user_id),
  563. profile_name=self._telegram_topic_profile_name(source), limit=10,
  564. )
  565. except Exception:
  566. logger.debug("Failed to list unlinked Telegram sessions", exc_info=True)
  567. sessions = []
  568. if sessions:
  569. lines.append(t("gateway.topic.previous_unlinked"))
  570. for session in sessions:
  571. preview = str(session.get("preview") or "").strip()
  572. lines.append(
  573. f"- {session.get('title') or t('gateway.topic.untitled_session')} — `{session.get('id') or ''}`"
  574. + (f" — {preview}" if preview else "")
  575. )
  576. lines.extend(["", t("gateway.topic.restore_one"), *_topic_restore_steps(),
  577. t("gateway.topic.restore_example", session_id=sessions[0].get("id"))])
  578. else:
  579. lines.extend([t("gateway.topic.no_unlinked"), "", t("gateway.topic.restore_later"), *_topic_restore_steps()])
  580. return "\n".join(lines)
  581. async def _restore_telegram_topic_session(self, event: MessageEvent, raw_session_id: str) -> str:
  582. """Restore an existing Telegram-owned Hermes session into this topic."""
  583. source = event.source
  584. db = self._session_db
  585. session_id = await db.resolve_session_id(raw_session_id.strip())
  586. session = await db.get_session(session_id) if session_id else None
  587. if not session:
  588. return t("gateway.topic.session_not_found", session_id=raw_session_id.strip())
  589. if str(session.get("source") or "") != "telegram":
  590. return t("gateway.topic.not_telegram_session")
  591. if str(session.get("user_id") or "") != str(source.user_id):
  592. return t("gateway.topic.not_your_session")
  593. linked = await db.is_telegram_session_linked_to_topic(session_id=session_id)
  594. topic_profile = self._telegram_topic_profile_name(source)
  595. current_binding = await db.get_telegram_topic_binding(
  596. chat_id=str(source.chat_id), thread_id=str(source.thread_id), profile_name=topic_profile,
  597. )
  598. already_linked = t("gateway.topic.already_linked")
  599. if linked and (not current_binding or current_binding.get("session_id") != session_id):
  600. return already_linked
  601. try:
  602. await db.bind_telegram_topic(
  603. chat_id=str(source.chat_id), thread_id=str(source.thread_id), user_id=str(source.user_id),
  604. session_key=self._session_key_for_source(source), session_id=session_id, managed_mode="restored",
  605. profile_name=topic_profile,
  606. )
  607. except ValueError as exc:
  608. if "already linked" in str(exc):
  609. return already_linked
  610. raise
  611. title = await db.get_session_title(session_id) or session_id
  612. last_assistant = None
  613. with suppress(Exception):
  614. for message in reversed(await db.get_messages(session_id)):
  615. if message.get("role") != "assistant":
  616. continue
  617. projected = project_compaction_message_for_display(message)
  618. if projected is not None and projected.get("content"):
  619. last_assistant = str(projected.get("content"))
  620. break
  621. response = t("gateway.topic.restored", title=title)
  622. return response + (t("gateway.topic.restored_last_message", text=last_assistant) if last_assistant else "")