The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Port from RooCodeInc/Roomote#1478: per-route webhook event coalescing
Teknium3aeb1736c57c
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex af7ae260493..3f8cc0df35e 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -34,6 +34,7 @@ except ImportError:from gateway.config import Platform, PlatformConfigfrom gateway.platforms.base import BasePlatformAdapter, SendResultfrom gateway.platforms.event import MessageEvent, MessageType+from gateway.platforms.webhook_coalesce import WebhookCoalescer, validate_coalesce_configfrom gateway.platforms.webhook_filters import DEFAULT_SCRIPT_TIMEOUT_SECONDS, WebhookRouteProcessorfrom gateway.response_filters import is_autonomous_silence_response@@ -188,6 +189,8 @@ class WebhookAdapter(BasePlatformAdapter):self._max_body_bytes: int = int(extra.get("max_body_bytes", 1_048_576)) # 1MBself._script_timeout_seconds: int = int(extra.get("script_timeout_seconds", DEFAULT_SCRIPT_TIMEOUT_SECONDS))self._route_processor = WebhookRouteProcessor(script_timeout_seconds=self._script_timeout_seconds)+ # Opt-in per-route debounce of rapid same-entity events (route ``coalesce`` block). #92066+ self._coalescer = WebhookCoalescer(dispatch=self._spawn_agent_run, render=self._render_prompt)# --- Lifecycle ---@@ -210,6 +213,7 @@ class WebhookAdapter(BasePlatformAdapter):raise ValueError(f"[webhook] Route '{name}' sets both deliver_only and cron_job. They are mutually "f"exclusive: deliver_only pushes the rendered template as a message, cron_job fires "f"an existing cron job (which handles its own delivery).")+ validate_coalesce_config(name, route)async def connect(self, *, is_reconnect: bool = False) -> bool:self._reload_dynamic_routes()@@ -248,6 +252,7 @@ class WebhookAdapter(BasePlatformAdapter):return Trueasync def disconnect(self) -> None:+ await self._coalescer.flush() # buffered events are dispatched, not dropped, on shutdown/reconnectif self._runner:await self._runner.cleanup()self._runner = None@@ -614,12 +619,28 @@ class WebhookAdapter(BasePlatformAdapter):if route_config.get("deliver_only"):return await self._handle_deliver_only(prompt, payload, route_config, route_name, event_type, delivery_id,profile)+ coalesce = route_config.get("coalesce")+ if isinstance(coalesce, dict) and self._coalescer.enqueue(+ route_name=route_name, coalesce=coalesce, payload=payload, event_type=event_type, prompt=prompt,+ delivery_id=delivery_id, now=now, route_config=route_config, profile=profile):+ return web.json_response({"status": "coalesced", "route": route_name, "event": event_type,+ "delivery_id": delivery_id}, status=202)return self._dispatch_agent_run(request, route_config, route_name, profile, payload, prompt, event_type,delivery_id, now)def _dispatch_agent_run(self, request, route_config: dict, route_name: str, profile, payload: Any, prompt: str,event_type: str, delivery_id: str, now: float) -> "web.Response":- """Record delivery info, spawn the agent run, and return 202 immediately."""+ """Spawn the agent run for one POST and return 202 immediately."""+ logger.info("[webhook] %s event=%s route=%s prompt_len=%d delivery=%s", request.method, event_type, route_name,+ len(prompt), delivery_id)+ self._spawn_agent_run(payload, prompt, delivery_id, now, route_config=route_config, route_name=route_name,+ profile=profile, event_type=event_type)+ return web.json_response({"status": "accepted", "route": route_name, "event": event_type,+ "delivery_id": delivery_id}, status=202)++ def _spawn_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,+ route_name: str, profile, event_type: str) -> "asyncio.Task":+ """Record delivery info and fire the agent run (shared by the immediate and coalesced paths)."""# delivery_id in the session key → concurrent webhooks on one route get independent runs.session_chat_id = f"webhook:{route_name}:{delivery_id}"# ``profile`` rides along so the reply leg (``send`` → ``_deliver_cross_platform``) egresses through@@ -636,15 +657,12 @@ class WebhookAdapter(BasePlatformAdapter):source.profile = profileevent = MessageEvent(text=prompt, message_type=MessageType.TEXT, source=source, raw_message=payload,message_id=delivery_id)- logger.info("[webhook] %s event=%s route=%s prompt_len=%d delivery=%s", request.method, event_type, route_name,- len(prompt), delivery_id)# The per-delivery session is closed by ``on_processing_complete`` once the run finishes# (``handle_message`` is fire-and-forget, so nothing can be closed here).task = asyncio.create_task(self.handle_message(event))self._background_tasks.add(task)task.add_done_callback(self._background_tasks.discard)- return web.json_response({"status": "accepted", "route": route_name, "event": event_type,- "delivery_id": delivery_id}, status=202)+ return taskasync def on_processing_complete(self, event: "MessageEvent", outcome: Any) -> None:"""Close the one-shot per-delivery session: ``prune_sessions`` only reaps rows with ``ended_at`` set, sodiff --git a/gateway/platforms/webhook_coalesce.py b/gateway/platforms/webhook_coalesce.pynew file mode 100644index 00000000000..a8aebbd587e--- /dev/null+++ b/gateway/platforms/webhook_coalesce.py@@ -0,0 +1,150 @@+"""Per-route event coalescing for the webhook adapter (opt-in ``coalesce`` route block).++Rapid distinct events on one logical entity (five pushes to a PR, a burst of ticket edits) each+carry a fresh delivery ID, so idempotency cannot suppress them and every event wakes an agent+run. Coalescing groups events by a payload-derived key and debounces them: only the LATEST event+of a group is dispatched once the quiet window passes, bounded by ``max_wait_seconds`` past the+group's first event so a steady stream cannot starve dispatch. Port of RooCodeInc/Roomote#1478+(one durable review task per PR, stale heads superseded). #92066+"""++from __future__ import annotations++import asyncio+import logging+import re+import time+from dataclasses import dataclass+from typing import Any, Callable, Dict, Optional++logger = logging.getLogger(__name__)++DEFAULT_WINDOW_SECONDS = 30.0+DEFAULT_MAX_WAIT_SECONDS = 300.0+_PLACEHOLDER_RE = re.compile(r"\{[a-zA-Z0-9_.]+\}")+++def validate_coalesce_config(route_name: str, route: dict) -> None:+ """Startup validation of a route's ``coalesce`` block; raises ValueError so a typo'd route fails+ fast instead of silently dispatching every event. Agent-mode routes only."""+ coalesce = route.get("coalesce")+ if coalesce is None:+ return+ for exclusive in ("deliver_only", "cron_job"):+ if route.get(exclusive):+ raise ValueError(f"[webhook] Route '{route_name}' combines {exclusive} with coalesce. Coalescing only "+ f"applies to agent-mode routes.")+ key = coalesce.get("key") if isinstance(coalesce, dict) else None+ if not isinstance(key, str) or not key.strip():+ raise ValueError(f"[webhook] Route '{route_name}' has a coalesce block without a non-empty string 'key'. "+ f"Set coalesce.key to a payload field (e.g. 'pull_request.number') or a template "+ f"(e.g. '{{repository.full_name}}#{{number}}').")+ for field in ("window_seconds", "max_wait_seconds"):+ value = coalesce.get(field)+ if value is not None and (isinstance(value, bool) or not isinstance(value, (int, float)) or value <= 0):+ raise ValueError(f"[webhook] Route '{route_name}' coalesce.{field} must be a positive number, got {value!r}.")+++@dataclass+class PendingEvent:+ """Newest event of a coalesce group plus the group's bookkeeping."""+ payload: Any+ prompt: str+ delivery_id: str+ first_at: float+ count: int+ dispatch_kwargs: Dict[str, Any]++ def prompt_with_note(self) -> str:+ if self.count <= 1:+ return self.prompt+ return (f"{self.prompt}\n\n(Note: {self.count} webhook events for this item arrived in quick succession "+ f"and were coalesced — this is the most recent one; earlier events are superseded.)")+++class WebhookCoalescer:+ """Debounce-and-supersede buffer. ``dispatch(payload, prompt, delivery_id, **kwargs)`` is the adapter's+ agent-run spawner. Only ever driven from the aiohttp event loop → no locking."""++ def __init__(self, dispatch: Callable[..., Any], render: Callable[[str, dict, str, str], str]):+ self._dispatch = dispatch+ self._render = render+ self._pending: Dict[str, PendingEvent] = {}+ self._timers: Dict[str, asyncio.Task] = {}++ @property+ def pending(self) -> Dict[str, PendingEvent]:+ return self._pending++ def group_key(self, route_name: str, key_template: str, payload: dict, event_type: str) -> Optional[str]:+ """``"{route}|{rendered key}"`` for a bare dotted field or a brace template; ``None`` when a field did+ not resolve — unrelated entities must not collapse into one shared group (review finding on #92066)."""+ template = key_template.strip()+ if "{" not in template:+ template = "{" + template + "}"+ rendered = self._render(template, payload, event_type, route_name)+ if _PLACEHOLDER_RE.search(rendered):+ return None+ return f"{route_name}|{rendered}"++ def enqueue(self, *, route_name: str, coalesce: dict, payload: dict, event_type: str, prompt: str,+ delivery_id: str, now: float, **dispatch_kwargs) -> bool:+ """Buffer one event; False when the key did not resolve and the caller must dispatch immediately."""+ group_key = self.group_key(route_name, coalesce["key"], payload, event_type)+ if group_key is None:+ logger.info("[webhook] coalesce key %r unresolved for delivery %s on route %s — dispatching immediately",+ coalesce["key"], delivery_id, route_name)+ return False+ window = float(coalesce.get("window_seconds", DEFAULT_WINDOW_SECONDS))+ max_wait = float(coalesce.get("max_wait_seconds", DEFAULT_MAX_WAIT_SECONDS))+ existing = self._pending.get(group_key)+ first_at = existing.first_at if existing else now+ count = existing.count + 1 if existing else 1+ dispatch_kwargs = {**dispatch_kwargs, "route_name": route_name, "event_type": event_type}+ self._pending[group_key] = PendingEvent(payload=payload, prompt=prompt, delivery_id=delivery_id,+ first_at=first_at, count=count, dispatch_kwargs=dispatch_kwargs)+ if existing is not None:+ logger.info("[webhook] coalesced delivery %s superseded by %s (group=%s, %d events)",+ existing.delivery_id, delivery_id, group_key, count)+ old = self._timers.pop(group_key, None)+ if old is not None and not old.done():+ old.cancel()+ # Quiet window from now, capped at max_wait past the group's FIRST event.+ delay = min(window, max(0.0, first_at + max_wait - now))+ self._timers[group_key] = asyncio.create_task(self._timer(group_key, delay))+ return True++ async def _timer(self, group_key: str, delay: float) -> None:+ try:+ if delay > 0:+ await asyncio.sleep(delay)+ except asyncio.CancelledError:+ return # superseded by a newer event's timer — the pending entry stays+ self._timers.pop(group_key, None)+ entry = self._pending.pop(group_key, None)+ if entry is not None:+ self._settle(group_key, entry)++ def _settle(self, group_key: str, entry: PendingEvent) -> Any:+ logger.info("[webhook] coalesce settled group=%s events=%d delivery=%s", group_key, entry.count,+ entry.delivery_id)+ return self._dispatch(entry.payload, entry.prompt_with_note(), entry.delivery_id, time.time(),+ **entry.dispatch_kwargs)++ async def flush(self) -> None:+ """Dispatch every pending group now and wait until each run is handed to the runner, so an adapter+ disconnect/reconnect drops nothing. A hard process kill still loses the current window's buffer."""+ for task in self._timers.values():+ if not task.done():+ task.cancel()+ self._timers.clear()+ pending, self._pending = self._pending, {}+ handed_off = []+ for group_key, entry in pending.items():+ try:+ handed_off.append(self._settle(group_key, entry))+ except Exception:+ logger.exception("[webhook] failed to flush coalesced group %s", group_key)+ awaitables = [t for t in handed_off if isinstance(t, asyncio.Future)]+ if awaitables:+ await asyncio.gather(*awaitables, return_exceptions=True)diff --git a/tests/gateway/test_webhook_coalescing.py b/tests/gateway/test_webhook_coalescing.pynew file mode 100644index 00000000000..3a0385a01ef--- /dev/null+++ b/tests/gateway/test_webhook_coalescing.py@@ -0,0 +1,119 @@+"""Per-route webhook event coalescing (#92066): rapid distinct events on one entity debounce into+a single agent run on the latest event's state; unrelated or unkeyed events are never merged."""++import asyncio+import json+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import PlatformConfig+from gateway.platforms.webhook import WebhookAdapter, _INSECURE_NO_AUTH+++def _make_adapter(routes=None):+ extra = {"host": "127.0.0.1", "port": 0, "routes": routes or {}, "rate_limit": 100}+ return WebhookAdapter(PlatformConfig(enabled=True, extra=extra))+++def _coalesce_route(**coalesce):+ return {"secret": _INSECURE_NO_AUTH, "prompt": "PR {pull_request.number}: {action}",+ "coalesce": coalesce or {"key": "pull_request.number"}}+++def _mock_request(body: bytes, route_name: str = "pr", delivery_id: str = ""):+ req = MagicMock()+ req.headers = {"X-GitHub-Delivery": delivery_id} if delivery_id else {}+ req.content_length = len(body)+ req.match_info = {"route_name": route_name}+ req.method = "POST"++ async def _read():+ return body++ req.read = _read+ return req+++def _payload(pr_number=None, action: str = "synchronize") -> bytes:+ body: dict = {"action": action}+ if pr_number is not None:+ body["pull_request"] = {"number": pr_number}+ return json.dumps(body).encode()++[email protected]("route, match", [+ ({**_coalesce_route(), "coalesce": {"window_seconds": 5}}, "coalesce block"),+ ({**_coalesce_route(), "coalesce": "pull_request.number"}, "coalesce block"),+ (_coalesce_route(key="pull_request.number", window_seconds=0), "window_seconds"),+ (_coalesce_route(key="pull_request.number", max_wait_seconds=True), "max_wait_seconds"),+ ({**_coalesce_route(), "deliver_only": True, "deliver": "telegram"}, "deliver_only"),+ ({**_coalesce_route(), "cron_job": "sweeper"}, "cron_job"),+])+async def test_invalid_coalesce_config_rejected_at_connect(route, match):+ with pytest.raises(ValueError, match=match):+ await _make_adapter(routes={"pr": route}).connect()+++async def test_rapid_same_entity_events_dispatch_once_with_latest():+ """Three events on PR 7 → one run carrying the last event's prompt/delivery id and a superseded+ note; a different PR in the same burst is its own group; a provider retry (same delivery id)+ is dropped by idempotency before coalescing and is not counted."""+ adapter = _make_adapter(routes={"pr": _coalesce_route(key="pull_request.number", window_seconds=0.05)})+ adapter.handle_message = AsyncMock()++ statuses = []+ for i, action in enumerate(["opened", "synchronize", "synchronize"]):+ resp = await adapter._handle_webhook(_mock_request(_payload(7, action), delivery_id=f"d{i}"))+ statuses.append((resp.status, json.loads(resp.text)["status"]))+ retry = await adapter._handle_webhook(_mock_request(_payload(7), delivery_id="d2"))+ other = await adapter._handle_webhook(_mock_request(_payload(8), delivery_id="other"))+ assert statuses == [(202, "coalesced")] * 3+ assert json.loads(retry.text)["status"] == "duplicate"+ assert json.loads(other.text)["status"] == "coalesced"+ adapter.handle_message.assert_not_called()++ await asyncio.sleep(0.15)++ events = {c.args[0].message_id: c.args[0] for c in adapter.handle_message.call_args_list}+ assert set(events) == {"d2", "other"}+ assert "PR 7: synchronize" in events["d2"].text and "3 webhook events" in events["d2"].text+ assert "coalesced" not in events["other"].text+ assert adapter._coalescer.pending == {}+++async def test_max_wait_caps_starvation_and_unresolved_key_dispatches_immediately():+ adapter = _make_adapter(routes={"pr": _coalesce_route(key="pull_request.number", window_seconds=10,+ max_wait_seconds=0.1)})+ adapter.handle_message = AsyncMock()++ # An event without the key field must not be folded into a shared "{pull_request.number}" group.+ resp = await adapter._handle_webhook(_mock_request(_payload(None, "created"), delivery_id="nokey"))+ assert json.loads(resp.text)["status"] == "accepted"+ await asyncio.sleep(0)+ assert adapter.handle_message.call_count == 1++ # A stream faster than the 10s window still dispatches once max_wait (0.1s) elapses.+ for i in range(3):+ await adapter._handle_webhook(_mock_request(_payload(5), delivery_id=f"s{i}"))+ await asyncio.sleep(0.02)+ await asyncio.sleep(0.15)+ assert adapter.handle_message.call_count == 2+ assert "3 webhook events" in adapter.handle_message.call_args[0][0].text+++async def test_disconnect_flushes_pending_groups():+ adapter = _make_adapter(routes={"pr": _coalesce_route(key="pull_request.number", window_seconds=60)})+ adapter.handle_message = AsyncMock()+ await adapter._handle_webhook(_mock_request(_payload(4), delivery_id="pend"))+ adapter.handle_message.assert_not_called()++ await adapter.disconnect()++ assert adapter.handle_message.call_count == 1+ assert adapter.handle_message.call_args[0][0].message_id == "pend"+ assert adapter._coalescer.pending == {}diff --git a/website/docs/user-guide/messaging/webhooks.md b/website/docs/user-guide/messaging/webhooks.mdindex ca258573edb..f4bbd1affb5 100644--- a/website/docs/user-guide/messaging/webhooks.md+++ b/website/docs/user-guide/messaging/webhooks.md@@ -90,6 +90,7 @@ Routes define how different webhook sources are handled. Each route is a named e| `deliver_extra` | No | Additional delivery config — keys depend on `deliver` type (e.g. `repo`, `pr_number`, `chat_id`). Values support the same `{dot.notation}` templates as `prompt`. || `deliver_only` | No | If `true`, skip the agent entirely — the rendered `prompt` template becomes the literal message that gets delivered. Zero LLM cost, sub-second delivery. See [Direct Delivery Mode](#direct-delivery-mode) for use cases. Requires `deliver` to be a real target (not `log`). || `cron_job` | No | Fire an existing cron job (by ID or name) on each event instead of starting a fresh webhook agent session. The rendered `prompt` becomes transient per-run context; the job's own prompt, skills, model, and delivery settings apply. Mutually exclusive with `deliver_only`. See [Event-Triggered Cron Jobs](#event-triggered-cron-jobs). |+| `coalesce` | No | Debounce rapid distinct events on the same logical entity into one agent run. Block with a required `key` (payload field or template identifying the entity, e.g. `pull_request.number`), optional `window_seconds` (quiet window, default 30) and `max_wait_seconds` (dispatch cap, default 300). See [Event Coalescing](#event-coalescing). Mutually exclusive with `deliver_only` and `cron_job`. |### Full example@@ -163,6 +164,42 @@ Supported operators:Field paths use dot notation. `payload.foo` reads from a top-level `payload` object when one exists, or from the root webhook body for flat payloads. `event` / `event_type` match the resolved event type, and `headers.<Name>` reads request headers.+### Event Coalescing {#event-coalescing}++Providers often fire several distinct events for the same logical entity in quick succession — five rapid pushes to one pull request, a burst of edits to one ticket, a flapping monitoring alert. Each event carries a fresh delivery ID, so the idempotency cache cannot suppress them and every event wakes a separate agent run.++Set `coalesce` on a route to debounce these into a single run per entity:++```yaml+platforms:+ webhook:+ extra:+ routes:+ github-pr:+ events: ["pull_request"]+ secret: "github-webhook-secret"+ coalesce:+ key: "{repository.full_name}#{pull_request.number}"+ window_seconds: 30 # quiet window (default 30)+ max_wait_seconds: 300 # dispatch cap (default 300)+ prompt: "Review PR #{pull_request.number}: {pull_request.title}"+ deliver: "github_comment"+ deliver_extra:+ repo: "{repository.full_name}"+ pr_number: "{pull_request.number}"+```++How it works:++- Events are grouped per route by the rendered `key`. A bare dotted field (`pull_request.number`) or a full template (`{repository.full_name}#{pull_request.number}`) both work.+- Each new event **replaces** the pending one and pushes the quiet-window timer back. When `window_seconds` pass with no new event, the group dispatches **one** agent run using the latest event's payload, prompt, and delivery templates.+- `max_wait_seconds` caps total buffering from the group's first event, so a steady event stream cannot postpone dispatch forever.+- When more than one event was coalesced, the prompt gets a short note telling the agent how many earlier events were superseded.+- If the `key` does not resolve for an event (the payload lacks the field — e.g. an `issue_comment` event on a route keyed by `pull_request.number`), that event is **dispatched immediately** instead of being coalesced, so unrelated entities never collapse into one group. Pick a key present on every event type the route accepts.+- Coalesced requests return HTTP 202 with `{"status": "coalesced"}`. Delivery-ID idempotency still runs first, so provider retries of the same delivery are dropped rather than counted.+- Pending groups are flushed (dispatched immediately) when the adapter disconnects — a gateway reconnect or `hermes gateway stop` — not dropped. Buffered events live in memory, so a hard process kill loses at most the current window's buffered burst.+- `coalesce` applies to agent-mode routes only; combining it with `deliver_only` or `cron_job` is rejected at startup.+### Script Filters and TransformsUse `script` when declarative filters are not enough. Scripts must live under `~/.hermes/scripts/` for the active profile; relative paths resolve there, and path traversal outside that directory is blocked. `.sh` and `.bash` scripts run with bash, and all other extensions run with the current Python interpreter.