bot_loop_guard.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. """Sliding-window budget for bot-authored inbound messages.
  2. ``{PLATFORM}_ALLOW_BOTS`` only decides admission, so two Hermes profiles replying to each other never stop.
  3. The guard counts admitted bot messages per conversation and drops further ones for ``cooldown_seconds``
  4. once ``max_events`` land inside ``window_seconds``. Settings: config.yaml ``gateway.bot_loop_guard``.
  5. The chain rules (``chain_admit``) end an exchange long before that budget: a human message starts a
  6. new chain; each bot message after it is one hop and ``max_hops`` caps them; a bot repeating the same
  7. text inside one chain is one hop, not a new ask; and with ``bot_replies_expect_reply`` false (the
  8. default) a bot answering the reply this bot delivered to it is not answered again (#137027).
  9. """
  10. from __future__ import annotations
  11. import hashlib
  12. import threading
  13. import time
  14. from collections import deque
  15. from dataclasses import dataclass
  16. from typing import Callable, Deque, Dict, Hashable, Tuple
  17. __all__ = ["BotLoopGuard", "BotLoopGuardSettings", "configured_bot_user", "load_settings", "settings_from_config"]
  18. _TRUTHY = frozenset({"true", "1", "yes", "on"})
  19. _FALSY = frozenset({"false", "0", "no", "off"})
  20. @dataclass(frozen=True)
  21. class BotLoopGuardSettings:
  22. enabled: bool = True
  23. max_events: int = 20
  24. window_seconds: float = 300.0
  25. cooldown_seconds: float = 600.0
  26. max_hops: int = 4
  27. bot_replies_expect_reply: bool = False
  28. def _as_bool(raw, default: bool) -> bool:
  29. if isinstance(raw, bool):
  30. return raw
  31. text = str(raw).strip().lower() if raw is not None else ""
  32. if text in _TRUTHY:
  33. return True
  34. if text in _FALSY:
  35. return False
  36. return default
  37. def _as_positive(raw, default: float) -> float:
  38. if isinstance(raw, bool):
  39. return default
  40. try:
  41. value = float(raw)
  42. except (TypeError, ValueError):
  43. return default
  44. return value if value > 0 else default
  45. def _as_positive_int(raw, default: int) -> int:
  46. value = _as_positive(raw, 0.0)
  47. return int(value) if value >= 1 and value == int(value) else default
  48. def settings_from_config(cfg) -> BotLoopGuardSettings:
  49. """Read ``gateway.bot_loop_guard`` from a loaded config dict. Unusable values keep the default."""
  50. from hermes_cli.config import cfg_get
  51. block = cfg_get(cfg, "gateway", "bot_loop_guard", default=None)
  52. if not isinstance(block, dict):
  53. return BotLoopGuardSettings()
  54. defaults = BotLoopGuardSettings()
  55. return BotLoopGuardSettings(
  56. enabled=_as_bool(block.get("enabled"), defaults.enabled),
  57. max_events=_as_positive_int(block.get("max_events"), defaults.max_events),
  58. window_seconds=_as_positive(block.get("window_seconds"), defaults.window_seconds),
  59. cooldown_seconds=_as_positive(block.get("cooldown_seconds"), defaults.cooldown_seconds),
  60. max_hops=_as_positive_int(block.get("max_hops"), defaults.max_hops),
  61. bot_replies_expect_reply=_as_bool(block.get("bot_replies_expect_reply"), defaults.bot_replies_expect_reply),
  62. )
  63. def configured_bot_user(platform_config, user_id) -> bool:
  64. """Whether ``user_id`` is in the adapter's ``bot_users`` list (config.yaml platform ``extra``): the
  65. opt-in that marks a peer bot on a platform whose events carry no bot flag (Mattermost, Matrix,
  66. Signal, IRC, ...), so this guard and the bot-peer delivery rules engage for it (#137027)."""
  67. if user_id is None or user_id == "":
  68. return False
  69. configured = (getattr(platform_config, "extra", None) or {}).get("bot_users")
  70. if isinstance(configured, str):
  71. configured = configured.split(",")
  72. return isinstance(configured, (list, tuple, set)) and str(user_id) in {str(v).strip() for v in configured}
  73. def load_settings() -> BotLoopGuardSettings:
  74. """Settings from the live config.yaml. Defaults when the config cannot be read."""
  75. try:
  76. from hermes_cli.config import load_config_readonly
  77. return settings_from_config(load_config_readonly())
  78. except Exception:
  79. return BotLoopGuardSettings()
  80. class BotLoopGuard:
  81. """Per-conversation sliding window with a cooldown once the budget trips. Thread-safe.
  82. Settings are re-read on every call so a config.yaml edit takes effect without a restart."""
  83. def __init__(
  84. self,
  85. settings: Callable[[], BotLoopGuardSettings] = load_settings,
  86. clock: Callable[[], float] = time.monotonic,
  87. ) -> None:
  88. self._settings = settings
  89. self._clock = clock
  90. self._lock = threading.Lock()
  91. self._events: dict[Hashable, deque[float]] = {}
  92. self._cooldown_until: dict[Hashable, float] = {}
  93. self._last_sweep = 0.0
  94. self._chains: dict[Hashable, _Chain] = {}
  95. @property
  96. def tracked_conversations(self) -> int:
  97. with self._lock:
  98. return len(self._events)
  99. @property
  100. def tracking_chains(self) -> bool:
  101. """Whether any bot exchange is open, so a human message has a chain to reset."""
  102. return bool(self._chains)
  103. def blocked(self, conversation: Hashable) -> bool:
  104. """True while ``conversation`` is cooling down. Reads only, so callers may ask as often as they like."""
  105. if not self._settings().enabled:
  106. return False
  107. with self._lock:
  108. return self._cooldown_until.get(conversation, 0.0) > self._clock()
  109. def admit(self, conversation: Hashable) -> tuple[bool, str]:
  110. """Count one admitted bot-authored message for ``conversation``.
  111. Returns ``(allowed, state)``; state is ``disabled``, ``ok``, ``tripped`` (this message started the cooldown) or ``cooldown``."""
  112. settings = self._settings()
  113. if not settings.enabled:
  114. return True, "disabled"
  115. now = self._clock()
  116. with self._lock:
  117. self._sweep(now, settings)
  118. if self._cooldown_until.get(conversation, 0.0) > now:
  119. return False, "cooldown"
  120. events = self._events.setdefault(conversation, deque())
  121. cutoff = now - settings.window_seconds
  122. while events and events[0] <= cutoff:
  123. events.popleft()
  124. if len(events) >= settings.max_events:
  125. self._cooldown_until[conversation] = now + settings.cooldown_seconds
  126. events.clear()
  127. return False, "tripped"
  128. events.append(now)
  129. return True, "ok"
  130. def chain_admit(self, conversation: Hashable, sender: str, text: str, *, is_bot: bool) -> tuple[bool, str]:
  131. """Apply the chain rules to one admitted inbound message. Returns ``(allowed, state)``; state is
  132. ``disabled``, ``human`` (chain reset), ``ok``, ``max_hops``, ``duplicate`` or ``reply_to_reply``."""
  133. settings = self._settings()
  134. if not settings.enabled:
  135. return True, "disabled"
  136. now = self._clock()
  137. with self._lock:
  138. self._sweep(now, settings)
  139. if not is_bot:
  140. self._chains.pop(conversation, None)
  141. return True, "human"
  142. chain = self._chains.get(conversation)
  143. if chain is None or now - chain.updated > settings.cooldown_seconds:
  144. chain = self._chains[conversation] = _Chain()
  145. chain.updated = now
  146. ask = (sender, hashlib.sha256(" ".join(str(text or "").split()).encode()).hexdigest())
  147. if ask in chain.asks:
  148. return False, "duplicate"
  149. if not settings.bot_replies_expect_reply and chain.replied_to == sender:
  150. return False, "reply_to_reply"
  151. if chain.hops >= settings.max_hops:
  152. return False, "max_hops"
  153. chain.hops += 1
  154. chain.asks.add(ask)
  155. return True, "ok"
  156. def note_reply(self, conversation: Hashable, recipient: str) -> None:
  157. """Record that this bot's reply to bot ``recipient`` went out. Only a delivered reply makes the
  158. recipient's next message an answer to an answer: a message still waiting for its turn, or one
  159. the turn chose to leave unanswered, does not."""
  160. if not self._settings().enabled:
  161. return
  162. with self._lock:
  163. chain = self._chains.get(conversation)
  164. if chain is not None:
  165. chain.replied_to = recipient
  166. def _sweep(self, now: float, settings: BotLoopGuardSettings) -> None:
  167. """Drop idle conversations at most once per window so memory stays bounded."""
  168. if now - self._last_sweep < settings.window_seconds:
  169. return
  170. self._last_sweep = now
  171. idle_cutoff = now - settings.window_seconds
  172. for key in [k for k, dq in self._events.items() if not dq or dq[-1] <= idle_cutoff]:
  173. del self._events[key]
  174. for key in [k for k, until in self._cooldown_until.items() if until <= now]:
  175. del self._cooldown_until[key]
  176. for key in [k for k, chain in self._chains.items() if now - chain.updated > settings.cooldown_seconds]:
  177. del self._chains[key]
  178. class _Chain:
  179. """One bot-to-bot exchange since the last human message in a conversation."""
  180. __slots__ = ("asks", "hops", "replied_to", "updated")
  181. def __init__(self) -> None:
  182. self.hops = 0
  183. self.asks: set[tuple[str, str]] = set()
  184. self.replied_to: str = ""
  185. self.updated = 0.0