The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(discord): re-arm the bot handoff window per chunk; trim salvage to invariants
teknium1b675e6dee7c7
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex 7c529f99a93..3f1d24261e6 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -4789,37 +4789,36 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):f"{getattr(getattr(message, 'author', None), 'id', '')}")+ def _bot_tag_window_seconds(self) -> float:+ return max(self._text_batch_delay_seconds, self._text_batch_split_delay_seconds)+def _record_bot_tag_debounce(self, message: Any) -> None:"""Open a short continuation window after a bot-authored tag."""if (self._text_batch_delay_seconds <= 0- or not getattr(getattr(message, "author", None), "bot", False)+ or not getattr(message.author, "bot", False)or not self._self_is_explicitly_mentioned(message)):return- window = max(- self._text_batch_delay_seconds,- self._text_batch_split_delay_seconds,- )self._bot_tag_debounce_until[self._bot_tag_debounce_key(message)] = (- time.monotonic() + window+ time.monotonic() + self._bot_tag_window_seconds())def _is_bot_tag_debounce_continuation(self, message: Any) -> bool:- """Return whether an unmentioned chunk belongs to a recent bot tag."""- if (- getattr(self, "_text_batch_delay_seconds", 0) <= 0- or not getattr(getattr(message, "author", None), "bot", False)- ):+ """Return whether an unmentioned chunk belongs to a recent bot tag.++ A hit re-arms the window: Discord paces a bot's sends at roughly one per+ second, so chunk N of a long handoff lands well after the tag itself; each+ admitted chunk therefore vouches for the next one. The gateway bot loop+ guard bounds a bot that never stops talking."""+ if self._text_batch_delay_seconds <= 0 or not getattr(message.author, "bot", False):return Falsekey = self._bot_tag_debounce_key(message)- debounce_until = getattr(self, "_bot_tag_debounce_until", None)- if not debounce_until:- return False- deadline = debounce_until.get(key, 0.0)- if deadline <= time.monotonic():- debounce_until.pop(key, None)+ now = time.monotonic()+ if self._bot_tag_debounce_until.get(key, 0.0) <= now:+ self._bot_tag_debounce_until.pop(key, None)return False+ self._bot_tag_debounce_until[key] = now + self._bot_tag_window_seconds()return Truedef _discord_free_response_channels(self) -> set:diff --git a/tests/gateway/test_discord_bot_inline_mentions.py b/tests/gateway/test_discord_bot_inline_mentions.pyindex 20405df129c..ade2bb45582 100644--- a/tests/gateway/test_discord_bot_inline_mentions.py+++ b/tests/gateway/test_discord_bot_inline_mentions.py@@ -1,4 +1,5 @@-"""Tests for hard-inline mention gating on bot-authored Discord messages."""+"""Bot-authored Discord messages need a typed ``<@bot>`` by default; a reply ping alone+no longer wakes the bot (two bots otherwise volley replies forever). Salvage of #106874."""from types import SimpleNamespacefrom unittest.mock import Mock@@ -7,96 +8,53 @@ import discordimport pytestfrom gateway.platforms.helpers import MessageDeduplicator-from hermes_cli.config_defaults import DEFAULT_CONFIGfrom plugins.platforms.discord.adapter import DiscordAdapterdef _adapter(*, allow_bots: str = "mentions", extra=None) -> DiscordAdapter:adapter = object.__new__(DiscordAdapter)- setattr(adapter, "config", SimpleNamespace(extra=extra or {}))+ adapter.config = SimpleNamespace(extra=extra or {})adapter._client = SimpleNamespace(user=SimpleNamespace(id=99, bot=True))adapter._dedup = MessageDeduplicator()adapter._get_allow_bots = Mock(return_value=allow_bots)adapter._is_allowed_user = Mock(return_value=True)+ adapter._text_batch_delay_seconds = 0.6+ adapter._text_batch_split_delay_seconds = 2.0+ adapter._bot_tag_debounce_until = {}return adapter-def _bot_message(adapter: DiscordAdapter, *, content: str, message_type):+def _reply_ping_from_bot(adapter: DiscordAdapter, content: str):+ # Discord populates ``mentions`` with the replied-to author even though the body+ # carries no ``<@99>`` token — that metadata is what used to count as a summons.return SimpleNamespace(id=123,author=SimpleNamespace(id=42, bot=True),channel=SimpleNamespace(id=7),content=content,- mentions=[getattr(adapter._client, "user")],- type=message_type,+ mentions=[adapter._client.user],+ type=discord.MessageType.reply,)-def test_bot_inline_mentions_are_required_by_default(monkeypatch):- monkeypatch.delenv("DISCORD_BOTS_REQUIRE_INLINE_MENTION", raising=False)- adapter = _adapter()-- assert adapter._discord_bots_require_inline_mention() is True- assert DEFAULT_CONFIG["discord"]["bots_require_inline_mention"] is True--@pytest.mark.parametrize("allow_bots", ["mentions", "all"])-def test_reply_ping_does_not_trigger_bot_by_default(monkeypatch, allow_bots):+def test_reply_ping_alone_does_not_trigger_bot_by_default(monkeypatch, allow_bots):monkeypatch.delenv("DISCORD_BOTS_REQUIRE_INLINE_MENTION", raising=False)adapter = _adapter(allow_bots=allow_bots)- message = _bot_message(- adapter,- content="reply without a hard mention",- message_type=discord.MessageType.reply,- )-- admitted, _ = adapter._discord_message_admission(message, claim=False)+ admitted, _ = adapter._discord_message_admission(+ _reply_ping_from_bot(adapter, "reply without a typed mention"), claim=False)assert admitted is False--def test_hard_inline_mention_triggers_bot_by_default(monkeypatch):- monkeypatch.delenv("DISCORD_BOTS_REQUIRE_INLINE_MENTION", raising=False)- adapter = _adapter(allow_bots="mentions")- message = _bot_message(- adapter,- content="<@99> intentional handoff",- message_type=discord.MessageType.default,- )-- admitted, _ = adapter._discord_message_admission(message, claim=False)-- assert admitted is True---def test_human_messages_are_unaffected_by_inline_mention_gate(monkeypatch):- monkeypatch.delenv("DISCORD_BOTS_REQUIRE_INLINE_MENTION", raising=False)- adapter = _adapter(allow_bots="none")- message = _bot_message(- adapter,- content="human reply without a hard mention",- message_type=discord.MessageType.reply,- )- message.author.bot = False- message.mentions = []-- admitted, _ = adapter._discord_message_admission(message, claim=False)-+ admitted, _ = adapter._discord_message_admission(+ _reply_ping_from_bot(adapter, "<@99> intentional handoff"), claim=False)assert admitted is Truedef test_explicit_false_restores_reply_ping_compatibility(monkeypatch):monkeypatch.delenv("DISCORD_BOTS_REQUIRE_INLINE_MENTION", raising=False)- adapter = _adapter(- allow_bots="mentions",- extra={"bots_require_inline_mention": False},- )- message = _bot_message(- adapter,- content="legacy reply handoff",- message_type=discord.MessageType.reply,- )-- admitted, _ = adapter._discord_message_admission(message, claim=False)+ adapter = _adapter(extra={"bots_require_inline_mention": False})+ admitted, _ = adapter._discord_message_admission(+ _reply_ping_from_bot(adapter, "legacy reply handoff"), claim=False)assert admitted is Truediff --git a/tests/gateway/test_discord_bot_tag_debounce.py b/tests/gateway/test_discord_bot_tag_debounce.pydeleted file mode 100644index 13e43a6960c..00000000000--- a/tests/gateway/test_discord_bot_tag_debounce.py+++ /dev/null@@ -1,99 +0,0 @@-"""Tests for coalescing rapid bot-authored Discord message chunks."""--import asyncio-from types import SimpleNamespace-from unittest.mock import AsyncMock, Mock--import discord-import pytest--from gateway.platforms.helpers import MessageDeduplicator-from plugins.platforms.discord.adapter import DiscordAdapter---def _message(*, author_id: int, channel_id: int, mentions=()):- return SimpleNamespace(- id=author_id * 100 + channel_id,- author=SimpleNamespace(id=author_id, bot=True),- channel=SimpleNamespace(id=channel_id),- mentions=list(mentions),- content="chunk",- type=discord.MessageType.default,- )---def _adapter():- adapter = object.__new__(DiscordAdapter)- adapter._bot_tag_debounce_until = {}- adapter._text_batch_delay_seconds = 0.6- adapter._text_batch_split_delay_seconds = 2.0- adapter._self_is_explicitly_mentioned = lambda message: bool(message.mentions)- return adapter---def test_tag_opens_short_window_for_same_bot_and_channel_only():- adapter = _adapter()- tagged = _message(author_id=1, channel_id=10, mentions=[SimpleNamespace(id=99)])- continuation = _message(author_id=1, channel_id=10)-- adapter._record_bot_tag_debounce(tagged)-- assert adapter._is_bot_tag_debounce_continuation(continuation) is True- assert adapter._is_bot_tag_debounce_continuation(- _message(author_id=2, channel_id=10)- ) is False- assert adapter._is_bot_tag_debounce_continuation(- _message(author_id=1, channel_id=11)- ) is False---def test_disabling_text_batching_disables_bot_tag_debounce():- adapter = _adapter()- adapter._text_batch_delay_seconds = 0- tagged = _message(author_id=1, channel_id=10, mentions=[SimpleNamespace(id=99)])-- adapter._record_bot_tag_debounce(tagged)-- assert adapter._is_bot_tag_debounce_continuation(- _message(author_id=1, channel_id=10)- ) is False---def test_uninitialized_debounce_state_is_treated_as_disabled():- adapter = object.__new__(DiscordAdapter)-- assert adapter._is_bot_tag_debounce_continuation(- _message(author_id=1, channel_id=10)- ) is False---def test_mentions_mode_admits_unmentioned_chunk_during_debounce():- adapter = _adapter()- own_user = SimpleNamespace(id=99)- adapter._client = SimpleNamespace(user=own_user)- adapter._dedup = MessageDeduplicator()- adapter._get_allow_bots = Mock(return_value="mentions")- adapter._discord_bots_require_inline_mention = Mock(return_value=True)- adapter._self_is_raw_mentioned = Mock(return_value=False)- tagged = _message(author_id=1, channel_id=10, mentions=[own_user])- continuation = _message(author_id=1, channel_id=10)- adapter._record_bot_tag_debounce(tagged)-- admitted, _ = adapter._discord_message_admission(continuation, claim=True)-- assert admitted is True---async def test_rejected_bot_tag_does_not_open_debounce_window():- adapter = _adapter()- adapter._ready_event = asyncio.Event()- adapter._ready_event.set()- adapter._record_bot_tag_debounce = Mock()- adapter._discord_message_admission = Mock(return_value=(False, False))- adapter._handle_message = AsyncMock()- message = _message(author_id=1, channel_id=10)-- assert await adapter._dispatch_discord_message(message) is False- adapter._record_bot_tag_debounce.assert_not_called()- adapter._handle_message.assert_not_awaited()diff --git a/tests/gateway/test_discord_free_response.py b/tests/gateway/test_discord_free_response.pyindex 0f715a381f2..1ed2dd3658f 100644--- a/tests/gateway/test_discord_free_response.py+++ b/tests/gateway/test_discord_free_response.py@@ -1,6 +1,7 @@"""Tests for Discord free-response defaults and mention gating."""import asyncio+import timefrom datetime import datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch@@ -251,8 +252,14 @@ async def test_unmentioned_bot_chunks_join_recent_tag_batch(adapter, monkeypatchthird = make_message(channel=channel, content="third chunk")third.id = 125third.author.bot = True+ # Fake clock: chunk 3 lands past the tag's own 2s window and is admitted only because+ # chunk 2 re-armed it (Discord paces bot sends at ~1/s, so real bursts look like this).+ clock = [1000.0]+ monkeypatch.setattr(discord_platform, "time", SimpleNamespace(monotonic=lambda: clock[0], time=time.time))assert await adapter._dispatch_discord_message(tagged) is True+ clock[0] += 1.5assert await adapter._dispatch_discord_message(second) is True+ clock[0] += 1.5assert await adapter._dispatch_discord_message(third) is Trueawait asyncio.wait_for(asyncio.gather(*adapter._pending_text_batch_tasks.values()), timeout=5.0,diff --git a/website/docs/user-guide/messaging/discord.md b/website/docs/user-guide/messaging/discord.mdindex e8011da1d79..0e4f5a757bd 100644--- a/website/docs/user-guide/messaging/discord.md+++ b/website/docs/user-guide/messaging/discord.md@@ -335,7 +335,7 @@ For example, bot A sends `<@BOT_B_ID> Here is the review …`, followed immediat#### Timing and limits-The admission window lasts `max(HERMES_DISCORD_TEXT_BATCH_DELAY_SECONDS, HERMES_DISCORD_TEXT_BATCH_SPLIT_DELAY_SECONDS)` after the admitted mention (2 seconds with the defaults). An unmentioned continuation **does not extend that admission deadline**. Separately, each queued text chunk restarts the batch's quiet timer; a tagged bot batch uses the split quiet period even when its first chunk is short. These settings control receiver batching, not sender pacing. Disabling text batching (`HERMES_DISCORD_TEXT_BATCH_DELAY_SECONDS=0`) also disables continuation admission.+The admission window lasts `max(HERMES_DISCORD_TEXT_BATCH_DELAY_SECONDS, HERMES_DISCORD_TEXT_BATCH_SPLIT_DELAY_SECONDS)` after the admitted mention (2 seconds with the defaults), and each admitted continuation re-arms it, so a long handoff paced at Discord's send rate arrives whole. Separately, each queued text chunk restarts the batch's quiet timer; a tagged bot batch uses the split quiet period even when its first chunk is short. These settings control receiver batching, not sender pacing. Disabling text batching (`HERMES_DISCORD_TEXT_BATCH_DELAY_SECONDS=0`) also disables continuation admission.This is a short-burst heuristic, not guaranteed multipart delivery. A delayed chunk outside the window needs its own mention under the default policy. Unrelated messages from the same bot and channel inside the window can also be admitted. The exception is not restricted to text: attachments and commands may pass admission, but only text enters this batcher; other message types follow their normal handling. Existing channel restrictions and `DISCORD_ALLOW_BOTS=none` still apply. History/backfill behavior is unchanged. The gateway's bot loop guard remains as a backstop: after 20 bot-authored messages in one channel inside 5 minutes, further bot messages there are dropped for 10 minutes (tunable under `gateway.bot_loop_guard` in `config.yaml`; human messages are never counted).