The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(relay): a relayed Discord interaction carries the text lane's chat and user labels
John Paul Soliva102c07403a66
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.pyindex 157d9655de2..fff04aa7ec2 100644--- a/gateway/relay/adapter.py+++ b/gateway/relay/adapter.py@@ -153,6 +153,10 @@ class RelayAdapter(RelayDiscordInteractionMixin, BasePlatformAdapter):self._auto_thread_waiters: dict[str, asyncio.Event] = {}# Bounded FIFO seen-set for inbound replay dedupe (insertion-ordered dict).self._seen_inbound: dict[str, None] = {}+ # Discord chat labels the text lane carries and a forwarded interaction does not:+ # (scope, chat) -> (chat_name, chat_topic); the second map is what the store holds.+ self._discord_chat_labels: dict[tuple, tuple] = {}+ self._discord_labels_recorded: dict[tuple, tuple] = {}# Live cards: draft_key -> draft_id of the OPEN native stream. Armed by# send_draft; consumed by send() to convert the turn-final into# draft(final=true) instead of a duplicate post. Keyed by _draft_key (chat +@@ -888,13 +892,21 @@ class RelayAdapter(RelayDiscordInteractionMixin, BasePlatformAdapter):returnself._seen_inbound[dedupe_key] = Noneself._evict_oldest(self._seen_inbound, self._SEEN_INBOUND_MAX)- self._capture_scope(event)- self._stamp_slack_session_thread(event)- # A structured prompt answer resolves its waiting primitive and is CONSUMED —- # never also dispatched as chat.- if await self._consume_prompt_response(event):- return- await self._localize_inbound_media(event)+ try:+ self._capture_scope(event)+ await self._remember_discord_labels(event.source)+ self._stamp_slack_session_thread(event)+ # A structured prompt answer resolves its waiting primitive and is CONSUMED —+ # never also dispatched as chat.+ if await self._consume_prompt_response(event):+ return+ await self._localize_inbound_media(event)+ except asyncio.CancelledError:+ # Teardown cancels the reader mid-frame, before admission and before the ACK, so the+ # connector replays this frame; the replay must be admitted, not dropped as seen.+ if dedupe_key is not None:+ self._seen_inbound.pop(dedupe_key, None)+ raiseif native:from datetime import datetime, timezonefrom gateway.platforms.webhook_ingress import admit_producer@@ -1147,31 +1159,6 @@ class RelayAdapter(RelayDiscordInteractionMixin, BasePlatformAdapter):"""Bridge a connector-delivered /stop into the per-session interrupt path."""await self.interrupt_session_activity(session_key, chat_id)- async def _on_passthrough(self, forward, buffer_id: Optional[str] = None) -> None:- """Handle a connector-forwarded passthrough request. The connector answered the- provider's latency-critical ACK at the edge, verified the signature and vaulted- any shared-identity credential; the agent later acts via the token-less- ``send_follow_up`` path. A Discord interaction becomes a normalized- ``MessageEvent`` on the SAME agent path as chat; other forwards are logged and- dropped. NEVER raises: a malformed forward must not kill the read loop."""- try:- platform = getattr(forward, "platform", "") or ""- if platform == "discord":- event = self._discord_interaction_to_event(forward)- if event is not None:- self._capture_scope(event)- # A prompt-token component press is consumed (same gate as _on_inbound).- if await self._consume_prompt_response(event):- return- await self.handle_message(event)- return- logger.info(- "relay passthrough_forward dropped (no handler): platform=%s method=%s path=%s",- platform, getattr(forward, "method", "?"), getattr(forward, "path", "?"),- )- except Exception:- logger.warning("relay passthrough_forward handling failed", exc_info=True)-async def disconnect(self) -> None:# The runner wraps this call in wait_for(adapter disconnect budget). Monitor# teardown and go_idle eat into the transport's drain time, so measure fromdiff --git a/gateway/relay/adapter_discord_interaction.py b/gateway/relay/adapter_discord_interaction.pyindex 1c837938316..93098b205a1 100644--- a/gateway/relay/adapter_discord_interaction.py+++ b/gateway/relay/adapter_discord_interaction.py@@ -1,18 +1,23 @@"""Forwarded Discord interaction -> ``MessageEvent`` normalization for the relay adapter.-``RelayAdapter`` mixes this in; the passthrough path (``RelayAdapter._on_passthrough``) calls-``_discord_interaction_to_event`` for every connector-forwarded Discord interaction body.+``RelayAdapter`` mixes this in; the passthrough path (``_on_passthrough``) calls+``_discord_interaction_to_event`` for every connector-forwarded Discord interaction body and gives it+the chat labels the text lane last carried (``_remember_discord_labels``)."""from __future__ import annotations+import asyncioimport json+import loggingimport refrom gateway.config import Platformfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.session import SessionSource+logger = logging.getLogger(__name__)+# Connector promptCodec.decodePromptCallback id alphabet ([A-Za-z0-9_.-], <=32)._PROMPT_ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,32}$")@@ -20,6 +25,90 @@ _PROMPT_ID_RE = re.compile(r"^[A-Za-z0-9_.\-]{1,32}$")class RelayDiscordInteractionMixin:"""Decode connector-forwarded Discord interactions into normalized inbound events."""+ _DISCORD_LABELS_MAX = 2048++ async def _remember_discord_labels(self, source) -> None:+ """Keep the text lane's Discord chat labels for the interaction lane: the pinned+ session-context prompt renders them, so a slash turn without them re-rendered the cached+ prefix and the next message rendered it back."""+ # A message carrying no labels is an observation too (a topic or name removed upstream):+ # the interaction must render what the text lane last rendered, not an older label.+ if getattr(source, "platform", None) != Platform.DISCORD or not source.chat_id:+ return+ key, labels = (str(source.scope_id or ""), str(source.chat_id)), (source.chat_name, source.chat_topic)+ self._discord_chat_labels[key] = labels+ self._evict_oldest(self._discord_chat_labels, self._DISCORD_LABELS_MAX)+ store = getattr(self, "_session_store", None)+ if store is None or self._discord_labels_recorded.get(key) == labels:+ return+ # Recorded when observed, so the interaction lane has them after a restart whatever order+ # the chat's sessions were created or reset in. Awaited before dispatch (the reader delivers+ # events one at a time, so records land in observation order) but off the loop: disk write.+ try:+ recorded = await asyncio.to_thread(store.record_chat_labels, source)+ except Exception:+ logger.debug("relay: Discord chat labels not recorded", exc_info=True)+ recorded = False+ if not recorded:+ # Not written (store fault, or no database handle right now): leave the key out so the+ # next message with these labels tries again.+ self._discord_labels_recorded.pop(key, None)+ return+ self._discord_labels_recorded[key] = labels+ self._evict_oldest(self._discord_labels_recorded, self._DISCORD_LABELS_MAX)++ async def _discord_chat_labels_for(self, scope: str, chat_id: str) -> tuple:+ """The text lane's last (chat_name, chat_topic) for a chat. After a restart (or eviction) the+ map is empty until the text lane speaks again, so ask the session store for what that lane+ last recorded; otherwise a first interaction re-renders the prompt the cache still holds."""+ key = (scope, chat_id)+ if key in self._discord_chat_labels:+ return self._discord_chat_labels[key]+ store = getattr(self, "_session_store", None)+ try:+ # Off the loop: the read takes the database's writer lock, which a write may be holding.+ recorded = (await asyncio.to_thread(store.chat_labels, Platform.DISCORD, scope, chat_id)+ if store is not None else None)+ except Exception:+ # Labels only keep the prompt cache warm; a store fault must not drop the interaction.+ # Not cached either: the next interaction asks the store again.+ logger.debug("relay: recorded Discord chat labels unreadable", exc_info=True)+ return (None, None)+ if recorded is not None:+ self._discord_labels_recorded[key] = recorded+ self._evict_oldest(self._discord_labels_recorded, self._DISCORD_LABELS_MAX)+ self._discord_chat_labels[key] = recorded or (None, None)+ self._evict_oldest(self._discord_chat_labels, self._DISCORD_LABELS_MAX)+ return self._discord_chat_labels[key]++ async def _on_passthrough(self, forward, buffer_id=None) -> None:+ """Handle a connector-forwarded passthrough request. The connector answered the+ provider's latency-critical ACK at the edge, verified the signature and vaulted+ any shared-identity credential; the agent later acts via the token-less+ ``send_follow_up`` path. A Discord interaction becomes a normalized+ ``MessageEvent`` on the SAME agent path as chat; other forwards are logged and+ dropped. NEVER raises: a malformed forward must not kill the read loop."""+ try:+ platform = getattr(forward, "platform", "") or ""+ if platform == "discord":+ event = self._discord_interaction_to_event(forward)+ if event is not None:+ self._capture_scope(event)+ # A prompt-token component press is consumed (same gate as _on_inbound).+ if await self._consume_prompt_response(event):+ return+ src = event.source+ src.chat_name, src.chat_topic = await self._discord_chat_labels_for(+ str(src.scope_id or ""), src.chat_id)+ await self.handle_message(event)+ return+ logger.info(+ "relay passthrough_forward dropped (no handler): platform=%s method=%s path=%s",+ platform, getattr(forward, "method", "?"), getattr(forward, "path", "?"),+ )+ except Exception:+ logger.warning("relay passthrough_forward handling failed", exc_info=True)+def _discord_interaction_to_event(self, forward):"""Convert a forwarded Discord interaction body to a MessageEvent, or None foran unusable body (a PING is answered at the edge and never forwarded). The@@ -52,17 +141,33 @@ class RelayDiscordInteractionMixin:if not isinstance(user, dict):user = {}guild_id = payload.get("guild_id")+ # The text lane's user_display_name is the native author.display_name: guild nick, else+ # global name, else username. The interaction carries all three as of now, so derive the+ # same name from it; a remembered one would outlive a nickname change.+ user_name = next(+ (str(v) for v in ((member.get("nick") if isinstance(member, dict) else None),+ user.get("global_name"), user.get("username")) if v), None)+ chat_id = str(payload.get("channel_id") or "")+ # The text lane keys a message inside a thread on chat_type "thread" + thread_id (both session-key+ # fields), so an interaction sent there must carry the same or it lands in a per-user "group"+ # session beside the thread's. The partial channel object marks a thread by type (10 announcement,+ # 11 public, 12 private: what discord.py's Thread covers) and names the parent.+ channel = payload.get("channel") if isinstance(payload.get("channel"), dict) else {}+ is_thread = bool(guild_id) and channel.get("type") in (10, 11, 12)source = SessionSource(# The LOGICAL platform, not RELAY: session keys must match the connector's# capability binding (platform="discord"), /sethome must file under the# logical platform, and _capture_scope skips the generic "relay".platform=Platform.DISCORD,- chat_id=str(payload.get("channel_id") or ""),+ chat_id=chat_id,# "group", not "channel": both the connector's capability binding and the# native Discord adapter key guild channels as "group".- chat_type="group" if guild_id else "dm",+ chat_type="thread" if is_thread else ("group" if guild_id else "dm"),+ thread_id=chat_id if is_thread else None,+ parent_chat_id=str(channel["parent_id"]) if is_thread and channel.get("parent_id") else None,user_id=str(user["id"]) if user.get("id") else None,- user_name=str(user["username"]) if user.get("username") else None,+ user_name=user_name,+ # chat_name / chat_topic: filled by _on_passthrough from what the text lane recorded.scope_id=str(guild_id) if guild_id else None,message_id=str(payload.get("id")) if payload.get("id") else None,# Same upstream-trust marker the relay text lane stamps. Set locally, neverdiff --git a/gateway/session_persistence.py b/gateway/session_persistence.pyindex 7cb6509ced5..05553d46b0e 100644--- a/gateway/session_persistence.py+++ b/gateway/session_persistence.py@@ -13,7 +13,7 @@ from typing import TYPE_CHECKING, Any, Dict, Optionalfrom utils import atomic_json_writeif TYPE_CHECKING:- from gateway.session import SessionEntry+ from gateway.session import SessionEntry, SessionSource# Log-record parity with the origin module.logger = logging.getLogger("gateway.session")@@ -244,6 +244,38 @@ class SessionPersistenceMixin:method = getattr(self._routing_db or None, name, None)return method if callable(method) else None+ @staticmethod+ def _chat_labels_meta_key(platform, scope_id, chat_id) -> str:+ return f"gateway_chat_labels:{getattr(platform, 'value', platform)}:{scope_id or ''}:{chat_id}"++ def record_chat_labels(self, source: SessionSource) -> bool:+ """Persist *source*'s ``chat_name`` / ``chat_topic`` as the chat's current labels, at the+ moment they are observed; True once written. A session origin cannot answer "what is this+ chat called now": it is written when its session is created, which can be after a newer+ observation (a delayed first turn), and a reset inherits it under a fresh ``created_at``.++ False when there is no database handle right now (open failed, backoff, JSONL fallback):+ nothing was written, so the caller must not treat these labels as recorded."""+ setter = self._routing_db_method("set_meta")+ if setter is None:+ return False+ setter(self._chat_labels_meta_key(source.platform, source.scope_id, source.chat_id),+ json.dumps([source.chat_name, source.chat_topic]))+ return True++ def chat_labels(self, platform, scope_id, chat_id) -> Optional[tuple]:+ """The ``(chat_name, chat_topic)`` last recorded for a chat, or None when none was. Raises+ when the store cannot be read, including when there is no database handle right now:+ "unreadable now" is not "never labelled"."""+ getter = self._routing_db_method("get_meta")+ if getter is None:+ raise LookupError("session database unavailable")+ raw = getter(self._chat_labels_meta_key(platform, scope_id, chat_id))+ if not raw:+ return None+ chat_name, chat_topic = json.loads(raw)+ return chat_name, chat_topic+def _load_routing_rows_locked(self) -> bool:"""Load state.db routing entries into ``_entries``; False when there is no loader or theload failed (warned). Lock held."""diff --git a/tests/gateway/relay/test_relay_discord_interaction_labels.py b/tests/gateway/relay/test_relay_discord_interaction_labels.pynew file mode 100644index 00000000000..e9a911e27cc--- /dev/null+++ b/tests/gateway/relay/test_relay_discord_interaction_labels.py@@ -0,0 +1,202 @@+"""A relayed Discord interaction carries the same chat/user labels as a relayed message in that chat.++The text lane gets ``chat_name``, ``chat_topic`` and ``user_display_name`` from the connector; a+forwarded interaction (slash command, component) is the raw Discord body. Both land in one session,+and the pinned session-context prompt renders those labels, so a slash turn built without them+re-rendered the cached prefix and the next message rendered it back.+"""++import asyncio+import json+import threading+from unittest.mock import AsyncMock++import pytest++import gateway.run as gateway_run+import gateway.session as gateway_session+from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.relay.ws_transport import _event_from_wire+from gateway.session import SessionStore, build_session_context, build_session_key+from tests.gateway.relay.test_relay_interactive import _adapter+++def _forward(**payload):+ body = {"type": 2, "id": "i1", "channel_id": "ch1", "guild_id": "g1", "data": {"name": "status"}}+ body.update(payload)++ class Forward:+ platform, method, path = "discord", "POST", "/interactions/bot1"++ Forward.body = json.dumps(body).encode()+ return Forward()+++def _pinned_prompt(source):+ runner = object.__new__(gateway_run.GatewayRunner)+ config = GatewayConfig(platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="x")})+ return runner._pinned_session_context_prompt(build_session_context(source, config), False, "k")+++def _message(chat, user="u1", chat_name="Hermes Server / #ops", chat_topic="Incident triage"):+ message_id = f"{user}:{chat_name}"+ return _event_from_wire({"text": "hi", "message_type": "text", "message_id": message_id, "source": {+ "platform": "discord", **chat, "scope_id": "g1",+ "user_id": user, "user_name": "ben", "user_display_name": "Ben D",+ "chat_name": chat_name, "chat_topic": chat_topic, "message_id": message_id}})+++async def _slash(adapter, **interaction):+ """Forward an interaction the way the transport does and return the event it admits."""+ adapter.handle_message = AsyncMock()+ await adapter._on_passthrough(_forward(**interaction))+ return adapter.handle_message.await_args.args[0]++[email protected]("case", [+ "warm", "restart", "thread", "rename", "peer-rename", "cleared", "late-session", "read-retry",+ "read-unavailable", "write-unavailable", "cancelled"])+async def test_slash_between_messages_keeps_one_pinned_prompt(tmp_path, monkeypatch, case):+ """Every case but ``warm`` and ``thread`` restarts the gateway after the last message, so the+ slash command is the first event the new process sees in that chat; its chat labels are the+ ones the session store recorded when the text lane carried them.+ ``thread``: both events happen inside a thread, which the text lane keys on chat_type "thread" ++ thread_id; the slash command must land in that session, not in a per-user "group" one.+ ``rename`` / ``peer-rename``: the channel was renamed before the restart. In ``peer-rename``+ another user's message carried the new labels and this user's session was reset since: a reset+ inherits the origin (old labels) under a fresh ``created_at``. ``cleared``: the last message carried+ no labels at all (name and topic removed upstream); the slash command must not revive the old ones.+ ``late-session``: another user's older message, still carrying the old labels, only gets its+ session after the rename was observed. What the chat is called follows the order the labels+ were observed in, not the order its sessions were created in.+ ``read-retry`` / ``read-unavailable``: the first read after the restart raises, or finds no+ database handle (open failed or in backoff). That interaction goes through without labels;+ the next one asks the store again instead of keeping "no labels".+ ``write-unavailable``: the first message's record found no database handle, so nothing was+ written; the next message with the same labels must write them.+ ``cancelled``: the reader is cancelled while the message's labels are being written, before+ the message was admitted. The connector replays the un-ACKed frame, and the replay is admitted."""+ config = GatewayConfig(platforms={Platform.DISCORD: PlatformConfig(enabled=True, token="x")})+ store = SessionStore(tmp_path, config)+ adapter, _stub = _adapter(platform="discord")+ adapter.set_session_store(store)+ adapter.handle_message = AsyncMock()+ chat = ({"chat_id": "th1", "chat_type": "thread", "thread_id": "th1", "parent_chat_id": "ch1"}+ if case == "thread" else {"chat_id": "ch1", "chat_type": "group"})+ renamed = {"chat_name": "Hermes Server / #triage", "chat_topic": "Renamed"}+ calls, held, entered = [], threading.Event(), threading.Event()++ def watch(store):+ # Note which thread touches the label record; hold the first write in ``cancelled``.+ db = store._routing_db+ for name in ("set_meta", "get_meta"):+ real = getattr(db, name)++ def spy(key, *args, _real=real, _name=name, **kwargs):+ if key.startswith("gateway_chat_labels:"):+ calls.append((_name, threading.get_ident()))+ if _name == "set_meta" and case == "cancelled" and not held.is_set():+ entered.set()+ held.wait(5)+ return _real(key, *args, **kwargs)++ setattr(db, name, spy)++ def unavailable_once(store, name):+ # What _routing_db_method returns while the database handle cannot be opened.+ real, faults = store._routing_db_method, [name]++ def method(wanted):+ if wanted in faults:+ faults.remove(wanted)+ return None+ return real(wanted)++ store._routing_db_method = method++ watch(store)+ if case == "write-unavailable":+ unavailable_once(store, "set_meta")++ async def relay(event):+ await adapter._on_inbound(event)+ return store.get_or_create_session(event.source)++ if case == "late-session":+ late = _message(chat, "u2")+ await adapter._on_inbound(late)+ message = _message(chat, **renamed)+ await relay(message)+ store.get_or_create_session(late.source)+ else:+ if case == "peer-rename":+ await relay(_message(chat, "u2"))+ message = _message(chat)+ if case == "cancelled":+ intake = asyncio.create_task(adapter._on_inbound(message))+ await asyncio.to_thread(entered.wait, 5)+ intake.cancel()+ held.set()+ with pytest.raises(asyncio.CancelledError):+ await intake+ entry = await relay(message)+ if case == "cancelled":+ adapter.handle_message.assert_awaited_once_with(message)+ if case == "write-unavailable":+ await relay(_message(chat, "u3"))+ if case == "cleared":+ renamed = {"chat_name": None, "chat_topic": None}+ if case in ("rename", "peer-rename", "cleared"):+ await relay(_message(chat, "u1" if case != "peer-rename" else "u2", **renamed))+ message = _message(chat, **renamed)+ if case == "peer-rename":+ store.reset_session(entry.session_key)+ if case not in ("warm", "thread"):+ store = SessionStore(tmp_path, config)+ watch(store)+ adapter, _stub = _adapter(platform="discord")+ adapter.set_session_store(store)+ interaction = {"member": {"nick": "Ben D", "user": {"id": "u1", "username": "ben"}}}+ if case == "thread":+ interaction.update(channel_id="th1", channel={"id": "th1", "type": 11, "parent_id": "ch1"})+ if case == "read-retry":+ get_meta, faults = store._routing_db.get_meta, [OSError("database is locked")]++ def flaky(key):+ if faults:+ raise faults.pop()+ return get_meta(key)++ store._routing_db.get_meta = flaky+ if case == "read-unavailable":+ unavailable_once(store, "get_meta")+ if case in ("read-retry", "read-unavailable"):+ assert (await _slash(adapter, **interaction)).source.chat_name is None+ slash = await _slash(adapter, **interaction)++ assert build_session_key(slash.source) == build_session_key(message.source)+ # With Discord tools loaded the prompt also renders the thread parent and whether a triggering+ # message id exists, so both renderings must agree.+ for tools_loaded in (False, True):+ monkeypatch.setattr(gateway_session, "_discord_tools_loaded", lambda: tools_loaded)+ assert len({_pinned_prompt(event.source) for event in (message, slash, message)}) == 1+ # The label record is disk I/O behind the database's writer lock; the gateway loop never waits on it.+ assert ("set_meta" in {name for name, _ in calls}+ and threading.get_ident() not in {ident for _, ident in calls})++[email protected]("member, expected", [+ ({"nick": "Benny", "user": {"id": "u1", "username": "ben", "global_name": "Ben D"}}, "Benny"),+ ({"user": {"id": "u1", "username": "ben", "global_name": "Ben D"}}, "Ben D"),+ ({"user": {"id": "u1", "username": "ben"}}, "ben"),+])+async def test_interaction_names_the_user_as_the_text_lane_would_now(member, expected):+ """The text lane's user_display_name is the native author.display_name (guild nick, else global+ name, else username), and an interaction carries all three as of now. The name an earlier+ message carried ("Ben D" here) must not win: it predates a nickname change."""+ adapter, _stub = _adapter(platform="discord")+ adapter.handle_message = AsyncMock()+ await adapter._on_inbound(_message({"chat_id": "ch1", "chat_type": "group"}))+ assert (await _slash(adapter, member=member)).source.user_name == expecteddiff --git a/website/docs/developer-guide/relay-connector-contract.md b/website/docs/developer-guide/relay-connector-contract.mdindex bc8ffa9fb39..45e831ecef8 100644--- a/website/docs/developer-guide/relay-connector-contract.md+++ b/website/docs/developer-guide/relay-connector-contract.md@@ -162,7 +162,17 @@ forward needs no response back (the provider was already satisfied), so it ridesthe same outbound WS as `inbound` via a `passthrough_forward` frame rather thanan HTTP POST. The gateway processes the decoded request through its normal agentpath (a Discord interaction is decoded to a `MessageEvent` and handled like a-message; the reply egresses over the outbound / `follow_up` path). `bufferId` is+message; the reply egresses over the outbound / `follow_up` path). An+interaction sent inside a thread (partial `channel.type` 10, 11 or 12) is keyed+like the text lane's thread message: `chat_type: thread`, `thread_id` = the+thread channel id, `parent_chat_id` = `channel.parent_id`. The connector's+capability binding for that interaction must derive the same fields, or a later+`follow_up` names a session the vault never bound. The raw interaction has no+chat labels, so the gateway gives it the `chat_name` / `chat_topic` the text lane+last carried for that chat (recorded as observed, so they survive a restart), and+names the user from the interaction itself: guild nick, else global name, else+username. The connector's `user_display_name` on a text message must resolve the+same way, or the two lanes name one user differently. `bufferId` ispresent when the forward was buffered (Phase 5 §5.3 buffered-only flip) and thegateway acks it after durable handoff.