Skip to content

The agent that grows with you

refactor(gateway): one text-batch cadence and one extra-float parser on BasePlatformAdapter

kshitijk4poor530fdb5867b3
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 1968ec0e28a..d9dc8495653 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -2383,6 +2383,33 @@ class BasePlatformAdapter(ABC):
_SPLIT_THRESHOLD: int = 4000
_text_batch_delay_seconds: float = 0.0
_text_batch_split_delay_seconds: float = 0.0
+ # Shared cadence for adapters that batch: a quiet period long enough to merge a client-side
+ # split (Telegram's measured envelope), short enough that a single short message is not
+ # visibly delayed (#44883). Ceilings bound a misconfigured value fed to asyncio.sleep().
+ _TEXT_BATCH_DEFAULT_DELAY_S: float = 0.3
+ _TEXT_BATCH_MAX_DELAY_S: float = 2.0
+ _TEXT_BATCH_DEFAULT_SPLIT_DELAY_S: float = 1.0
+ _TEXT_BATCH_MAX_SPLIT_DELAY_S: float = 4.0
+
+ def _coerce_float_extra(self, key: str, default: float, *, min_value: float = 0.0, max_value: Optional[float] = None) -> float:
+ """Float from ``config.extra``; NaN/Inf/negative/unparseable → ``default``; clamped to ``[min_value, max_value]``."""
+ import math
+ extra = getattr(self.config, "extra", None) or {}
+ try: # float(None) → TypeError → default
+ parsed = float(extra.get(key))
+ except (TypeError, ValueError):
+ parsed = float(default)
+ if not math.isfinite(parsed) or parsed < 0:
+ parsed = float(default)
+ return min(max(parsed, min_value), max_value) if max_value is not None else max(parsed, min_value)
+
+ def _configure_text_batch_delays(self) -> None:
+ """Read ``text_batch_delay_seconds`` / ``text_batch_split_delay_seconds`` from ``config.extra`` at the shared cadence."""
+ self._text_batch_delay_seconds = self._coerce_float_extra(
+ "text_batch_delay_seconds", self._TEXT_BATCH_DEFAULT_DELAY_S, max_value=self._TEXT_BATCH_MAX_DELAY_S)
+ self._text_batch_split_delay_seconds = self._coerce_float_extra(
+ "text_batch_split_delay_seconds", self._TEXT_BATCH_DEFAULT_SPLIT_DELAY_S,
+ min_value=self._text_batch_delay_seconds, max_value=self._TEXT_BATCH_MAX_SPLIT_DELAY_S)
def _event_session_key(self, event: "MessageEvent") -> str:
"""Adapter-level session key for ``event``, profile-namespaced like the agent run."""
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.py
index 540da6f4981..260981f0d03 100644
--- a/gateway/platforms/weixin.py
+++ b/gateway/platforms/weixin.py
@@ -726,26 +726,12 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
self._split_multiline_messages = _coerce_bool(_extra_or_secret(extra, "split_multiline_messages", ""), default=False)
# Text debounce batching (Telegram pattern): iLink delivers messages individually, so rapid bursts would each
# trigger a separate agent run. Telegram cadence and ceilings (#44883); ``0`` dispatches immediately.
- self._text_batch_delay_seconds = self._coerce_float_extra("text_batch_delay_seconds", 0.3, max_value=2.0)
- self._text_batch_split_delay_seconds = self._coerce_float_extra(
- "text_batch_split_delay_seconds", 1.0, min_value=self._text_batch_delay_seconds, max_value=4.0)
+ self._configure_text_batch_delays()
persisted = load_weixin_account(hermes_home, self._account_id) if self._account_id and not self._token else None
if persisted:
self._token = str(persisted.get("token") or "").strip()
self._base_url = str(persisted.get("base_url") or self._base_url).strip().rstrip("/")
- def _coerce_float_extra(self, key: str, default: float, *, min_value: float = 0.0, max_value: Optional[float] = None) -> float:
- """Float from ``config.extra``; fed to ``asyncio.sleep()``, so NaN/Inf/negative/unparseable → default; clamped."""
- import math
- value = (self.config.extra or {}).get(key)
- try:
- parsed = float(value) if value is not None else float(default)
- except (TypeError, ValueError):
- parsed = float(default)
- if not math.isfinite(parsed) or parsed < 0:
- parsed = float(default)
- return min(max(parsed, min_value), max_value) if max_value is not None else max(parsed, min_value)
-
@staticmethod
def _coerce_list(value: Any) -> List[str]:
if value is None:
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index e00201994a8..ff7d6ac041c 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -502,9 +502,11 @@ class TelegramAdapter(BasePlatformAdapter):
# Aggregate client-side splits of long messages into one MessageEvent; bounds are conservative
# for Telegram's ~1 edit/s flood envelope.
self._text_batch_delay_seconds = self._env_float_clamped(
- "HERMES_TELEGRAM_TEXT_BATCH_DELAY_SECONDS", 0.3, min_value=0.08, max_value=2.0)
+ "HERMES_TELEGRAM_TEXT_BATCH_DELAY_SECONDS", self._TEXT_BATCH_DEFAULT_DELAY_S,
+ min_value=0.08, max_value=self._TEXT_BATCH_MAX_DELAY_S)
self._text_batch_split_delay_seconds = self._env_float_clamped(
- "HERMES_TELEGRAM_TEXT_BATCH_SPLIT_DELAY_SECONDS", 1.0, min_value=self._text_batch_delay_seconds, max_value=4.0)
+ "HERMES_TELEGRAM_TEXT_BATCH_SPLIT_DELAY_SECONDS", self._TEXT_BATCH_DEFAULT_SPLIT_DELAY_S,
+ min_value=self._text_batch_delay_seconds, max_value=self._TEXT_BATCH_MAX_SPLIT_DELAY_S)
self._drop_delayed_deliveries = False
# Held across disconnect: PTB advances the offset before our drop-guard runs, so Telegram won't
# redeliver — dropping is permanent loss (see _hold_inbound_event).
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py
index 9a8faa6fa24..add70f4d671 100644
--- a/plugins/platforms/whatsapp/adapter.py
+++ b/plugins/platforms/whatsapp/adapter.py
@@ -289,20 +289,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
self._shutting_down = False
# Text debounce batching: rapid bursts (forwards, paste-splits) would otherwise each trigger a separate agent turn.
# Telegram cadence and ceilings (#44883); ``0`` dispatches each message immediately.
- self._text_batch_delay_seconds = self._coerce_float_extra("text_batch_delay_seconds", 0.3, max_value=2.0)
- self._text_batch_split_delay_seconds = self._coerce_float_extra(
- "text_batch_split_delay_seconds", 1.0, min_value=self._text_batch_delay_seconds, max_value=4.0)
-
- def _coerce_float_extra(self, key: str, default: float, *, min_value: float = 0.0, max_value: Optional[float] = None) -> float:
- """Read a float from ``config.extra``; NaN/Inf/negative/unparseable → ``default``; clamped (fed to asyncio.sleep)."""
- import math
- try: # float(None) → TypeError → default
- parsed = float(self.config.extra.get(key) if getattr(self.config, "extra", None) else None)
- except (TypeError, ValueError):
- parsed = float(default)
- if not math.isfinite(parsed) or parsed < 0:
- parsed = float(default)
- return min(max(parsed, min_value), max_value) if max_value is not None else max(parsed, min_value)
+ self._configure_text_batch_delays()
def _bridge_url(self, path: str) -> str:
return f"http://127.0.0.1:{self._bridge_port}/{path}"
diff --git a/tests/gateway/test_text_batch_delay_defaults.py b/tests/gateway/test_text_batch_delay_defaults.py
index c6912fc9328..16aa5c3f127 100644
--- a/tests/gateway/test_text_batch_delay_defaults.py
+++ b/tests/gateway/test_text_batch_delay_defaults.py
@@ -25,5 +25,18 @@ def test_default_text_batch_delays_match_telegram_cadence(adapter_cls, platform,
short_event = MessageEvent(text="hello", message_type=MessageType.TEXT, source=source)
short_event._last_chunk_len = len(short_event.text)
+ assert adapter._text_batch_delay_for(short_event) == adapter._TEXT_BATCH_DEFAULT_DELAY_S
+ assert adapter._text_batch_split_delay_seconds == adapter._TEXT_BATCH_DEFAULT_SPLIT_DELAY_S
assert adapter._text_batch_delay_for(short_event) <= 0.5
- assert adapter._text_batch_split_delay_seconds <= 1.5
+
+
+ "adapter_cls", [WhatsAppAdapter, WeixinAdapter], ids=["whatsapp", "weixin"],
+)
+def test_text_batch_delays_clamped_to_shared_ceilings(adapter_cls, tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ adapter = adapter_cls(PlatformConfig(
+ enabled=True, extra={"text_batch_delay_seconds": "2.5", "text_batch_split_delay_seconds": 7}))
+
+ assert adapter._text_batch_delay_seconds == adapter._TEXT_BATCH_MAX_DELAY_S
+ assert adapter._text_batch_split_delay_seconds == adapter._TEXT_BATCH_MAX_SPLIT_DELAY_S
diff --git a/tests/gateway/test_whatsapp_text_batching.py b/tests/gateway/test_whatsapp_text_batching.py
index e58e46925c1..591897e60f0 100644
--- a/tests/gateway/test_whatsapp_text_batching.py
+++ b/tests/gateway/test_whatsapp_text_batching.py
@@ -42,15 +42,6 @@ def test_batch_delays_overridden_via_config_extra():
assert adapter._text_batch_split_delay_seconds == 3.0
-def test_batch_delays_clamped_to_telegram_ceilings():
- adapter = _make_adapter(
- text_batch_delay_seconds="2.5",
- text_batch_split_delay_seconds=7,
- )
- assert adapter._text_batch_delay_seconds == 2.0
- assert adapter._text_batch_split_delay_seconds == 4.0
-
-
def test_invalid_config_value_falls_back_to_default():
adapter = _make_adapter(
text_batch_delay_seconds="garbage",
diff --git a/website/docs/user-guide/messaging/weixin.md b/website/docs/user-guide/messaging/weixin.md
index 09a9e1c8d42..45d85b42466 100644
--- a/website/docs/user-guide/messaging/weixin.md
+++ b/website/docs/user-guide/messaging/weixin.md
@@ -123,8 +123,8 @@ Set these in `config.yaml` under `platforms.weixin.extra`:
| `allow_from` | `[]` | User IDs allowed for DMs (when dm_policy=allowlist) |
| `group_allow_from` | `[]` | Group IDs allowed (when group_policy=allowlist) |
| `split_multiline_messages` | `false` | When `true`, split multi-line replies into multiple chat messages (legacy behavior). When `false`, keep multi-line replies as one message unless they exceed the length limit. |
-| `text_batch_delay_seconds` | `0.3` | Quiet period (seconds) before a buffered burst of rapid text messages is flushed as one combined request. iLink delivers messages individually, so this debounce avoids one agent invocation per fragment. Set `0` to dispatch each message immediately. |
-| `text_batch_split_delay_seconds` | `1.0` | Extended flush delay used when the latest fragment is near the split threshold (long messages iLink may have chunked). |
+| `text_batch_delay_seconds` | `0.3` | Quiet period (seconds, max `2.0`) before a buffered burst of rapid text messages is flushed as one combined request. iLink delivers messages individually, so this debounce avoids one agent invocation per fragment. Set `0` to dispatch each message immediately. |
+| `text_batch_split_delay_seconds` | `1.0` | Extended flush delay (max `4.0`; never below `text_batch_delay_seconds`) used when the latest fragment is near the split threshold (long messages iLink may have chunked). |
## Access Policies