The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): fire pre_gateway_dispatch once per inbound message, never at execution
unsupportedpastelse3fdebbf871a
diff --git a/gateway/platforms/webhook_ingress.py b/gateway/platforms/webhook_ingress.pyindex f6c8df86466..9d5e4646531 100644--- a/gateway/platforms/webhook_ingress.py+++ b/gateway/platforms/webhook_ingress.py@@ -1,4 +1,5 @@"""Receipt-only adapter ingress: the authority, not an HTTP/WS task, owns execution."""+import asynciofrom contextlib import asynccontextmanagerfrom hermes_state_runtime import RuntimeStoreError@@ -39,62 +40,139 @@ 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.+ """Commit a producer delivery; ``None`` when a plugin skipped or 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."""+ ``pre_gateway_dispatch`` and ``post_gateway_admission`` (#129958) fire once per admission, like+ ``GatewayInboundMixin._handle_message``: before the commit (a skipped or consumed delivery is+ never admitted, a rewrite is what gets committed; a consumer's reply 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 (PLG-5)."""async with producer_scope(adapter, event) as authority:from gateway.config import Platformfrom gateway.run_inbound_consumer import POST_ADMISSION_HOOKfrom hermes_cli.lifecycle import has_hookwebhook = 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]):+ hooks = [name for name in ('pre_gateway_dispatch', POST_ADMISSION_HOOK) if has_hook(name)]+ if not (webhook or hooks):+ return await authority.admit_native(event)+ from gateway.session_authority import native_write_started+ payload, principal = await _prepared(authority, event)+ writing = native_write_started.set(False)+ try:+ # An identical delivery (provider retry, relay re-send) overlapping this one waits here, then+ # rechecks the ledger: the retry check, the hooks and the commit run once per delivery.+ async with _delivery_turn((authority.profile_id, principal, event.message_id)):+ committed = payload, _committed(authority, principal, event.message_id)+ return await _admit_once(authority, event, webhook, hooks, committed)+ except (Exception, asyncio.CancelledError) as exc:+ # Refused after preparing (a command-shaped rewrite, a drain during the hooks, a conflict),+ # or cancelled (relay disconnect, shutdown) before the admission write began. A cancelled+ # write still commits (it is shielded): the bytes it commits are never released here.+ if not (isinstance(exc, asyncio.CancelledError) and native_write_started.get()):+ await asyncio.shield(_release_preparation(authority, payload))+ raise+ finally:+ native_write_started.reset(writing)+++async def _admit_once(authority, event, webhook, hooks, committed):+ from gateway.run_inbound_consumer import POST_ADMISSION_HOOK+ if webhook:+ prior = await _webhook_retry(authority, event, *committed)+ if prior is not None:+ return prior+ admitted = event+ if hooks and (webhook or not committed[1]):+ runner = authority.runner+ if 'pre_gateway_dispatch' in hooks:+ admitted = await runner._hm_pre_gateway_dispatch_hook(event, event.source)+ if admitted is None:+ await _release_preparation(authority, committed[0])+ return None+ if admitted is not event:+ # The rewrite is committed with the fingerprint of the delivery as received:+ # a provider retry or relay re-send resends that, and resolves to this row.+ from gateway.session_ingress_media import ingress_fingerprint+ admitted._ingress_sha256 = ingress_fingerprint(committed[0], event.raw_message)+ if POST_ADMISSION_HOOK in hooks:from gateway.run_inbound_consumer import run_post_admission_hook- runner = authority.runnerconsumed, event._consumer_reply = await run_post_admission_hook(- runner, event, event.source, runner._session_key_for_source(event.source))+ runner, admitted, admitted.source, runner._session_key_for_source(admitted.source))if consumed:+ await _release_preparation(authority, committed[0])return None- return await authority.admit_native(event)+ return await authority.admit_native(admitted)+++# Producer deliveries in flight by (profile, principal, provider id) -> [lock, holder + waiters]. This+# gateway is the only owner of producer ingress, so in-process coordination covers every request.+_deliveries = {}-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."""+@asynccontextmanager+async def _delivery_turn(key):+ if not key[2]: # no provider id: admission mints one, nothing can overlap+ yield+ return+ entry = _deliveries.setdefault(key, [asyncio.Lock(), 0])+ entry[1] += 1+ try:+ async with entry[0]:+ yield+ finally:+ entry[1] -= 1+ if not entry[1]:+ del _deliveries[key]+++async def _release_preparation(authority, payload):+ """A delivery a plugin skipped or consumed, or one refused or cancelled after preparing, is never+ admitted: release the media its preparation (``_prepared``) copied into the retained store. A path+ another admission or an in-flight capture holds is kept, as for a refused admission."""+ from gateway.session_ingress_media import release_unheld_media+ if media := payload['native_text_v1'].get('media'):+ await asyncio.to_thread(release_unheld_media, authority.db, media, retain_history=False)+++async def _prepared(authority, event):+ """``(validated payload, principal)`` of this delivery. Preparing the payload runs the same+ authorization as admission, so a refused sender raises here."""import jsonfrom gateway.session_envelope import prepare_native, restore_nativepayload = await prepare_native(authority.runner, event)source = restore_native(payload).sourceidentity = 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+ return payload, 'messaging:' + identity++def _committed(authority, principal, request_id):+ """The rows of this delivery's identity in the FIFO."""+ return authority.db._read_all('SELECT admission_id FROM session_admissions '+ 'WHERE principal_id=? AND request_id=?', (principal, request_id))-async def _webhook_retry(authority, event):+async def _webhook_retry(authority, event, payload, rows):# One-shot finalization ends the route. Resolve an existing provider receipt# before SessionStore would rotate it into a new physical session.+ from gateway.session_ingress_media import ingress_fingerprintfrom hermes_state_runtime import get_session_admission- payload, rows = await _committed(authority, event)if not rows:return Nonerow = get_session_admission(authority.db, admission_id=rows[0]['admission_id'])retained = row['payload']['native_text_v1']- if 'webhook_delivery' not in retained and 'webhook_route' not in retained:- # A pre-destination receipt is still a receipt, not permission to infer- # again. Do not retrofit today's destination into its queued execution.- payload['native_text_v1'].pop('webhook_delivery')- payload['native_text_v1'].pop('webhook_route')- if 'provenance' not in retained:- payload['native_text_v1'].pop('provenance', None)- if len(rows) != 1 or row['payload'] != payload:+ if 'ingress_sha256' in retained:+ # Committed rewritten: the provider resends the delivery as received.+ same = retained['ingress_sha256'] == ingress_fingerprint(payload, event.raw_message)+ else:+ if 'webhook_delivery' not in retained and 'webhook_route' not in retained:+ # A pre-destination receipt is still a receipt, not permission to infer+ # again. Do not retrofit today's destination into its queued execution.+ payload['native_text_v1'].pop('webhook_delivery')+ payload['native_text_v1'].pop('webhook_route')+ if 'provenance' not in retained:+ payload['native_text_v1'].pop('provenance', None)+ same = row['payload'] == payload+ if len(rows) != 1 or not same:raise RuntimeStoreError('admission_conflict')event._webhook_duplicate = Truereceipt = authority._receipt(row)diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex fff04aa7ec2..62e121c243f 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -27,7 +27,6 @@ from gateway.platforms.event import ProcessingOutcomefrom agent.i18n import tfrom gateway.relay.adapter_discord_interaction import RelayDiscordInteractionMixinfrom gateway.relay.descriptor import CapabilityDescriptor-from hermes_state_runtime import RuntimeStoreErrorfrom gateway.relay.egress import (EGRESS_DECLINE_CODE,decline_error,@@ -877,8 +876,9 @@ class RelayAdapter(RelayDiscordInteractionMixin, BasePlatformAdapter):# class default is False, so only an explicit descriptor bit turns it on.self.supports_inchannel_continuable = bool(getattr(descriptor, "supports_inchannel_continuable", False))- async def _on_inbound(self, event) -> None:- """Bridge a connector-delivered MessageEvent into the normal adapter path."""+ async def _on_inbound(self, event) -> Optional[asyncio.Task]:+ """Bridge a connector-delivered MessageEvent into the normal adapter path; a task when its+ admission runs off the reader (``admit_relay_delivery``) and the transport ACKs on its end."""# Inbound replay dedupe: the relay leg is at-least-once — on WS re-handshake# the connector replays its durable buffer, and a long turn straddling a# quiet socket drop got re-run (final answer 2-5x). Platform message identity@@ -908,33 +908,15 @@ class RelayAdapter(RelayDiscordInteractionMixin, BasePlatformAdapter):self._seen_inbound.pop(dedupe_key, None)raiseif native:- from datetime import datetime, timezone- from gateway.platforms.webhook_ingress import admit_producer+ from datetime import datetime+ from gateway.relay.inbound_admission import admit_relay_delivery# The connector does not transmit a provider timestamp. Local arrival# time must not change the fingerprint of a retried provider identity.event.timestamp = datetime.fromtimestamp(0, UTC)- # Wait only for the SQLite receipt, never inference or outbound ACKs- # (those need this same WS reader). A permanent refusal returns, so the- # transport ACKs it (a replay would be refused again: main's runner dropped- # it too); any other failure withholds the ACK so the connector redelivers.- try:- receipt = await admit_producer(self, event)- except RuntimeStoreError as exc:- if exc.reason not in _PERMANENT_REFUSALS:- raise- logger.warning("relay inbound refused (%s) for %s chat=%s; acknowledged, not replayed",- exc.reason, event.source.platform.value, event.source.chat_id)- return- if receipt 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)+ # Never wait for inference or outbound ACKs (those need this same WS reader).+ return await admit_relay_delivery(self, runner, event)+ await self.handle_message(event)+ return None_SEEN_INBOUND_MAX = 512diff --git a/gateway/relay/inbound_admission.py b/gateway/relay/inbound_admission.pynew file mode 100644index 00000000000..74468439490--- /dev/null+++ b/gateway/relay/inbound_admission.py@@ -0,0 +1,59 @@+"""Native admission of a connector-delivered relay message (``RelayAdapter._on_inbound``)."""+import asyncio+import logging++from hermes_state_runtime import RuntimeStoreError++logger = logging.getLogger("gateway.relay.adapter")+++async def admit_relay_delivery(adapter, runner, event):+ """Admit *event*; the transport ACKs the frame once this returns, or once the returned task does.++ Without producer hooks admission waits only for the SQLite receipt, on the socket reader. With+ one, ``pre_gateway_dispatch`` or ``post_gateway_admission`` plugin code runs before the commit and+ may await ``adapter.send()``, whose ``outbound_result`` only that reader delivers, or wait for+ another inbound message: the admission then runs in a task off the reader, after any earlier+ admission of the same chat, so one chat's deliveries still commit in arrival order."""+ from gateway.run_inbound_consumer import POST_ADMISSION_HOOK+ from hermes_cli.lifecycle import has_hook+ if not (has_hook('pre_gateway_dispatch') or has_hook(POST_ADMISSION_HOOK)):+ await _admit(adapter, runner, event)+ return None+ lanes = adapter.__dict__.setdefault('_admission_lanes', {})+ lane = (event.source.platform.value, event.source.chat_id)+ task = asyncio.create_task(_admit_after(lanes.get(lane), adapter, runner, event))+ lanes[lane] = task+ task.add_done_callback(lambda done: lanes.pop(lane) if lanes.get(lane) is done else None)+ adapter._background_tasks.add(task) # cancelled with the adapter's work on shutdown+ task.add_done_callback(adapter._background_tasks.discard)+ return task+++async def _admit_after(previous, adapter, runner, event):+ if previous is not None:+ await asyncio.wait([previous]) # its outcome is its own frame's ACK, not this one's+ await _admit(adapter, runner, event)+++async def _admit(adapter, runner, event):+ # A permanent refusal returns, so the transport ACKs it (a replay would be refused again: main's+ # runner dropped it too); any other failure withholds the ACK so the connector redelivers.+ from gateway.platforms.webhook_ingress import admit_producer+ from gateway.relay.adapter import _PERMANENT_REFUSALS+ try:+ receipt = await admit_producer(adapter, event)+ except RuntimeStoreError as exc:+ if exc.reason not in _PERMANENT_REFUSALS:+ raise+ logger.warning("relay inbound refused (%s) for %s chat=%s; acknowledged, not replayed",+ exc.reason, event.source.platform.value, event.source.chat_id)+ return+ if receipt 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(+ adapter, event, runner._session_key_for_source(event.source), event._consumer_reply))+ adapter._background_tasks.add(task)+ task.add_done_callback(adapter._background_tasks.discard)diff --git a/gateway/relay/transport.py b/gateway/relay/transport.pyindex 7c93179bbe7..1810017feb8 100644--- a/gateway/relay/transport.py+++ b/gateway/relay/transport.py@@ -9,13 +9,15 @@ until >=2 Class-1 platforms validate it. See website/docs/developer-guide/relay-from __future__ import annotations+import asynciofrom typing import Any, Awaitable, Callable, Dict, Optional, Protocol, runtime_checkablefrom gateway.platforms.event import MessageEventfrom gateway.relay.descriptor import CapabilityDescriptor-# Callback the transport invokes for each inbound normalized event.-InboundHandler = Callable[[MessageEvent], Awaitable[None]]+# Callback the transport invokes for each inbound normalized event: a task it returns is the+# event's admission still running off the reader, and the frame is ACKed when that task succeeds.+InboundHandler = Callable[[MessageEvent], Awaitable[Optional["asyncio.Task[None]"]]]# Callback for each forwarded passthrough request (§5.1): ``(forward, buffer_id)``.# ``forward`` is a ws_transport.PassthroughForward, typed Any here becausediff --git a/gateway/relay/ws_transport.py b/gateway/relay/ws_transport.pyindex 3410fb97fd2..445868522b3 100644--- a/gateway/relay/ws_transport.py+++ b/gateway/relay/ws_transport.py@@ -365,6 +365,7 @@ class WebSocketRelayTransport:self._ws: Any = Noneself._reader: Optional[asyncio.Task[None]] = Noneself._inbound: Optional[InboundHandler] = None+ self._inbound_acks: set[asyncio.Task[None]] = set() # ACKs of off-reader admissionsself._interrupt_inbound_handler: Any = Noneself._passthrough_handler: Any = None# `_descriptor` is the FIRST (primary-identity) descriptor; the map holds@@ -939,7 +940,7 @@ class WebSocketRelayTransport:event = _event_from_wire(frame.get("event", {}))try:with relay_callback(self, event):- await self._inbound(event)+ admitting = await self._inbound(event)except Exception:# A handler failure is not a socket failure: keep this reader, withhold the# ACK so the connector redelivers the buffered frame later.@@ -948,9 +949,25 @@ class WebSocketRelayTransport:# A replayed buffered delivery carries a bufferId; ack AFTER the handler# has taken it so the connector advances its cursor (no dup).buffer_id = frame.get("bufferId")- if buffer_id:+ if admitting is not None:+ # Admitted off this reader (plugin hooks may await a send only this reader answers).+ admitting.add_done_callback(lambda done: self._ack_admitted(done, buffer_id))+ elif buffer_id:await self._send_inbound_ack(str(buffer_id))+ def _ack_admitted(self, admission: asyncio.Task, buffer_id: Optional[str]) -> None:+ """ACK a frame once its off-reader admission committed (or was permanently refused); a+ cancelled or failed one stays unacknowledged, as above, so the connector redelivers it."""+ if admission.cancelled() or admission.exception() is not None:+ if not admission.cancelled():+ logger.error("relay: inbound handler failed; frame left unacknowledged",+ exc_info=admission.exception())+ return+ if buffer_id:+ ack = asyncio.create_task(self._send_inbound_ack(str(buffer_id)))+ self._inbound_acks.add(ack)+ ack.add_done_callback(self._inbound_acks.discard)+async def _on_going_idle_ack(self, frame: dict[str, Any]) -> None:if self._going_idle_ack is not None and not self._going_idle_ack.done():self._going_idle_ack.set_result(None)diff --git a/gateway/run_inbound_hooks.py b/gateway/run_inbound_hooks.pyindex 07ffb720407..a4b0e9c93c5 100644--- a/gateway/run_inbound_hooks.py+++ b/gateway/run_inbound_hooks.py@@ -65,7 +65,16 @@ class GatewayInboundHooksMixin:) -> 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."""+ ``allow``/None → normal dispatch. On the messaging path it runs BEFORE auth so plugins can handle+ unauthorized senders; on the producer path (webhook/relay, ``admit_producer``) it runs AFTER the+ delivery's authorization, which preparing its payload performs, so it never sees a refused sender.++ Once per inbound message, at ingress (here, or ``admit_producer`` for webhook/relay), never+ while an admitted row EXECUTES: a messaging turn already passed it before its commit, and a+ local CLI/TUI/Desktop turn never fired it on main, so a skip must not drop committed input."""+ from gateway.session_ingress import executing_admission+ if executing_admission.get():+ return eventtry:from hermes_cli.lifecycle import ainvoke_hook as _ainvoke_hook_hook_results = await _ainvoke_hook(diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex dc062223ebc..775b1fcffe8 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport asyncioimport contextlib+from contextvars import ContextVarfrom dataclasses import asdict, dataclass, fieldfrom functools import partialimport sqlite3@@ -28,6 +29,9 @@ from hermes_state_runtime import (_CLAIM_RETRY_MIN_S, _CLAIM_RETRY_MAX_S = 0.25, 5.0# Longest a settled turn's adapter may hold its adopted crash marker before the follower is claimed._MARKER_RELEASE_WAIT_S = 60.0+# True in the admitting task once ``admit_native``'s shielded ledger write began: a caller cancelled+# after that may still see the row commit, so it must not release the media the write commits.+native_write_started = ContextVar('native_write_started', default=False)@dataclass@@ -359,6 +363,8 @@ class SessionAuthority:from gateway.session_envelope import prepare_native, restore_native_sourceself._require_admission_open()payload = await prepare_native(self.runner, event)+ if fingerprint := getattr(event, '_ingress_sha256', None):+ payload['native_text_v1']['ingress_sha256'] = fingerprint # the delivery before a rewriteself._require_admission_open()source = restore_native_source(payload) # no re-hash of the just-captured media on the loopfrom gateway.session_runtime_workers import tracked_write@@ -371,12 +377,14 @@ class SessionAuthority:def admitted(row):committed[0] = SessionRef(self.profile_id, row.get('target_session_id') or ref.session_id)return self._admitted(committed[0], event, row)+ native_write_started.set(True) # shielded from here: a cancelled caller may still commitreturn await tracked_write(self, partial(self._admit_native_write, principal_id='messaging:' + identity, session_id=ref.session_id,- request_id=request_id, payload=payload, authorize=self._admission_gate()),+ request_id=request_id, payload=payload, authorize=self._admission_gate(),+ raw=getattr(event, 'raw_message', None)),then=admitted, ordered=True, after=lambda _receipt: self._schedule_admitted(committed[0]))- def _admit_native_write(self, *, principal_id, session_id, request_id, payload, authorize):+ def _admit_native_write(self, *, principal_id, session_id, request_id, payload, authorize, raw=None):# Off the loop and in admission order: the redelivery reconcile reads the ledger it decides# against, so a concurrent first delivery of the same message cannot slip between them.from gateway.session_ingress_media import drop_capture_lease, reconcile_native_retry, release_unheld_media@@ -384,7 +392,7 @@ class SessionAuthority:session_id = self._current_owner(session_id)try:payload = reconcile_native_retry(self.db, principal_id=principal_id, session_id=session_id,- request_id=request_id, payload=payload)+ request_id=request_id, payload=payload, raw=raw)return admit_session_input(self.db, epoch=self.epoch, principal_id=principal_id, session_id=session_id,request_id=request_id, payload=payload, _authorize_write=authorize)except Exception:diff --git a/gateway/session_ingress_media.py b/gateway/session_ingress_media.pyindex 4789c26eea9..ec67a50a7ab 100644--- a/gateway/session_ingress_media.py+++ b/gateway/session_ingress_media.py@@ -132,31 +132,57 @@ def admit_attachments(attachments, *, admitted=None):return {'attachments_v1': {'media': capture_native_media(paths), 'media_types': mimes}}-def reconcile_native_retry(db, *, principal_id, session_id, request_id, payload):+def ingress_fingerprint(payload, raw=None):+ """SHA-256 of a delivery as received: its prepared payload and the provider payload the hook also+ sees (``raw_message``: a webhook's parsed, route-script-transformed body; None on relay, whose+ wire fields are all in the payload). Transport headers (delivery id, signature, attempt counters,+ timestamps) never reach the hook and are not hashed. Media count by bytes: a redelivery+ re-captures them under a fresh staging name (``reconcile_native_retry``)."""+ envelope = {**payload['native_text_v1']}+ envelope.pop('ingress_sha256', None)+ if 'media' in envelope:+ envelope['media'] = [[media['sha256'], media['size']] for media in envelope['media']]+ received = {**payload, 'native_text_v1': envelope}+ if raw is not None:+ received = {'payload': received, 'raw_message': raw}+ canonical = json.dumps(received, sort_keys=True, separators=(',', ':'), default=repr)+ return hashlib.sha256(canonical.encode()).hexdigest()+++def reconcile_native_retry(db, *, principal_id, session_id, request_id, payload, raw=None):"""A redelivered native message (lost provider ACK, Relay buffer replay) re-downloads its mediaunder a fresh disposable staging name, so its captured path differs from the committed one.Retry identity is the committed bytes, not that name: when this exact identity already holdsthe same digests and sizes in the same order, the committed references stand in for the freshcapture (whose now-unowned copy is collected) and the admission digest decides the rest, so- changed bytes or any other changed field still conflict."""- fresh = payload.get('native_text_v1', {}).get('media')- if not fresh:- return payload+ changed bytes or any other changed field still conflict. A delivery committed in+ ``pre_gateway_dispatch``-rewritten form resolves to its committed payload when the resend matches+ the fingerprint recorded at ingress (``ingress_fingerprint``); a changed resend, or a row+ committed before fingerprints, is compared exactly as above."""+ fresh = payload.get('native_text_v1', {}).get('media') or []with db._read_ctx() as conn:row = conn.execute('SELECT status, payload_json FROM session_admissions WHERE principal_id=? AND ''target_session_id=? AND request_id=?', (principal_id, session_id, request_id)).fetchone()- committed = json.loads(row[1]).get('native_text_v1', {}).get('media') if row is not None else None- if not committed or [(r['sha256'], r['size']) for r in committed] != [(r['sha256'], r['size']) for r in fresh]:- return payload- if row[0] != 'terminal':+ retained = json.loads(row[1]) if row is not None else {}+ recorded = retained.get('native_text_v1', {}).get('ingress_sha256')+ if recorded is not None and recorded == ingress_fingerprint(payload, raw):+ resolved = retained+ else:+ committed = retained.get('native_text_v1', {}).get('media')+ if not fresh or not committed or [(r['sha256'], r['size']) for r in committed] != [+ (r['sha256'], r['size']) for r in fresh]:+ return payload+ resolved = {**payload, 'native_text_v1': {**payload['native_text_v1'], 'media': committed}}+ committed = resolved['native_text_v1'].get('media', [])+ if committed and row[0] != 'terminal':# A live row still executes these bytes, so they must verify (a terminal one is digest evidence).restore_native_media(committed)kept = {reference['path'] for reference in committed}unowned = [reference for reference in fresh if reference['path'] not in kept]- drop_capture_lease({reference['path'] for reference in unowned})- release_unheld_media(db, unowned, retain_history=False)- return {**payload, 'native_text_v1': {**payload['native_text_v1'], 'media': committed}}-+ if unowned:+ drop_capture_lease({reference['path'] for reference in unowned})+ release_unheld_media(db, unowned, retain_history=False)+ return resolveddef _attachment_hashes(paths):hashes = []diff --git a/tests/gateway/test_pre_gateway_dispatch.py b/tests/gateway/test_pre_gateway_dispatch.pyindex 74aa9cb130e..810f0740633 100644--- a/tests/gateway/test_pre_gateway_dispatch.py+++ b/tests/gateway/test_pre_gateway_dispatch.py@@ -198,6 +198,572 @@ async def test_rewritten_message_keeps_its_callback_provenance_and_is_admitted(massert (payload["text"], payload["native_text_v1"].get("provenance")) == ("rewritten", expected)+async def test_hook_fires_once_at_messaging_ingress_and_never_when_an_admission_executes(monkeypatch):+ """PLG-5: executing an admitted row (a local CLI/TUI/Desktop turn, or a messaging turn's first+ run or restart replay) re-enters ``_handle_message``. The hook already ran at ingress (main has+ no other firing point), so it must not run again there, and a "skip" never drops admitted input."""+ import gateway.session_authorities as authorities+ import gateway.session_ingress as ingress++ _clear_auth_env(monkeypatch)+ fired = []++ async def hook(name, **kwargs):+ if name != "pre_gateway_dispatch":+ return []+ fired.append(kwargs["event"].text)+ return [{"action": "skip"}] if kwargs["event"].text == "drop me" else []++ async def admit(_authority, event):+ admitted.append(event.text)+ return "admitted"++ admitted = []+ monkeypatch.setattr("hermes_cli.lifecycle.ainvoke_hook", hook)+ monkeypatch.setattr(authorities, "active_authority", lambda _runner: object())+ monkeypatch.setattr(ingress, "admit_message", admit)+ runner, adapter = _make_runner(Platform.WHATSAPP)+ runner._is_user_authorized_for_source = lambda _s: True+ runner._admit_bot_message_for_source = lambda _s: True+ runner._delivery_adapter_for = runner._intake_adapter_for = lambda _s: adapter+ runner._rescue_orphaned_overflow = lambda _k, _a: None+ runner._enqueue_fifo = MagicMock()+ runner._handle_message_with_agent = AsyncMock(return_value="agent-ok")+ runner._run_post_turn_hooks = AsyncMock()++ assert await runner._handle_message(_make_event("drop me")) is None+ assert await runner._handle_message(_make_event("keep me")) == "admitted"+ assert admitted == ["keep me"] and fired == ["drop me", "keep me"]++ token = ingress.executing_admission.set(True)+ try:+ assert await runner._handle_message(_make_event("drop me")) == "agent-ok"+ finally:+ ingress.executing_admission.reset(token)+ assert fired == ["drop me", "keep me"]+++async def test_webhook_delivery_fires_the_hook_once_at_ingress_before_commit():+ """PLG-5: on main the webhook adapter's ``handle_message`` fired the hook once per delivery,+ before anything ran. Receipt-only ingress (``admit_producer``) must keep that: a skip commits+ nothing, a rewrite is what gets committed and executed, the real drain's execution does not+ fire it again, 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 hermes_cli.plugins import get_plugin_manager+ from tests.gateway.fixtures.webhook_route_authority import mount_authority+ from tests.waiting import async_wait_until++ fired = []++ def hook(event, **_kwargs):+ fired.append(event.message_id)+ if "drop" in event.text:+ return {"action": "skip"}+ return {"action": "rewrite", "text": "rewritten"} if "rewrite" in event.text else None++ manager = get_plugin_manager()+ manager._discovered = True+ manager._hooks.setdefault("pre_gateway_dispatch", []).append(hook)+ adapter = WebhookAdapter(PlatformConfig(enabled=True, extra={"secret": "owned-secret", "routes": {+ "fixture": {"prompt": "{text}"}}}))+ adapter._deliver_to = AsyncMock()+ 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:+ runner = adapter._message_handler.__self__+ authority = runner.session_authority+ del authority._schedule # this test needs the real drain to execute the admitted row+ runner._handle_message_with_agent = AsyncMock(return_value="agent-ok")+ assert (await post(client, "drop this", "d-drop")).status == 202+ assert fired == ["d-drop"] and not authority.db._read_all("SELECT 1 FROM session_admissions")++ assert (await post(client, "keep this", "d-keep")).status == 202+ assert (await post(client, "please rewrite", "d-rewrite")).status == 202+ def settled():+ rows = authority.db._read_all("SELECT request_id, status, payload_json FROM session_admissions")+ return rows if len(rows) == 2 and all(row["status"] == "terminal" for row in rows) else None++ rows = await async_wait_until(settled, what="both admitted deliveries executed")+ assert sorted((row["request_id"], row["status"], json.loads(row["payload_json"])["text"]) for row in rows) == [+ ("d-keep", "terminal", "keep this"), ("d-rewrite", "terminal", "rewritten")]+ executed = sorted(call.args[0].text for call in runner._handle_message_with_agent.await_args_list)+ assert executed == ["keep this", "rewritten"]+ assert (await post(client, "keep this", "d-keep")).status in (200, 202)+ assert fired == ["d-drop", "d-keep", "d-rewrite"]+++def _rewriting_hook(fired):+ from hermes_cli.plugins import get_plugin_manager++ def hook(event, **_kwargs):+ fired.append(event.message_id)+ return {"action": "rewrite", "text": "rewritten"} if "rewrite" in event.text else None++ manager = get_plugin_manager()+ manager._discovered = True+ manager._hooks.setdefault("pre_gateway_dispatch", []).append(hook)+++def _webhook_app(prompt="{text}"):+ from aiohttp import web++ from gateway.platforms.webhook import WebhookAdapter+ from tests.gateway.fixtures.webhook_route_authority import mount_authority++ adapter = WebhookAdapter(PlatformConfig(enabled=True, extra={"secret": "owned-secret", "routes": {+ "fixture": {"prompt": prompt}}}))+ adapter._deliver_to = AsyncMock()+ app = web.Application()+ mount_authority(app, adapter)+ app.router.add_post("/webhooks/{route_name}", adapter._handle_webhook)+ return adapter, app+++async def _post_webhook(client, text, delivery_id):+ import hashlib+ import hmac+ import json++ body = json.dumps(text if isinstance(text, dict) else {"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 def test_a_resend_whose_raw_payload_changed_conflicts_even_when_its_prompt_did_not():+ """The hook sees the parsed provider payload (``raw_message``), not only the rendered prompt. A+ resend under the same delivery id whose prompt renders the same but whose raw field the hook+ rewrote from changed is refused: no duplicate receipt, no second hook call, no second row. The+ exact resend keeps its receipt, and so does a delivery rewritten to empty text."""+ import json++ from aiohttp.test_utils import TestClient, TestServer+ from hermes_cli.plugins import get_plugin_manager++ fired = []++ def hook(event, **_kwargs):+ fired.append(event.raw_message["detail"])+ return {"action": "rewrite", "text": event.raw_message["detail"].replace("blank", "")}++ manager = get_plugin_manager()+ manager._discovered = True+ manager._hooks.setdefault("pre_gateway_dispatch", []).append(hook)+ adapter, app = _webhook_app(prompt="{action}")+ async with TestClient(TestServer(app)) as client:+ authority = adapter._message_handler.__self__.session_authority+ for delivery_id, detail in (("d-1", "handle one"), ("d-2", "blank")):+ assert (await _post_webhook(client, {"action": "opened", "detail": detail}, delivery_id)).status == 202+ retry = await _post_webhook(client, {"action": "opened", "detail": detail}, delivery_id)+ assert (retry.status, (await retry.json())["status"]) == (200, "duplicate")+ changed = await _post_webhook(client, {"action": "opened", "detail": "handle two"}, "d-1")+ assert changed.status == 503+ rows = authority.db._read_all("SELECT request_id, payload_json FROM session_admissions")+ assert sorted((row["request_id"], json.loads(row["payload_json"])["text"]) for row in rows) == [+ ("d-1", "handle one"), ("d-2", "")]+ assert fired == ["handle one", "blank"]+++async def test_rewritten_webhook_delivery_retries_to_its_receipt_and_a_changed_one_is_refused():+ """The committed payload of a rewritten delivery differs from what the provider resends. An exact+ retry still gets the duplicate receipt (not 503 forever), without offering it to the hook again;+ a changed payload under the same delivery id is still refused."""+ import json++ from aiohttp.test_utils import TestClient, TestServer++ fired = []+ _rewriting_hook(fired)+ adapter, app = _webhook_app()+ async with TestClient(TestServer(app)) as client:+ authority = adapter._message_handler.__self__.session_authority+ assert (await _post_webhook(client, "please rewrite", "d-1")).status == 202+ retry = await _post_webhook(client, "please rewrite", "d-1")+ assert (retry.status, (await retry.json())["status"]) == (200, "duplicate")+ assert (await _post_webhook(client, "please rewrite it twice", "d-1")).status == 503+ rows = authority.db._read_all("SELECT payload_json FROM session_admissions")+ assert [json.loads(row["payload_json"])["text"] for row in rows] == ["rewritten"]+ assert fired == ["d-1"]+++async def test_a_webhook_row_committed_before_the_fingerprint_retries_exactly_and_runs_without_the_hook():+ """Upgrade: a row committed before ingress fingerprints (every main-era row: the original payload,+ no hook at ingress) keeps exact retry comparison, and when it executes after the upgrade the hook+ does not fire: the committed text runs as admitted."""+ import json++ from aiohttp.test_utils import TestClient, TestServer++ from gateway.session_contract import SessionRef+ from tests.waiting import async_wait_until++ fired = []+ adapter, app = _webhook_app()+ async with TestClient(TestServer(app)) as client:+ runner = adapter._message_handler.__self__+ authority = runner.session_authority+ runner._handle_message_with_agent = AsyncMock(return_value="agent-ok")+ assert (await _post_webhook(client, "please rewrite", "d-old")).status == 202+ _rewriting_hook(fired) # the plugin arrives with the upgrade+ retry = await _post_webhook(client, "please rewrite", "d-old")+ assert (retry.status, (await retry.json())["status"]) == (200, "duplicate")+ assert (await _post_webhook(client, "please rewrite it twice", "d-old")).status == 503+ [row] = authority.db._read_all("SELECT target_session_id, payload_json FROM session_admissions")+ assert "ingress_sha256" not in json.loads(row["payload_json"])["native_text_v1"]++ del authority._schedule # the queued row now runs on the real drain+ authority._schedule(SessionRef(authority.profile_id, row["target_session_id"]))+ await async_wait_until(lambda: authority.db._read_all("SELECT 1 FROM session_admissions WHERE status='terminal'"),+ what="the queued row executed")+ executed = [call.args[0].text for call in runner._handle_message_with_agent.await_args_list]+ assert executed == ["please rewrite"]+ assert fired == []+++async def test_relay_resend_of_a_rewritten_delivery_resolves_its_admission(tmp_path, monkeypatch):+ """A relay re-send of a rewritten delivery resolves the existing admission (same receipt, no second+ hook call, one row) instead of being acknowledged as a permanent ``admission_conflict``."""+ import asyncio+ import json++ websockets = pytest.importorskip("websockets")+ import gateway.platforms.webhook_ingress as ingress+ from gateway.relay.adapter import RelayAdapter+ from gateway.relay.descriptor import CapabilityDescriptor+ from gateway.relay.ws_transport import WebSocketRelayTransport+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.session_results import execution_result+ from tests.waiting import async_wait_until++ outgoing, ready, turns, outcomes, fired = [], asyncio.Queue(), [], [], []+ descriptor = CapabilityDescriptor(1, "telegram", "Fixture", 4096, False, True, False, "plain", "chars")++ async def connector(ws):+ await ws.recv() # hello+ await ws.send(json.dumps({"type": "descriptor", "descriptor": json.loads(descriptor.to_json())}) + "\n")+ await ready.put(ws)+ async for line in ws:+ frame = json.loads(line)+ outgoing.append(frame)+ if frame["type"] == "outbound":+ await ws.send(json.dumps({"type": "outbound_result", "requestId": frame["requestId"],+ "result": {"success": True, "message_id": "sent"}}) + "\n")++ async def turn(event, *_args, **_kwargs):+ turns.append(event.text)+ execution_result.get()["result"] = {"final_response": "ok", "messages": []}+ return "ok"++ admit = ingress.admit_producer++ async def observed(adapter, event):+ try:+ receipt = await admit(adapter, event)+ except Exception as exc:+ outcomes.append(getattr(exc, "reason", repr(exc)))+ raise+ outcomes.append(receipt.admission_id)+ return receipt++ monkeypatch.setattr(ingress, "admit_producer", observed)+ _rewriting_hook(fired)+ async with websockets.serve(connector, "127.0.0.1", 0) as relay:+ transport = WebSocketRelayTransport(+ f"ws://127.0.0.1:{relay.sockets[0].getsockname()[1]}/relay", "telegram", "fixture-bot",+ gateway_id="fixture-gateway", upgrade_secret="fixture-secret", reconnect=True, reconnect_backoff_s=.05)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ monkeypatch.setattr(runner, "_handle_message_with_agent", turn)+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="relay-retry")+ adapter = RelayAdapter(PlatformConfig(enabled=True), descriptor, transport)+ adapter.gateway_runner = runner+ runner.adapters[Platform.RELAY] = adapter+ runner._wire_adapter_handlers(adapter)+ try:+ assert await adapter.connect()+ ws = await asyncio.wait_for(ready.get(), 5)+ event = {"text": "please rewrite", "message_id": "r1",+ "source": {"platform": "telegram", "chat_id": "relay-chat", "chat_type": "dm",+ "user_id": "relay-user"}}+ acked = lambda: {f.get("bufferId") for f in outgoing if f.get("type") == "inbound_ack"}+ for buffer_id in ("buf-1", "buf-2"): # the connector re-sends after a lost ACK+ await ws.send(json.dumps({"type": "inbound", "event": event, "bufferId": buffer_id}) + "\n")+ await async_wait_until(lambda: buffer_id in acked() and turns, timeout=20,+ what=f"{buffer_id} acknowledged after the turn ran")+ rows = authority.db._read_all("SELECT admission_id, payload_json FROM session_admissions")+ finally:+ await adapter.disconnect()+ authority.db.close()+ assert [json.loads(row["payload_json"])["text"] for row in rows] == ["rewritten"]+ assert outcomes == [rows[0]["admission_id"]] * 2+ assert (turns, fired) == (["rewritten"], ["r1"])+++async def test_relay_resend_of_a_rewritten_media_delivery_reuses_its_admission_and_changed_bytes_conflict(+ tmp_path, monkeypatch):+ """A rewritten relay delivery with media, still queued: an exact re-send (same bytes, re-downloaded+ under a fresh staging name) resolves to the original admission and releases its freshly retained+ copy; a re-send whose bytes changed conflicts and retains nothing."""+ import asyncio+ import json+ import threading+ from http.server import ThreadingHTTPServer+ from pathlib import Path++ websockets = pytest.importorskip("websockets")+ import gateway.platforms.webhook_ingress as ingress+ from gateway.relay.adapter import RelayAdapter+ from gateway.relay.descriptor import CapabilityDescriptor+ from gateway.relay.media import RelayMediaClient+ from gateway.relay.ws_transport import WebSocketRelayTransport+ from gateway.run import GatewayRunner+ from gateway.session_authority import SessionAuthority, initialize_session_authority+ from gateway.session_ingress_media import _media_root+ from tests.gateway.test_native_media_redelivery import PNG, _Media+ from tests.waiting import async_wait_until++ outgoing, ready, outcomes, fired = [], asyncio.Queue(), [], []+ descriptor = CapabilityDescriptor(1, "telegram", "Fixture", 4096, False, True, False, "plain", "chars")+ monkeypatch.setattr(SessionAuthority, "_schedule", lambda self, ref: None) # the row stays queued, bytes held+ media = ThreadingHTTPServer(("127.0.0.1", 0), _Media)+ threading.Thread(target=media.serve_forever, daemon=True).start()+ url = f"http://127.0.0.1:{media.server_port}/photo.png"++ async def connector(ws):+ await ws.recv() # hello+ await ws.send(json.dumps({"type": "descriptor", "descriptor": json.loads(descriptor.to_json())}) + "\n")+ await ready.put(ws)+ async for line in ws:+ frame = json.loads(line)+ outgoing.append(frame)+ if frame["type"] == "outbound":+ await ws.send(json.dumps({"type": "outbound_result", "requestId": frame["requestId"],+ "result": {"success": True, "message_id": "sent"}}) + "\n")++ admit = ingress.admit_producer++ async def observed(adapter, event):+ try:+ receipt = await admit(adapter, event)+ except Exception as exc:+ outcomes.append(getattr(exc, "reason", repr(exc)))+ raise+ outcomes.append(receipt.admission_id)+ return receipt++ monkeypatch.setattr(ingress, "admit_producer", observed)+ _rewriting_hook(fired)+ retained = lambda: sorted(_media_root().rglob("*.png"))+ async with websockets.serve(connector, "127.0.0.1", 0) as relay:+ transport = WebSocketRelayTransport(+ f"ws://127.0.0.1:{relay.sockets[0].getsockname()[1]}/relay", "telegram", "fixture-bot",+ gateway_id="fixture-gateway", upgrade_secret="fixture-secret", reconnect=True, reconnect_backoff_s=.05)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="relay-media")+ adapter = RelayAdapter(PlatformConfig(enabled=True), descriptor, transport)+ adapter._media_client = RelayMediaClient(f"http://127.0.0.1:{media.server_port}", None, None)+ adapter.gateway_runner = runner+ runner.adapters[Platform.RELAY] = adapter+ runner._wire_adapter_handlers(adapter)+ acked = lambda: {f.get("bufferId") for f in outgoing if f.get("type") == "inbound_ack"}+ try:+ assert await adapter.connect()+ ws = await asyncio.wait_for(ready.get(), 5)+ event = {"text": "please rewrite", "message_id": "r1", "message_type": "photo",+ "media_urls": [url], "media": [{"url": url, "mime": "image/png"}],+ "source": {"platform": "telegram", "chat_id": "relay-chat", "chat_type": "dm",+ "user_id": "relay-user"}}+ for buffer_id in ("buf-1", "buf-2"): # the connector re-sends after a lost ACK+ await ws.send(json.dumps({"type": "inbound", "event": event, "bufferId": buffer_id}) + "\n")+ await async_wait_until(lambda: buffer_id in acked() and len(outcomes) == int(buffer_id[-1]),+ timeout=20, what=f"{buffer_id} acknowledged")+ kept = retained()+ _Media.body = PNG + b"changed"+ await ws.send(json.dumps({"type": "inbound", "event": event, "bufferId": "buf-3"}) + "\n")+ await async_wait_until(lambda: "buf-3" in acked(), timeout=20, what="the changed re-send acknowledged")+ after_conflict = retained()+ rows = authority.db._read_all("SELECT admission_id, payload_json FROM session_admissions")+ finally:+ _Media.body = PNG+ media.shutdown()+ media.server_close()+ await adapter.disconnect()+ authority.db.close()+ [row] = rows+ committed = json.loads(row["payload_json"])+ assert committed["text"] == "rewritten" and len(committed["native_text_v1"]["media"]) == 1+ assert outcomes == [row["admission_id"]] * 2 + ["admission_conflict"]+ assert kept == after_conflict == [Path(committed["native_text_v1"]["media"][0]["path"])], (+ "a re-send's fresh copy must be released, the original's kept")+ assert fired == ["r1"]+++async def test_an_identical_webhook_delivery_waits_for_the_running_hook_and_gets_its_receipt(monkeypatch):+ """Overlapping identical deliveries (a provider retry while the first request is still in the hook)+ are coordinated by delivery identity: the second waits, rechecks the ledger, and resolves to the+ committed receipt, so the hook and its external actions run once and one row is committed."""+ import asyncio+ import json++ from aiohttp.test_utils import TestClient, TestServer++ import gateway.platforms.webhook_ingress as ingress+ from hermes_cli.plugins import get_plugin_manager+ from tests.waiting import async_wait_until++ fired, release, entered = [], asyncio.Event(), []++ async def hook(event, **_kwargs):+ fired.append(event.message_id)+ await release.wait()+ return {"action": "rewrite", "text": "rewritten"}++ manager = get_plugin_manager()+ manager._discovered = True+ manager._hooks.setdefault("pre_gateway_dispatch", []).append(hook)+ admit = ingress.admit_producer++ async def observed(adapter, event):+ entered.append(event.message_id)+ return await admit(adapter, event)++ monkeypatch.setattr(ingress, "admit_producer", observed)+ adapter, app = _webhook_app()+ async with TestClient(TestServer(app)) as client:+ authority = adapter._message_handler.__self__.session_authority+ first = asyncio.create_task(_post_webhook(client, "please rewrite", "d-1"))+ await async_wait_until(lambda: fired, what="the first delivery in the hook")+ second = asyncio.create_task(_post_webhook(client, "please rewrite", "d-1"))+ parked = lambda: any(waiting > 1 for _lock, waiting in getattr(ingress, "_deliveries", {}).values())+ await async_wait_until(lambda: len(entered) == 2 and (len(fired) > 1 or parked()),+ what="the identical delivery parked or in the hook")+ release.set()+ first, second = await asyncio.gather(first, second)+ assert first.status == 202+ assert (second.status, (await second.json())["status"]) == (200, "duplicate")+ rows = authority.db._read_all("SELECT payload_json FROM session_admissions")+ assert [json.loads(row["payload_json"])["text"] for row in rows] == ["rewritten"]+ assert fired == ["d-1"]++[email protected]("hook_name, verdict, outcome", [+ ("pre_gateway_dispatch", {"action": "skip"}, None),+ ("post_gateway_admission", {"action": "handled"}, None),+ ("pre_gateway_dispatch", {"action": "rewrite", "text": "/status"}, "invalid_params"),+ ("pre_gateway_dispatch", "drain", "runtime_draining"),+])+async def test_a_relay_media_delivery_no_admission_owns_retains_no_bytes(+ tmp_path, monkeypatch, hook_name, verdict, outcome):+ """Preparing a producer delivery copies its media into the retained store before the hooks run. A+ delivery a plugin skips or consumes, or whose admission is refused after the hook (a command-shaped+ rewrite, a drain that began during the hook), is never admitted: that copy is released."""+ import asyncio+ import json+ import threading+ from http.server import ThreadingHTTPServer++ websockets = pytest.importorskip("websockets")+ import gateway.platforms.webhook_ingress as ingress+ from gateway.relay.adapter import RelayAdapter+ from gateway.relay.descriptor import CapabilityDescriptor+ from gateway.relay.media import RelayMediaClient+ from gateway.relay.ws_transport import WebSocketRelayTransport+ from gateway.run import GatewayRunner+ from gateway.session_authority import initialize_session_authority+ from gateway.session_ingress_media import _media_root+ from hermes_cli.plugins import get_plugin_manager+ from tests.gateway.test_native_media_redelivery import _Media+ from tests.waiting import async_wait_until++ outgoing, ready, fired, outcomes = [], asyncio.Queue(), [], []+ descriptor = CapabilityDescriptor(1, "telegram", "Fixture", 4096, False, True, False, "plain", "chars")+ media = ThreadingHTTPServer(("127.0.0.1", 0), _Media)+ threading.Thread(target=media.serve_forever, daemon=True).start()+ url = f"http://127.0.0.1:{media.server_port}/photo.png"++ def hook(**kwargs):+ fired.append(hook_name)+ if verdict == "drain":+ runner._draining = True # the owner began draining while the hook ran+ return None+ return verdict++ manager = get_plugin_manager()+ manager._discovered = True+ manager._hooks.setdefault(hook_name, []).append(hook)+ admit = ingress.admit_producer++ async def observed(adapter, event):+ try:+ outcomes.append(await admit(adapter, event))+ except Exception as exc:+ outcomes.append(getattr(exc, "reason", repr(exc)))+ raise++ monkeypatch.setattr(ingress, "admit_producer", observed)++ async def connector(ws):+ await ws.recv() # hello+ await ws.send(json.dumps({"type": "descriptor", "descriptor": json.loads(descriptor.to_json())}) + "\n")+ await ready.put(ws)+ async for line in ws:+ outgoing.append(json.loads(line))++ async with websockets.serve(connector, "127.0.0.1", 0) as relay:+ transport = WebSocketRelayTransport(+ f"ws://127.0.0.1:{relay.sockets[0].getsockname()[1]}/relay", "telegram", "fixture-bot",+ gateway_id="fixture-gateway", upgrade_secret="fixture-secret", reconnect=True, reconnect_backoff_s=.05)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="relay-skip")+ adapter = RelayAdapter(PlatformConfig(enabled=True), descriptor, transport)+ adapter._media_client = RelayMediaClient(f"http://127.0.0.1:{media.server_port}", None, None)+ adapter.gateway_runner = runner+ runner.adapters[Platform.RELAY] = adapter+ runner._wire_adapter_handlers(adapter)+ try:+ assert await adapter.connect()+ ws = await asyncio.wait_for(ready.get(), 5)+ event = {"text": "look", "message_id": "r1", "message_type": "photo",+ "media_urls": [url], "media": [{"url": url, "mime": "image/png"}],+ "source": {"platform": "telegram", "chat_id": "relay-chat", "chat_type": "dm",+ "user_id": "relay-user"}}+ await ws.send(json.dumps({"type": "inbound", "event": event, "bufferId": "buf-1"}) + "\n")+ await async_wait_until(lambda: outcomes, timeout=20, what="the delivery decided")+ rows = authority.db._read_all("SELECT 1 FROM session_admissions")+ finally:+ runner._draining = False+ media.shutdown()+ media.server_close()+ await adapter.disconnect()+ authority.db.close()+ assert (fired, outcomes, rows) == ([hook_name], [outcome], [])+ assert not list(_media_root().rglob("*.png")), "a delivery no admission owns left its retained copy"++def test_relay_binding_moves_to_a_text_rewrite_but_never_to_a_new_source():"""The relay binding gets the same treatment as the native one, under the same guard: it followsa text-only rewrite, and is never carried to an event whose source object was swapped."""diff --git a/tests/gateway/test_pre_gateway_dispatch_relay_reader.py b/tests/gateway/test_pre_gateway_dispatch_relay_reader.pynew file mode 100644index 00000000000..1906baf0bae--- /dev/null+++ b/tests/gateway/test_pre_gateway_dispatch_relay_reader.py@@ -0,0 +1,216 @@+"""``pre_gateway_dispatch`` on relay deliveries runs at admission, before the commit, but never on the+relay socket reader: a hook may await ``adapter.send()``, whose ``outbound_result`` only that reader+delivers, or wait for another inbound message. A cancelled admission releases the media its+preparation copied unless the admission write already began (that write may still commit)."""+import asyncio+import json+import threading+from contextlib import asynccontextmanager+from http.server import ThreadingHTTPServer+from pathlib import Path++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+++def _hook(callback):+ from hermes_cli.plugins import get_plugin_manager++ manager = get_plugin_manager()+ manager._discovered = True+ manager._hooks.setdefault("pre_gateway_dispatch", []).append(callback)+++def _inbound(message_id, chat_id="relay-chat", **fields):+ return {"text": "hello", "message_id": message_id, **fields,+ "source": {"platform": "telegram", "chat_id": chat_id, "chat_type": "dm", "user_id": "relay-user"}}+++@asynccontextmanager+async def _relay(tmp_path, monkeypatch, media=None):+ """A real relay adapter, transport and reader against a fixture connector that answers every+ outbound frame. Yields ``(adapter, ws, outgoing, authority, admissions)``: ``admissions`` are the+ tasks ``admit_producer`` ran in."""+ websockets = pytest.importorskip("websockets")+ import gateway.platforms.webhook_ingress as ingress+ from gateway.relay.adapter import RelayAdapter+ from gateway.relay.descriptor import CapabilityDescriptor+ from gateway.relay.media import RelayMediaClient+ from gateway.relay.ws_transport import WebSocketRelayTransport+ from gateway.run import GatewayRunner+ from gateway.session_authority import SessionAuthority, initialize_session_authority++ monkeypatch.setattr(SessionAuthority, "_schedule", lambda self, ref: None) # rows stay queued+ outgoing, ready, admissions = [], asyncio.Queue(), []+ descriptor = CapabilityDescriptor(1, "telegram", "Fixture", 4096, False, True, False, "plain", "chars")+ admit = ingress.admit_producer++ async def observed(adapter, event):+ admissions.append(asyncio.current_task())+ return await admit(adapter, event)++ monkeypatch.setattr(ingress, "admit_producer", observed)++ async def connector(ws):+ await ws.recv() # hello+ await ws.send(json.dumps({"type": "descriptor", "descriptor": json.loads(descriptor.to_json())}) + "\n")+ await ready.put(ws)+ async for line in ws:+ frame = json.loads(line)+ outgoing.append(frame)+ if frame["type"] == "outbound":+ await ws.send(json.dumps({"type": "outbound_result", "requestId": frame["requestId"],+ "result": {"success": True, "message_id": "sent"}}) + "\n")++ async with websockets.serve(connector, "127.0.0.1", 0) as relay:+ # A short outbound timeout bounds a send the reader cannot answer.+ transport = WebSocketRelayTransport(+ f"ws://127.0.0.1:{relay.sockets[0].getsockname()[1]}/relay", "telegram", "fixture-bot",+ gateway_id="fixture-gateway", upgrade_secret="fixture-secret", reconnect=True,+ reconnect_backoff_s=.05, outbound_timeout_s=3)+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="relay-reader")+ adapter = RelayAdapter(PlatformConfig(enabled=True), descriptor, transport)+ if media is not None:+ adapter._media_client = RelayMediaClient(f"http://127.0.0.1:{media.server_port}", None, None)+ adapter.gateway_runner = runner+ runner.adapters[Platform.RELAY] = adapter+ runner._wire_adapter_handlers(adapter)+ try:+ assert await adapter.connect()+ yield adapter, await asyncio.wait_for(ready.get(), 5), outgoing, authority, admissions+ finally:+ await adapter.disconnect()+ authority.db.close()+++@asynccontextmanager+async def _media_server():+ from tests.gateway.test_native_media_redelivery import _Media++ media = ThreadingHTTPServer(("127.0.0.1", 0), _Media)+ threading.Thread(target=media.serve_forever, daemon=True).start()+ try:+ yield media, f"http://127.0.0.1:{media.server_port}/photo.png"+ finally:+ media.shutdown()+ media.server_close()+++def _acked(outgoing):+ return [frame["bufferId"] for frame in outgoing if frame.get("type") == "inbound_ack"]+++async def test_a_hook_that_sends_a_reply_gets_its_outbound_result_and_the_ack_follows_the_commit(+ tmp_path, monkeypatch):+ from tests.waiting import async_wait_until++ sent = []++ async def hook(event, gateway, **_kwargs):+ sent.append(await gateway.adapters[Platform.RELAY].send(event.source.chat_id, "one moment"))++ _hook(hook)+ async with _relay(tmp_path, monkeypatch) as (_adapter, ws, outgoing, authority, _admissions):+ await ws.send(json.dumps({"type": "inbound", "event": _inbound("r1"), "bufferId": "buf-1"}) + "\n")+ await async_wait_until(lambda: _acked(outgoing), timeout=20, what="buf-1 acknowledged")+ rows = authority.db._read_all("SELECT request_id FROM session_admissions")+ assert [result.success for result in sent] == [True], "the hook's send never got its outbound_result"+ assert [row["request_id"] for row in rows] == ["r1"]+ kinds = [frame["type"] for frame in outgoing]+ assert kinds.index("outbound") < kinds.index("inbound_ack")+++async def test_a_hook_waiting_for_another_chat_does_not_block_it_and_one_chat_still_admits_in_order(+ tmp_path, monkeypatch):+ """The hook for chat A's first message waits for chat B's message: B's hook runs meanwhile, A's+ second message waits for A's first, and A's rows commit in arrival order."""+ from tests.waiting import async_wait_until++ fired, b_arrived = [], asyncio.Event()++ async def hook(event, **_kwargs):+ fired.append(event.message_id)+ if event.message_id == "a1":+ await b_arrived.wait()+ if event.message_id == "b1":+ b_arrived.set()++ _hook(hook)+ async with _relay(tmp_path, monkeypatch) as (_adapter, ws, outgoing, authority, _admissions):+ for buffer_id, message_id, chat_id in (("buf-1", "a1", "chat-a"), ("buf-2", "a2", "chat-a"),+ ("buf-3", "b1", "chat-b")):+ event = _inbound(message_id, chat_id)+ await ws.send(json.dumps({"type": "inbound", "event": event, "bufferId": buffer_id}) + "\n")+ await async_wait_until(lambda: len(_acked(outgoing)) == 3, timeout=20, what="all three acknowledged")+ rows = authority.db._read_all("SELECT request_id FROM session_admissions ORDER BY rowid")+ assert fired == ["a1", "b1", "a2"]+ assert [row["request_id"] for row in rows if row["request_id"].startswith("a")] == ["a1", "a2"]+++async def test_an_admission_cancelled_while_the_hook_waits_releases_its_prepared_media(tmp_path, monkeypatch):+ """A relay disconnect or shutdown cancels the admission while the hook waits: no admission owns+ the copy preparing it made, so it is released, and the cancellation still propagates."""+ from gateway.session_ingress_media import _media_root+ from tests.waiting import async_wait_until++ entered = asyncio.Event()++ async def hook(**_kwargs):+ entered.set()+ await asyncio.Event().wait() # never answers++ _hook(hook)+ async with _media_server() as (media, url), _relay(tmp_path, monkeypatch, media) as (+ _adapter, ws, outgoing, authority, admissions):+ event = _inbound("r1", message_type="photo", media_urls=[url], media=[{"url": url, "mime": "image/png"}])+ await ws.send(json.dumps({"type": "inbound", "event": event, "bufferId": "buf-1"}) + "\n")+ await asyncio.wait_for(entered.wait(), 20)+ copied = sorted(_media_root().rglob("*.png"))+ [admission] = admissions+ admission.cancel()+ await asyncio.wait([admission])+ await async_wait_until(lambda: not list(_media_root().rglob("*.png")), timeout=10,+ what="the prepared copy released")+ rows = authority.db._read_all("SELECT 1 FROM session_admissions")+ assert copied and admission.cancelled()+ assert (rows, _acked(outgoing)) == ([], [])+++async def test_an_admission_cancelled_after_its_write_began_keeps_the_media_the_write_commits(+ tmp_path, monkeypatch):+ """Cancelled once the shielded admission write is running, the write still commits: the bytes it+ commits stay on disk."""+ from gateway.session_authority import SessionAuthority+ from tests.waiting import async_wait_until++ writing, proceed = threading.Event(), threading.Event()+ write = SessionAuthority._admit_native_write++ def held_write(self, **kwargs):+ writing.set()+ proceed.wait(20)+ return write(self, **kwargs)++ monkeypatch.setattr(SessionAuthority, "_admit_native_write", held_write)+ _hook(lambda **_kwargs: None)+ async with _media_server() as (media, url), _relay(tmp_path, monkeypatch, media) as (+ _adapter, ws, outgoing, authority, admissions):+ event = _inbound("r1", message_type="photo", media_urls=[url], media=[{"url": url, "mime": "image/png"}])+ await ws.send(json.dumps({"type": "inbound", "event": event, "bufferId": "buf-1"}) + "\n")+ assert await asyncio.to_thread(writing.wait, 20), "the admission write never began"+ [admission] = admissions+ admission.cancel()+ await asyncio.wait([admission])+ proceed.set()+ rows = await async_wait_until(+ lambda: authority.db._read_all("SELECT payload_json FROM session_admissions"), timeout=20,+ what="the shielded write committed")+ [reference] = json.loads(rows[0]["payload_json"])["native_text_v1"]["media"]+ assert admission.cancelled() and _acked(outgoing) == []+ assert Path(reference["path"]).is_file(), "a cancellation deleted media its admission committed"diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.mdindex 124926c6a44..317be17ed0d 100644--- a/website/docs/user-guide/features/hooks.md+++ b/website/docs/user-guide/features/hooks.md@@ -475,7 +475,7 @@ Payload fields below are the exact event-specific fields supplied by each call s| `on_skill_lifecycle` | Observer | After an authoritative skill-usage state change; return ignored. | `action`, `skill_name`, `provenance`, `task_id`, `session_id`, `use_count`, `reused`, `reuse_after_patch` | Exposes the local skill name and provenance. || `subagent_start` | Observer | Child constructed and about to run; return ignored. | `parent_session_id`, `parent_turn_id`, `parent_subagent_id`, `child_session_id`, `child_subagent_id`, `child_role`, `child_goal` | Child goal may contain user/project content. || `subagent_stop` | Observer | Child exit; return ignored. | `parent_session_id`, `parent_turn_id`, `child_session_id`, `child_role`, `child_summary`, `child_status`, `tool_call_history`, `duration_ms` | Summary and redacted tool-history metadata may reveal project structure. |-| `pre_gateway_dispatch` | Directive/control | Incoming non-internal message before auth/pairing/dispatch; first valid `skip`, `rewrite`, or `allow` controls flow. | `event`, `gateway`, `session_store` | Extremely privileged in-process objects expose inbound user/routing data and host handles. |+| `pre_gateway_dispatch` | Directive/control | Once per incoming non-internal message, at ingress: platform-adapter messages before auth/pairing/dispatch; webhook and relay deliveries after their authorization, before the admission commits; never for local CLI/TUI/Desktop or API turns, a retry of a committed delivery, or a queued admission when it executes. First valid `skip`, `rewrite`, or `allow` controls flow. | `event`, `gateway`, `session_store` | Extremely privileged in-process objects expose inbound user/routing data and host handles. || `post_gateway_admission` | Directive/control (fail-open) | Admitted non-internal message after auth, pause/drain, pending-reply, running-session and slash-command lanes, inside the claimed session slot and the routed profile's scope; first `handled` result skips the agent turn, anything else (including a raise or timeout) runs it. | `session_key`, `platform`, `source` (dict snapshot), `message_id`, `text` | Inbound text is untrusted user data; no runner or session-store handles are passed. || `gateway_platform_event` | Observer | After the gateway's profile-scoped authorization succeeds, when a supported platform-native event is normalized at the gateway boundary (Telegram: reactions, message edits; Discord: message edits/deletes, thread created/renamed); return ignored. | `platform`, `event_type`, `payload` (event-type-specific dict — see the per-event contracts below) | Normalized plain-dict envelope only; raw SDK objects, adapter handles, and bot clients are never exposed. || `pre_command` | Observer | Recognized slash command about to be dispatched, before the handler runs, on CLI and gateway cold-path dispatch; return ignored in v1 (directive-shaped dicts are logged at debug). Gateway running-agent intercept commands (`/stop`, `/approve` during an active run) are deliberately excluded — control-plane escape hatches must stay outside plugin reach. | `surface` (`"cli"` \| `"gateway"`), `command` (canonical name), `alias_used`, `args_raw`, `session_key`, `platform` | `args_raw` may contain user content or secrets typed after the command. |@@ -1234,7 +1234,7 @@ With heavy delegation (e.g. orchestrator roles × 5 leaves × nested depth), `su### `pre_gateway_dispatch`-Fires **once per incoming `MessageEvent`** in the gateway, after the internal-event guard but **before** auth/pairing and agent dispatch. This is the interception point for gateway-level message-flow policies (listen-only windows, human handover, per-chat routing, etc.) that don't fit cleanly into any single platform adapter.+Fires **once per incoming `MessageEvent`** in the gateway, at ingress, after the internal-event guard and before the message is admitted or dispatched. Where it runs relative to authorization depends on how the message arrived (see **Fires** below). This is the interception point for gateway-level message-flow policies (listen-only windows, human handover, per-chat routing, etc.) that don't fit cleanly into any single platform adapter.**Callback signature:**@@ -1248,7 +1248,14 @@ def my_callback(event, gateway, session_store, **kwargs):| `gateway` | `GatewayRunner` | The active gateway runner, so plugins can call `gateway.adapters[platform].send(...)` for side-channel replies (owner notifications, etc.). || `session_store` | `SessionStore` | For silent transcript ingestion via `session_store.append_to_transcript(...)`. |-**Fires:** In `gateway/run.py`, inside `GatewayRunner._handle_message()`, immediately after `is_internal` is computed. **Internal events skip the hook entirely** (they are system-generated — background-process completions, etc. — and must not be gate-kept by user-facing policy).+**Fires:** **Internal events skip the hook entirely** (they are system-generated — background-process completions, etc. — and must not be gate-kept by user-facing policy). Otherwise:++| Path | When the hook runs |+|------|--------------------|+| Platform adapters (Telegram, Discord, Slack, …) and relay slash commands | In `GatewayRunner._handle_message()` (`_hm_admit_event` in `gateway/run_inbound.py`), **before** auth/pairing, so a plugin can handle unauthorized senders. |+| Webhook deliveries and relay messages | In `admit_producer` (`gateway/platforms/webhook_ingress.py`), **after** the delivery's authorization and **before** its admission commits: a refused sender never reaches the hook, a skipped delivery is never admitted, and a rewrite is what gets admitted. A provider retry or relay re-send of a delivery that was already admitted resolves to that admission without calling the hook again. On the relay, admission with a registered hook runs off the relay socket reader, so a callback may await `gateway.adapters[...].send(...)`; one chat's messages still wait for each other, in arrival order. |+| Local CLI, TUI, Desktop and API-server turns | Never. |+| A queued admission when it executes (first run or restart replay) | Never: the message already passed the hook at ingress, so a `skip` can't drop admitted input. |**Return value:** `None` or a dict. The first recognized action dict wins; remaining plugin results are ignored. Exceptions in plugin callbacks are caught and logged; the gateway always falls through to normal dispatch on error.@@ -1256,13 +1263,13 @@ Callbacks may be `async def`: they are awaited on the gateway's own event loop,| Return | Effect ||--------|--------|-| `{"action": "skip", "reason": "..."}` | Drop the message — no agent reply, no pairing flow, no auth. Plugin is assumed to have handled it (e.g. silent-ingested into the transcript). |+| `{"action": "skip", "reason": "..."}` | Drop the message — no agent reply, no pairing flow, no auth (a webhook or relay delivery is acknowledged and never admitted). Plugin is assumed to have handled it (e.g. silent-ingested into the transcript). || `{"action": "rewrite", "text": "new text"}` | Replace `event.text`, then continue normal dispatch with the modified event. Useful for collapsing buffered ambient messages into a single prompt. |-| `{"action": "allow"}` / `None` | Normal dispatch — runs the full auth / pairing / agent-loop chain. |+| `{"action": "allow"}` / `None` | Normal dispatch — runs the rest of the auth / pairing / agent-loop chain. |**Use cases:** Listen-only group chats (only respond when tagged; buffer ambient messages into context); human handover (silent-ingest customer messages while owner handles the chat manually); per-profile rate limiting; policy-driven routing.-**Example — drop unauthorized DMs silently without triggering the pairing code:**+**Example — drop unauthorized DMs silently without triggering the pairing code** (platform-adapter messages; a refused webhook or relay sender never reaches the hook):```pythondef deny_unauthorized_dms(event, **kwargs):