The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): native admission keeps WhatsApp metadata, path text and reply_expected
Teknium298a96d51c55
diff --git a/gateway/session_envelope.py b/gateway/session_envelope.pyindex 83b0cc6ab7a..bc42116eb5b 100644--- a/gateway/session_envelope.py+++ b/gateway/session_envelope.py@@ -6,6 +6,7 @@ Relay snapshots bind the authenticated connector and exact source; replay rechec"""from copy import copy, deepcopyfrom datetime import datetime+import jsonfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.session import SessionSource@@ -17,15 +18,48 @@ _EVENT_FIELDS = ('reply_to_message_id', 'reply_to_text', 'reply_to_author_id','reply_to_author_name', 'reply_to_is_own_message', 'allow_gateway_control',)-_CONTEXT_FIELDS = ('auto_skill', 'channel_prompt', 'channel_context')+_CONTEXT_FIELDS = ('auto_skill', 'channel_prompt', 'channel_context', 'reply_expected')+# Closed metadata contract: only the keys the Baileys adapter stamps on ordinary inbound+# (``WhatsAppAdapter._build_message_event``) cross native admission; any other key refuses.+_WHATSAPP_METADATA = frozenset({'whatsapp_native_type', 'whatsapp_native', 'whatsapp_from_owner'})+# Top-level ``nativeMetadata`` keys the bridge emits (scripts/whatsapp-bridge/bridge_helpers.js).+_WHATSAPP_NATIVE_KEYS = frozenset({'video', 'audio', 'sticker', 'location', 'contact', 'contacts',+ 'reaction', 'poll', 'pollUpdate'})+_WHATSAPP_NATIVE_MAX_BYTES = 16 * 1024+++def _native_metadata(event):+ """JSON projection of the adapter metadata a native replay keeps; ``None`` refuses the event.+ An oversized ``whatsapp_native`` (vCards with photos) is dropped, never refused."""+ metadata = event.metadata+ if not metadata:+ return {}+ if (not isinstance(metadata, dict) or event.source.platform.value != 'whatsapp'+ or not set(metadata) <= _WHATSAPP_METADATA):+ return None+ kind, native = metadata.get('whatsapp_native_type'), metadata.get('whatsapp_native')+ if (kind is not None and not (isinstance(kind, str) and 0 < len(kind) <= 64)+ or metadata.get('whatsapp_from_owner') not in (None, True)+ or native is not None and not (isinstance(native, dict) and set(native) <= _WHATSAPP_NATIVE_KEYS)):+ return None+ projected = {key: metadata[key] for key in ('whatsapp_native_type', 'whatsapp_from_owner') if key in metadata}+ if native is not None:+ try:+ encoded = json.dumps(native, ensure_ascii=False, allow_nan=False)+ except (TypeError, ValueError):+ return None+ if len(encoded.encode()) <= _WHATSAPP_NATIVE_MAX_BYTES:+ projected['whatsapp_native'] = json.loads(encoded)+ return projecteddef _validate_native(runner, event, provenance=None, fresh_roles=False):source = event.sourceif (source is None or not isinstance(event.text, str)or not isinstance(event.message_type, MessageType)- or event.message_type == MessageType.COMMAND or event.is_command()- or event.internal or event.metadata or event.prompt_response+ # The ingress router's own classifier: ``/tmp/x is broken`` is text, not a command.+ or event.message_type == MessageType.COMMAND or event.get_command()+ or event.internal or _native_metadata(event) is None or event.prompt_responseor (source.role_authorized and not fresh_roles)or (source.delivered_via_upstream_relay and not (provenance and 'relay' in provenance))or source.profile_route_rejected@@ -38,8 +72,9 @@ def _validate_native(runner, event, provenance=None, fresh_roles=False):delegated = fresh_roles or bool(provenance and 'relay' in provenance)if not runner._is_user_authorized_for_source(source, allow_adapter_delegation=delegated):raise RuntimeStoreError('permission_denied')- if any(value is not None and not isinstance(value, str)- for value in (event.channel_prompt, event.channel_context)):+ if (any(value is not None and not isinstance(value, str)+ for value in (event.channel_prompt, event.channel_context))+ or event.reply_expected is not None and type(event.reply_expected) is not bool):raise RuntimeStoreError('invalid_params')skill = event.auto_skillif not (skill is None or isinstance(skill, str)@@ -104,6 +139,8 @@ def _snapshot_native(runner, event, provenance, fresh_roles=False):# its fingerprint. Explicit context (including an empty skill list) is exact.envelope['event'].update({name: deepcopy(getattr(event, name)) for name in _CONTEXT_FIELDSif getattr(event, name) is not None})+ if metadata := _native_metadata(event):+ envelope['event']['metadata'] = metadataif event.message_type != MessageType.TEXT:envelope['message_type'] = event.message_type.valueif event.media_urls:diff --git a/tests/gateway/test_native_admission_metadata.py b/tests/gateway/test_native_admission_metadata.pynew file mode 100644index 00000000000..ce3c1a1f124--- /dev/null+++ b/tests/gateway/test_native_admission_metadata.py@@ -0,0 +1,122 @@+"""Native admission keeps main's inbound contract: real adapter events run a turn (N78-N80)."""+import ast+from dataclasses import replace+from pathlib import Path++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.platforms.base import SendResult+from gateway.platforms.event import MessageEvent+from gateway.run import GatewayRunner+from gateway.session_authority import initialize_session_authority+from gateway.session_envelope import restore_native, snapshot_native+from gateway.session_results import execution_result+from hermes_state_runtime import RuntimeStoreError+from tests.waiting import async_wait_until++REPO = Path(__file__).resolve().parents[2]+CHAT = '[email protected]'+VCARD = 'BEGIN:VCARD\nPHOTO;BASE64:' + 'A' * 20000 + '\nEND:VCARD'+# (bridge payload overrides, expected turn text, expected restored metadata)+BRIDGE_SHAPES = [+ ({'body': 'hello', 'nativeType': 'conversation'}, 'hello', {'whatsapp_native_type': 'conversation'}),+ ({'body': 'quoted', 'nativeType': 'extendedTextMessage'}, 'quoted',+ {'whatsapp_native_type': 'extendedTextMessage'}),+ ({'body': '/tmp/report.csv is broken', 'nativeType': 'conversation'}, '/tmp/report.csv is broken',+ {'whatsapp_native_type': 'conversation'}),+ ({'body': 'π here', 'mediaType': 'location', 'nativeType': 'locationMessage',+ 'nativeMetadata': {'location': {'latitude': 1.5, 'longitude': 2.5, 'live': False}}}, 'π here',+ {'whatsapp_native_type': 'locationMessage',+ 'whatsapp_native': {'location': {'latitude': 1.5, 'longitude': 2.5, 'live': False}}}),+ ({'body': 'π', 'mediaType': 'reaction', 'nativeType': 'reactionMessage',+ 'nativeMetadata': {'reaction': {'text': 'π', 'messageId': 'x', 'remoteJid': '1', 'participant': ''}}}, 'π',+ {'whatsapp_native_type': 'reactionMessage',+ 'whatsapp_native': {'reaction': {'text': 'π', 'messageId': 'x', 'remoteJid': '1', 'participant': ''}}}),+ ({'body': 'Poll: lunch?', 'mediaType': 'poll', 'nativeType': 'pollCreationMessage',+ 'nativeMetadata': {'poll': {'question': 'lunch?', 'options': ['a', 'b'], 'selectableCount': 1}}},+ 'Poll: lunch?', {'whatsapp_native_type': 'pollCreationMessage',+ 'whatsapp_native': {'poll': {'question': 'lunch?', 'options': ['a', 'b'],+ 'selectableCount': 1}}}),+ # A vCard with a photo exceeds the bound: the bulky native block is dropped, the turn still runs.+ ({'body': 'Contact: Ann', 'mediaType': 'contact', 'nativeType': 'contactMessage',+ 'nativeMetadata': {'contact': {'displayName': 'Ann', 'vcard': VCARD}}}, 'Contact: Ann',+ {'whatsapp_native_type': 'contactMessage'}),+ # WHATSAPP_FORWARD_OWNER_MESSAGES owner forward: main runs it as a turn, so does the owner.+ ({'body': 'owner typed', 'nativeType': 'conversation', 'fromOwner': True}, '[owner reply] owner typed',+ {'whatsapp_native_type': 'conversation', 'whatsapp_from_owner': True}),+]+++async def test_real_whatsapp_bridge_events_run_a_turn_through_native_admission(tmp_path, monkeypatch):+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter+ monkeypatch.setenv('WHATSAPP_ALLOWED_USERS', '15551234567')+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))+ adapter = WhatsAppAdapter(PlatformConfig(enabled=True, extra={+ 'text_batch_delay_seconds': 0, 'session_path': str(tmp_path / 'wa')}))+ adapter.gateway_runner, runner.adapters = runner, {Platform.WHATSAPP: adapter}+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='wa')+ runner._wire_adapter_handlers(adapter)+ sent, turns = [], []++ async def send(chat_id, content, **_):+ sent.append(content)+ return SendResult(success=True, message_id='s')++ async def turn(event, *_args, **_kwargs):+ turns.append((event.text, event.metadata))+ execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}+ return 'ok'++ monkeypatch.setattr(adapter, 'send', send)+ monkeypatch.setattr(runner, '_handle_message_with_agent', turn)+ try:+ for index, (shape, text, metadata) in enumerate(BRIDGE_SHAPES):+ event = await adapter._build_message_event(+ {'messageId': f'm{index}', 'chatId': CHAT, 'senderId': CHAT, **shape})+ adapter._enqueue_text_event(event)+ await async_wait_until(lambda: len(sent) > index and not adapter._background_tasks,+ timeout=20, what=f'reply to {shape["nativeType"]}')+ assert sent[index] == 'ok', sent+ assert turns[index] == (text, metadata), turns+ finally:+ authority.db.close()+++async def test_native_codec_closed_metadata_contract_and_reply_expected(tmp_path, monkeypatch):+ from plugins.platforms.whatsapp.adapter import WhatsAppAdapter+ monkeypatch.setenv('WHATSAPP_ALLOWED_USERS', '15551234567')+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / 'sessions'))+ adapter = WhatsAppAdapter(PlatformConfig(enabled=True, extra={'session_path': str(tmp_path / 'wa')}))+ runner.adapters = {Platform.WHATSAPP: adapter}+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='codec')+ try:+ event = MessageEvent(text='chatter', source=adapter.build_source(chat_id=CHAT, user_id=CHAT, chat_type='group'),+ message_id='c1')+ # Slack-style silence policy survives the envelope (N80); unknown stays absent (old digest).+ assert 'reply_expected' not in snapshot_native(runner, event)['native_text_v1']['event']+ for value in (False, True):+ assert restore_native(snapshot_native(runner, replace(event, reply_expected=value))).reply_expected is value+ refused = [{'whatsapp_native_type': 'x', 'internal': True}, {'gateway_session_id': 's'},+ {'_authorization_profile_home': '/x'}, {'arbitrary': 1}, {'whatsapp_native_type': 'x' * 65},+ {'whatsapp_native': {'gateway_session_id': 's'}}, {'whatsapp_from_owner': 'yes'},+ {'whatsapp_native': {'poll': {1, 2}}}]+ for metadata in refused:+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ snapshot_native(runner, replace(event, metadata=metadata))+ for bad in (replace(event, reply_expected='no'), replace(event, text='/new now')):+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ snapshot_native(runner, bad)+ finally:+ authority.db.close()+ # Closed producer matrix: no other adapter stamps MessageEvent.metadata on ordinary inbound,+ # so the WhatsApp keys above are the whole contract. A new producer must extend it here.+ producers = set()+ for path in [*REPO.glob('gateway/platforms/**/*.py'), *REPO.glob('plugins/platforms/**/*.py')]:+ for node in ast.walk(ast.parse(path.read_text(encoding='utf-8'))):+ if (isinstance(node, ast.Call) and getattr(node.func, 'id', getattr(node.func, 'attr', '')) == 'MessageEvent'+ and any(k.arg == 'metadata' for k in node.keywords)):+ producers.add(path.relative_to(REPO).as_posix())+ assert producers == {'plugins/platforms/whatsapp/adapter.py'}, producers