The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telegram): strip our handle only as sole addressee; keep the identity line session-stable
Tekniumbc31e04d83ee
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 555ba218cf8..bf29b640cc2 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -5657,10 +5657,11 @@ class TelegramAdapter(BasePlatformAdapter):return Falseasync def _build_triggered_event(self, msg, update, msg_type: MessageType) -> MessageEvent:- """Keep group conversation addressing; normalize command triggers for dispatch."""+ """Event for an addressed text/command: trigger text cleaned (sole addressee only), replied-to+ media cached, attribution applied."""+ from plugins.platforms.telegram.telegram_context import group_trigger_textevent = self._build_message_event(msg, msg_type, update_id=update.update_id)- if msg_type == MessageType.COMMAND or not self._is_group_chat(msg):- event.text = self._clean_bot_trigger_text(event.text)+ event.text = group_trigger_text(self, msg, event.text)await self._cache_replied_media(msg, event)return self._apply_telegram_group_observe_attribution(event)@@ -5979,13 +5980,14 @@ class TelegramAdapter(BasePlatformAdapter):if self._should_observe_unmentioned_group_message(msg):_event = self._build_message_event(msg, self._media_message_type(msg), update_id=update.update_id)if msg.caption:- _event.text = msg.caption+ _event.text = self._clean_bot_trigger_text(msg.caption)await self._cache_observed_media(msg, _event)self._observe_unmentioned_group_message(msg, _event.message_type, update_id=update.update_id, event=_event)returnevent = self._build_message_event(msg, self._media_message_type(msg), update_id=update.update_id)if msg.caption:- event.text = msg.caption if self._is_group_chat(msg) else self._clean_bot_trigger_text(msg.caption)+ from plugins.platforms.telegram.telegram_context import group_trigger_text+ event.text = group_trigger_text(self, msg, msg.caption)# Stickers: _handle_sticker overwrites event.text with its vision description, so observe attribution must run after it.if msg.sticker:await self._handle_sticker(msg, event)@@ -6282,14 +6284,14 @@ class TelegramAdapter(BasePlatformAdapter):is_bot=bool(getattr(user, "is_bot", False)) if user else False)reply_to_id, reply_to_text = self._reply_context(message)from gateway.platforms.base import resolve_channel_prompt # per-channel/topic ephemeral prompt- from plugins.platforms.telegram.telegram_context import group_addressing_prompt+ from plugins.platforms.telegram.telegram_context import group_identity_prompt_chat_id_str = str(chat.id)channel_prompt = resolve_channel_prompt(self.config.extra, thread_id_str or _chat_id_str, _chat_id_str if thread_id_str else None)return MessageEvent(text=message.text or "", message_type=msg_type, source=source, raw_message=message,message_id=str(message.message_id), platform_update_id=update_id,reply_to_message_id=reply_to_id, reply_to_text=reply_to_text, auto_skill=topic_skill,- channel_prompt=group_addressing_prompt(self, message, channel_prompt),+ channel_prompt=group_identity_prompt(self, message, channel_prompt),timestamp=message.date)# -- Message reactions (processing lifecycle) --diff --git a/plugins/platforms/telegram/telegram_context.py b/plugins/platforms/telegram/telegram_context.pyindex a4ab9ada1b1..b02f9ca3134 100644--- a/plugins/platforms/telegram/telegram_context.py+++ b/plugins/platforms/telegram/telegram_context.py@@ -1,27 +1,53 @@-"""Per-message Telegram addressing facts, outside the cached session prompt."""+"""Telegram group addressing helpers, kept out of the adapter facade.-from typing import TYPE_CHECKING+The identity line lives in ``channel_prompt`` and therefore in the cached-agent signature: it+must be stable for the life of a session (username only — never a per-message fact).+"""++from typing import TYPE_CHECKING, Optionalif TYPE_CHECKING:from telegram import Messagefrom plugins.platforms.telegram.adapter import TelegramAdapter-def group_addressing_prompt(- adapter: "TelegramAdapter", message: "Message", channel_prompt: str | None,-) -> str | None:+def mentions_other_participants(adapter: "TelegramAdapter", message: "Message") -> bool:+ """True when a ``mention``/``text_mention`` entity names someone other than this bot."""+ own = adapter._current_bot_username()+ bot_id = getattr(adapter._bot, "id", None) if adapter._bot else None+ for source_text, entities in adapter._entity_sources(message):+ for entity in entities:+ entity_type = adapter._entity_type(entity)+ if entity_type == "mention":+ handle = (adapter._entity_span(source_text, entity) or "").strip().lstrip("@").lower()+ if handle and handle != own:+ return True+ elif entity_type == "text_mention":+ user = getattr(entity, "user", None)+ if user is not None and getattr(user, "id", None) != bot_id:+ return True+ return False+++def group_trigger_text(adapter: "TelegramAdapter", message: "Message", text: Optional[str]) -> Optional[str]:+ """Strip our own handle only when we are the sole addressee. With other participants named,+ ``@research_bot , @ops_bot are you both listening?`` must not reach us as ``, @ops_bot …``."""+ if adapter._is_group_chat(message) and mentions_other_participants(adapter, message):+ return text+ return adapter._clean_bot_trigger_text(text)+++def group_identity_prompt(+ adapter: "TelegramAdapter", message: "Message", channel_prompt: Optional[str],+) -> Optional[str]:+ """Session-stable identity line so the model can read retained @mentions as itself or not."""if not adapter._is_group_chat(message) or not getattr(adapter, "_bot", None):return channel_promptusername = adapter._current_bot_username()if not username:return channel_prompt- # Use the same entity-aware check as admission, not the cleaned text or the- # fact that a turn was dispatched (replies/wake words/open groups also pass).- mentioned = "yes" if adapter._message_mentions_bot(message) else "no"- addressing = (- "Telegram addressing context (current message only):\n"- f"- Your Telegram bot username: @{username}\n"- f"- Current message explicitly mentions you: {mentioned}\n"- "Mentions of other bots do not by themselves ask you to relay the message."+ identity = (+ f"Your Telegram bot username in this group: @{username}. "+ "Mentions of other bots are not requests for you to relay the message.")- return f"{channel_prompt}\n\n{addressing}" if channel_prompt else addressing+ return f"{channel_prompt}\n\n{identity}" if channel_prompt else identitydiff --git a/tests/gateway/test_telegram_mention_context.py b/tests/gateway/test_telegram_mention_context.pyindex 35c36985f06..b20b6b63e50 100644--- a/tests/gateway/test_telegram_mention_context.py+++ b/tests/gateway/test_telegram_mention_context.py@@ -1,4 +1,5 @@-"""Addressing information must survive routing into the agent's event."""+"""Multi-bot addressing must survive routing into the agent's event without destabilising the+session prompt."""import asynciofrom types import SimpleNamespace@@ -7,12 +8,19 @@ from unittest.mock import AsyncMockimport pytestfrom gateway.platforms.base import MessageType+from gateway.run import GatewayRunnerfrom tests.gateway.test_telegram_group_gating import (_dm_message, _group_message, _group_voice_message, _make_adapter,_mention_entities,)+def _prompt_signature(event):+ return GatewayRunner._agent_config_signature(+ "model", {"api_key": "k", "base_url": "u", "provider": "p"}, ["messaging"], event.channel_prompt or "",+ )++@pytest.mark.parametrize("media", [False, True])@pytest.mark.parametrize("observe", [False, True])def test_multi_bot_addressing_survives_real_handlers(media, observe):@@ -48,8 +56,7 @@ def test_multi_bot_addressing_survives_real_handlers(media, observe):assert len(events) == 1event = events[0]assert text in event.text # Preserve both recipients and their positions.- assert f"Your Telegram bot username: @{username}" in event.channel_prompt- assert "Current message explicitly mentions you: yes" in event.channel_prompt+ assert f"@{username}" in event.channel_promptassert "Keep answers concise." in event.channel_promptassert ("observed Telegram group context" in event.channel_prompt) == observeassert event.source.user_id == (None if observe else "111")@@ -58,7 +65,10 @@ def test_multi_bot_addressing_survives_real_handlers(media, observe):@pytest.mark.parametrize("trigger", ["mention", "text_mention", "reply", "wake_word", "open", "code", "command", "dm"])-def test_addressing_context_reports_original_entities_without_inventing_mentions(trigger):+def test_sole_addressee_text_stays_clean_and_prompt_is_session_stable(trigger):+ """Our own handle is still stripped when nobody else is named (clarify answers like ``@bot 2``+ keep resolving), and the identity block is identical across turns: it rides the cached-agent+ signature, so a per-message fact there would rebuild the agent every turn."""async def run():adapter = _make_adapter(require_mention=trigger != "open", mention_patterns=["^wake\\b"])adapter._ensure_forum_commands = AsyncMock()@@ -74,7 +84,7 @@ def test_addressing_context_reports_original_entities_without_inventing_mentionselif trigger == "text_mention":msg = _group_message("Hermes hello", entities=[SimpleNamespace(type="text_mention", offset=0, length=6, user=SimpleNamespace(id=999))])elif trigger == "mention":- text = "😀 @hermes_bot hello"+ text = "😀 @hermes_bot 2"msg = _group_message(text, entities=[SimpleNamespace(type="mention", offset=3, length=11)])elif trigger == "code":# Telegram says this is code, not a mention; a reply admits the turn.@@ -84,18 +94,25 @@ def test_addressing_context_reports_original_entities_without_inventing_mentionsif msg.reply_to_message:for attr in ("photo", "video", "voice", "audio", "document"):setattr(msg.reply_to_message, attr, None)- update = SimpleNamespace(update_id=1002, message=msg, effective_message=None)handler = adapter._handle_command if msg_type == MessageType.COMMAND else adapter._handle_text_message- await handler(update, SimpleNamespace())+ await handler(SimpleNamespace(update_id=1002, message=msg, effective_message=None), SimpleNamespace())+ # Second turn in the same chat with a different addressing shape (reply, no entities).+ follow_up = _dm_message("thanks") if trigger == "dm" else _group_message("thanks", reply_to_bot=True)+ if follow_up.reply_to_message:+ for attr in ("photo", "video", "voice", "audio", "document"):+ setattr(follow_up.reply_to_message, attr, None)+ await adapter._handle_text_message(SimpleNamespace(update_id=1003, message=follow_up, effective_message=None), SimpleNamespace())- assert len(events) == 1- event = events[0]+ assert len(events) == 2+ first, second = events+ expected_text = {"command": "/new", "mention": "😀 2", "code": "@hermes_bot"}.get(trigger, msg.text)+ assert first.text == expected_textif trigger == "dm":- assert not event.channel_prompt+ assert not first.channel_promptelse:- expected = "yes" if trigger in {"mention", "text_mention", "command"} else "no"- assert f"Current message explicitly mentions you: {expected}" in event.channel_prompt- assert event.text == ("/new" if trigger == "command" else msg.text)- assert event.source.user_id == "111"+ assert "@hermes_bot" in first.channel_prompt+ assert first.channel_prompt == second.channel_prompt+ assert _prompt_signature(first) == _prompt_signature(second)+ assert first.source.user_id == "111"asyncio.run(run())diff --git a/website/docs/user-guide/messaging/telegram.md b/website/docs/user-guide/messaging/telegram.mdindex 6d1e2a19b7d..deb60b4e727 100644--- a/website/docs/user-guide/messaging/telegram.md+++ b/website/docs/user-guide/messaging/telegram.md@@ -578,7 +578,7 @@ telegram:With this setup, a group message like `@research_bot @ops_bot summarize this` is processed by `research_bot` and `ops_bot` only. Other Hermes bots in the group stay silent, even if the message is a reply to one of their earlier messages or would otherwise match a shared wake word.-Group conversation text and media captions retain all mentions, including the receiving bot's own handle. Each turn also includes the bot's Telegram username and whether the original message explicitly mentioned it. This preserves multi-bot addressing without treating replies, wake words, or open-group messages as explicit mentions. Slash commands still use the normal command-trigger cleanup.+Group conversation text and media captions keep every mention when the message names other participants too (`@research_bot , @ops_bot are you both listening?` reaches `research_bot` verbatim); when this bot is the only one addressed, its own handle is still stripped so short answers such as `@hermes_bot 2` keep working. Group turns also carry the bot's own Telegram username in the per-channel context so the model can tell which retained mentions are for it. Slash commands still use the normal command-trigger cleanup.Set `exclusive_bot_mentions: false` only for legacy groups where explicit mentions should not override reply and wake-word triggers.