Skip to content

The agent that grows with you

fix: webhook and relay deliveries fire post_gateway_admission once per admission

Teknium15e1ccfdfa02
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.py
index 989aeb7bb36..c01037fb2d1 100644
--- a/gateway/platforms/webhook.py
+++ b/gateway/platforms/webhook.py
@@ -307,6 +307,9 @@ class WebhookAdapter(BasePlatformAdapter):
except Exception:
logger.warning("[webhook] Destination unavailable for %s", chat_id, exc_info=True)
return SendResult(success=False, error="Webhook destination unavailable or unauthorized")
+ return await self._deliver_to(delivery, chat_id, content)
+
+ async def _deliver_to(self, delivery: Dict[str, Any], chat_id: str, content: str) -> SendResult:
deliver_type = delivery["deliver"]
if deliver_type == "log":
logger.info("[webhook] Response for %s: %s", chat_id, content[:200])
@@ -760,6 +763,15 @@ class WebhookAdapter(BasePlatformAdapter):
return None
if getattr(event, '_webhook_duplicate', False):
return "duplicate"
+ if receipt is None:
+ # A post_gateway_admission plugin consumed the delivery: nothing was committed, so the
+ # reply goes to the destination this request just validated, not a retained row.
+ reply = getattr(event, '_consumer_reply', None)
+ if reply:
+ from gateway.platforms.webhook_delivery import snapshot_destination
+ await self._deliver_to(snapshot_destination(self, self._delivery_info.get(session_chat_id)),
+ session_chat_id, reply)
+ return "accepted"
from gateway.session_authorities import active_authority, authority_for_profile_id
runner = self._message_handler.__self__
authority = authority_for_profile_id(runner, receipt.ref.profile_id) or active_authority(runner)
diff --git a/gateway/platforms/webhook_ingress.py b/gateway/platforms/webhook_ingress.py
index e67f389dc1f..f6c8df86466 100644
--- a/gateway/platforms/webhook_ingress.py
+++ b/gateway/platforms/webhook_ingress.py
@@ -39,27 +39,50 @@ async def producer_scope(adapter, event):
async def admit_producer(adapter, event):
+ """Commit a producer delivery; ``None`` when a ``post_gateway_admission`` plugin consumed it.
+
+ The hook (#129958) fires once per admission, like ``GatewayInboundMixin._handle_message``:
+ after authorization and before the commit (a consumed delivery is never admitted; its reply,
+ if any, rides ``event._consumer_reply`` for the caller's own reply leg), and never for a
+ replay of an already-committed delivery (provider retry, relay re-send) nor at execution."""
async with producer_scope(adapter, event) as authority:
from gateway.config import Platform
- if adapter.platform == Platform.WEBHOOK:
+ from gateway.run_inbound_consumer import POST_ADMISSION_HOOK
+ from hermes_cli.lifecycle import has_hook
+ webhook = adapter.platform == Platform.WEBHOOK
+ if webhook:
prior = await _webhook_retry(authority, event)
if prior is not None:
return prior
+ if has_hook(POST_ADMISSION_HOOK) and (webhook or not (await _committed(authority, event))[1]):
+ from gateway.run_inbound_consumer import run_post_admission_hook
+ runner = authority.runner
+ consumed, event._consumer_reply = await run_post_admission_hook(
+ runner, event, event.source, runner._session_key_for_source(event.source))
+ if consumed:
+ return None
return await authority.admit_native(event)
-async def _webhook_retry(authority, event):
- # One-shot finalization ends the route. Resolve an existing provider receipt
- # before SessionStore would rotate it into a new physical session.
+async def _committed(authority, event):
+ """``(validated payload, rows)`` of this delivery's identity in the FIFO. Preparing the payload
+ runs the same authorization as admission, so a refused sender raises here."""
import json
from gateway.session_envelope import prepare_native, restore_native
- from hermes_state_runtime import get_session_admission
payload = await prepare_native(authority.runner, event)
source = restore_native(payload).source
identity = json.dumps([source.profile, source.platform.value, source.chat_id,
source.thread_id, source.user_id], separators=(',', ':'))
rows = authority.db._read_all('SELECT admission_id FROM session_admissions '
'WHERE principal_id=? AND request_id=?', ('messaging:' + identity, event.message_id))
+ return payload, rows
+
+
+async def _webhook_retry(authority, event):
+ # One-shot finalization ends the route. Resolve an existing provider receipt
+ # before SessionStore would rotate it into a new physical session.
+ from hermes_state_runtime import get_session_admission
+ payload, rows = await _committed(authority, event)
if not rows:
return None
row = get_session_admission(authority.db, admission_id=rows[0]['admission_id'])
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.py
index 73de4cbdc4e..9d80f857a12 100644
--- a/gateway/relay/adapter.py
+++ b/gateway/relay/adapter.py
@@ -902,7 +902,14 @@ class RelayAdapter(BasePlatformAdapter):
event.timestamp = datetime.fromtimestamp(0, timezone.utc)
# Wait only for the SQLite receipt, never inference or outbound ACKs
# (those need this same WS reader). Exceptions deliberately suppress ACK.
- await admit_producer(self, event)
+ if await admit_producer(self, event) is None and getattr(event, '_consumer_reply', None):
+ # A post_gateway_admission plugin consumed it (never committed); its reply is
+ # sent off this reader, like an executed admission's.
+ from gateway.session_ingress import deliver_response
+ task = asyncio.create_task(deliver_response(
+ self, event, runner._session_key_for_source(event.source), event._consumer_reply))
+ self._background_tasks.add(task)
+ task.add_done_callback(self._background_tasks.discard)
else:
await self.handle_message(event)
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 35abb79276f..f0aea314479 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -26,6 +26,7 @@ from gateway.platforms.event import MessageEvent, MessageType
from gateway.run_busy import approval_input_words
from gateway.run_common import _UNSET
from gateway.run_inbound_media import rehome_inbound_media
+from gateway.run_inbound_hooks import GatewayInboundHooksMixin
from gateway.run_plugin_injection import GatewayPluginInjectionMixin
from gateway.run_inbound_unauthorized import (
UnauthorizedOwnerNotifier, pairing_code_reply, pairing_profile_arg, pairing_rate_limited_reply,
@@ -67,46 +68,9 @@ def strip_discord_triggering_note(event: Any, message_text: Any) -> Any:
return message_text[len(prefix):] if message_text.startswith(prefix) else message_text
-class GatewayInboundMixin(GatewayPluginInjectionMixin):
+class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayPluginInjectionMixin):
"""Inbound message pipeline (_handle_message, text/media preparation, durable-turn markers, plugin injection) for GatewayRunner."""
- async def _hm_pre_gateway_dispatch_hook(
- self, event: "MessageEvent", source: SessionSource
- ) -> Optional["MessageEvent"]:
- """Run the ``pre_gateway_dispatch`` plugin hook; None = drop, else the (maybe rewritten) event.
- Results: ``{"action": "skip"}`` → drop; ``{"action": "rewrite", "text"}`` → replace ``event.text``;
- ``allow``/None → normal dispatch. Runs BEFORE auth so plugins can handle unauthorized senders."""
- try:
- from hermes_cli.lifecycle import ainvoke_hook as _ainvoke_hook
- _hook_results = await _ainvoke_hook(
- "pre_gateway_dispatch", event=event, gateway=self,
- # getattr: bare-runner tests build GatewayRunner via object.__new__ without __init__.
- session_store=getattr(self, "session_store", None),
- )
- except Exception as _hook_exc:
- logger.warning("pre_gateway_dispatch invocation failed: %s", _hook_exc)
- _hook_results = []
-
- for _result in _hook_results:
- if not isinstance(_result, dict):
- continue
- _action = _result.get("action")
- if _action == "skip":
- logger.info(
- "pre_gateway_dispatch skip: reason=%s platform=%s chat=%s",
- _result.get("reason"), source.platform.value if source.platform else "unknown",
- source.chat_id or "unknown",
- )
- return None
- if _action == "rewrite":
- _new_text = _result.get("text")
- if isinstance(_new_text, str):
- event = dataclasses.replace(event, text=_new_text)
- break
- if _action == "allow":
- break
- return event
-
async def _hm_offer_pairing_code(self, source: SessionSource) -> None:
"""DM an unauthorized sender a pairing code (rate-limited; groups never reach here)."""
platform_name = source.platform.value if source.platform else "unknown"
@@ -781,70 +745,6 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):
self._queue_or_replace_pending_event(_quick_key, event)
return None
- def _hm_quick_commands(self) -> dict:
- """User-defined ``quick_commands`` mapping from config (empty dict when unset/malformed)."""
- cfg = self.config
- qc = (cfg.get("quick_commands") if isinstance(cfg, dict) else getattr(cfg, "quick_commands", None)) or {}
- return qc if isinstance(qc, dict) else {}
-
- @staticmethod
- def _hm_expand_alias_quick_command(event: "MessageEvent", qcmd: dict) -> Optional[str]:
- """Rewrite ``event.text`` to an alias quick command's target; returns the new command name."""
- target = (qcmd.get("target") or "").strip()
- if not target:
- return None
- target = target if target.startswith("/") else f"/{target}"
- event.text = f"{target} {event.get_command_args().strip()}".strip()
- target_command = target.lstrip("/")
- return target_command.split()[0] if target_command else target_command
-
- async def _hm_command_hooks(
- self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: str, canonical: str
- ) -> Tuple[bool, Optional[str], Optional[str]]:
- """Fire ``pre_command`` (observer) and ``command:<canonical>`` (interceptor) hooks →
- ``(handled, result, new_command)`` (``new_command`` set when a handler rewrote the command).
- The running-agent path deliberately does NOT fire these — a slow or hostile plugin must not
- interfere with the operator's escape hatches for a live agent."""
- raw_args = event.get_command_args().strip()
- platform = source.platform.value if source.platform else ""
- try:
- from hermes_cli.plugins import fire_pre_command_hook
- fire_pre_command_hook(
- surface="gateway", command=str(canonical), alias_used=str(command),
- args_raw=raw_args, session_key=_quick_key, platform=platform,
- )
- except Exception as _pre_cmd_err:
- logger.debug("pre_command hook dispatch failed (non-fatal): %s", _pre_cmd_err)
-
- # Handlers may return ``{"decision": "deny" | "handled" | "rewrite", ...}`` to intercept
- # dispatch; handlers returning nothing behave as plain observers.
- hook_ctx = {
- "platform": platform, "user_id": source.user_id, "command": canonical,
- "raw_command": command, "args": raw_args, "raw_args": raw_args,
- }
- try:
- hook_results = await self.hooks.emit_collect(f"command:{canonical}", hook_ctx)
- except Exception as _hook_err:
- logger.debug("command:%s hook dispatch failed (non-fatal): %s", canonical, _hook_err)
- hook_results = []
-
- for hook_result in hook_results:
- if not isinstance(hook_result, dict):
- continue
- decision = str(hook_result.get("decision", "")).strip().lower()
- message = hook_result.get("message")
- message = message if isinstance(message, str) and message else None
- if decision == "deny":
- return True, message or t("gateway.hooks.command_blocked", command=command), None
- if decision == "handled":
- return True, message, None
- if decision == "rewrite":
- new_command = str(hook_result.get("command_name", "")).strip().lstrip("/")
- if new_command:
- event.text = f"/{new_command} {str(hook_result.get('raw_args', '')).strip()}".strip()
- return False, None, event.get_command()
- return False, None, None
-
async def _hm_resolve_command(
self, event: "MessageEvent", source: SessionSource, _quick_key: str
) -> Tuple[bool, Optional[str], Optional[str], Optional[str]]:
@@ -1061,86 +961,6 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):
return await getattr(self, f"_hm_cmd_{canonical}")(event, source, _quick_key)
return False, None
- async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str) -> str:
- """Run a ``type: exec`` quick command in the gateway process (30 s cap, sanitized env — the
- gateway process has every API key in os.environ; output is redacted too)."""
- try:
- from tools.environments.local import build_subprocess_env
- proc = await asyncio.create_subprocess_shell(
- exec_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
- env=build_subprocess_env(),
- )
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
- output = (stdout or stderr).decode().strip()
- if output:
- from agent.redact import redact_sensitive_text
- output = redact_sensitive_text(output)
- return output or t("gateway.quick_command.no_output")
- except asyncio.TimeoutError:
- return t("gateway.quick_command.timed_out")
- except Exception as e:
- return t("gateway.quick_command.error", error=e)
-
- async def _hm_dispatch_quick_and_plugin_commands(
- self, event: "MessageEvent", source: SessionSource, command: Optional[str]
- ) -> Tuple[bool, Optional[str], Optional[str]]:
- """Drain gate, user-defined quick commands (exec/alias) and plugin slash commands →
- ``(handled, result, command)``; an alias quick command rewrites ``command``."""
- if self._draining:
- return True, t("gateway.busy.drain_rejected_new_work", action=self._status_action_gerund()), command
-
- # User-defined quick commands (bypass agent loop, no LLM call)
- qcmd = self._hm_quick_commands().get(command) if command else None
- if qcmd is not None:
- # Quick commands are slash capabilities too — and type:exec ones run a shell command in
- # the gateway process. They are never in the registry, so the early gate never fires for
- # them; apply the same admin/user policy to the raw typed name here.
- # The early gate above only fires for registry-known commands, so quick commands (never in the
- # registry) would otherwise reach this dispatch sink unchecked. (#44727)
- _denied = self._check_slash_access(source, command)
- if _denied is not None:
- return True, _denied, command
- qtype = qcmd.get("type")
- if qtype == "exec":
- exec_cmd = qcmd.get("command", "")
- if not exec_cmd:
- return True, t("gateway.quick_command.no_command", command=command), command
- return True, await self._hm_run_exec_quick_command(command, exec_cmd), command
- if qtype != "alias":
- return True, t("gateway.quick_command.unsupported_type", command=command), command
- new_command = self._hm_expand_alias_quick_command(event, qcmd)
- if new_command is None:
- return True, t("gateway.quick_command.no_target", command=command), command
- command = new_command # Fall through to normal command dispatch below
-
- # Plugin-registered slash commands. Underscores normalize to hyphens so Telegram's
- # underscored autocomplete form matches plugin commands registered with hyphens.
- if command:
- try:
- from hermes_cli.plugins import get_plugin_command_handler
- plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
- if plugin_handler:
- # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
- # sits before it, so a handler reading get_session_env() would see an empty or a
- # foreign (cron agent's os.environ) session (#108698). No session_entry exists yet,
- # so session_key is derived from source. Sync handlers run on the gateway pool
- # (contextvars carried), never the loop thread: blocking I/O there starves the
- # liveness watchdog and the process exits 75 mid-handler (#105279).
- _plugin_context = build_session_context(source, self.config)
- _plugin_context.session_key = self._session_key_for_source(source)
- user_args = event.get_command_args().strip()
- with self._session_env_scope(_plugin_context):
- if asyncio.iscoroutinefunction(plugin_handler):
- result = await plugin_handler(user_args)
- else:
- result = await self._run_in_executor_with_context(plugin_handler, user_args)
- if asyncio.iscoroutine(result):
- result = await result
- return True, str(result) if result else None, command
- except Exception as e:
- logger.warning("Plugin command dispatch failed: %s", e)
- return False, None, command
-
def _hm_bundle_slash_rewrite(
self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: str
) -> bool:
@@ -1360,10 +1180,7 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):
# its whole request timeout.
if self._is_session_running(_quick_key) and await self._hm_busy_preempt(event, source, _quick_key):
return None
- # Ingress-side, once per inbound message (#129958): a consumed message is never
- # admitted, and a committed row never re-fires it at execution or restart replay.
- from gateway.run_inbound_consumer import run_post_admission_hook
- _consumed, _consumer_reply = await run_post_admission_hook(self, event, source, _quick_key)
+ _consumed, _consumer_reply = await self._hm_post_admission_consume(event, source, _quick_key)
if _consumed:
return _consumer_reply
return await admit_message(authority, event)
@@ -1421,12 +1238,9 @@ class GatewayInboundMixin(GatewayPluginInjectionMixin):
_run_generation = self._begin_session_run_generation(_quick_key)
try:
- # Fail-open plugin consume inside the claimed slot (#129958). An admitted row already
- # ran it at ingress, before its commit: execution never offers the same message twice.
- from gateway.session_ingress import executing_admission
- if not is_internal and not executing_admission.get():
- from gateway.run_inbound_consumer import run_post_admission_hook
- _consumed, _consumer_reply = await run_post_admission_hook(self, event, source, _quick_key)
+ # Fail-open plugin consume inside the claimed slot (#129958); once per message.
+ if not is_internal:
+ _consumed, _consumer_reply = await self._hm_post_admission_consume(event, source, _quick_key)
if _consumed:
return _consumer_reply
try:
diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.py
new file mode 100644
index 00000000000..879d809aae6
--- /dev/null
+++ b/gateway/run_inbound_hooks.py
@@ -0,0 +1,219 @@
+"""Plugin and user extension points on the inbound pipeline (moved out of ``gateway/run_inbound.py``).
+
+``pre_gateway_dispatch`` (before auth), ``post_gateway_admission`` (once per admitted inbound
+message, #129958), ``pre_command`` / ``command:<name>`` hooks, user ``quick_commands`` and
+plugin-registered slash commands. Bound onto ``GatewayRunner`` through ``GatewayInboundMixin``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import logging
+from typing import Optional, Tuple
+
+from agent.i18n import t
+from gateway.platforms.event import MessageEvent
+from gateway.session import SessionSource, build_session_context
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("gateway.run")
+
+
+class GatewayInboundHooksMixin:
+ """Hook, quick-command and plugin-command dispatch for ``GatewayInboundMixin``."""
+
+ async def _hm_post_admission_consume(
+ self, event: "MessageEvent", source: SessionSource, session_key: str
+ ) -> Tuple[bool, Optional[str]]:
+ """``post_gateway_admission`` exactly once per inbound message: ``(consumed, reply)``.
+
+ Never while an admitted row EXECUTES (first run or restart replay): the authority path
+ already offered the message at ingress, before its commit, so a consumed message is never
+ admitted and an admitted one is never offered twice."""
+ from gateway.session_ingress import executing_admission
+ if executing_admission.get():
+ return False, None
+ from gateway.run_inbound_consumer import run_post_admission_hook
+ return await run_post_admission_hook(self, event, source, session_key)
+
+ async def _hm_pre_gateway_dispatch_hook(
+ self, event: "MessageEvent", source: SessionSource
+ ) -> Optional["MessageEvent"]:
+ """Run the ``pre_gateway_dispatch`` plugin hook; None = drop, else the (maybe rewritten) event.
+ Results: ``{"action": "skip"}`` → drop; ``{"action": "rewrite", "text"}`` → replace ``event.text``;
+ ``allow``/None → normal dispatch. Runs BEFORE auth so plugins can handle unauthorized senders."""
+ try:
+ from hermes_cli.lifecycle import ainvoke_hook as _ainvoke_hook
+ _hook_results = await _ainvoke_hook(
+ "pre_gateway_dispatch", event=event, gateway=self,
+ # getattr: bare-runner tests build GatewayRunner via object.__new__ without __init__.
+ session_store=getattr(self, "session_store", None),
+ )
+ except Exception as _hook_exc:
+ logger.warning("pre_gateway_dispatch invocation failed: %s", _hook_exc)
+ _hook_results = []
+
+ for _result in _hook_results:
+ if not isinstance(_result, dict):
+ continue
+ _action = _result.get("action")
+ if _action == "skip":
+ logger.info(
+ "pre_gateway_dispatch skip: reason=%s platform=%s chat=%s",
+ _result.get("reason"), source.platform.value if source.platform else "unknown",
+ source.chat_id or "unknown",
+ )
+ return None
+ if _action == "rewrite":
+ _new_text = _result.get("text")
+ if isinstance(_new_text, str):
+ event = dataclasses.replace(event, text=_new_text)
+ break
+ if _action == "allow":
+ break
+ return event
+
+ def _hm_quick_commands(self) -> dict:
+ """User-defined ``quick_commands`` mapping from config (empty dict when unset/malformed)."""
+ cfg = self.config
+ qc = (cfg.get("quick_commands") if isinstance(cfg, dict) else getattr(cfg, "quick_commands", None)) or {}
+ return qc if isinstance(qc, dict) else {}
+
+ @staticmethod
+ def _hm_expand_alias_quick_command(event: "MessageEvent", qcmd: dict) -> Optional[str]:
+ """Rewrite ``event.text`` to an alias quick command's target; returns the new command name."""
+ target = (qcmd.get("target") or "").strip()
+ if not target:
+ return None
+ target = target if target.startswith("/") else f"/{target}"
+ event.text = f"{target} {event.get_command_args().strip()}".strip()
+ target_command = target.lstrip("/")
+ return target_command.split()[0] if target_command else target_command
+
+ async def _hm_command_hooks(
+ self, event: "MessageEvent", source: SessionSource, _quick_key: str, command: str, canonical: str
+ ) -> Tuple[bool, Optional[str], Optional[str]]:
+ """Fire ``pre_command`` (observer) and ``command:<canonical>`` (interceptor) hooks →
+ ``(handled, result, new_command)`` (``new_command`` set when a handler rewrote the command).
+ The running-agent path deliberately does NOT fire these — a slow or hostile plugin must not
+ interfere with the operator's escape hatches for a live agent."""
+ raw_args = event.get_command_args().strip()
+ platform = source.platform.value if source.platform else ""
+ try:
+ from hermes_cli.plugins import fire_pre_command_hook
+ fire_pre_command_hook(
+ surface="gateway", command=str(canonical), alias_used=str(command),
+ args_raw=raw_args, session_key=_quick_key, platform=platform,
+ )
+ except Exception as _pre_cmd_err:
+ logger.debug("pre_command hook dispatch failed (non-fatal): %s", _pre_cmd_err)
+
+ # Handlers may return ``{"decision": "deny" | "handled" | "rewrite", ...}`` to intercept
+ # dispatch; handlers returning nothing behave as plain observers.
+ hook_ctx = {
+ "platform": platform, "user_id": source.user_id, "command": canonical,
+ "raw_command": command, "args": raw_args, "raw_args": raw_args,
+ }
+ try:
+ hook_results = await self.hooks.emit_collect(f"command:{canonical}", hook_ctx)
+ except Exception as _hook_err:
+ logger.debug("command:%s hook dispatch failed (non-fatal): %s", canonical, _hook_err)
+ hook_results = []
+
+ for hook_result in hook_results:
+ if not isinstance(hook_result, dict):
+ continue
+ decision = str(hook_result.get("decision", "")).strip().lower()
+ message = hook_result.get("message")
+ message = message if isinstance(message, str) and message else None
+ if decision == "deny":
+ return True, message or t("gateway.hooks.command_blocked", command=command), None
+ if decision == "handled":
+ return True, message, None
+ if decision == "rewrite":
+ new_command = str(hook_result.get("command_name", "")).strip().lstrip("/")
+ if new_command:
+ event.text = f"/{new_command} {str(hook_result.get('raw_args', '')).strip()}".strip()
+ return False, None, event.get_command()
+ return False, None, None
+
+ async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str) -> str:
+ """Run a ``type: exec`` quick command in the gateway process (30 s cap, sanitized env — the
+ gateway process has every API key in os.environ; output is redacted too)."""
+ try:
+ from tools.environments.local import build_subprocess_env
+ proc = await asyncio.create_subprocess_shell(
+ exec_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
+ env=build_subprocess_env(),
+ )
+ stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
+ output = (stdout or stderr).decode().strip()
+ if output:
+ from agent.redact import redact_sensitive_text
+ output = redact_sensitive_text(output)
+ return output or t("gateway.quick_command.no_output")
+ except asyncio.TimeoutError:
+ return t("gateway.quick_command.timed_out")
+ except Exception as e:
+ return t("gateway.quick_command.error", error=e)
+
+ async def _hm_dispatch_quick_and_plugin_commands(
+ self, event: "MessageEvent", source: SessionSource, command: Optional[str]
+ ) -> Tuple[bool, Optional[str], Optional[str]]:
+ """Drain gate, user-defined quick commands (exec/alias) and plugin slash commands →
+ ``(handled, result, command)``; an alias quick command rewrites ``command``."""
+ if self._draining:
+ return True, t("gateway.busy.drain_rejected_new_work", action=self._status_action_gerund()), command
+
+ # User-defined quick commands (bypass agent loop, no LLM call)
+ qcmd = self._hm_quick_commands().get(command) if command else None
+ if qcmd is not None:
+ # Quick commands are slash capabilities too — and type:exec ones run a shell command in
+ # the gateway process. They are never in the registry, so the early gate never fires for
+ # them; apply the same admin/user policy to the raw typed name here.
+ # The early gate above only fires for registry-known commands, so quick commands (never in the
+ # registry) would otherwise reach this dispatch sink unchecked. (#44727)
+ _denied = self._check_slash_access(source, command)
+ if _denied is not None:
+ return True, _denied, command
+ qtype = qcmd.get("type")
+ if qtype == "exec":
+ exec_cmd = qcmd.get("command", "")
+ if not exec_cmd:
+ return True, t("gateway.quick_command.no_command", command=command), command
+ return True, await self._hm_run_exec_quick_command(command, exec_cmd), command
+ if qtype != "alias":
+ return True, t("gateway.quick_command.unsupported_type", command=command), command
+ new_command = self._hm_expand_alias_quick_command(event, qcmd)
+ if new_command is None:
+ return True, t("gateway.quick_command.no_target", command=command), command
+ command = new_command # Fall through to normal command dispatch below
+
+ # Plugin-registered slash commands. Underscores normalize to hyphens so Telegram's
+ # underscored autocomplete form matches plugin commands registered with hyphens.
+ if command:
+ try:
+ from hermes_cli.plugins import get_plugin_command_handler
+ plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
+ if plugin_handler:
+ # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
+ # sits before it, so a handler reading get_session_env() would see an empty or a
+ # foreign (cron agent's os.environ) session (#108698). No session_entry exists yet,
+ # so session_key is derived from source. Sync handlers run on the gateway pool
+ # (contextvars carried), never the loop thread: blocking I/O there starves the
+ # liveness watchdog and the process exits 75 mid-handler (#105279).
+ _plugin_context = build_session_context(source, self.config)
+ _plugin_context.session_key = self._session_key_for_source(source)
+ user_args = event.get_command_args().strip()
+ with self._session_env_scope(_plugin_context):
+ if asyncio.iscoroutinefunction(plugin_handler):
+ result = await plugin_handler(user_args)
+ else:
+ result = await self._run_in_executor_with_context(plugin_handler, user_args)
+ if asyncio.iscoroutine(result):
+ result = await result
+ return True, str(result) if result else None, command
+ except Exception as e:
+ logger.warning("Plugin command dispatch failed: %s", e)
+ return False, None, command
diff --git a/tests/gateway/test_post_gateway_admission.py b/tests/gateway/test_post_gateway_admission.py
index 0febb479745..e6b19a0e97b 100644
--- a/tests/gateway/test_post_gateway_admission.py
+++ b/tests/gateway/test_post_gateway_admission.py
@@ -154,3 +154,51 @@ async def test_under_an_authority_the_hook_fires_once_at_ingress_never_at_execut
finally:
ingress.executing_admission.reset(token)
assert fired == ["eat me", "keep me"]
+
+
+async def test_webhook_deliveries_fire_the_hook_once_per_admission_never_on_a_provider_retry():
+ """Webhook/relay traffic enters through ``webhook_ingress.admit_producer``, not
+ ``_handle_message``: plugins still see each delivery once, a consumed one is never committed
+ (its reply goes to the route's destination), and a provider retry of a committed delivery
+ is not offered again."""
+ import hashlib
+ import hmac
+ import json
+
+ from aiohttp import web
+ from aiohttp.test_utils import TestClient, TestServer
+
+ from gateway.platforms.webhook import WebhookAdapter
+ from tests.gateway.fixtures.webhook_route_authority import mount_authority
+
+ fired = []
+ _register(lambda **kwargs: fired.append(kwargs["message_id"]) or (
+ {"action": "handled", "reply": "plugin took it"} if "eat" in kwargs["text"] else None))
+ adapter = WebhookAdapter(PlatformConfig(enabled=True, extra={"secret": "owned-secret", "routes": {
+ "fixture": {"prompt": "{text}"}}}))
+ sent = []
+
+ async def _sink(delivery, chat_id, content):
+ sent.append(content)
+
+ adapter._deliver_to = _sink
+ app = web.Application()
+ mount_authority(app, adapter)
+ app.router.add_post("/webhooks/{route_name}", adapter._handle_webhook)
+
+ async def _post(client, text, delivery_id):
+ body = json.dumps({"text": text}).encode()
+ signature = "sha256=" + hmac.new(b"owned-secret", body, hashlib.sha256).hexdigest()
+ return await client.post("/webhooks/fixture", data=body, headers={
+ "X-GitHub-Delivery": delivery_id, "X-Hub-Signature-256": signature})
+
+ async with TestClient(TestServer(app)) as client:
+ db = adapter._message_handler.__self__.session_authority.db
+ assert (await _post(client, "eat this", "d-eat")).status == 202
+ assert sent == ["plugin took it"] and not db._read_all("SELECT 1 FROM session_admissions")
+ assert (await _post(client, "keep this", "d-keep")).status == 202
+ assert (await _post(client, "keep this", "d-keep")).status in (200, 202)
+ rows = db._read_all("SELECT request_id FROM session_admissions")
+ assert [row["request_id"] for row in rows] == ["d-keep"]
+ assert fired == ["d-eat", "d-keep"]