Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion gateway/authz_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@
_ALLOWED_USERS_ENV = {Platform(k): v for k, v in _PLATFORM_ALLOWLIST_ENV.items()}
_ALLOW_ALL_ENV = {p: v.replace("_ALLOWED_USERS", "_ALLOW_ALL_USERS") for p, v in _ALLOWED_USERS_ENV.items()}
_GROUP_USER_ENV = {Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_USERS"}
_GROUP_CHAT_ENV = {Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_CHATS", Platform.QQBOT: "QQ_GROUP_ALLOWED_USERS"}
_GROUP_CHAT_ENV = {
Platform.TELEGRAM: "TELEGRAM_GROUP_ALLOWED_CHATS", Platform.QQBOT: "QQ_GROUP_ALLOWED_USERS",
# WhatsApp group-level chat grant: admit user-less group principals the same way Telegram
# observe-mode does (anonymous senders, adapter flows that deliver without a user id).
Platform.WHATSAPP: "WHATSAPP_GROUP_ALLOWED_CHATS",
}
_ALLOW_BOTS_ENV = {
# Bots admitted by {PLATFORM}_ALLOW_BOTS bypass the human allowlist (#4466). Checked before the
# no-user-id guard below: some platforms deliver bot/automation traffic with no user_id at all -- e.g.
Expand Down
120 changes: 120 additions & 0 deletions gateway/platforms/whatsapp_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@

from __future__ import annotations

import dataclasses
import json
import logging
import os
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional

Expand Down Expand Up @@ -264,6 +266,124 @@ def _should_process_message(self, data: Dict[str, Any]) -> bool:
or self._message_matches_mention_patterns(data)
)

# ---------------------------------------------- observed group context (Telegram observe_unmentioned parity)

def _whatsapp_observe_unmentioned_group_messages(self) -> bool:
"""``extra.observe_unmentioned_group_messages`` else WHATSAPP_OBSERVE_UNMENTIONED_GROUP_MESSAGES (default false)."""
configured = (self.config.extra or {}).get("observe_unmentioned_group_messages")
if configured is None:
configured = _get_wsecret("WHATSAPP_OBSERVE_UNMENTIONED_GROUP_MESSAGES", default="false") or "false"
if isinstance(configured, str):
return configured.lower() in _TRUTHY
return bool(configured)

def _whatsapp_observe_allowed_chats(self) -> set:
"""Chats where observed context may be collected: ``extra.observe_allowed_chats`` (blank = unset)
else WHATSAPP_OBSERVE_ALLOWED_CHATS. Empty = observe nothing (explicit allowlist required,
mirroring Telegram's ``observe_allowed_chats`` gate)."""
return self._coerce_allow_list(
_extra_or_wsecret(self.config.extra, "observe_allowed_chats", "WHATSAPP_OBSERVE_ALLOWED_CHATS"))

def _whatsapp_observe_scope_active(self, chat_id: str) -> bool:
"""Single effective observe scope used by BOTH collection and attribution (F-002): feature
enabled + chat explicitly allowlisted + mention-gated intake (require_mention on, chat not
free-response). When normal processing already dispatches every message there is nothing
to observe and no attribution may re-source the event."""
if not self._whatsapp_observe_unmentioned_group_messages():
return False
if not self._whatsapp_require_mention():
return False
if chat_id in self._whatsapp_free_response_chats():
return False
allowed = self._whatsapp_observe_allowed_chats()
return bool(allowed) and chat_id in allowed

def _whatsapp_should_observe_unmentioned_group_message(self, data: Dict[str, Any]) -> bool:
"""True when a group message skipped by the trigger gate should be stored as observed context."""
if not data.get("isGroup", False) or data.get("fromMe"):
return False
chat_id = str(data.get("chatId") or "")
# Single effective scope: mention-gated intake + explicit chat allowlist (F-002).
if not self._whatsapp_observe_scope_active(chat_id):
return False
# Only observe messages the require_mention gate would skip.
if (
str(data.get("body") or "").strip().startswith("/")
or self._message_is_reply_to_bot(data)
or self._message_mentions_bot(data)
or self._message_matches_mention_patterns(data)
):
return False
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Constrain both observation and attribution to effective mention-gated scope (F-002)

The observer predicate omits not _whatsapp_require_mention(), while polling still runs the normal build/queue arm after the observer. Attribution likewise ignores require_mention and free_response_chats.

Repro conditions: Keep the opt-in observation flag/list configured, but set require_mention: false. Independently, use an explicitly configured free_response_chats entry with require_mention: true.

Normally handled chatter is additionally stored as observed context, and normal/free-response traffic loses its original principal and text/session shape. This creates duplicate context and can also reach the admission failure in F-001; it is not passive-only behavior.

Observed evidence: A single legitimate text message through the real polling loop produced one normal queue event plus one real observed SQLite row at the head; merge base produced one queue event and zero observed rows. A separate free-response event-build/attribution probe changed user_id to None and prefixed text at the head, while baseline preserved both. The bridge response and queue sink were inert substitutes, not live delivery.

Required repair: Use one effective observe-chat predicate in collection and attribution: feature enabled, explicit observe list, supported group intake, mention gating enabled, and not free-response. Alternatively decide process/observe/drop once at poll entry and keep the dispositions exclusive. Preserve the intentional passive group-context utility rather than disabling it.

Regression contract: For require_mention=False, require one normal queue event and zero observed writes through actual polling plus a real store. For free-response chats, require the original principal/text and zero observe attribution. Keep a mention-gated unmentioned positive case with an observed write and no normal dispatch, and an addressed trigger control.

Pinned source:


@staticmethod
def _whatsapp_group_observe_shared_source(source):
"""Shared-session source: the sender id is KEPT (admission/slash checks still see the
principal) but the session is declared shared, so observed chatter, addressed turns and
commands all key ONE group lane (F-001/F-003)."""
return dataclasses.replace(source, shared_session=True)

@staticmethod
def _whatsapp_group_observe_attributed_text(event) -> str:
user_id = event.source.user_id or "unknown"
return f"[{event.source.user_name or user_id}|{user_id}]\n{event.text or ''}"

def _whatsapp_group_observe_channel_prompt(self) -> str:
return (
"You are handling a WhatsApp group chat message.\n"
"- observed WhatsApp group context may be provided in a separate context-only block "
"before the current message; it is not necessarily addressed to you.\n"
"- Treat only the current new message as a request explicitly directed at you, "
"and use observed context only when the current message asks for it.")

async def _observe_unmentioned_group_message(self, data: Dict[str, Any]) -> None:
"""Append skipped group chatter to the group's shared session without dispatching."""
store = getattr(self, "_session_store", None)
if not store:
return
try:
event = await self._build_message_event(data, _skip_policy_gate=True)
if event is None:
return
session_entry = store.get_or_create_session(self._whatsapp_group_observe_shared_source(event.source))
entry = {
"role": "user", "content": self._whatsapp_group_observe_attributed_text(event),
"timestamp": datetime.now(tz=timezone.utc), "observed": True}
if event.message_id:
entry["message_id"] = str(event.message_id)
store.append_to_transcript(session_entry.session_id, entry)
logger.info(
"[%s] WhatsApp group message observed (no bot trigger): chat=%s from=%s",
getattr(self, "name", "whatsapp"), data.get("chatId") or "unknown",
event.source.user_id or "unknown")
except Exception as exc:
logger.warning("[%s] Failed to observe WhatsApp group message: %s", getattr(self, "name", "whatsapp"), exc)

def _apply_whatsapp_group_observe_attribution(self, event):
"""Align triggered group turns with observed-history attribution (adds the channel prompt).

The caller identity survives admission (F-001): the source keeps ``user_id`` and only the
routing declaration (``shared_session``) changes, so session controls act on the same
shared lane as the observed transcript (F-003)."""
if not event:
return event
raw = getattr(event, "raw_message", None)
if not raw or not raw.get("isGroup", False):
return event
chat_id = str(raw.get("chatId") or "")
if not self._whatsapp_observe_scope_active(chat_id):
return event
observe_prompt = self._whatsapp_group_observe_channel_prompt()
channel_prompt = f"{event.channel_prompt}\n\n{observe_prompt}" if event.channel_prompt else observe_prompt
shared_source = dataclasses.replace(event.source, shared_session=True)
if str(getattr(event, "text", "") or "").strip().startswith("/"):
# Commands keep the original source (user_id) so sender checks identify the sender,
# but route to the shared session (F-003).
return dataclasses.replace(event, source=shared_source, channel_prompt=channel_prompt)
return dataclasses.replace(
event, text=self._whatsapp_group_observe_attributed_text(event),
source=shared_source, channel_prompt=channel_prompt)

# ------------------------------------------------------------------ formatting
def format_message(self, content: str) -> str:
"""Convert markdown to WhatsApp syntax (*bold*, _italic_, ~strike~); fenced and
Expand Down
8 changes: 6 additions & 2 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -1167,16 +1167,20 @@ def _build_replay_entry(


_TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER = "observed Telegram group context"
_WHATSAPP_OBSERVED_CONTEXT_PROMPT_MARKER = "observed WhatsApp group context"
_OBSERVED_GROUP_CONTEXT_HEADER = "[Observed Telegram group context - context only, not requests]"
_CURRENT_ADDRESSED_MESSAGE_HEADER = "[Current addressed message - answer only this unless it explicitly asks you to use the observed context]"


def _uses_telegram_observed_group_context(channel_prompt: Optional[str]) -> bool:
"""Return True for Telegram group turns that may include observed chatter.
"""Return True for group turns (Telegram or WhatsApp) that may include observed chatter.

Observed rows must not replay as ordinary user turns, or a weak wake word makes old chatter look like work.
"""
return bool(channel_prompt and _TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER in channel_prompt)
if not channel_prompt:
return False
return (_TELEGRAM_OBSERVED_CONTEXT_PROMPT_MARKER in channel_prompt
or _WHATSAPP_OBSERVED_CONTEXT_PROMPT_MARKER in channel_prompt)


def _csv_or_list_to_set(raw: Any) -> set[str]:
Expand Down
21 changes: 18 additions & 3 deletions gateway/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ class SessionSource:
# Discord auto-thread continuity: the thread id a CHANNEL message WILL be delivered into, so
# the initiating message and later in-thread follow-ups share ONE session.
prospective_thread_id: Optional[str] = None
# The adapter declares this chat's session shared by every participant even though the
# sender id is kept (WhatsApp/Telegram observe mode: commands and text turns keep user_id
# for admission/slash-access checks while observed chatter keys the shared lane).
shared_session: bool = False
# Wire-INVISIBLE trust signal (never in to_dict/from_dict, so a peer cannot forge it): came
# over the authenticated relay WebSocket. ``platform`` is the UNDERLYING platform, not
# ``relay``, so authz must key upstream trust off THIS flag.
Expand Down Expand Up @@ -143,6 +147,8 @@ def _optional(names) -> None:
_optional(self._OPTIONAL_POST_SCOPE)
if self.auto_thread_created:
d["auto_thread_created"] = True
if self.shared_session:
d["shared_session"] = True
_optional(self._OPTIONAL_TAIL)
return d

Expand All @@ -157,7 +163,8 @@ def from_dict(cls, data: Dict[str, Any]) -> "SessionSource":
platform=Platform(data["platform"]), chat_id=str(data["chat_id"]),
chat_type=data.get("chat_type", "dm"),
scope_id=data.get("scope_id", data.get("guild_id")),
auto_thread_created=bool(data.get("auto_thread_created", False)), **plain,
auto_thread_created=bool(data.get("auto_thread_created", False)),
shared_session=bool(data.get("shared_session", False)), **plain,
)


Expand Down Expand Up @@ -647,6 +654,8 @@ def is_shared_multi_user_session(
isolation rules in :func:`build_session_key`)."""
if source.chat_type == "dm":
return False
if getattr(source, "shared_session", False):
return True
return not (thread_sessions_per_user if source.thread_id else group_sessions_per_user)


Expand Down Expand Up @@ -706,8 +715,14 @@ def build_session_key(
isolate_user = not chat_id
else:
# Threads are shared by default; per-user isolation only via thread_sessions_per_user or
# outside a thread.
isolate_user = group_sessions_per_user and not (thread_id and not thread_sessions_per_user)
# outside a thread. An adapter-declared shared_session keeps one lane even with the
# sender id present (WhatsApp/Telegram observe mode: commands keep user_id for access
# checks but must act on the shared conversation).
isolate_user = (
group_sessions_per_user
and not (thread_id and not thread_sessions_per_user)
and not getattr(source, "shared_session", False)
)
# Duck-typed sources may lack user_id_alt: read the participant only when it matters.
participant_id = _canonical_participant(source) if (isolate_user or not is_dm) else None

Expand Down
31 changes: 23 additions & 8 deletions plugins/platforms/whatsapp/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@
client; messages are polled over a local HTTP API and responses are posted back through it."""

import asyncio
import dataclasses
import logging
import mimetypes
import os
import platform
import re
import signal
import subprocess
from datetime import datetime, timezone
from contextlib import suppress
from functools import wraps
from pathlib import Path
Expand Down Expand Up @@ -481,10 +483,12 @@ def _bridge_env(self) -> dict:
bridge_env.update(HERMES_IMAGE_CACHE_DIR=str(img_dir), HERMES_AUDIO_CACHE_DIR=str(audio_dir), HERMES_DOCUMENT_CACHE_DIR=str(doc_dir))
return bridge_env

def _bridge_died(self, detail: str) -> bool:
def _bridge_died(self, detail: str, code: str = "whatsapp_bridge_exited") -> bool:
print(f"[{self.name}] {detail}")
print(f"[{self.name}] Check log: {self._bridge_log}")
self._close_bridge_log()
# Named so the reconnect status and connect telemetry say why instead of an unclassified failure.
self._set_fatal_error(code, f"{detail} (see {self._bridge_log})", retryable=True)
return False

async def _poll_bridge_health(self, died_msg: str) -> tuple[Optional[bool], bool, dict]:
Expand Down Expand Up @@ -514,7 +518,7 @@ async def _wait_for_bridge(self) -> bool:
if connected is False:
return False
if not http_ready:
return self._bridge_died("Bridge HTTP server did not start in 15s")
return self._bridge_died("Bridge HTTP server did not start in 15s", "whatsapp_bridge_timeout")
if data.get("status") != "connected":
print(f"[{self.name}] Bridge HTTP ready, waiting for WhatsApp connection...")
connected, _, _ = await self._poll_bridge_health("Bridge process died during connection")
Expand Down Expand Up @@ -570,7 +574,7 @@ async def connect(self, *, is_reconnect: bool = False) -> bool:
f"{exc}. Set platforms.whatsapp.extra.bridge_port to a distinct free port; "
"or stop the process holding it.", retryable=False)
return False
if not self._preflight():
if not await asyncio.to_thread(self._preflight):
return False
bridge_path = Path(self._bridge_script)
lock_acquired = False
Expand Down Expand Up @@ -859,14 +863,19 @@ async def _poll_messages(self) -> None:
async with self._bridge_req("get", "messages", 30) as resp:
if resp.status == 200:
for msg_data in await resp.json():
# Observed-context collector runs BEFORE the trigger gate so a skipped
# group message is stored (never dispatched) when configured.
if not msg_data.get("isGroup", False) or not msg_data.get("fromMe", False):
if self._whatsapp_should_observe_unmentioned_group_message(msg_data):
await self._observe_unmentioned_group_message(msg_data)
event = await self._build_message_event(msg_data)
if event:
# Fire-and-forget: a slow bridge /read must not delay dispatch.
asyncio.create_task(self._send_read_receipt(msg_data))
if event.message_type == MessageType.TEXT:
self._enqueue_text_event(event)
self._enqueue_text_event(self._apply_whatsapp_group_observe_attribution(event))
else:
await self.handle_message(event)
await self.handle_message(self._apply_whatsapp_group_observe_attribution(event))
except asyncio.CancelledError:
break
except Exception as e:
Expand Down Expand Up @@ -967,10 +976,14 @@ def _quoted_media(self, data: Dict[str, Any], raw_reply_id: Any) -> list[tuple[s
print(f"[{self.name}] Attached quoted-reply media: {path}", flush=True)
return accepted

async def _build_message_event(self, data: Dict[str, Any]) -> Optional[MessageEvent]:
"""Build a MessageEvent from bridge message data, downloading images to cache."""
async def _build_message_event(self, data: Dict[str, Any], *, _skip_policy_gate: bool = False) -> Optional[MessageEvent]:
"""Build a MessageEvent from bridge message data, downloading images to cache.

``_skip_policy_gate=True`` is for the observed-context collector: the message already passed
``_whatsapp_should_observe_unmentioned_group_message``, so the trigger gate must not re-drop it.
"""
try:
if not self._should_process_message(data):
if not _skip_policy_gate and not self._should_process_message(data):
return None
msg_type = self._classify_bridge_message(data)
source = self.build_source(chat_id=data.get("chatId", ""), chat_name=data.get("chatName"), chat_type="group" if data.get("isGroup", False) else "dm",
Expand Down Expand Up @@ -1156,6 +1169,8 @@ def interactive_setup() -> None:
("group_policy", "WHATSAPP_GROUP_POLICY", "lower"), ("mention_patterns", "WHATSAPP_MENTION_PATTERNS", "json"),
("free_response_chats", "WHATSAPP_FREE_RESPONSE_CHATS", "csv"), ("allow_from", "WHATSAPP_ALLOWED_USERS", "csv"),
("group_allow_from", "WHATSAPP_GROUP_ALLOWED_USERS", "csv"),
("observe_unmentioned_group_messages", "WHATSAPP_OBSERVE_UNMENTIONED_GROUP_MESSAGES", "lower"),
("observe_allowed_chats", "WHATSAPP_OBSERVE_ALLOWED_CHATS", "csv"),
)


Expand Down
Loading