Skip to content

The agent that grows with you

refactor(plugins/whatsapp,wecom): dedupe send/media/stream paths, drop dead helpers, compact docs (4357->3048 LOC, bridge/WeCom payload + crypto parity verified)

Tekniumce08af613969
diff --git a/plugins/platforms/wecom/adapter.py b/plugins/platforms/wecom/adapter.py
index 02385d2955e..8e527a2fe30 100644
--- a/plugins/platforms/wecom/adapter.py
+++ b/plugins/platforms/wecom/adapter.py
@@ -1,28 +1,8 @@
-"""
-WeCom (Enterprise WeChat) platform adapter.
-
-Uses the WeCom AI Bot WebSocket gateway: authenticate via ``aibot_subscribe``,
-receive ``aibot_msg_callback`` events, send markdown via ``aibot_send_msg`` /
-``aibot_respond_msg``, upload media via ``aibot_upload_media_*``. Native
-streaming lives in ``streaming.py``, media in ``media.py``, the per-chat
-send queue in ``send_queue.py``.
-
-Configuration in config.yaml:
- platforms:
- wecom:
- enabled: true
- extra:
- bot_id: "your-bot-id" # or WECOM_BOT_ID env var
- secret: "your-secret" # or WECOM_SECRET env var
- websocket_url: "wss://openws.work.weixin.qq.com"
- dm_policy: "pairing" # open | allowlist | disabled | pairing
- allow_from: ["user_id_1"]
- group_policy: "pairing" # open | allowlist | disabled | pairing
- group_allow_from: ["group_id_1"]
- groups:
- group_id_1:
- allow_from: ["user_id_1"]
-"""
+"""WeCom (Enterprise WeChat) AI Bot adapter over the ``openws`` WebSocket gateway.
+Streaming lives in ``streaming.py``, media in ``media.py``, per-chat send queue in ``send_queue.py``.
+Config (``platforms.wecom.extra``): ``bot_id``/``secret`` (or WECOM_BOT_ID / WECOM_SECRET), ``websocket_url``,
+``dm_policy``/``group_policy`` (open|allowlist|disabled|pairing), ``allow_from``, ``group_allow_from``,
+``groups: {<group_id>: {allow_from: [...]}}``."""
from __future__ import annotations
@@ -37,17 +17,14 @@ from typing import Any, Dict, List, Optional, Tuple
try:
import aiohttp
- AIOHTTP_AVAILABLE = True
except ImportError:
- AIOHTTP_AVAILABLE = False
aiohttp = None # type: ignore[assignment]
-
try:
import httpx
- HTTPX_AVAILABLE = True
except ImportError:
- HTTPX_AVAILABLE = False
httpx = None # type: ignore[assignment]
+AIOHTTP_AVAILABLE = aiohttp is not None
+HTTPX_AVAILABLE = httpx is not None
from gateway.config import Platform, PlatformConfig
from gateway.platforms.helpers import MessageDeduplicator
@@ -85,20 +62,18 @@ RECONNECT_BACKOFF = [2, 5, 10, 30, 60]
DEDUP_MAX_SIZE = 1000
+
def check_wecom_requirements() -> bool:
- """Check if WeCom runtime dependencies are available."""
return AIOHTTP_AVAILABLE and HTTPX_AVAILABLE
def _coerce_list(value: Any) -> List[str]:
- """Coerce config values into a trimmed string list."""
- if value is None:
- return []
+ """Coerce config values (None | "a, b" | iterable | scalar) into a trimmed, non-empty string list."""
if isinstance(value, str):
- return [item.strip() for item in value.split(",") if item.strip()]
- if isinstance(value, (list, tuple, set)):
- return [str(item).strip() for item in value if str(item).strip()]
- return [str(value).strip()] if str(value).strip() else []
+ value = value.split(",")
+ elif not isinstance(value, (list, tuple, set)):
+ value = [] if value is None else [value]
+ return [item for item in (str(item).strip() for item in value) if item]
def _normalize_entry(raw: str) -> str:
@@ -114,8 +89,7 @@ def _entry_matches(entries: List[str], target: str) -> bool:
def _dict_or_empty(container: Dict[str, Any], key: str) -> Dict[str, Any]:
- value = container.get(key)
- return value if isinstance(value, dict) else {}
+ return container.get(key) if isinstance(container.get(key), dict) else {}
def _content_of(container: Dict[str, Any], key: str) -> str:
@@ -139,15 +113,12 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
SUPPORTS_MESSAGE_EDITING = False
- # msgtype "stream" via aibot_respond_msg bypasses the edit-based streaming path.
- SUPPORTS_NATIVE_STREAMING = True
+ SUPPORTS_NATIVE_STREAMING = True # msgtype "stream" via aibot_respond_msg, not edit-based
MAX_STREAM_CONTENT_LENGTH = MAX_STREAM_CONTENT_LENGTH
- # Chunks near the 4000-char WeCom client split are almost certainly continued.
- _SPLIT_THRESHOLD = 3900
+ _SPLIT_THRESHOLD = 3900 # chunks near the 4000-char client split are almost certainly continued
def __init__(self, config: PlatformConfig):
super().__init__(config, Platform.WECOM)
-
extra = config.extra or {}
def _extra_float(key: str, default: float) -> float:
@@ -156,127 +127,77 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
except (TypeError, ValueError):
return default
- self._bot_id = str(extra.get("bot_id") or _get_scoped_secret("WECOM_BOT_ID", "")).strip()
- self._secret = str(extra.get("secret") or _get_scoped_secret("WECOM_SECRET", "")).strip()
- self._ws_url = str(
- extra.get("websocket_url") or extra.get("websocketUrl") or _get_scoped_secret("WECOM_WEBSOCKET_URL", DEFAULT_WS_URL)
- ).strip() or DEFAULT_WS_URL
-
- self._dm_policy = str(extra.get("dm_policy") or _get_scoped_secret("WECOM_DM_POLICY", "pairing")).strip().lower()
- # Env-only setups (dm_policy=allowlist via env) need the WECOM_ALLOWED_USERS
- # fallback or every authorized DM is dropped at intake.
- self._allow_from = _coerce_list(
- extra.get("allow_from") or extra.get("allowFrom") or _get_scoped_secret("WECOM_ALLOWED_USERS", "")
- )
- self._group_policy = str(extra.get("group_policy") or _get_scoped_secret("WECOM_GROUP_POLICY", "pairing")).strip().lower()
+ def _setting(*keys: str, env: str = "", default: str = "") -> str:
+ return str(next((extra[k] for k in keys if extra.get(k)), None) or (_get_scoped_secret(env, default) if env else "")).strip()
+
+ self._bot_id = _setting("bot_id", env="WECOM_BOT_ID")
+ self._secret = _setting("secret", env="WECOM_SECRET")
+ self._ws_url = _setting("websocket_url", "websocketUrl", env="WECOM_WEBSOCKET_URL", default=DEFAULT_WS_URL) or DEFAULT_WS_URL
+ self._dm_policy = _setting("dm_policy", env="WECOM_DM_POLICY", default="pairing").lower()
+ # WECOM_ALLOWED_USERS fallback: env-only allowlist setups otherwise drop every DM at intake.
+ self._allow_from = _coerce_list(extra.get("allow_from") or extra.get("allowFrom") or _get_scoped_secret("WECOM_ALLOWED_USERS", ""))
+ self._group_policy = _setting("group_policy", env="WECOM_GROUP_POLICY", default="pairing").lower()
self._group_allow_from = _coerce_list(extra.get("group_allow_from") or extra.get("groupAllowFrom"))
self._groups = extra.get("groups") if isinstance(extra.get("groups"), dict) else {}
-
- self._session: Optional["aiohttp.ClientSession"] = None
- self._ws: Optional["aiohttp.ClientWebSocketResponse"] = None
- self._http_client: Optional["httpx.AsyncClient"] = None
- self._listen_task: Optional[asyncio.Task] = None
- self._heartbeat_task: Optional[asyncio.Task] = None
+ self._session = self._ws = self._http_client = self._listen_task = self._heartbeat_task = None
self._pending_responses: Dict[str, asyncio.Future] = {}
self._reply_queues: Dict[str, ReplyQueue] = {}
- self._dedup = MessageDeduplicator(max_size=DEDUP_MAX_SIZE)
- self._reply_req_ids: Dict[str, str] = {}
-
- # Text batching: WeCom clients split long messages around 4000 chars.
+ self._dedup, self._reply_req_ids = MessageDeduplicator(max_size=DEDUP_MAX_SIZE), {}
+ # Text batching (clients split long messages ~4000 chars); attachment-only frames are held
+ # for the merge window so the trailing text callback joins the same event (official: 800ms).
self._text_batch_delay_seconds = env_float("HERMES_WECOM_TEXT_BATCH_DELAY_SECONDS", 0.6)
self._text_batch_split_delay_seconds = env_float("HERMES_WECOM_TEXT_BATCH_SPLIT_DELAY_SECONDS", 2.0)
- # WeCom sends "image + text" as two callbacks a few hundred ms apart; hold an
- # attachment-only message this long so the trailing text merges into ONE
- # event (official plugin: ATTACHMENT_TEXT_MERGE_WINDOW_MS = 800).
self._attachment_text_merge_delay_seconds = _extra_float("attachment_text_merge_delay_seconds", 0.8)
self._pending_text_batches: Dict[str, MessageEvent] = {}
self._pending_text_batch_tasks: Dict[str, asyncio.Task] = {}
-
# Stream keep-alive config (see streaming.py STREAM_* constants).
self._stream_safe_duration_seconds = _extra_float("stream_safe_duration_seconds", STREAM_SAFE_DURATION_SECONDS)
self._stream_keepalive_enabled = bool(extra.get("stream_keepalive_enabled", STREAM_KEEPALIVE_ENABLED_DEFAULT))
- self._stream_keepalive_interval_seconds = _extra_float(
- "stream_keepalive_interval_seconds", STREAM_KEEPALIVE_INTERVAL_SECONDS
- )
-
+ self._stream_keepalive_interval_seconds = _extra_float("stream_keepalive_interval_seconds", STREAM_KEEPALIVE_INTERVAL_SECONDS)
self._device_id = uuid.uuid4().hex
self._last_chat_req_ids: Dict[str, str] = {}
- # Per-turn stream state keyed f"{chat_id}:{req_id|turn_id}" so concurrent
- # messages (e.g. approval during streaming) never share a stream.
+ # Turns keyed f"{chat_id}:{req_id|turn_id}"; expired chats clear on the next inbound req_id.
self._stream_turns: Dict[str, StreamTurn] = {}
- # Chats whose stream session was retired (846608 / 846609 / no req_id);
- # cleared when a fresh inbound callback gives the chat a new req_id.
- self._stream_expired_chats: set[str] = set()
- # Group chats can't receive proactive APP_CMD_SEND (populated in _on_message).
- self._group_chat_ids: set[str] = set()
-
- # Per-chat FIFO send queues (normal + control lanes) with token-bucket
- # rate limiting — see send_queue.py.
- self._chat_queues: Dict[str, asyncio.Queue] = {}
- self._chat_workers: Dict[str, asyncio.Task] = {}
- self._control_queues: Dict[str, asyncio.Queue] = {}
- self._control_workers: Dict[str, asyncio.Task] = {}
- self._chat_token_usage: Dict[str, Dict[str, float]] = {}
-
- # ------------------------------------------------------------------
- # Connection lifecycle
- # ------------------------------------------------------------------
+ self._stream_expired_chats, self._group_chat_ids = set(), set() # groups can't receive proactive APP_CMD_SEND
+ # Per-chat FIFO send queues (normal + control lanes) + token buckets — see send_queue.py.
+ self._chat_queues, self._chat_workers, self._control_queues, self._control_workers, self._chat_token_usage = {}, {}, {}, {}, {}
+
+ def _startup_failure(self, code: str, message: str, log_msg: str, *args: Any) -> bool:
+ self._set_fatal_error(code, message, retryable=True)
+ logger.warning(log_msg, self.name, message, *args)
+ return False
async def connect(self, *, is_reconnect: bool = False) -> bool:
- """Connect to the WeCom AI Bot gateway."""
for available, dep in ((AIOHTTP_AVAILABLE, "aiohttp"), (HTTPX_AVAILABLE, "httpx")):
if not available:
- message = f"WeCom startup failed: {dep} not installed"
- self._set_fatal_error("wecom_missing_dependency", message, retryable=True)
- logger.warning("[%s] %s. Run: pip install %s", self.name, message, dep)
- return False
+ return self._startup_failure("wecom_missing_dependency", f"WeCom startup failed: {dep} not installed", "[%s] %s. Run: pip install %s", dep)
if not self._bot_id or not self._secret:
- message = "WeCom startup failed: WECOM_BOT_ID and WECOM_SECRET are required"
- self._set_fatal_error("wecom_missing_credentials", message, retryable=True)
- logger.warning("[%s] %s", self.name, message)
- return False
-
+ return self._startup_failure("wecom_missing_credentials", "WeCom startup failed: WECOM_BOT_ID and WECOM_SECRET are required", "[%s] %s")
try:
# Tighter keepalive so idle CLOSE_WAIT drains promptly.
from gateway.platforms._http_client_limits import platform_httpx_limits
from gateway.platforms.base import _ssrf_redirect_guard
from tools.url_safety import create_ssrf_safe_async_client
-
- self._http_client = create_ssrf_safe_async_client(
- timeout=30.0,
- follow_redirects=True,
- event_hooks={"response": [_ssrf_redirect_guard]},
- limits=platform_httpx_limits(),
- )
+ self._http_client = create_ssrf_safe_async_client(timeout=30.0, follow_redirects=True, event_hooks={"response": [_ssrf_redirect_guard]}, limits=platform_httpx_limits())
await self._open_connection()
self._mark_connected()
- self._listen_task = asyncio.create_task(self._listen_loop())
- self._heartbeat_task = asyncio.create_task(self._heartbeat_loop())
+ self._listen_task, self._heartbeat_task = asyncio.create_task(self._listen_loop()), asyncio.create_task(self._heartbeat_loop())
logger.info("[%s] Connected to %s", self.name, self._ws_url)
self._wire_plugin_handlers(None) # ctx.register_platform_handler hooks
return True
except Exception as exc:
- message = f"WeCom startup failed: {exc}"
- self._set_fatal_error("wecom_connect_error", message, retryable=True)
+ self._set_fatal_error("wecom_connect_error", f"WeCom startup failed: {exc}", retryable=True)
logger.error("[%s] Failed to connect: %s", self.name, exc, exc_info=True)
- await self._cleanup_ws()
- await self._close_http_client()
+ await self._teardown()
return False
- async def _close_http_client(self) -> None:
- if self._http_client:
- await self._http_client.aclose()
- self._http_client = None
-
async def disconnect(self) -> None:
- """Disconnect from WeCom."""
self._running = False
self._mark_disconnected()
for task in list(self._chat_workers.values()) + list(self._control_workers.values()):
task.cancel()
for registry in (self._chat_workers, self._control_workers, self._chat_queues, self._control_queues):
registry.clear()
-
for attr in ("_listen_task", "_heartbeat_task"):
task = getattr(self, attr)
if task:
@@ -286,60 +207,55 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
except asyncio.CancelledError:
pass
setattr(self, attr, None)
-
- self._fail_pending_responses(RuntimeError("WeCom adapter disconnected"))
- self._fail_reply_queues(RuntimeError("WeCom adapter disconnected"))
- await self._cleanup_ws()
- await self._close_http_client()
+ self._fail_all(RuntimeError("WeCom adapter disconnected"))
+ await self._teardown()
self._dedup.clear()
logger.info("[%s] Disconnected", self.name)
+ def _fail_all(self, exc: Exception) -> None:
+ self._fail_pending_responses(exc)
+ self._fail_reply_queues(exc)
+
async def _cleanup_ws(self) -> None:
- """Close the live websocket/session, if any."""
- if self._ws and not self._ws.closed:
- await self._ws.close()
- self._ws = None
- if self._session and not self._session.closed:
- await self._session.close()
- self._session = None
+ """Close the live websocket, then its session, if any."""
+ for attr in ("_ws", "_session"):
+ live = getattr(self, attr)
+ if live and not live.closed:
+ await live.close()
+ setattr(self, attr, None)
+
+ async def _teardown(self) -> None:
+ """_cleanup_ws, then close the httpx client."""
+ await self._cleanup_ws()
+ if self._http_client:
+ await self._http_client.aclose()
+ self._http_client = None
async def _open_connection(self) -> None:
- """Open and authenticate a websocket connection."""
await self._cleanup_ws()
- # certifi's CA bundle so aiohttp trusts the same roots as urllib/requests
- # (avoids SSL_CERTIFICATE_VERIFY_FAILED on macOS with a stale OpenSSL path).
+ # certifi's CA bundle so aiohttp trusts the same roots as urllib/requests (macOS stale OpenSSL path).
import ssl as _ssl
try:
import certifi
- _ssl_ctx = _ssl.create_default_context(cafile=certifi.where())
+ cafile = certifi.where()
except ImportError:
- _ssl_ctx = _ssl.create_default_context()
+ cafile = None
+ _ssl_ctx = _ssl.create_default_context(cafile=cafile)
self._session = aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=aiohttp.TCPConnector(ssl=_ssl_ctx))
- self._ws = await self._session.ws_connect(
- self._ws_url, heartbeat=HEARTBEAT_INTERVAL_SECONDS * 2, timeout=CONNECT_TIMEOUT_SECONDS,
- )
-
+ self._ws = await self._session.ws_connect(self._ws_url, heartbeat=HEARTBEAT_INTERVAL_SECONDS * 2, timeout=CONNECT_TIMEOUT_SECONDS)
req_id = self._new_req_id("subscribe")
- await self._send_json({
- "cmd": APP_CMD_SUBSCRIBE,
- "headers": {"req_id": req_id},
- "body": {"bot_id": self._bot_id, "secret": self._secret, "device_id": self._device_id},
- })
+ await self._send_json({"cmd": APP_CMD_SUBSCRIBE, "headers": {"req_id": req_id}, "body": {"bot_id": self._bot_id, "secret": self._secret, "device_id": self._device_id}})
auth_payload = await self._wait_for_handshake(req_id)
errcode = auth_payload.get("errcode", 0)
if errcode not in {0, None}:
- errmsg = auth_payload.get("errmsg", "authentication failed")
- raise RuntimeError(f"{errmsg} (errcode={errcode})")
+ raise RuntimeError(f"{auth_payload.get('errmsg', 'authentication failed')} (errcode={errcode})")
async def _wait_for_handshake(self, req_id: str) -> Dict[str, Any]:
- """Wait for the subscribe acknowledgement."""
if not self._ws:
raise RuntimeError("WebSocket not initialized")
- deadline = asyncio.get_running_loop().time() + CONNECT_TIMEOUT_SECONDS
- while True:
- remaining = deadline - asyncio.get_running_loop().time()
- if remaining <= 0:
- raise TimeoutError("Timed out waiting for WeCom subscribe acknowledgement")
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + CONNECT_TIMEOUT_SECONDS
+ while (remaining := deadline - loop.time()) > 0:
msg = await asyncio.wait_for(self._ws.receive(), timeout=remaining)
if msg.type == aiohttp.WSMsgType.TEXT:
payload = self._parse_json(msg.data)
@@ -350,9 +266,9 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
logger.debug("[%s] Ignoring pre-auth payload: %s", self.name, payload.get("cmd"))
elif msg.type in {aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.ERROR}:
raise RuntimeError("WeCom websocket closed during authentication")
+ raise TimeoutError("Timed out waiting for WeCom subscribe acknowledgement")
async def _listen_loop(self) -> None:
- """Read websocket events forever, reconnecting on errors."""
backoff_idx = 0
while self._running:
try:
@@ -364,11 +280,9 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
if not self._running:
return
logger.warning("[%s] WebSocket error: %s", self.name, exc)
- self._fail_pending_responses(RuntimeError("WeCom connection interrupted"))
- self._fail_reply_queues(RuntimeError("WeCom connection interrupted"))
- delay = RECONNECT_BACKOFF[min(backoff_idx, len(RECONNECT_BACKOFF) - 1)]
+ self._fail_all(RuntimeError("WeCom connection interrupted"))
+ await asyncio.sleep(RECONNECT_BACKOFF[min(backoff_idx, len(RECONNECT_BACKOFF) - 1)])
backoff_idx += 1
- await asyncio.sleep(delay)
try:
await self._open_connection()
backoff_idx = 0
@@ -378,132 +292,89 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
logger.warning("[%s] Reconnect failed: %s", self.name, reconnect_exc)
async def _read_events(self) -> None:
- """Read websocket frames until the connection closes."""
if not self._ws:
raise RuntimeError("WebSocket not connected")
while self._running and self._ws and not self._ws.closed:
msg = await self._ws.receive()
if msg.type in (aiohttp.WSMsgType.TEXT, aiohttp.WSMsgType.BINARY):
- is_binary = msg.type == aiohttp.WSMsgType.BINARY
- data_len = len(msg.data) if isinstance(msg.data, (str, bytes, bytearray)) else -1
- if is_binary:
- # WeCom is expected to send TEXT; log a decoded preview so an
- # unhandled transport for group messages isn't silently discarded.
- try:
- decoded = msg.data.decode("utf-8", errors="replace")
- except Exception:
- decoded = "<undecodable>"
- logger.info(
- "[%s] Inbound BINARY frame received (len=%d) head=%r — attempting JSON parse",
- self.name, data_len, decoded[:200],
- )
- payload = self._parse_json(msg.data)
- if payload:
- await self._dispatch_payload(payload)
- elif is_binary:
- logger.info("[%s] BINARY frame not parseable as JSON — dropped", self.name)
- else:
- # _parse_json logged the detail; make the DROP itself visible at
- # INFO so a missing inbound message can be correlated to a bad frame.
- logger.info("[%s] Inbound TEXT frame dropped (unparseable/non-dict) len=%d", self.name, data_len)
+ await self._handle_frame(msg.data, msg.type == aiohttp.WSMsgType.BINARY)
elif msg.type in {aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR, aiohttp.WSMsgType.CLOSING}:
raise RuntimeError("WeCom websocket closed")
else:
logger.info("[%s] Inbound frame ignored: WSMsgType=%s", self.name, msg.type)
+ async def _handle_frame(self, data: Any, is_binary: bool) -> None:
+ """Parse one TEXT/BINARY frame and dispatch it; every drop is logged at INFO."""
+ data_len = len(data) if isinstance(data, (str, bytes, bytearray)) else -1
+ if is_binary: # WeCom should send TEXT; log a preview so an unhandled transport isn't silently dropped
+ decoded = data.decode("utf-8", errors="replace") if isinstance(data, (bytes, bytearray)) else "<undecodable>"
+ logger.info("[%s] Inbound BINARY frame received (len=%d) head=%r — attempting JSON parse", self.name, data_len, decoded[:200])
+ payload = self._parse_json(data)
+ if payload:
+ await self._dispatch_payload(payload)
+ elif is_binary:
+ logger.info("[%s] BINARY frame not parseable as JSON — dropped", self.name)
+ else: # _parse_json logged the detail; make the DROP itself visible at INFO
+ logger.info("[%s] Inbound TEXT frame dropped (unparseable/non-dict) len=%d", self.name, data_len)
+
async def _heartbeat_loop(self) -> None:
- """Send lightweight application-level pings."""
try:
while self._running:
await asyncio.sleep(HEARTBEAT_INTERVAL_SECONDS)
- if not self._ws or self._ws.closed:
- continue
try:
- await self._send_json({"cmd": APP_CMD_PING, "headers": {"req_id": self._new_req_id("ping")}, "body": {}})
+ if self._ws and not self._ws.closed:
+ await self._send_json({"cmd": APP_CMD_PING, "headers": {"req_id": self._new_req_id("ping")}, "body": {}})
except Exception as exc:
logger.debug("[%s] Heartbeat send failed: %s", self.name, exc)
except asyncio.CancelledError:
pass
async def _dispatch_payload(self, payload: Dict[str, Any]) -> None:
- """Route inbound websocket payloads."""
req_id = self._payload_req_id(payload)
cmd = str(payload.get("cmd") or "")
body_dict = payload.get("body") if isinstance(payload.get("body"), dict) else None
-
- # Diagnostics for ack-timeout analysis: do WeCom acks arrive at all, and
- # under which cmd?
if self._reply_queues and cmd != APP_CMD_PING:
- logger.debug(
- "[%s] _dispatch_payload[ALL]: req_id=%s cmd=%r active_queues=%s",
- self.name, req_id or "(none)", cmd or "(empty)",
- list(self._reply_queues.keys()),
- )
+ logger.debug("[%s] _dispatch_payload[ALL]: req_id=%s cmd=%r active_queues=%s", self.name, req_id or "(none)", cmd or "(empty)", list(self._reply_queues.keys()))
if req_id and self._reply_queues.get(req_id):
logger.debug(
- "[%s] _dispatch_payload: req_id=%s cmd=%r has_pending_ack=%s "
- "errcode=%s in_NON_RESPONSE=%s payload_keys=%s",
- self.name, req_id, cmd, self._reply_queues[req_id].pending_ack is not None,
- body_dict.get("errcode", "N/A") if body_dict is not None else "N/A",
- cmd in NON_RESPONSE_COMMANDS,
- list(payload.keys()),
+ "[%s] _dispatch_payload: req_id=%s cmd=%r has_pending_ack=%s errcode=%s in_NON_RESPONSE=%s payload_keys=%s", self.name, req_id, cmd,
+ self._reply_queues[req_id].pending_ack is not None, body_dict.get("errcode", "N/A") if body_dict is not None else "N/A", cmd in NON_RESPONSE_COMMANDS, list(payload.keys()),
)
-
- # aibot_respond_msg acks arrive with the inbound req_id and no/other cmd.
- # Reply-queue acks MUST be checked before _pending_responses so the
- # _send_reply_request path can't steal them.
+ # Reply-queue acks (inbound req_id, no/other cmd) MUST win over _pending_responses.
if req_id and cmd not in NON_RESPONSE_COMMANDS:
if self._resolve_reply_ack(req_id, payload):
return
if req_id in self._pending_responses:
- future = self._pending_responses.get(req_id)
+ future = self._pending_responses[req_id]
if future and not future.done():
future.set_result(payload)
return
-
if cmd in CALLBACK_COMMANDS:
await self._on_message(payload)
- return
- if cmd == APP_CMD_PING:
- return
- if cmd == APP_CMD_EVENT_CALLBACK:
- # "Kicked by server": another connection was established elsewhere.
- # Mirror the official SDK — suppress reconnect to avoid mutual kicking.
- body = payload.get("body") or {}
- if str(body.get("event_type") or "") == "disconnected_event":
- logger.warning(
- "[%s] Kicked by server (another WS connection established). "
- "Suppressing reconnect to avoid mutual kicking. "
- "Check for duplicate gateway instances.",
- self.name,
- )
+ elif cmd == APP_CMD_EVENT_CALLBACK:
+ # Kicked by server (another connection exists): suppress reconnect like the official SDK.
+ if str((payload.get("body") or {}).get("event_type") or "") == "disconnected_event":
+ logger.warning("[%s] Kicked by server (another WS connection established). Suppressing reconnect to avoid mutual kicking. Check for duplicate gateway instances.", self.name)
self._running = False
- return
-
- # Unrouted: if WeCom delivered group messages under an unknown cmd they
- # would land here, so log cmd + body keys at INFO.
- logger.info(
- "[%s] Unrouted websocket payload dropped: cmd=%r req_id=%s body_keys=%s",
- self.name, cmd or "(empty)", req_id or "(none)",
- list(body_dict.keys()) if body_dict is not None else None,
- )
+ elif cmd != APP_CMD_PING:
+ logger.info("[%s] Unrouted websocket payload dropped: cmd=%r req_id=%s body_keys=%s", self.name, cmd or "(empty)", req_id or "(none)", list(body_dict.keys()) if body_dict is not None else None)
def _fail_pending_responses(self, exc: Exception) -> None:
- """Fail all outstanding request futures."""
for req_id, future in list(self._pending_responses.items()):
if not future.done():
future.set_exception(exc)
self._pending_responses.pop(req_id, None)
- async def _send_json(self, payload: Dict[str, Any]) -> None:
- """Send a raw JSON frame over the active websocket."""
+ def _require_ws(self) -> None:
if not self._ws or self._ws.closed:
raise RuntimeError("WeCom websocket is not connected")
+
+ async def _send_json(self, payload: Dict[str, Any]) -> None:
+ self._require_ws()
await self._ws.send_json(payload)
async def _request(self, cmd: str, req_id: str, body: Dict[str, Any], timeout: float) -> Dict[str, Any]:
- future = asyncio.get_running_loop().create_future()
- self._pending_responses[req_id] = future
+ future = self._pending_responses[req_id] = asyncio.get_running_loop().create_future()
try:
await self._send_json({"cmd": cmd, "headers": {"req_id": req_id}, "body": body})
return await asyncio.wait_for(future, timeout=timeout)
@@ -511,21 +382,20 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
self._pending_responses.pop(req_id, None)
async def _send_request(self, cmd: str, body: Dict[str, Any], timeout: float = REQUEST_TIMEOUT_SECONDS) -> Dict[str, Any]:
- """Send a JSON request and await the correlated response."""
- if not self._ws or self._ws.closed:
- raise RuntimeError("WeCom websocket is not connected")
+ self._require_ws()
return await self._request(cmd, self._new_req_id(cmd), body, timeout)
- async def _send_reply_request(
- self, reply_req_id: str, body: Dict[str, Any], cmd: str = APP_CMD_RESPONSE, timeout: float = REQUEST_TIMEOUT_SECONDS,
- ) -> Dict[str, Any]:
+ async def _send_reply_request(self, reply_req_id: str, body: Dict[str, Any], cmd: str = APP_CMD_RESPONSE, timeout: float = REQUEST_TIMEOUT_SECONDS) -> Dict[str, Any]:
"""Send a reply frame correlated to an inbound callback req_id."""
- if not self._ws or self._ws.closed:
- raise RuntimeError("WeCom websocket is not connected")
- normalized_req_id = str(reply_req_id or "").strip()
- if not normalized_req_id:
+ self._require_ws()
+ return await self._request(cmd, self._require_reply_req_id(reply_req_id), body, timeout)
+
+ @staticmethod
+ def _require_reply_req_id(reply_req_id: str) -> str:
+ normalized = str(reply_req_id or "").strip()
+ if not normalized:
raise ValueError("reply_req_id is required")
- return await self._request(cmd, normalized_req_id, body, timeout)
+ return normalized
@staticmethod
def _new_req_id(prefix: str) -> str:
@@ -542,179 +412,113 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
try:
payload = json.loads(raw)
except json.JSONDecodeError:
- # WeCom sometimes sends unescaped control chars (raw newlines) inside
- # JSON strings; strict=False accepts them.
+ # WeCom sometimes sends raw control chars inside JSON strings; strict=False accepts them.
try:
text = raw if isinstance(raw, str) else raw.decode("utf-8", errors="replace")
payload = json.JSONDecoder(strict=False).decode(text)
logger.info("WeCom payload required strict=False fallback (len=%d)", raw_len)
except Exception as exc2:
- logger.warning(
- "Failed to parse WeCom payload (strict=False also failed): "
- "error=%s len=%d tail=%r",
- exc2, raw_len,
- raw[-100:] if isinstance(raw, (str, bytes)) and len(raw) > 100 else raw,
- )
+ tail = raw[-100:] if isinstance(raw, (str, bytes)) and len(raw) > 100 else raw
+ logger.warning("Failed to parse WeCom payload (strict=False also failed): error=%s len=%d tail=%r", exc2, raw_len, tail)
return None
except Exception as exc:
logger.warning("Failed to parse WeCom payload: error=%s len=%d", exc, raw_len)
return None
return payload if isinstance(payload, dict) else None
- # ------------------------------------------------------------------
- # Inbound message parsing
- # ------------------------------------------------------------------
-
async def _on_message(self, payload: Dict[str, Any]) -> None:
- """Process an inbound WeCom message callback event."""
body = payload.get("body")
if not isinstance(body, dict):
return
req_id = self._payload_req_id(payload)
msg_id = str(body.get("msgid") or req_id or uuid.uuid4().hex)
- sender = body.get("from") if isinstance(body.get("from"), dict) else {}
+ sender = _dict_or_empty(body, "from")
sender_id = str(sender.get("userid") or "").strip()
if self._dedup.is_duplicate(msg_id):
- # INFO (not debug): is_duplicate marks at check time, so a msgid
- # redelivered after a processing exception is dropped for the TTL —
- # a top suspect for intermittent group non-replies.
- logger.info(
- "[%s] Duplicate message %s ignored (dedup drop) req_id=%s sender=%r chattype=%r",
- self.name, msg_id, req_id, sender.get("userid") if sender else None, body.get("chattype"),
- )
+ # INFO: a msgid redelivered after a processing exception is dropped for the TTL.
+ logger.info("[%s] Duplicate message %s ignored (dedup drop) req_id=%s sender=%r chattype=%r", self.name, msg_id, req_id, sender.get("userid") if sender else None, body.get("chattype"))
return
_bounded_put(self._reply_req_ids, msg_id, req_id)
-
chat_id = str(body.get("chatid") or sender_id).strip()
- # Shape of every inbound callback at INFO: group frames may arrive with
- # a chattype other than the literal "group".
- logger.info(
- "[%s] Inbound callback: chattype=%r chatid=%r sender=%r msgtype=%r has_chatid=%s",
- self.name, body.get("chattype"), body.get("chatid"), sender_id, body.get("msgtype"), bool(body.get("chatid")),
- )
+ logger.info("[%s] Inbound callback: chattype=%r chatid=%r sender=%r msgtype=%r has_chatid=%s", self.name, body.get("chattype"), body.get("chatid"), sender_id, body.get("msgtype"), bool(body.get("chatid")))
if not chat_id:
logger.info("[%s] Missing chat id, skipping message; body_keys=%s", self.name, list(body.keys()))
return
-
is_group = str(body.get("chattype") or "").lower() == "group"
- if is_group:
- self._group_chat_ids.add(chat_id)
- if not self._is_group_allowed(chat_id, sender_id):
- logger.info(
- "[%s] Group message DROPPED by policy: chat=%s sender=%s group_policy=%r "
- "(set group_policy to 'open' or add to group_allow_from to receive)",
- self.name, chat_id, sender_id, self._group_policy,
- )
- return
- elif not self._is_dm_intake_allowed(sender_id):
- logger.info("[%s] DM sender %s blocked by policy", self.name, sender_id)
+ if not self._admit_inbound(is_group, chat_id, sender_id):
return
-
- # After policy checks: cache the req_id so proactive sends can fall back to
- # APP_CMD_RESPONSE (required for groups, where APP_CMD_SEND is blocked).
+ # Post-policy: cache req_id so sends can fall back to passive reply (required in groups).
self._remember_chat_req_id(chat_id, req_id)
-
text, reply_text = self._extract_text(body)
if is_group and text:
- # Strip leading @mention so "@Bot /approve" is recognized as "/approve".
- text = re.sub(r"^@\S+\s*", "", text).strip()
+ text = re.sub(r"^@\S+\s*", "", text).strip() # "@Bot /approve" -> "/approve"
media_urls, media_types = await self._extract_media(body)
message_type = self._derive_message_type(body, text, media_types)
has_reply_context = bool(reply_text and (text or media_urls))
- if not text and reply_text and not media_urls:
+ if reply_text and not has_reply_context: # quote-only message: the quote becomes the text
text = reply_text
if not text and not media_urls:
- logger.info(
- "[%s] Empty WeCom message skipped: is_group=%s chat=%s msgtype=%r",
- self.name, is_group, chat_id, body.get("msgtype"),
- )
+ logger.info("[%s] Empty WeCom message skipped: is_group=%s chat=%s msgtype=%r", self.name, is_group, chat_id, body.get("msgtype"))
return
-
- source = self.build_source(
- chat_id=chat_id, chat_type="group" if is_group else "dm", user_id=sender_id or None, user_name=sender_id or None,
- )
+ source = self.build_source(chat_id=chat_id, chat_type="group" if is_group else "dm", user_id=sender_id or None, user_name=sender_id or None)
event = MessageEvent(
- text=text, message_type=message_type, source=source, raw_message=payload, message_id=msg_id,
- media_urls=media_urls, media_types=media_types,
- reply_to_message_id=f"quote:{msg_id}" if has_reply_context else None,
- reply_to_text=reply_text if has_reply_context else None,
- timestamp=datetime.now(tz=timezone.utc),
+ text=text, message_type=message_type, source=source, raw_message=payload, message_id=msg_id, media_urls=media_urls, media_types=media_types,
+ reply_to_message_id=f"quote:{msg_id}" if has_reply_context else None, reply_to_text=reply_text if has_reply_context else None, timestamp=datetime.now(tz=timezone.utc),
)
-
- # Only plain text is batched (commands/media aren't split by the client),
- # EXCEPT an attachment-only message, which is held for the merge window so
- # the trailing text callback merges into the same event instead of
- # "interrupting" a run the attachment already spawned.
+ # Only plain text is batched, EXCEPT attachment-only messages, which are held so the
+ # trailing text callback merges instead of "interrupting" a run the attachment spawned.
has_pending_batch = self._text_batch_key(event) in self._pending_text_batches
is_attachment_only = bool(media_urls) and not (text or "").strip()
- if message_type == MessageType.TEXT and (self._text_batch_delay_seconds > 0 or has_pending_batch):
- self._enqueue_text_event(event)
- elif is_attachment_only and self._attachment_text_merge_delay_seconds > 0:
+ if (message_type == MessageType.TEXT and (self._text_batch_delay_seconds > 0 or has_pending_batch)) or (is_attachment_only and self._attachment_text_merge_delay_seconds > 0):
self._enqueue_text_event(event)
else:
await self.handle_message(event)
- # ------------------------------------------------------------------
- # Text message aggregation (handles WeCom client-side splits)
- # ------------------------------------------------------------------
+ def _admit_inbound(self, is_group: bool, chat_id: str, sender_id: str) -> bool:
+ """Apply group_policy / dm_policy at intake; logs and returns False when dropped."""
+ if not is_group:
+ allowed = self._is_dm_intake_allowed(sender_id)
+ if not allowed:
+ logger.info("[%s] DM sender %s blocked by policy", self.name, sender_id)
+ return allowed
+ self._group_chat_ids.add(chat_id)
+ allowed = self._is_group_allowed(chat_id, sender_id)
+ if not allowed:
+ logger.info(
+ "[%s] Group message DROPPED by policy: chat=%s sender=%s group_policy=%r (set group_policy to 'open' or add to group_allow_from to receive)",
+ self.name, chat_id, sender_id, self._group_policy,
+ )
+ return allowed
def _enqueue_text_event(self, event: MessageEvent) -> None:
- """Buffer an event and reset the flush timer.
-
- Merges both 4000-char client splits and the "attachment-only frame, then
- text frame" pair: once real text joins a buffered attachment the type is
- promoted to TEXT (and it inherits the text frame's quote context).
- """
- key = self._text_batch_key(event)
- existing = self._pending_text_batches.get(key)
- chunk_len = len(event.text or "")
- if existing is None:
- event._last_chunk_len = chunk_len # type: ignore[attr-defined]
- self._pending_text_batches[key] = event
- else:
- if event.text:
- existing.text = f"{existing.text}\n{event.text}" if existing.text else event.text
- existing._last_chunk_len = chunk_len # type: ignore[attr-defined]
- if event.media_urls:
- existing.media_urls.extend(event.media_urls)
- existing.media_types.extend(event.media_types)
- if event.text and (event.text or "").strip():
- existing.message_type = MessageType.TEXT
- if event.reply_to_text and not existing.reply_to_text:
- existing.reply_to_text = event.reply_to_text
- existing.reply_to_message_id = event.reply_to_message_id
-
- prior_task = self._pending_text_batch_tasks.get(key)
- if prior_task and not prior_task.done():
- prior_task.cancel()
- self._pending_text_batch_tasks[key] = asyncio.create_task(self._flush_text_batch(key))
+ """Buffer + reset the flush timer; real text joining a buffered attachment promotes it to TEXT and inherits the quote context."""
+ existing = self._pending_text_batches.get(self._text_batch_key(event))
+ super()._enqueue_text_event(event) # merge text/media + restart the flush timer
+ if existing is not None and event.text and event.text.strip():
+ existing.message_type = MessageType.TEXT
+ if event.reply_to_text and not existing.reply_to_text:
+ existing.reply_to_text = event.reply_to_text
+ existing.reply_to_message_id = event.reply_to_message_id
async def _flush_text_batch(self, key: str) -> None:
- """Wait for the quiet period then dispatch the aggregated text."""
current_task = asyncio.current_task()
try:
pending = self._pending_text_batches.get(key)
- last_len = getattr(pending, "_last_chunk_len", 0) if pending else 0
if pending and pending.media_urls and not (pending.text or "").strip():
delay = self._attachment_text_merge_delay_seconds # attachment-only: wait for text
- elif last_len >= self._SPLIT_THRESHOLD:
+ elif pending and getattr(pending, "_last_chunk_len", 0) >= self._SPLIT_THRESHOLD:
delay = self._text_batch_split_delay_seconds # continuation almost certain
else:
delay = self._text_batch_delay_seconds
await asyncio.sleep(delay)
- # Cancel-delivery race: if the sleep timer fired just before cancel(),
- # CancelledError is delivered at the NEXT await, after we'd have popped
- # the merged event — so the superseding task would find nothing.
- # This check is synchronous (no await between it and the pop).
+ # Cancel-delivery race: CancelledError lands at the NEXT await, so this identity check
+ # must stay synchronous (no await between it and the pop).
if self._pending_text_batch_tasks.get(key) is not current_task:
return
event = self._pending_text_batches.pop(key, None)
if not event:
return
- logger.info(
- "[WeCom] Flushing batch %s (%d chars, %d media)",
- key, len(event.text or ""), len(event.media_urls or []),
- )
+ logger.info("[WeCom] Flushing batch %s (%d chars, %d media)", key, len(event.text or ""), len(event.media_urls or []))
await self.handle_message(event)
finally:
if self._pending_text_batch_tasks.get(key) is current_task:
@@ -722,23 +526,15 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
@staticmethod
def _extract_text(body: Dict[str, Any]) -> Tuple[str, Optional[str]]:
- """Extract plain text and quoted text from a callback payload."""
- text_parts: List[str] = []
msgtype = str(body.get("msgtype") or "").lower()
if msgtype == "mixed":
items = _dict_or_empty(body, "mixed").get("msg_item")
- for item in items if isinstance(items, list) else []:
- if isinstance(item, dict) and str(item.get("msgtype") or "").lower() == "text":
- content = _content_of(item, "text")
- if content:
- text_parts.append(content)
- else:
- text_parts.append(_content_of(body, "text"))
- if msgtype == "voice":
- text_parts.append(_content_of(body, "voice"))
- if msgtype == "appmsg": # attachment title (filename)
- text_parts.append(str(_dict_or_empty(body, "appmsg").get("title") or "").strip())
-
+ text_parts = [_content_of(item, "text") for item in (items if isinstance(items, list) else []) if isinstance(item, dict) and str(item.get("msgtype") or "").lower() == "text"]
+ else: # voice transcript / appmsg attachment title (filename) follow the text; empties drop below
+ text_parts = [
+ _content_of(body, "text"), _content_of(body, "voice") if msgtype == "voice" else "",
+ str(_dict_or_empty(body, "appmsg").get("title") or "").strip() if msgtype == "appmsg" else "",
+ ]
quote = _dict_or_empty(body, "quote")
quote_type = str(quote.get("msgtype") or "").lower()
reply_text = _content_of(quote, quote_type) or None if quote_type in ("text", "voice") else None
@@ -746,7 +542,6 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
@staticmethod
def _derive_message_type(body: Dict[str, Any], text: str, media_types: List[str]) -> MessageType:
- """Choose the normalized inbound message type."""
if any(mtype.startswith(("application/", "text/")) for mtype in media_types):
return MessageType.DOCUMENT
if any(mtype.startswith("image/") for mtype in media_types):
@@ -755,97 +550,65 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
return MessageType.VOICE
return MessageType.TEXT
- # ------------------------------------------------------------------
- # Policy helpers
- # ------------------------------------------------------------------
-
@property
def enforces_own_access_policy(self) -> bool:
"""WeCom gates DM/group access at intake via dm_policy/group_policy."""
return True
def _open_dm_opted_in(self) -> bool:
- # Scoped reads: the default profile's allow-all flag must not leak into a
- # multiplexed secondary profile's admission gate.
- return any(
- (_get_scoped_secret(var, "") or "").lower() in {"true", "1", "yes"}
- for var in ("GATEWAY_ALLOW_ALL_USERS", "WECOM_ALLOW_ALL_USERS")
- )
+ # Scoped reads: default profile's allow-all flag must not leak into a multiplexed profile.
+ return any((_get_scoped_secret(var, "") or "").lower() in {"true", "1", "yes"} for var in ("GATEWAY_ALLOW_ALL_USERS", "WECOM_ALLOW_ALL_USERS"))
def _is_dm_allowed(self, sender_id: str) -> bool:
if self._dm_policy == "allowlist":
return _entry_matches(self._allow_from, sender_id)
- if self._dm_policy == "open":
- return self._open_dm_opted_in()
- return False
+ return self._dm_policy == "open" and self._open_dm_opted_in()
def _is_dm_intake_allowed(self, sender_id: str) -> bool:
principal = str(sender_id or "").strip()
- if not principal:
- return False
- if self._dm_policy == "pairing":
- return True
- return self._is_dm_allowed(principal)
+ return bool(principal) and (self._dm_policy == "pairing" or self._is_dm_allowed(principal))
def _is_group_allowed(self, chat_id: str, sender_id: str) -> bool:
- if self._group_policy in ("disabled", "pairing"):
- return False
- if self._group_policy == "allowlist" and not _entry_matches(self._group_allow_from, chat_id):
+ if self._group_policy in ("disabled", "pairing") or (self._group_policy == "allowlist" and not _entry_matches(self._group_allow_from, chat_id)):
return False
group_cfg = self._resolve_group_cfg(chat_id)
sender_allow = _coerce_list(group_cfg.get("allow_from") or group_cfg.get("allowFrom"))
return _entry_matches(sender_allow, sender_id) if sender_allow else True
def _resolve_group_cfg(self, chat_id: str) -> Dict[str, Any]:
+ """Exact key, then case-insensitive key, then ``"*"``; only dict values count."""
if not isinstance(self._groups, dict):
return {}
- if isinstance(self._groups.get(chat_id), dict):
- return self._groups[chat_id]
lowered = chat_id.lower()
- for key, value in self._groups.items():
- if isinstance(key, str) and key.lower() == lowered and isinstance(value, dict):
- return value
- wildcard = self._groups.get("*")
- return wildcard if isinstance(wildcard, dict) else {}
+ candidates = (self._groups.get(chat_id), next((v for k, v in self._groups.items() if isinstance(k, str) and k.lower() == lowered and isinstance(v, dict)), None), self._groups.get("*"))
+ return next((c for c in candidates if isinstance(c, dict)), {})
def _remember_chat_req_id(self, chat_id: str, req_id: str) -> None:
- """Cache the most recent inbound req_id per chat (bounded like _reply_req_ids).
-
- Fallback reply target for group sends (APP_CMD_SEND is blocked in groups).
- A fresh req_id also resurrects the chat's stream channel.
- """
+ """Cache the chat's latest inbound req_id; a fresh one also resurrects its stream channel."""
if _bounded_put(self._last_chat_req_ids, chat_id, req_id):
self._stream_expired_chats.discard(str(chat_id).strip())
def _reply_req_id_for_message(self, reply_to: Optional[str]) -> Optional[str]:
normalized = str(reply_to or "").strip()
- if not normalized or normalized.startswith("quote:"):
- return None
- return self._reply_req_ids.get(normalized)
+ return None if not normalized or normalized.startswith("quote:") else self._reply_req_ids.get(normalized)
- async def _force_reconnect_on_stale_subscription(self, errcode: int) -> None:
- """On 846609 (subscription lost) invalidate cached req_ids bound to the dead session.
+ def _cached_reply_req_id(self, chat_id: str, reply_to: Optional[str]) -> Optional[str]:
+ """Explicit reply_to mapping, else the chat's last inbound req_id."""
+ return self._reply_req_id_for_message(reply_to) or self._last_chat_req_ids.get(chat_id)
- Do NOT close the WS: that makes _listen_loop open a second connection,
- WeCom kicks it and invalidates the first — an infinite kick-reconnect
- loop. The server closes the WS itself and _listen_loop reconnects then.
- """
+ async def _force_reconnect_on_stale_subscription(self, errcode: int) -> None:
+ """On 846609 (subscription lost) drop req_ids bound to the dead session. Do NOT close the
+ WS: a second connection gets kicked and invalidates the first (infinite kick loop)."""
if errcode != STREAM_NOT_SUBSCRIBED_ERRCODE:
return
logger.warning("[%s] Got errcode %d (subscription lost) — clearing stale state", self.name, errcode)
self._last_chat_req_ids.clear()
self._reply_req_ids.clear()
- # ------------------------------------------------------------------
- # Outbound messaging
- # ------------------------------------------------------------------
-
@staticmethod
def _response_error(response: Dict[str, Any]) -> Optional[str]:
errcode = response.get("errcode", 0)
- if errcode in {0, None}:
- return None
- return f"WeCom errcode {errcode}: {response.get('errmsg') or 'unknown error'}"
+ return None if errcode in {0, None} else f"WeCom errcode {errcode}: {response.get('errmsg') or 'unknown error'}"
@classmethod
def _raise_for_wecom_error(cls, response: Dict[str, Any], operation: str) -> None:
@@ -853,123 +616,72 @@ class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, BasePl
if error:
raise RuntimeError(f"{operation} failed: {error}")
+ def _markdown_body(self, content: str) -> Dict[str, Any]:
+ return {"msgtype": "markdown", "markdown": {"content": content[:self.MAX_MESSAGE_LENGTH]}}
+
async def _send_reply_markdown(self, reply_req_id: str, content: str) -> Dict[str, Any]:
- response = await self._send_reply_request(
- reply_req_id, {"msgtype": "markdown", "markdown": {"content": content[:self.MAX_MESSAGE_LENGTH]}},
- )
+ response = await self._send_reply_request(reply_req_id, self._markdown_body(content))
self._raise_for_wecom_error(response, "send reply markdown")
return response
async def _send_proactive_markdown(self, chat_id: str, content: str) -> Dict[str, Any]:
- return await self._send_request(
- APP_CMD_SEND,
- {"chatid": chat_id, "msgtype": "markdown", "markdown": {"content": content[:self.MAX_MESSAGE_LENGTH]}},
- )
-
- async def send(
- self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
- ) -> SendResult:
- """Send markdown to a WeCom chat as a standalone message (never touches active streams).
+ return await self._send_request(APP_CMD_SEND, {"chatid": chat_id, **self._markdown_body(content)})
- Serialized per chat to stay under 30 msgs/min/chat (errcode 846607).
- ``metadata["is_approval_prompt"]`` routes through the control lane.
- """
+ async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
+ """Send standalone markdown (never touches active streams); serialized per chat for the 30 msgs/min
+ limit (846607). ``metadata["is_approval_prompt"]`` uses the control lane."""
if not chat_id:
return SendResult(success=False, error="chat_id is required")
- is_control = False
- force_proactive = False
- if metadata:
- is_control = metadata.pop("is_approval_prompt", False)
- # Approval *confirmations* must not consume the req_id the stream
- # consumer needs for resumed output. The initial approval *prompt*
- # still uses passive reply (required in groups).
- force_proactive = bool(metadata.pop("force_proactive_send", False))
- return await self._enqueue_chat_send(
- chat_id,
- lambda: self._send_inner(chat_id, content, reply_to, force_proactive=force_proactive),
- is_control=is_control,
- )
-
- async def _send_inner(
- self, chat_id: str, content: str, reply_to: Optional[str] = None, *, force_proactive: bool = False,
- ) -> SendResult:
- """Actual send logic, run under the per-chat queue.
-
- force_proactive: always use APP_CMD_SEND instead of passive reply
- (except in groups, where APP_CMD_SEND is blocked).
- """
+ metadata = metadata or {} # pops mutate the caller's dict on purpose (consumed flags)
+ is_control = metadata.pop("is_approval_prompt", False)
+ # Approval *confirmations* must not consume the req_id the stream consumer still needs.
+ force_proactive = bool(metadata.pop("force_proactive_send", False))
+ return await self._enqueue_chat_send(chat_id, lambda: self._send_inner(chat_id, content, reply_to, force_proactive=force_proactive), is_control=is_control)
+
+ async def _send_inner(self, chat_id: str, content: str, reply_to: Optional[str] = None, *, force_proactive: bool = False) -> SendResult:
+ """Send under the per-chat queue; force_proactive skips passive reply except in groups."""
try:
- reply_req_id = self._reply_req_id_for_message(reply_to)
- if not reply_req_id and chat_id in self._last_chat_req_ids:
- reply_req_id = self._last_chat_req_ids[chat_id]
- if force_proactive and chat_id not in self._group_chat_ids:
- reply_req_id = None
-
+ reply_req_id = None if force_proactive and chat_id not in self._group_chat_ids else self._cached_reply_req_id(chat_id, reply_to)
if reply_req_id:
try:
response = await self._send_reply_markdown(reply_req_id, content)
except (asyncio.TimeoutError, RuntimeError) as passive_err:
- # req_id may be stale after a WS reconnect — proactive send
- # doesn't depend on any prior req_id.
- logger.warning(
- "[%s] Passive reply failed (%s), falling back to proactive send",
- self.name, passive_err,
- )
+ # req_id may be stale after a reconnect — proactive send needs none.
+ logger.warning("[%s] Passive reply failed (%s), falling back to proactive send", self.name, passive_err)
response = await self._send_proactive_markdown(chat_id, content)
+ elif chat_id in self._group_chat_ids:
+ logger.warning("[%s] No cached req_id for group chat %s — cannot send (groups require passive reply via req_id)", self.name, chat_id)
+ return SendResult(success=False, error="No req_id available for group chat (passive reply required)")
else:
- if chat_id in self._group_chat_ids:
- logger.warning(
- "[%s] No cached req_id for group chat %s — "
- "cannot send (groups require passive reply via req_id)",
- self.name, chat_id,
- )
- return SendResult(success=False, error="No req_id available for group chat (passive reply required)")
response = await self._send_proactive_markdown(chat_id, content)
except asyncio.TimeoutError:
return SendResult(success=False, error="Timeout sending message to WeCom")
except Exception as exc:
logger.error("[%s] Send failed: %s", self.name, exc)
- # 846609 (subscription lost): clear stale req_ids so later sends don't
- # fail for minutes while the dead WS lingers.
- if str(STREAM_NOT_SUBSCRIBED_ERRCODE) in str(exc):
- asyncio.ensure_future(self._force_reconnect_on_stale_subscription(STREAM_NOT_SUBSCRIBED_ERRCODE))
- return SendResult(success=False, error=str(exc))
+ return self._send_failure(str(exc), str(STREAM_NOT_SUBSCRIBED_ERRCODE) in str(exc))
+ if error := self._response_error(response):
+ return self._send_failure(error, response.get("errcode", 0) == STREAM_NOT_SUBSCRIBED_ERRCODE)
+ return SendResult(success=True, message_id=self._payload_req_id(response) or uuid.uuid4().hex[:12], raw_response=response)
- error = self._response_error(response)
- if error:
- errcode = response.get("errcode", 0)
- if errcode == STREAM_NOT_SUBSCRIBED_ERRCODE:
- asyncio.ensure_future(self._force_reconnect_on_stale_subscription(errcode))
- return SendResult(success=False, error=error)
- return SendResult(
- success=True,
- message_id=self._payload_req_id(response) or uuid.uuid4().hex[:12],
- raw_response=response,
- )
+ def _send_failure(self, error: str, subscription_lost: bool) -> SendResult:
+ """Failed SendResult; on 846609 schedule the stale-req_id purge so later sends recover."""
+ if subscription_lost:
+ asyncio.ensure_future(self._force_reconnect_on_stale_subscription(STREAM_NOT_SUBSCRIBED_ERRCODE))
+ return SendResult(success=False, error=error)
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
- """Return minimal chat info."""
return {"name": chat_id, "type": "group" if chat_id and chat_id.lower().startswith("group") else "dm"}
-# ------------------------------------------------------------------
-# QR code scan flow for obtaining bot credentials
-# ------------------------------------------------------------------
-
_QR_GENERATE_URL = "https://work.weixin.qq.com/ai/qc/generate"
_QR_QUERY_URL = "https://work.weixin.qq.com/ai/qc/query_result"
_QR_CODE_PAGE = "https://work.weixin.qq.com/ai/qc/gen?source=hermes&scode="
-_QR_POLL_INTERVAL = 3 # seconds
-_QR_POLL_TIMEOUT = 300 # 5 minutes
+_QR_POLL_INTERVAL, _QR_POLL_TIMEOUT = 3, 300 # seconds (poll every 3s, give up after 5 minutes)
def qr_scan_for_bot_info(*, timeout_seconds: int = _QR_POLL_TIMEOUT) -> Optional[Dict[str, str]]:
- """Fetch a WeCom QR code, render it in the terminal, poll until scanned or timeout.
-
- Returns ``{"bot_id", "secret"}`` or None. The ``ai/qc/{generate,query_result}``
- endpoints back the admin-console bot-creation UI, not the public API, and
- may change without notice.
- """
+ """Fetch a WeCom QR code, render it, poll until scanned or timeout; ``{"bot_id", "secret"}`` or None.
+ The ``ai/qc/*`` endpoints back the admin console, not the public API, and may change."""
import urllib.request
import urllib.parse
@@ -978,109 +690,77 @@ def qr_scan_for_bot_info(*, timeout_seconds: int = _QR_POLL_TIMEOUT) -> Optional
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
+ def _fail(log_msg: str, detail: Any, shown: Any) -> None:
+ logger.error(log_msg, detail)
+ print(f" failed: {shown}")
+
print(" Connecting to WeCom...", end="", flush=True)
try:
raw = _get_json(f"{_QR_GENERATE_URL}?source=hermes", 15)
except Exception as exc:
- logger.error("WeCom QR: failed to fetch QR code: %s", exc)
- print(f" failed: {exc}")
- return None
- data = raw.get("data") or {}
- scode = str(data.get("scode") or "").strip()
- auth_url = str(data.get("auth_url") or "").strip()
+ return _fail("WeCom QR: failed to fetch QR code: %s", exc, exc)
+ scode, auth_url = (str((raw.get("data") or {}).get(k) or "").strip() for k in ("scode", "auth_url"))
if not scode or not auth_url:
- logger.error("WeCom QR: unexpected response format: %s", raw)
- print(" failed: unexpected response format")
- return None
- print(" done.")
-
- print()
- qr_rendered = False
+ return _fail("WeCom QR: unexpected response format: %s", raw, "unexpected response format")
+ print(" done.\n")
+ page_url = f"{_QR_CODE_PAGE}{urllib.parse.quote(scode)}"
try:
import qrcode as _qrcode
qr = _qrcode.QRCode()
qr.add_data(auth_url)
qr.make(fit=True)
qr.print_ascii(invert=True)
- qr_rendered = True
- except Exception:
- pass
- page_url = f"{_QR_CODE_PAGE}{urllib.parse.quote(scode)}"
- if qr_rendered:
print(f"\n Scan the QR code above, or open this URL directly:\n {page_url}")
- else:
+ except Exception:
print(f" Open this URL in WeCom on your phone:\n\n {page_url}\n")
print(" Tip: pip install qrcode to display a scannable QR code here next time")
- print()
- print(" Fetching configuration results...", end="", flush=True)
-
+ print("\n Fetching configuration results...", end="", flush=True)
deadline = time.monotonic() + timeout_seconds
query_url = f"{_QR_QUERY_URL}?scode={urllib.parse.quote(scode)}"
while time.monotonic() < deadline:
try:
result = _get_json(query_url, 10)
+ print(".", end="", flush=True) # progress dot on every poll
except Exception as exc:
logger.debug("WeCom QR poll error: %s", exc)
+ result = {}
+ result_data = result.get("data") or {}
+ if str(result_data.get("status") or "").lower() != "success":
time.sleep(_QR_POLL_INTERVAL)
continue
- print(".", end="", flush=True) # progress dot on every poll
- result_data = result.get("data") or {}
- if str(result_data.get("status") or "").lower() == "success":
+ bot_info = result_data.get("bot_info") or {}
+ bot_id, secret = str(bot_info.get("botid") or bot_info.get("bot_id") or "").strip(), str(bot_info.get("secret") or "").strip()
+ if bot_id and secret:
print()
- bot_info = result_data.get("bot_info") or {}
- bot_id = str(bot_info.get("botid") or bot_info.get("bot_id") or "").strip()
- secret = str(bot_info.get("secret") or "").strip()
- if bot_id and secret:
- return {"bot_id": bot_id, "secret": secret}
- logger.warning("WeCom QR: scan reported success but bot_info missing or incomplete: %s", result_data)
- print(
- " QR scan reported success but no bot credentials were returned.\n"
- " This usually means the bot was not actually created on the WeCom side.\n"
- " Falling back to manual credential entry."
- )
- return None
- time.sleep(_QR_POLL_INTERVAL)
-
- print()
- print(f" QR scan timed out ({timeout_seconds // 60} minutes). Please try again.")
+ return {"bot_id": bot_id, "secret": secret}
+ logger.warning("WeCom QR: scan reported success but bot_info missing or incomplete: %s", result_data)
+ print("\n QR scan reported success but no bot credentials were returned.\n This usually means the bot was not actually created on the WeCom side.\n Falling back to manual credential entry.")
+ return None
+ print(f"\n QR scan timed out ({timeout_seconds // 60} minutes). Please try again.")
return None
-# ──────────────────────────────────────────────────────────────────────────
-# Plugin glue: register() exposes both WeCom platforms (wecom + wecom_callback)
-# via the registry; env→PlatformConfig seeding stays in core.
-# ──────────────────────────────────────────────────────────────────────────
-
-
async def _send_via(adapter, chat_id, message, *, live: bool):
try:
result = await adapter.send(chat_id, message)
except Exception as e:
return {"error": f"WeCom live adapter send failed: {e}" if live else f"WeCom send failed: {e}"}
- if not result.success:
- return {"error": f"WeCom send failed: {result.error}"}
- return {"success": True, "platform": "wecom", "chat_id": chat_id, "message_id": result.message_id}
+ if result.success:
+ return {"success": True, "platform": "wecom", "chat_id": chat_id, "message_id": result.message_id}
+ return {"error": f"WeCom send failed: {result.error}"}
async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):
- """standalone_sender_fn: reuse the live gateway adapter when in-process, else
- open an ephemeral connection. WeCom allows ONE WebSocket per bot — a second
- connection kicks the first."""
+ """Reuse the live gateway adapter in-process, else connect ephemerally (WeCom allows ONE
+ WebSocket per bot — a second connection kicks the first)."""
try:
from gateway.run import _gateway_runner_ref
runner = _gateway_runner_ref()
+ adapter = runner.adapters.get(Platform.WECOM) if runner is not None else None
except Exception:
- runner = None
- if runner is not None:
- from gateway.platforms.base import Platform
adapter = None
- try:
- adapter = runner.adapters.get(Platform.WECOM)
- except Exception:
- pass
- if adapter is not None:
- return await _send_via(adapter, chat_id, message, live=True)
-
+ if adapter is not None:
+ return await _send_via(adapter, chat_id, message, live=True)
if not check_wecom_requirements():
return {"error": "WeCom requirements not met. Need aiohttp + WECOM_BOT_ID/SECRET."}
try:
@@ -1095,64 +775,61 @@ async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_f
return {"error": f"WeCom send failed: {e}"}
+_MANUAL_SETUP_STEPS = (
+ "1. Go to WeCom Application → Workspace → Smart Robot -> Create smart robots",
+ "2. Select API Mode",
+ "3. Copy the Bot ID and Secret from the bot's credentials info",
+ "4. The bot connects via WebSocket — no public endpoint needed",
+)
+# (menu label, env saves, (print level, message)...) per unauthorized-user choice; index 3 = skip
+_ACCESS_CHOICES = (
+ ("Enable open access (anyone can message the bot)", (("WECOM_DM_POLICY", "open"), ("GATEWAY_ALLOW_ALL_USERS", "true")),
+ (("warning", "Open access enabled — anyone can use your bot!"),)),
+ ("Use DM pairing (unknown users request access, you approve with 'hermes pairing approve')", (("WECOM_DM_POLICY", "pairing"),),
+ (("success", "DM pairing mode — users will receive a code to request access."), ("info", "Approve with: hermes pairing approve <platform> <code>"))),
+ ("Disable direct messages", (("WECOM_DM_POLICY", "disabled"),), (("warning", "Direct messages disabled."),)),
+ ("Skip for now (bot will deny all users until configured)", (), (("info", "Skipped — configure later with 'hermes gateway setup'"),)),
+)
+
+
def interactive_setup() -> None:
- """Interactive setup for WeCom — QR scan or manual credential input."""
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
from hermes_cli.setup import prompt_choice
- from hermes_cli.cli_output import (
- prompt, prompt_yes_no, print_header, print_info, print_success, print_warning,
- )
-
+ from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_info, print_success, print_warning
print_header("WeCom (Enterprise WeChat)")
- existing_bot_id = get_env_value("WECOM_BOT_ID")
- existing_secret = get_env_value("WECOM_SECRET")
- if existing_bot_id and existing_secret:
+ if get_env_value("WECOM_BOT_ID") and get_env_value("WECOM_SECRET"):
print_success("WeCom is already configured.")
if not prompt_yes_no("Reconfigure WeCom?", False):
return
-
- method_idx = prompt_choice(
- "How would you like to set up WeCom?",
- ["Scan QR code to obtain Bot ID and Secret automatically (recommended)", "Enter existing Bot ID and Secret manually"],
- 0,
- )
- bot_id = None
- secret = None
+ method_idx = prompt_choice("How would you like to set up WeCom?", ["Scan QR code to obtain Bot ID and Secret automatically (recommended)", "Enter existing Bot ID and Secret manually"], 0)
+ bot_id = secret = None
if method_idx == 0:
try:
- credentials = qr_scan_for_bot_info()
+ credentials = qr_scan_for_bot_info() or {}
except KeyboardInterrupt:
print_warning("WeCom setup cancelled.")
return
except Exception as exc:
print_warning(f"QR scan failed: {exc}")
- credentials = None
+ credentials = {}
if credentials:
- bot_id = credentials.get("bot_id", "")
- secret = credentials.get("secret", "")
+ bot_id, secret = credentials.get("bot_id", ""), credentials.get("secret", "")
print_success("✔ QR scan successful! Bot ID and Secret obtained.")
if not bot_id or not secret:
print_info("QR scan did not complete. Continuing with manual input.")
- bot_id = None
- secret = None
-
+ bot_id = secret = None
if not bot_id or not secret:
- print_info("1. Go to WeCom Application → Workspace → Smart Robot -> Create smart robots")
- print_info("2. Select API Mode")
- print_info("3. Copy the Bot ID and Secret from the bot's credentials info")
- print_info("4. The bot connects via WebSocket — no public endpoint needed")
- bot_id = prompt("Bot ID", password=False)
- if not bot_id:
- print_warning("Skipped — WeCom won't work without a Bot ID.")
- return
- secret = prompt("Secret", password=True)
- if not secret:
- print_warning("Skipped — WeCom won't work without a Secret.")
- return
-
+ for line in _MANUAL_SETUP_STEPS:
+ print_info(line)
+ creds = []
+ for label, password in (("Bot ID", False), ("Secret", True)):
+ creds.append(prompt(label, password=password))
+ if not creds[-1]:
+ print_warning(f"Skipped — WeCom won't work without a {label}.")
+ return
+ bot_id, secret = creds
save_env_value("WECOM_BOT_ID", bot_id)
save_env_value("WECOM_SECRET", secret)
-
print_info("The gateway DENIES all users by default for security.")
print_info("Enter user IDs to create an allowlist, or leave empty.")
allowed = prompt("Allowed user IDs (comma-separated, or empty)", password=False)
@@ -1160,48 +837,26 @@ def interactive_setup() -> None:
save_env_value("WECOM_ALLOWED_USERS", allowed.replace(" ", ""))
print_success("Saved — only these users can interact with the bot.")
else:
- access_idx = prompt_choice(
- "How should unauthorized users be handled?",
- [
- "Enable open access (anyone can message the bot)",
- "Use DM pairing (unknown users request access, you approve with 'hermes pairing approve')",
- "Disable direct messages",
- "Skip for now (bot will deny all users until configured)",
- ],
- 1,
- )
- if access_idx == 0:
- save_env_value("WECOM_DM_POLICY", "open")
- save_env_value("GATEWAY_ALLOW_ALL_USERS", "true")
- print_warning("Open access enabled — anyone can use your bot!")
- elif access_idx == 1:
- save_env_value("WECOM_DM_POLICY", "pairing")
- print_success("DM pairing mode — users will receive a code to request access.")
- print_info("Approve with: hermes pairing approve <platform> <code>")
- elif access_idx == 2:
- save_env_value("WECOM_DM_POLICY", "disabled")
- print_warning("Direct messages disabled.")
- else:
- print_info("Skipped — configure later with 'hermes gateway setup'")
-
- home = prompt("Home chat ID (optional, for cron/notifications)", password=False).strip()
- if home:
+ access_idx = prompt_choice("How should unauthorized users be handled?", [label for label, _, _ in _ACCESS_CHOICES], 1)
+ _, saves, messages = _ACCESS_CHOICES[access_idx if access_idx in (0, 1, 2) else 3]
+ for key, value in saves:
+ save_env_value(key, value)
+ for level, message in messages:
+ {"warning": print_warning, "success": print_success, "info": print_info}[level](message)
+ if home := prompt("Home chat ID (optional, for cron/notifications)", password=False).strip():
save_env_value("WECOM_HOME_CHANNEL", home)
print_success(f"Home channel set to {home}")
elif remove_env_value("WECOM_HOME_CHANNEL"):
print_info("Home channel cleared.")
-
print_success("💬 WeCom configured!")
def _is_connected(config) -> bool:
- """Connected when a bot_id is configured."""
- extra = getattr(config, "extra", {}) or {}
- return bool(extra.get("bot_id"))
+ return bool((getattr(config, "extra", {}) or {}).get("bot_id"))
def _callback_is_connected(config) -> bool:
- """Callback mode is connected when corp_id (or a multi-app `apps` block) is configured."""
+ """Callback mode: corp_id or a multi-app `apps` block."""
extra = getattr(config, "extra", {}) or {}
return bool(extra.get("corp_id") or extra.get("apps"))
@@ -1216,42 +871,18 @@ def _build_callback_adapter(config):
def register(ctx) -> None:
- """Plugin entry point — registers both WeCom platforms."""
+ common = dict(install_hint="Run `hermes setup` to install WeCom support.", emoji="💼", allow_update_command=True)
ctx.register_platform(
- name="wecom",
- label="WeCom (Enterprise WeChat)",
- adapter_factory=_build_adapter,
- check_fn=check_wecom_requirements,
- is_connected=_is_connected,
- validate_config=_is_connected,
- required_env=["WECOM_BOT_ID", "WECOM_SECRET"],
- install_hint="Run `hermes setup` to install WeCom support.",
- setup_fn=interactive_setup,
- allowed_users_env="WECOM_ALLOWED_USERS",
- allow_all_env="WECOM_ALLOW_ALL_USERS",
- cron_deliver_env_var="WECOM_HOME_CHANNEL",
- standalone_sender_fn=_standalone_send,
- max_message_length=4000,
- emoji="💼",
- allow_update_command=True,
- )
-
- from plugins.platforms.wecom.callback_adapter import (
- check_wecom_callback_requirements,
- ensure_wecom_callback_requirements,
+ name="wecom", label="WeCom (Enterprise WeChat)", adapter_factory=_build_adapter, check_fn=check_wecom_requirements,
+ is_connected=_is_connected, validate_config=_is_connected, required_env=["WECOM_BOT_ID", "WECOM_SECRET"],
+ setup_fn=interactive_setup, allowed_users_env="WECOM_ALLOWED_USERS", allow_all_env="WECOM_ALLOW_ALL_USERS",
+ cron_deliver_env_var="WECOM_HOME_CHANNEL", standalone_sender_fn=_standalone_send, max_message_length=4000, **common,
)
+ from plugins.platforms.wecom.callback_adapter import check_wecom_callback_requirements, ensure_wecom_callback_requirements
ctx.register_platform(
- name="wecom_callback",
- label="WeCom Callback (self-built apps)",
- adapter_factory=_build_callback_adapter,
- check_fn=check_wecom_callback_requirements,
- ensure_deps_fn=ensure_wecom_callback_requirements,
- is_connected=_callback_is_connected,
- validate_config=_callback_is_connected,
+ name="wecom_callback", label="WeCom Callback (self-built apps)", adapter_factory=_build_callback_adapter,
+ check_fn=check_wecom_callback_requirements, ensure_deps_fn=ensure_wecom_callback_requirements,
+ is_connected=_callback_is_connected, validate_config=_callback_is_connected,
required_env=["WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"],
- install_hint="Run `hermes setup` to install WeCom support.",
- allowed_users_env="WECOM_CALLBACK_ALLOWED_USERS",
- allow_all_env="WECOM_CALLBACK_ALLOW_ALL_USERS",
- emoji="💼",
- allow_update_command=True,
+ allowed_users_env="WECOM_CALLBACK_ALLOWED_USERS", allow_all_env="WECOM_CALLBACK_ALLOW_ALL_USERS", **common,
)
diff --git a/plugins/platforms/wecom/callback_adapter.py b/plugins/platforms/wecom/callback_adapter.py
index 5b69ad47fd1..e3dbecde9bd 100644
--- a/plugins/platforms/wecom/callback_adapter.py
+++ b/plugins/platforms/wecom/callback_adapter.py
@@ -1,10 +1,5 @@
-"""WeCom callback-mode adapter for self-built enterprise applications.
-
-WeCom POSTs encrypted XML to an HTTP endpoint; we decrypt, queue for the agent
-and ack immediately. Replies go out later via the proactive ``message/send``
-API with an access-token. Multiple apps per gateway are scoped by
-``corp_id:user_id`` to avoid cross-corp collisions.
-"""
+"""WeCom callback-mode adapter (self-built apps): decrypt POSTed XML, queue for the agent, ack at once;
+reply later via proactive ``message/send``. Multiple apps are scoped by ``corp_id:user_id``."""
from __future__ import annotations
@@ -17,7 +12,6 @@ from typing import Any, Dict, List, Optional
# Untrusted pre-auth bodies are parsed with defusedxml (billion-laughs / XXE).
try:
import defusedxml.ElementTree as ET
-
DEFUSEDXML_AVAILABLE = True
except ImportError:
ET = None # type: ignore[assignment]
@@ -25,7 +19,6 @@ except ImportError:
try:
from aiohttp import web
-
AIOHTTP_AVAILABLE = True
except ImportError:
web = None # type: ignore[assignment]
@@ -33,7 +26,6 @@ except ImportError:
try:
import httpx
-
HTTPX_AVAILABLE = True
except ImportError:
httpx = None # type: ignore[assignment]
@@ -45,16 +37,14 @@ from plugins.platforms.wecom.wecom_crypto import WXBizMsgCrypt, WeComCryptoError
logger = logging.getLogger(__name__)
-# None → aiohttp binds one socket per address family (IPv4 + IPv6); "0.0.0.0"
-# was unreachable on IPv6-only networks. Pin via WECOM_CALLBACK_HOST / extra.host.
-DEFAULT_HOST = None
+DEFAULT_HOST = None # dual-stack bind ("0.0.0.0" broke IPv6-only); pin via extra.host
DEFAULT_PORT = 8645
DEFAULT_PATH = "/wecom/callback"
-# Pre-auth body cap: callbacks are small encrypted XML envelopes (media is
-# out-of-band via MediaId), so 64 KB bounds unauthenticated work.
-_MAX_BODY = 65_536
+_MAX_BODY = 65_536 # pre-auth body cap: callbacks are small encrypted XML envelopes
ACCESS_TOKEN_TTL_SECONDS = 7200
MESSAGE_DEDUP_TTL_SECONDS = 300
+_SEND_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="
+_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
def check_wecom_callback_requirements() -> bool:
@@ -63,23 +53,23 @@ def check_wecom_callback_requirements() -> bool:
def ensure_wecom_callback_requirements() -> bool:
- """ACTIVE lazy-installer (``ensure_deps_fn``): installs ``defusedxml`` — the
- only non-core dep — when the passive probe fails, and rebinds module globals."""
+ """ACTIVE lazy-installer (``ensure_deps_fn``): installs ``defusedxml`` and rebinds globals."""
if check_wecom_callback_requirements():
return True
def _import() -> dict:
import defusedxml.ElementTree as _ET
-
return {"ET": _ET, "DEFUSEDXML_AVAILABLE": True}
try:
from tools.lazy_deps import ensure_and_bind
except Exception: # pragma: no cover — defensive
return False
- if not ensure_and_bind("platform.wecom_callback", _import, globals(), prompt=False):
- return False
- return check_wecom_callback_requirements()
+ return bool(ensure_and_bind("platform.wecom_callback", _import, globals(), prompt=False)) and check_wecom_callback_requirements()
+
+
+def _ack():
+ return web.Response(text="success", content_type="text/plain")
class WecomCallbackAdapter(BasePlatformAdapter):
@@ -91,12 +81,8 @@ class WecomCallbackAdapter(BasePlatformAdapter):
self._port = int(extra.get("port") or DEFAULT_PORT)
self._path = str(extra.get("path") or DEFAULT_PATH)
self._apps: List[Dict[str, Any]] = self._normalize_apps(extra)
- self._runner: Optional[web.AppRunner] = None
- self._site: Optional[web.TCPSite] = None
- self._app: Optional[web.Application] = None
- self._http_client: Optional[httpx.AsyncClient] = None
+ self._runner = self._site = self._app = self._http_client = self._poll_task = None
self._message_queue: asyncio.Queue[MessageEvent] = asyncio.Queue()
- self._poll_task: Optional[asyncio.Task] = None
self._seen_messages: Dict[str, float] = {}
self._user_app_map: Dict[str, str] = {}
self._access_tokens: Dict[str, Dict[str, Any]] = {}
@@ -111,14 +97,8 @@ class WecomCallbackAdapter(BasePlatformAdapter):
if isinstance(apps, list) and apps:
return [dict(app) for app in apps if isinstance(app, dict)]
if extra.get("corp_id"):
- return [{
- "name": extra.get("name") or "default",
- "corp_id": extra.get("corp_id", ""),
- "corp_secret": extra.get("corp_secret", ""),
- "agent_id": str(extra.get("agent_id", "")),
- "token": extra.get("token", ""),
- "encoding_aes_key": extra.get("encoding_aes_key", ""),
- }]
+ return [{"name": extra.get("name") or "default", "corp_id": extra.get("corp_id", ""), "corp_secret": extra.get("corp_secret", ""),
+ "agent_id": str(extra.get("agent_id", "")), "token": extra.get("token", ""), "encoding_aes_key": extra.get("encoding_aes_key", "")}]
return []
async def connect(self, *, is_reconnect: bool = False) -> bool:
@@ -129,7 +109,6 @@ class WecomCallbackAdapter(BasePlatformAdapter):
if not check_wecom_callback_requirements():
logger.warning("[WecomCallback] aiohttp/httpx not installed")
return False
-
try: # quick port-in-use check
with _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM) as sock:
sock.settimeout(1)
@@ -138,7 +117,6 @@ class WecomCallbackAdapter(BasePlatformAdapter):
return False
except (ConnectionRefusedError, OSError):
pass
-
try:
from gateway.platforms._http_client_limits import platform_httpx_limits
self._http_client = httpx.AsyncClient(timeout=20.0, limits=platform_httpx_limits())
@@ -158,10 +136,7 @@ class WecomCallbackAdapter(BasePlatformAdapter):
try:
await self._refresh_access_token(app)
except Exception as exc:
- logger.warning(
- "[WecomCallback] Initial token refresh failed for app '%s': %s",
- app.get("name", "default"), exc,
- )
+ logger.warning("[WecomCallback] Initial token refresh failed for app '%s': %s", app.get("name", "default"), exc)
return True
except Exception:
await self._cleanup()
@@ -185,61 +160,35 @@ class WecomCallbackAdapter(BasePlatformAdapter):
self._site = None
if self._runner:
await self._runner.cleanup()
- self._runner = None
- self._app = None
+ self._runner = self._app = None
if self._http_client:
await self._http_client.aclose()
- self._http_client = None
-
- async def send(
- self,
- chat_id: str,
- content: str,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
- ) -> SendResult:
+ self._http_client = None
+
+ async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
app = self._resolve_app_for_chat(chat_id)
- touser = chat_id.split(":", 1)[1] if ":" in chat_id else chat_id
try:
- payload = {
- "touser": touser,
- "msgtype": "text",
- "agentid": int(str(app.get("agent_id") or 0)),
- "text": {"content": content[:2048]},
- "safe": 0,
- }
+ payload = {"touser": chat_id.split(":", 1)[-1], "msgtype": "text", "agentid": int(str(app.get("agent_id") or 0)), "text": {"content": content[:2048]}, "safe": 0}
for _attempt in range(2):
token = await self._get_access_token(app)
- resp = await self._http_client.post(
- f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={token}",
- json=payload,
- )
+ resp = await self._http_client.post(f"{_SEND_URL}{token}", json=payload)
data = resp.json()
errcode = data.get("errcode")
- if errcode in {40001, 42001} and _attempt == 0:
- # Token rejected — evict so the next call fetches a fresh one.
- logger.warning(
- "[WecomCallback] Token rejected for app '%s' (errcode=%s), refreshing",
- app.get("name", "default"), errcode,
- )
+ if errcode in {40001, 42001} and _attempt == 0: # token rejected — evict so the retry fetches a fresh one
+ logger.warning("[WecomCallback] Token rejected for app '%s' (errcode=%s), refreshing", app.get("name", "default"), errcode)
self._access_tokens.pop(app["name"], None)
continue
- if errcode != 0:
- return SendResult(success=False, error=str(data))
- return SendResult(success=True, message_id=str(data.get("msgid", "")), raw_response=data)
+ return SendResult(success=True, message_id=str(data.get("msgid", "")), raw_response=data) if errcode == 0 else SendResult(success=False, error=str(data))
return SendResult(success=False, error="send failed after token refresh")
except Exception as exc:
return SendResult(success=False, error=str(exc))
def _resolve_app_for_chat(self, chat_id: str) -> Dict[str, Any]:
- """Pick the app associated with *chat_id*, falling back sensibly."""
app_name = self._user_app_map.get(chat_id)
if not app_name and ":" not in chat_id: # legacy bare user_id — unique match only
matching = [k for k in self._user_app_map if k.endswith(f":{chat_id}")]
- if len(matching) == 1:
- app_name = self._user_app_map.get(matching[0])
- app = self._get_app_by_name(app_name) if app_name else None
- return app or self._apps[0]
+ app_name = self._user_app_map.get(matching[0]) if len(matching) == 1 else app_name
+ return self._get_app_by_name(app_name) or self._apps[0]
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
return {"name": chat_id, "type": "dm"}
@@ -262,28 +211,23 @@ class WecomCallbackAdapter(BasePlatformAdapter):
async def _handle_callback(self, request: web.Request) -> web.Response:
"""POST endpoint — receive an encrypted message callback."""
msg_signature, timestamp, nonce = self._signature_params(request)
- # Explicit guard in addition to client_max_size (DoS / zip bombs).
- body_bytes = await request.read()
+ body_bytes = await request.read() # explicit guard in addition to client_max_size
if len(body_bytes) > _MAX_BODY:
logger.warning("[WecomCallback] Payload too large (%d bytes) — rejected", len(body_bytes))
return web.Response(status=413, text="payload too large")
body = body_bytes.decode("utf-8", errors="replace")
-
for app in self._apps:
try:
- decrypted = self._decrypt_request(app, body, msg_signature, timestamp, nonce)
- event = self._build_event(app, decrypted)
+ event = self._build_event(app, self._decrypt_request(app, body, msg_signature, timestamp, nonce))
if event is not None:
# WeCom retries callbacks on timeout → duplicate inbound messages.
if event.message_id and self._is_duplicate(event.message_id):
logger.debug("[WecomCallback] Duplicate MsgId %s, skipping", event.message_id)
- return web.Response(text="success", content_type="text/plain")
+ return _ack()
if event.source and event.source.user_id:
- map_key = self._user_app_key(str(app.get("corp_id") or ""), event.source.user_id)
- self._user_app_map[map_key] = app["name"]
+ self._user_app_map[self._user_app_key(str(app.get("corp_id") or ""), event.source.user_id)] = app["name"]
await self._message_queue.put(event)
- # Ack immediately — the reply arrives later via proactive message/send.
- return web.Response(text="success", content_type="text/plain")
+ return _ack() # ack immediately — the reply arrives later via proactive message/send
except WeComCryptoError:
continue
except Exception:
@@ -293,15 +237,12 @@ class WecomCallbackAdapter(BasePlatformAdapter):
@staticmethod
def _signature_params(request: web.Request):
- q = request.query
- return q.get("msg_signature", ""), q.get("timestamp", ""), q.get("nonce", "")
+ return tuple(request.query.get(k, "") for k in ("msg_signature", "timestamp", "nonce"))
def _is_duplicate(self, message_id: str) -> bool:
now = time.time()
- if message_id in self._seen_messages:
- if now - self._seen_messages[message_id] < MESSAGE_DEDUP_TTL_SECONDS:
- return True
- del self._seen_messages[message_id]
+ if now - self._seen_messages.get(message_id, float("-inf")) < MESSAGE_DEDUP_TTL_SECONDS:
+ return True
self._seen_messages[message_id] = now
if len(self._seen_messages) > 2000: # prune expired entries
cutoff = now - MESSAGE_DEDUP_TTL_SECONDS
@@ -309,7 +250,6 @@ class WecomCallbackAdapter(BasePlatformAdapter):
return False
async def _poll_loop(self) -> None:
- """Drain the message queue and dispatch to the gateway runner."""
while True:
event = await self._message_queue.get()
try:
@@ -326,52 +266,33 @@ class WecomCallbackAdapter(BasePlatformAdapter):
def _build_event(self, app: Dict[str, Any], xml_text: str) -> Optional[MessageEvent]:
root = ET.fromstring(xml_text)
msg_type = (root.findtext("MsgType") or "").lower()
- # Lifecycle events are silently acknowledged.
- if msg_type == "event" and (root.findtext("Event") or "").lower() in {"enter_agent", "subscribe"}:
- return None
- if msg_type not in {"text", "event"}:
+ # Lifecycle events (enter_agent/subscribe) and non-text types are silently acknowledged.
+ if msg_type not in {"text", "event"} or (msg_type == "event" and (root.findtext("Event") or "").lower() in {"enter_agent", "subscribe"}):
return None
-
user_id = root.findtext("FromUserName", default="")
corp_id = root.findtext("ToUserName", default=app.get("corp_id", ""))
- scoped_chat_id = self._user_app_key(corp_id, user_id)
- content = root.findtext("Content", default="").strip()
- if not content and msg_type == "event":
- content = "/start"
+ content = root.findtext("Content", default="").strip() or ("/start" if msg_type == "event" else "")
msg_id = root.findtext("MsgId") or f"{user_id}:{root.findtext('CreateTime', default='0')}"
- source = self.build_source(chat_id=scoped_chat_id, chat_name=user_id, chat_type="dm", user_id=user_id, user_name=user_id)
+ source = self.build_source(chat_id=self._user_app_key(corp_id, user_id), chat_name=user_id, chat_type="dm", user_id=user_id, user_name=user_id)
return MessageEvent(text=content, message_type=MessageType.TEXT, source=source, raw_message=xml_text, message_id=msg_id)
def _crypt_for_app(self, app: Dict[str, Any]) -> WXBizMsgCrypt:
- return WXBizMsgCrypt(
- token=str(app.get("token") or ""),
- encoding_aes_key=str(app.get("encoding_aes_key") or ""),
- receive_id=str(app.get("corp_id") or ""),
- )
+ return WXBizMsgCrypt(token=str(app.get("token") or ""), encoding_aes_key=str(app.get("encoding_aes_key") or ""), receive_id=str(app.get("corp_id") or ""))
def _get_app_by_name(self, name: Optional[str]) -> Optional[Dict[str, Any]]:
return next((app for app in self._apps if app.get("name") == name), None) if name else None
async def _get_access_token(self, app: Dict[str, Any]) -> str:
cached = self._access_tokens.get(app["name"])
- now = time.time()
- if cached and cached.get("expires_at", 0) > now + 60:
- return cached["token"]
- return await self._refresh_access_token(app)
+ return cached["token"] if cached and cached.get("expires_at", 0) > time.time() + 60 else await self._refresh_access_token(app)
async def _refresh_access_token(self, app: Dict[str, Any]) -> str:
- resp = await self._http_client.get(
- "https://qyapi.weixin.qq.com/cgi-bin/gettoken",
- params={"corpid": app.get("corp_id"), "corpsecret": app.get("corp_secret")},
- )
+ resp = await self._http_client.get(_TOKEN_URL, params={"corpid": app.get("corp_id"), "corpsecret": app.get("corp_secret")})
data = resp.json()
if data.get("errcode") != 0:
raise RuntimeError(f"WeCom token refresh failed: {data}")
token = data["access_token"]
expires_in = int(data.get("expires_in", ACCESS_TOKEN_TTL_SECONDS))
self._access_tokens[app["name"]] = {"token": token, "expires_at": time.time() + expires_in}
- logger.info(
- "[WecomCallback] Token refreshed for app '%s' (corp=%s), expires in %ss",
- app.get("name", "default"), app.get("corp_id", ""), expires_in,
- )
+ logger.info("[WecomCallback] Token refreshed for app '%s' (corp=%s), expires in %ss", app.get("name", "default"), app.get("corp_id", ""), expires_in)
return token
diff --git a/plugins/platforms/wecom/media.py b/plugins/platforms/wecom/media.py
index f31b45c0858..ba3bfb0da3e 100644
--- a/plugins/platforms/wecom/media.py
+++ b/plugins/platforms/wecom/media.py
@@ -1,8 +1,5 @@
-"""WeCom media: inbound attachment caching and outbound upload/send.
-
-Mixed into :class:`WeComAdapter`. Outbound media goes through the chunked
-``aibot_upload_media_*`` flow and is then sent natively (image/video/voice/file).
-"""
+"""WeCom media mixin: inbound attachment caching; outbound chunked ``aibot_upload_media_*`` upload then
+native send (image/video/voice/file)."""
from __future__ import annotations
@@ -35,62 +32,54 @@ UPLOAD_CHUNK_SIZE = 512 * 1024
MAX_UPLOAD_CHUNKS = 100
VOICE_SUPPORTED_MIMES = {"audio/amr"}
+_IMAGE_MAGIC = ((b"\x89PNG\r\n\x1a\n", ".png"), (b"\xff\xd8\xff", ".jpg"), ((b"GIF87a", b"GIF89a"), ".gif"))
+_MIME_PREFIX_KINDS = (("image/", "image"), ("video/", "video"), ("audio/", "voice"))
+# type -> (max bytes, Chinese label, human cap) for the "downgrade to file" notice
+_TYPE_LIMITS = {"image": (IMAGE_MAX_BYTES, "图片", "10MB"), "video": (VIDEO_MAX_BYTES, "视频", "10MB"), "voice": (VOICE_MAX_BYTES, "语音", "2MB")}
+
def _size_verdict(final_type: str, *, reject: Optional[str] = None, downgrade: Optional[str] = None) -> Dict[str, Any]:
- return {
- "final_type": final_type,
- "rejected": reject is not None,
- "reject_reason": reject,
- "downgraded": downgrade is not None,
- "downgrade_note": downgrade,
- }
+ return {"final_type": final_type, "rejected": reject is not None, "reject_reason": reject, "downgraded": downgrade is not None, "downgrade_note": downgrade}
-class WeComMediaMixin:
- """Media helpers for WeComAdapter (expects ``_http_client``, ``_send_request``,
- ``_send_reply_request``, ``send``, ``_reply_req_id_for_message``,
- ``_last_chat_req_ids``, ``_stream_expired_chats``, ``_find_active_turn_for_chat``)."""
+def _dict_at(container: Dict[str, Any], key: str) -> Dict[str, Any]:
+ return container.get(key) if isinstance(container.get(key), dict) else {}
+
- # ── Inbound ──────────────────────────────────────────────────────────
+def _media_body(media_type: str, media_id: str) -> Dict[str, Any]:
+ return {"msgtype": media_type, media_type: {"media_id": media_id}}
+
+
+class WeComMediaMixin:
+ """Media helpers mixed into WeComAdapter (uses its transport, req_id cache and stream registry)."""
async def _extract_media(self, body: Dict[str, Any]) -> Tuple[List[str], List[str]]:
- """Best-effort extraction of inbound media to local cache paths."""
refs: List[Tuple[str, Dict[str, Any]]] = []
msgtype = str(body.get("msgtype") or "").lower()
def _ref(kind: str, container: Dict[str, Any]) -> bool:
- if isinstance(container.get(kind), dict):
+ found = isinstance(container.get(kind), dict)
+ if found:
refs.append((kind, container[kind]))
- return True
- return False
+ return found
if msgtype == "mixed":
- mixed = body.get("mixed") if isinstance(body.get("mixed"), dict) else {}
- items = mixed.get("msg_item") if isinstance(mixed.get("msg_item"), list) else []
- for item in items:
+ mixed = _dict_at(body, "mixed")
+ for item in mixed.get("msg_item") if isinstance(mixed.get("msg_item"), list) else []:
if isinstance(item, dict) and str(item.get("msgtype") or "").lower() == "image":
_ref("image", item)
else:
_ref("image", body)
if msgtype == "file":
_ref("file", body)
- # appmsg = WeCom AI Bot attachments (PDF/Word/Excel)
- if msgtype == "appmsg" and isinstance(body.get("appmsg"), dict):
+ if msgtype == "appmsg" and isinstance(body.get("appmsg"), dict): # AI Bot attachments (PDF/Word/Excel)
_ref("file", body["appmsg"]) or _ref("image", body["appmsg"])
-
- quote = body.get("quote") if isinstance(body.get("quote"), dict) else {}
+ quote = _dict_at(body, "quote")
quote_type = str(quote.get("msgtype") or "").lower()
if quote_type in ("image", "file"):
_ref(quote_type, quote)
-
- media_paths: List[str] = []
- media_types: List[str] = []
- for kind, ref in refs:
- cached = await self._cache_media(kind, ref)
- if cached:
- media_paths.append(cached[0])
- media_types.append(cached[1])
- return media_paths, media_types
+ cached = [c for c in [await self._cache_media(kind, ref) for kind, ref in refs] if c]
+ return [c[0] for c in cached], [c[1] for c in cached]
async def _cache_media(self, kind: str, media: Dict[str, Any]) -> Optional[Tuple[str, str]]:
"""Cache an inbound image/file reference (inline base64 or URL) to local storage."""
@@ -100,37 +89,30 @@ class WeComMediaMixin:
except Exception as exc:
logger.debug("[%s] Failed to decode %s base64 media: %s", self.name, kind, exc)
return None
- if kind == "image":
- ext = self._detect_image_ext(raw)
- return self._cache_image(raw, ext, self._mime_for_ext(ext, fallback="image/jpeg"), "")
filename = str(media.get("filename") or media.get("name") or "wecom_file")
- return cache_document_from_bytes(raw, filename), mimetypes.guess_type(filename)[0] or "application/octet-stream"
-
+ return self._store_media(kind, raw, self._detect_image_ext(raw), "", filename, mimetypes.guess_type(filename)[0] or "application/octet-stream", "")
url = str(media.get("url") or "").strip()
if not url:
return None
+ aes_key = str(media.get("aeskey") or "").strip()
try:
+ step = "download"
raw, headers = await self._download_remote_bytes(url, max_bytes=ABSOLUTE_MAX_BYTES)
+ step = "decrypt"
+ raw = self._decrypt_file_bytes(raw, aes_key) if aes_key else raw
except Exception as exc:
- logger.debug("[%s] Failed to download %s from %s: %s", self.name, kind, url, exc)
+ logger.debug("[%s] Failed to %s %s from %s: %s", self.name, step, kind, url, exc)
return None
- aes_key = str(media.get("aeskey") or "").strip()
- if aes_key:
- try:
- raw = self._decrypt_file_bytes(raw, aes_key)
- except Exception as exc:
- logger.debug("[%s] Failed to decrypt %s from %s: %s", self.name, kind, url, exc)
- return None
content_type = str(headers.get("content-type") or "").split(";", 1)[0].strip() or "application/octet-stream"
- if kind == "image":
- ext = self._guess_extension(url, content_type, fallback=self._detect_image_ext(raw))
- return self._cache_image(raw, ext, content_type or self._mime_for_ext(ext, fallback="image/jpeg"), f" from {url}")
- filename = self._guess_filename(url, headers.get("content-disposition"), content_type)
- return cache_document_from_bytes(raw, filename), content_type
+ ext = self._guess_extension(url, content_type, fallback=self._detect_image_ext(raw))
+ return self._store_media(kind, raw, ext, content_type, self._guess_filename(url, headers.get("content-disposition"), content_type), content_type, f" from {url}")
- def _cache_image(self, raw: bytes, ext: str, mime: str, origin: str) -> Optional[Tuple[str, str]]:
+ def _store_media(self, kind, raw, ext, image_mime, filename, doc_mime, origin) -> Optional[Tuple[str, str]]:
+ """Cache bytes as an image (``kind == "image"``) or a document; returns (path, mime)."""
+ if kind != "image":
+ return cache_document_from_bytes(raw, filename), doc_mime
try:
- return cache_image_from_bytes(raw, ext), mime
+ return cache_image_from_bytes(raw, ext), image_mime or self._mime_for_ext(ext, fallback="image/jpeg")
except ValueError as exc:
logger.warning("[%s] Rejected non-image bytes%s: %s", self.name, origin, exc)
return None
@@ -141,15 +123,8 @@ class WeComMediaMixin:
@staticmethod
def _detect_image_ext(data: bytes) -> str:
- if data.startswith(b"\x89PNG\r\n\x1a\n"):
- return ".png"
- if data.startswith(b"\xff\xd8\xff"):
- return ".jpg"
- if data.startswith((b"GIF87a", b"GIF89a")):
- return ".gif"
- if data.startswith(b"RIFF") and data[8:12] == b"WEBP":
- return ".webp"
- return ".jpg"
+ webp = ".webp" if data.startswith(b"RIFF") and data[8:12] == b"WEBP" else ".jpg"
+ return next((ext for magic, ext in _IMAGE_MAGIC if data.startswith(magic)), webp)
@staticmethod
def _mime_for_ext(ext: str, fallback: str = "application/octet-stream") -> str:
@@ -162,14 +137,11 @@ class WeComMediaMixin:
@staticmethod
def _guess_filename(url: str, content_disposition: Optional[str], content_type: str) -> str:
- if content_disposition:
- match = re.search(r'filename="?([^";]+)"?', content_disposition)
- if match:
- return match.group(1)
+ match = re.search(r'filename="?([^";]+)"?', content_disposition or "")
+ if match:
+ return match.group(1)
name = Path(urlparse(url).path).name or "document"
- if "." not in name:
- name = f"{name}{mimetypes.guess_extension(content_type) or '.bin'}"
- return name
+ return name if "." in name else f"{name}{mimetypes.guess_extension(content_type) or '.bin'}"
@staticmethod
def _decrypt_file_bytes(encrypted_data: bytes, aes_key: str) -> bytes:
@@ -177,9 +149,7 @@ class WeComMediaMixin:
raise ValueError("encrypted_data is empty")
if not aes_key:
raise ValueError("aes_key is required")
- # WeCom doesn't pad base64 keys; add padding if needed
- aes_key = aes_key + '=' * ((4 - len(aes_key) % 4) % 4)
- key = base64.b64decode(aes_key)
+ key = base64.b64decode(aes_key + '=' * ((4 - len(aes_key) % 4) % 4)) # WeCom doesn't pad base64 keys
if len(key) != 32:
raise ValueError(f"Invalid WeCom AES key length: expected 32 bytes, got {len(key)}")
try:
@@ -199,67 +169,41 @@ class WeComMediaMixin:
from gateway.platforms.base import _ssrf_redirect_guard
from tools.url_safety import create_ssrf_safe_async_client, is_safe_url
from plugins.platforms.wecom import adapter as _adapter_mod
-
if not is_safe_url(url):
raise ValueError(f"Blocked unsafe URL (SSRF protection): {url[:80]}")
if not _adapter_mod.HTTPX_AVAILABLE:
raise RuntimeError("httpx is required for WeCom media download")
-
- client = self._http_client or create_ssrf_safe_async_client(
- timeout=30.0, follow_redirects=True, event_hooks={"response": [_ssrf_redirect_guard]},
- )
- created_client = client is not self._http_client
+ client = self._http_client or create_ssrf_safe_async_client(timeout=30.0, follow_redirects=True, event_hooks={"response": [_ssrf_redirect_guard]})
try:
- async with client.stream(
- "GET", url, headers={"User-Agent": "HermesAgent/1.0", "Accept": "*/*"},
- ) as response:
+ async with client.stream("GET", url, headers={"User-Agent": "HermesAgent/1.0", "Accept": "*/*"}) as response:
response.raise_for_status()
headers = {key.lower(): value for key, value in response.headers.items()}
content_length = headers.get("content-length")
if content_length and content_length.isdigit() and int(content_length) > max_bytes:
- raise ValueError(
- f"Remote media exceeds WeCom limit: {int(content_length)} bytes > {max_bytes} bytes"
- )
+ raise ValueError(f"Remote media exceeds WeCom limit: {int(content_length)} bytes > {max_bytes} bytes")
data = bytearray()
async for chunk in response.aiter_bytes():
data.extend(chunk)
if len(data) > max_bytes:
- raise ValueError(
- f"Remote media exceeds WeCom limit while downloading: {len(data)} bytes > {max_bytes} bytes"
- )
+ raise ValueError(f"Remote media exceeds WeCom limit while downloading: {len(data)} bytes > {max_bytes} bytes")
return bytes(data), headers
finally:
- if created_client:
+ if client is not self._http_client:
await client.aclose()
- # ── Outbound classification ──────────────────────────────────────────
-
@staticmethod
def _guess_mime_type(filename: str) -> str:
- mime_type = mimetypes.guess_type(filename)[0]
- if mime_type:
- return mime_type
- if Path(filename).suffix.lower() == ".amr":
- return "audio/amr"
- return "application/octet-stream"
+ return mimetypes.guess_type(filename)[0] or ("audio/amr" if Path(filename).suffix.lower() == ".amr" else "application/octet-stream")
@staticmethod
def _normalize_content_type(content_type: str, filename: str) -> str:
normalized = str(content_type or "").split(";", 1)[0].strip().lower()
- if not normalized or normalized in {"application/octet-stream", "text/plain"}:
- return WeComMediaMixin._guess_mime_type(filename)
- return normalized
+ return normalized if normalized and normalized not in {"application/octet-stream", "text/plain"} else WeComMediaMixin._guess_mime_type(filename)
@staticmethod
def _detect_wecom_media_type(content_type: str) -> str:
mime_type = str(content_type or "").strip().lower()
- if mime_type.startswith("image/"):
- return "image"
- if mime_type.startswith("video/"):
- return "video"
- if mime_type.startswith("audio/") or mime_type == "application/ogg":
- return "voice"
- return "file"
+ return "voice" if mime_type == "application/ogg" else next((kind for prefix, kind in _MIME_PREFIX_KINDS if mime_type.startswith(prefix)), "file")
@staticmethod
def _apply_file_size_limits(file_size: int, detected_type: str, content_type: Optional[str] = None) -> Dict[str, Any]:
@@ -267,21 +211,12 @@ class WeComMediaMixin:
normalized_type = str(detected_type or "file").lower()
normalized_content_type = str(content_type or "").strip().lower()
if file_size > ABSOLUTE_MAX_BYTES:
- return _size_verdict(normalized_type, reject=(
- f"文件大小 {file_size_mb:.2f}MB 超过了企业微信允许的最大限制 20MB,无法发送。"
- "请尝试压缩文件或减小文件大小。"
- ))
- if normalized_type == "image" and file_size > IMAGE_MAX_BYTES:
- return _size_verdict("file", downgrade=f"图片大小 {file_size_mb:.2f}MB 超过 10MB 限制,已转为文件格式发送")
- if normalized_type == "video" and file_size > VIDEO_MAX_BYTES:
- return _size_verdict("file", downgrade=f"视频大小 {file_size_mb:.2f}MB 超过 10MB 限制,已转为文件格式发送")
- if normalized_type == "voice":
- if normalized_content_type and normalized_content_type not in VOICE_SUPPORTED_MIMES:
- return _size_verdict("file", downgrade=(
- f"语音格式 {normalized_content_type} 不支持,企微仅支持 AMR 格式,已转为文件格式发送"
- ))
- if file_size > VOICE_MAX_BYTES:
- return _size_verdict("file", downgrade=f"语音大小 {file_size_mb:.2f}MB 超过 2MB 限制,已转为文件格式发送")
+ return _size_verdict(normalized_type, reject=(f"文件大小 {file_size_mb:.2f}MB 超过了企业微信允许的最大限制 20MB,无法发送。" "请尝试压缩文件或减小文件大小。"))
+ if normalized_type == "voice" and normalized_content_type and normalized_content_type not in VOICE_SUPPORTED_MIMES:
+ return _size_verdict("file", downgrade=f"语音格式 {normalized_content_type} 不支持,企微仅支持 AMR 格式,已转为文件格式发送")
+ max_bytes, label, cap = _TYPE_LIMITS.get(normalized_type, (None, "", ""))
+ if max_bytes is not None and file_size > max_bytes:
+ return _size_verdict("file", downgrade=f"{label}大小 {file_size_mb:.2f}MB 超过 {cap} 限制,已转为文件格式发送")
return _size_verdict(normalized_type)
@staticmethod
@@ -294,77 +229,50 @@ class WeComMediaMixin:
raise ValueError("media source is required")
if re.fullmatch(r"<[^>\n]+>", source):
raise ValueError(f"Media placeholder was not replaced with a real file path: {source}")
-
parsed = urlparse(source)
if parsed.scheme in {"http", "https"}:
data, headers = await self._download_remote_bytes(source, max_bytes=ABSOLUTE_MAX_BYTES)
- content_disposition = headers.get("content-disposition")
- resolved_name = file_name or self._guess_filename(source, content_disposition, headers.get("content-type", ""))
- content_type = self._normalize_content_type(headers.get("content-type", ""), resolved_name)
- return data, content_type, resolved_name
-
+ resolved_name = file_name or self._guess_filename(source, headers.get("content-disposition"), headers.get("content-type", ""))
+ return data, self._normalize_content_type(headers.get("content-type", ""), resolved_name), resolved_name
local_path = Path(unquote(parsed.path) if parsed.scheme == "file" else source).expanduser()
- if not local_path.is_absolute():
- local_path = (Path.cwd() / local_path).resolve()
- if not local_path.exists() or not local_path.is_file():
+ local_path = local_path if local_path.is_absolute() else (Path.cwd() / local_path).resolve()
+ if not local_path.is_file():
raise FileNotFoundError(f"Media file not found: {local_path}")
- data = local_path.read_bytes()
resolved_name = file_name or local_path.name
- return data, self._normalize_content_type("", resolved_name), resolved_name
+ return local_path.read_bytes(), self._normalize_content_type("", resolved_name), resolved_name
async def _prepare_outbound_media(self, media_source: str, file_name: Optional[str] = None) -> Dict[str, Any]:
data, content_type, resolved_name = await self._load_outbound_media(media_source, file_name=file_name)
detected_type = self._detect_wecom_media_type(content_type)
- size_check = self._apply_file_size_limits(len(data), detected_type, content_type)
- return {"data": data, "content_type": content_type, "file_name": resolved_name, "detected_type": detected_type, **size_check}
+ return {"data": data, "content_type": content_type, "file_name": resolved_name, "detected_type": detected_type, **self._apply_file_size_limits(len(data), detected_type, content_type)}
- # ── Outbound upload + send ───────────────────────────────────────────
+ async def _checked_request(self, cmd: str, body: Dict[str, Any], operation: str) -> Dict[str, Any]:
+ self._raise_for_wecom_error(response := await self._send_request(cmd, body), operation)
+ return response
async def _upload_media_bytes(self, data: bytes, media_type: str, filename: str) -> Dict[str, Any]:
if not data:
raise ValueError("Cannot upload empty media")
- total_size = len(data)
- total_chunks = (total_size + UPLOAD_CHUNK_SIZE - 1) // UPLOAD_CHUNK_SIZE
+ total_size, total_chunks = len(data), (len(data) + UPLOAD_CHUNK_SIZE - 1) // UPLOAD_CHUNK_SIZE
if total_chunks > MAX_UPLOAD_CHUNKS:
raise ValueError(f"File too large: {total_chunks} chunks exceeds maximum of {MAX_UPLOAD_CHUNKS} chunks")
-
- init_response = await self._send_request(APP_CMD_UPLOAD_MEDIA_INIT, {
- "type": media_type, "filename": filename, "total_size": total_size, "total_chunks": total_chunks,
- "md5": hashlib.md5(data).hexdigest(),
- })
- self._raise_for_wecom_error(init_response, "media upload init")
- init_body = init_response.get("body") if isinstance(init_response.get("body"), dict) else {}
- upload_id = str(init_body.get("upload_id") or "").strip()
+ init_payload = {"type": media_type, "filename": filename, "total_size": total_size, "total_chunks": total_chunks, "md5": hashlib.md5(data).hexdigest()}
+ init_response = await self._checked_request(APP_CMD_UPLOAD_MEDIA_INIT, init_payload, "media upload init")
+ upload_id = str(_dict_at(init_response, "body").get("upload_id") or "").strip()
if not upload_id:
raise RuntimeError(f"media upload init failed: missing upload_id in response {init_response}")
-
- for chunk_index, start in enumerate(range(0, total_size, UPLOAD_CHUNK_SIZE)):
- chunk_response = await self._send_request(APP_CMD_UPLOAD_MEDIA_CHUNK, {
- "upload_id": upload_id,
- "chunk_index": chunk_index, # official SDK uses 0-based chunk indexes
- "base64_data": base64.b64encode(data[start : start + UPLOAD_CHUNK_SIZE]).decode("ascii"),
- })
- self._raise_for_wecom_error(chunk_response, f"media upload chunk {chunk_index}")
-
- finish_response = await self._send_request(APP_CMD_UPLOAD_MEDIA_FINISH, {"upload_id": upload_id})
- self._raise_for_wecom_error(finish_response, "media upload finish")
- finish_body = finish_response.get("body") if isinstance(finish_response.get("body"), dict) else {}
+ for chunk_index, start in enumerate(range(0, total_size, UPLOAD_CHUNK_SIZE)): # official SDK uses 0-based chunk indexes
+ chunk_b64 = base64.b64encode(data[start : start + UPLOAD_CHUNK_SIZE]).decode("ascii")
+ await self._checked_request(APP_CMD_UPLOAD_MEDIA_CHUNK, {"upload_id": upload_id, "chunk_index": chunk_index, "base64_data": chunk_b64}, f"media upload chunk {chunk_index}")
+ finish_response = await self._checked_request(APP_CMD_UPLOAD_MEDIA_FINISH, {"upload_id": upload_id}, "media upload finish")
+ finish_body = _dict_at(finish_response, "body")
media_id = str(finish_body.get("media_id") or "").strip()
if not media_id:
raise RuntimeError(f"media upload finish failed: missing media_id in response {finish_response}")
return {"type": str(finish_body.get("type") or media_type), "media_id": media_id, "created_at": finish_body.get("created_at")}
async def _send_media_message(self, chat_id: str, media_type: str, media_id: str) -> Dict[str, Any]:
- response = await self._send_request(
- APP_CMD_SEND, {"chatid": chat_id, "msgtype": media_type, media_type: {"media_id": media_id}},
- )
- self._raise_for_wecom_error(response, "send media message")
- return response
-
- async def _send_reply_media_message(self, reply_req_id: str, media_type: str, media_id: str) -> Dict[str, Any]:
- response = await self._send_reply_request(reply_req_id, {"msgtype": media_type, media_type: {"media_id": media_id}})
- self._raise_for_wecom_error(response, "send reply media message")
- return response
+ return await self._checked_request(APP_CMD_SEND, {"chatid": chat_id, **_media_body(media_type, media_id)}, "send media message")
async def _send_followup_markdown(self, chat_id: str, content: str, reply_to: Optional[str] = None) -> Optional[SendResult]:
if not content:
@@ -374,98 +282,60 @@ class WeComMediaMixin:
logger.warning("[%s] Follow-up markdown send failed: %s", self.name, result.error)
return result
- async def _send_media_source(
- self, chat_id: str, media_source: str, caption: Optional[str] = None, file_name: Optional[str] = None,
- reply_to: Optional[str] = None,
- ) -> SendResult:
+ async def _send_media_source(self, chat_id: str, media_source: str, caption: Optional[str] = None, file_name: Optional[str] = None, reply_to: Optional[str] = None) -> SendResult:
if not chat_id:
return SendResult(success=False, error="chat_id is required")
try:
prepared = await self._prepare_outbound_media(media_source, file_name=file_name)
- except FileNotFoundError as exc:
- return SendResult(success=False, error=str(exc))
except Exception as exc:
- logger.error("[%s] Failed to prepare outbound media %s: %s", self.name, media_source, exc)
+ if not isinstance(exc, FileNotFoundError):
+ logger.error("[%s] Failed to prepare outbound media %s: %s", self.name, media_source, exc)
return SendResult(success=False, error=str(exc))
-
if prepared["rejected"]:
await self._send_followup_markdown(chat_id, f"⚠️ {prepared['reject_reason']}", reply_to=reply_to)
return SendResult(success=False, error=prepared["reject_reason"])
-
- reply_req_id = self._reply_req_id_for_message(reply_to)
- if not reply_req_id and chat_id in self._last_chat_req_ids:
- reply_req_id = self._last_chat_req_ids[chat_id]
- # Media MUST use the proactive path when a stream was/is active for the
- # chat: passive replyMedia cannot overwrite a replyStream thinking bubble
- # and the stream "owns" the req_id (server ignores or never acks).
+ reply_req_id = self._cached_reply_req_id(chat_id, reply_to)
+ # Active/expired stream owns the req_id (passive replyMedia is never acked): go proactive.
if self._find_active_turn_for_chat(chat_id) or chat_id in self._stream_expired_chats:
reply_req_id = None
-
try:
upload_result = await self._upload_media_bytes(prepared["data"], prepared["final_type"], prepared["file_name"])
logger.info("[%s] upload_media_bytes OK: media_id=%s type=%s", self.name, upload_result.get("media_id"), prepared["final_type"])
- if reply_req_id:
- media_response = await self._send_reply_media_message(reply_req_id, prepared["final_type"], upload_result["media_id"])
- logger.info("[%s] send_reply_media OK: %s", self.name, media_response)
+ if reply_req_id: # passive reply when a req_id is usable, else proactive APP_CMD_SEND
+ media_response = await self._send_reply_request(reply_req_id, _media_body(prepared["final_type"], upload_result["media_id"]))
+ self._raise_for_wecom_error(media_response, "send reply media message")
else:
media_response = await self._send_media_message(chat_id, prepared["final_type"], upload_result["media_id"])
- logger.info("[%s] send_media_message OK: %s", self.name, media_response)
+ logger.info("[%s] %s OK: %s", self.name, "send_reply_media" if reply_req_id else "send_media_message", media_response)
except asyncio.TimeoutError:
logger.error("[%s] TIMEOUT in _send_media_source for %s", self.name, media_source)
return SendResult(success=False, error="Timeout sending media to WeCom")
except Exception as exc:
logger.error("[%s] Failed to send media %s: %s", self.name, media_source, exc)
return SendResult(success=False, error=str(exc))
-
- caption_result = downgrade_result = None
- if caption:
- caption_result = await self._send_followup_markdown(chat_id, caption, reply_to=reply_to)
- if prepared["downgraded"] and prepared["downgrade_note"]:
- downgrade_result = await self._send_followup_markdown(chat_id, f"ℹ️ {prepared['downgrade_note']}", reply_to=reply_to)
-
- return SendResult(
- success=True,
- message_id=self._payload_req_id(media_response) or uuid.uuid4().hex[:12],
- raw_response={
- "upload": upload_result,
- "media": media_response,
- "caption": caption_result.raw_response if caption_result else None,
- "caption_error": caption_result.error if caption_result and not caption_result.success else None,
- "downgrade": downgrade_result.raw_response if downgrade_result else None,
- "downgrade_error": downgrade_result.error if downgrade_result and not downgrade_result.success else None,
- },
- )
-
- async def send_image(
- self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
- ) -> SendResult:
- del metadata
+ raw: Dict[str, Any] = {"upload": upload_result, "media": media_response}
+ for key, text in (("caption", caption), ("downgrade", f"ℹ️ {prepared['downgrade_note']}" if prepared["downgraded"] and prepared["downgrade_note"] else None)):
+ followup = await self._send_followup_markdown(chat_id, text, reply_to=reply_to) if text else None
+ raw[key] = followup.raw_response if followup else None
+ raw[f"{key}_error"] = followup.error if followup and not followup.success else None
+ return SendResult(success=True, message_id=self._payload_req_id(media_response) or uuid.uuid4().hex[:12], raw_response=raw)
+
+ async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
result = await self._send_media_source(chat_id=chat_id, media_source=image_url, caption=caption, reply_to=reply_to)
if result.success or not self._looks_like_url(image_url):
return result
logger.warning("[%s] Falling back to text send for image URL %s: %s", self.name, image_url, result.error)
- fallback_text = f"{caption}\n{image_url}" if caption else image_url
- return await self.send(chat_id=chat_id, content=fallback_text, reply_to=reply_to)
+ return await self.send(chat_id=chat_id, content=f"{caption}\n{image_url}" if caption else image_url, reply_to=reply_to)
async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:
- del kwargs
return await self._send_media_source(chat_id=chat_id, media_source=image_path, caption=caption, reply_to=reply_to)
- async def send_document(
- self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
- reply_to: Optional[str] = None, **kwargs,
- ) -> SendResult:
- del kwargs
+ async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:
logger.info("[%s] send_document called: chat=%s file=%s", self.name, chat_id, file_path)
- return await self._send_media_source(
- chat_id=chat_id, media_source=file_path, caption=caption, file_name=file_name, reply_to=reply_to,
- )
+ return await self._send_media_source(chat_id=chat_id, media_source=file_path, caption=caption, file_name=file_name, reply_to=reply_to)
async def send_voice(self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:
- del kwargs
return await self._send_media_source(chat_id=chat_id, media_source=audio_path, caption=caption, reply_to=reply_to)
async def send_video(self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:
- del kwargs
return await self._send_media_source(chat_id=chat_id, media_source=video_path, caption=caption, reply_to=reply_to)
diff --git a/plugins/platforms/wecom/send_queue.py b/plugins/platforms/wecom/send_queue.py
index 435da40bc39..286308c28bf 100644
--- a/plugins/platforms/wecom/send_queue.py
+++ b/plugins/platforms/wecom/send_queue.py
@@ -1,10 +1,5 @@
-"""Per-chat FIFO send queues with token-bucket rate limiting for WeCom.
-
-Mirrors OpenClaw's chat-queue.ts (serial per chat) plus a token bucket that
-keeps each chat under WeCom's 30 msgs/min/chat limit (errcode 846607). Two
-lanes per chat: a normal lane and a high-priority control lane (approval
-prompts, finalize frames, error notices) backed by a reserved token pool.
-"""
+"""Per-chat FIFO send queues (OpenClaw chat-queue.ts) + token bucket for WeCom's 30 msgs/min/chat limit (846607).
+Two lanes per chat: normal, and a control lane (approval prompts, finalize frames) backed by a reserved token pool."""
from __future__ import annotations
@@ -25,44 +20,31 @@ class ChatSendQueueMixin:
_BUCKET_RESERVED_TOKENS = 6
def _get_token_usage(self, chat_id: str) -> Dict[str, float]:
- """Get or create token usage tracking for a chat."""
- key = str(chat_id or "").strip()
- if key not in self._chat_token_usage:
- self._chat_token_usage[key] = {"normal": 0.0, "reserved": 0.0, "last_reset": time.monotonic()}
- return self._chat_token_usage[key]
+ return self._chat_token_usage.setdefault(str(chat_id or "").strip(), {"normal": 0.0, "reserved": 0.0, "last_reset": time.monotonic()})
def _bucket_try_consume(self, chat_id: str, is_control: bool = False) -> float:
- """Consume one token. Returns 0 if available, else seconds until the next minute window.
-
- Normal messages only use the normal quota; control messages use normal
- quota first (don't waste reserved), then the reserved pool.
- """
+ """Consume one token: 0 if available, else seconds until the next minute window. Control messages use the normal quota first, then the reserved pool."""
usage = self._get_token_usage(chat_id)
now = time.monotonic()
if now - usage["last_reset"] > 60.0: # reset counters every minute
- usage["normal"] = 0.0
- usage["reserved"] = 0.0
- usage["last_reset"] = now
- if usage["normal"] < self._BUCKET_NORMAL_TOKENS:
- usage["normal"] += 1.0
- return 0.0
- if is_control and usage["reserved"] < self._BUCKET_RESERVED_TOKENS:
- usage["reserved"] += 1.0
- return 0.0
+ usage.update(normal=0.0, reserved=0.0, last_reset=now)
+ for lane, cap, allowed in (("normal", self._BUCKET_NORMAL_TOKENS, True), ("reserved", self._BUCKET_RESERVED_TOKENS, is_control)):
+ if allowed and usage[lane] < cap:
+ usage[lane] += 1.0
+ return 0.0
return 60.0 - (now - usage["last_reset"])
- async def _enqueue_chat_send(self, chat_id: str, coro_factory, is_control: bool = False):
- """Enqueue a send task for a chat and await its result (FIFO per chat, parallel across chats).
+ def _lane(self, is_control: bool):
+ return (self._control_queues, self._control_workers) if is_control else (self._chat_queues, self._chat_workers)
- Control-lane sends bypass the normal queue so approval prompts are never blocked.
- """
+ async def _enqueue_chat_send(self, chat_id: str, coro_factory, is_control: bool = False):
+ """Enqueue a send for a chat and await its result (FIFO per chat); the control lane bypasses the normal queue so approval prompts are never blocked."""
key = str(chat_id or "").strip()
lane = "control" if is_control else "normal"
- queues = self._control_queues if is_control else self._chat_queues
+ queues, workers = self._lane(is_control)
if key not in queues:
logger.debug("[%s] Creating %s queue + worker for chat %s", self.name, lane, key)
queues[key] = asyncio.Queue()
- workers = self._control_workers if is_control else self._chat_workers
workers[key] = asyncio.create_task(self._send_worker(key, is_control))
queue = queues[key]
logger.debug("[%s] Enqueuing send for chat %s (lane=%s, qsize=%d)", self.name, key, lane, queue.qsize())
@@ -72,10 +54,8 @@ class ChatSendQueueMixin:
async def _send_worker(self, chat_key: str, is_control: bool) -> None:
"""Per-chat worker: drain one lane's queue under the token bucket."""
- if is_control:
- queue = self._control_queues[chat_key]
- else:
- queue = self._chat_queues[chat_key]
+ queue = self._lane(is_control)[0][chat_key]
+ if not is_control:
logger.debug("[%s] Normal send worker started for chat %s", self.name, chat_key)
try:
while True:
@@ -84,10 +64,7 @@ class ChatSendQueueMixin:
wait = self._bucket_try_consume(chat_key, is_control)
if wait > 0:
if not is_control:
- logger.debug(
- "[%s] Normal worker rate-limited for chat %s, waiting %.1fs",
- self.name, chat_key, wait,
- )
+ logger.debug("[%s] Normal worker rate-limited for chat %s, waiting %.1fs", self.name, chat_key, wait)
await asyncio.sleep(wait)
self._bucket_try_consume(chat_key, is_control) # re-consume after wait
result = await coro_factory()
@@ -100,9 +77,6 @@ class ChatSendQueueMixin:
queue.task_done()
except asyncio.CancelledError:
while not queue.empty():
- try:
- _, future = queue.get_nowait()
- if not future.done():
- future.set_exception(RuntimeError("WeCom adapter shutting down"))
- except asyncio.QueueEmpty:
- break
+ _, future = queue.get_nowait()
+ if not future.done():
+ future.set_exception(RuntimeError("WeCom adapter shutting down"))
diff --git a/plugins/platforms/wecom/streaming.py b/plugins/platforms/wecom/streaming.py
index 6c06d2a6c5c..7769ea7ae1b 100644
--- a/plugins/platforms/wecom/streaming.py
+++ b/plugins/platforms/wecom/streaming.py
@@ -1,9 +1,5 @@
-"""WeCom native streaming (``msgtype: stream`` via aibot_respond_msg).
-
-Per-turn stream state, per-req_id ack tracking (official SDK's
-replyStreamNonBlocking semantics), the stream-level keep-alive heartbeat and
-the finalize clock fallback. Mixed into :class:`WeComAdapter`.
-"""
+"""WeCom native streaming mixin (``msgtype: stream`` via aibot_respond_msg): per-turn state, per-req_id
+ack tracking (official replyStreamNonBlocking semantics), keep-alive heartbeat, finalize clock fallback."""
from __future__ import annotations
@@ -18,47 +14,32 @@ logger = logging.getLogger("plugins.platforms.wecom.adapter")
APP_CMD_RESPONSE = "aibot_respond_msg"
-# WeCom binds a ~6-minute lifetime to each reply stream (stream_id + req_id);
-# the connection-level ping does NOT refresh it. Past that window updates come
-# back 846608 (stream update window) / 846604 (req_id reply-request window) —
-# both mean the reply flow is dead and further frames will be rejected.
+# Each reply stream lives ~6 minutes (the connection ping does NOT refresh it); afterwards
+# 846608 (stream window) / 846604 (req_id window) mean the reply flow is dead. 846609 = ws
+# lost its subscription. 6000 = finalize raced a newer frame (bubble already replaced: benign).
STREAM_EXPIRED_ERRCODE = 846608
STREAM_REQUEST_EXPIRED_ERRCODE = 846604
-STREAM_NOT_SUBSCRIBED_ERRCODE = 846609 # ws connection lost the subscription
-# 6000 = finalize raced a newer frame on the same stream_id: the bubble was
-# ALREADY replaced, so for a finalize frame this is benign, not a failure.
+STREAM_NOT_SUBSCRIBED_ERRCODE = 846609
STREAM_VERSION_CONFLICT_ERRCODE = 6000
MAX_STREAM_CONTENT_LENGTH = 20480 # WeCom server-enforced byte limit per frame
-# WeCom SDK has a 100-frame per-reqId queue; cap intermediates at 85 (matches
-# the openclaw plugin) so the finalize frame always has room. Past the cap
-# intermediates are silently dropped — finalize still sends unconditionally.
+# SDK queue is 100 frames per reqId; cap intermediates (openclaw uses 85) so finalize has room.
MAX_INTERMEDIATE_FRAMES = 85
-# Two independent defences against the 6-min stream window, both defaulting
-# to the safe side (see docs/wecom-stream-keepalive-*.md):
-# Layer 2 — clock fallback (always on): finalize declines the finish=true
-# frame once the stream is older than STREAM_SAFE_DURATION_SECONDS and
-# returns False so the consumer's send() fallback delivers the content.
-# Layer 1 — keep-alive heartbeat (OFF by default): every
-# STREAM_KEEPALIVE_INTERVAL_SECONDS re-send the accumulated text as a
-# finish=false frame. Never sends a placeholder. Off by default because an
-# extra intermediate frame widens the ack race the double-send
-# coordination depends on.
+# Two defences against the 6-min window (docs/wecom-stream-keepalive-*.md): Layer 2 clock
+# fallback (always on) declines finish=true past STREAM_SAFE_DURATION_SECONDS so the consumer's
+# send() delivers; Layer 1 keep-alive (OFF by default) re-sends accumulated text as finish=false
+# every interval — off because an extra frame widens the ack race double-send relies on.
STREAM_SAFE_DURATION_SECONDS = 330.0
STREAM_KEEPALIVE_INTERVAL_SECONDS = 120.0
STREAM_KEEPALIVE_ENABLED_DEFAULT = False
class WeComStreamExpiredError(RuntimeError):
- """Raised on errcode 846608/846604: the stream/req_id reply flow is dead.
-
- Callers must fall back to a proactive ``aibot_send_msg``.
- """
+ """Raised on errcode 846608/846604: the stream/req_id reply flow is dead; fall back to ``aibot_send_msg``."""
def __init__(self, errcode: int = STREAM_EXPIRED_ERRCODE, errmsg: str = ""):
super().__init__(f"WeCom stream expired (errcode={errcode}): {errmsg or 'no detail'}")
- self.errcode = errcode
- self.errmsg = errmsg
+ self.errcode, self.errmsg = errcode, errmsg
@dataclass
@@ -73,142 +54,94 @@ class ReplyFrame:
class ReplyQueue:
"""Per-req_id pending-ack tracker: intermediates skip while an ack is pending, finals wait."""
def __init__(self, req_id: str):
- self.req_id = req_id
- self.pending_ack: Optional[ReplyFrame] = None
+ self.req_id, self.pending_ack = req_id, None # pending_ack: Optional[ReplyFrame]
class StreamTurn:
"""Per-turn stream state so concurrent messages never share a stream."""
def __init__(self, chat_id: str, req_id: str):
- self.chat_id = chat_id
- self.req_id = req_id
- self.stream_id = f"stream_{uuid.uuid4().hex[:12]}"
+ self.chat_id, self.req_id, self.stream_id = chat_id, req_id, f"stream_{uuid.uuid4().hex[:12]}"
self.accumulated_text = ""
- self.finalized = False
- self.seeded = False # seed frame sent (prevents double seed → errcode 6000)
+ self.finalized = self.seeded = self.expired = False # seeded prevents a double seed (errcode 6000)
self.start_time = time.monotonic()
- self.expired = False
- # Last content ACTUALLY sent (not skipped) — finalize uses it to avoid a
- # duplicate-content final frame that WeCom silently drops.
- self.last_sent_content: str = ""
+ self.last_sent_content: str = "" # content ACTUALLY sent; final frame must differ or WeCom drops it
self._intermediate_frames_sent: int = 0
- # Keep-alive TimerHandle; MUST be cancelled on every turn-exit path
- # (finalize / expired / error / cleanup) so it never fires on a dead turn.
- self.keepalive_handle: Optional[asyncio.TimerHandle] = None
+ self.keepalive_handle: Optional[asyncio.TimerHandle] = None # cancel on EVERY turn-exit path
def _stream_of(body: Dict[str, Any]) -> Dict[str, Any]:
return body.get("stream", {}) if isinstance(body.get("stream"), dict) else {}
-class WeComStreamMixin:
- """Native streaming for WeComAdapter (expects ``_ws``, ``_send_json``, ``_reply_queues``,
- ``_stream_turns``, ``_stream_expired_chats``, ``_last_chat_req_ids`` and the
- ``_stream_*`` config attributes set in ``__init__``)."""
-
- MAX_STREAM_CONTENT_LENGTH = MAX_STREAM_CONTENT_LENGTH
-
- # Ack timeout matches the official plugin's REPLY_SEND_TIMEOUT_MS = 15_000; a
- # shorter window widened the race where the final-frame ack is still in
- # flight while the gateway's normal final send fires → duplicate messages.
- _REPLY_ACK_TIMEOUT = 15.0
+def _stream_desc(body: Dict[str, Any]) -> tuple:
+ stream = _stream_of(body)
+ return stream.get("id", "N/A"), stream.get("finish", "N/A")
- # ── Per-req_id reply queue (ack tracking) ────────────────────────────
- async def _send_reply_queued(
- self, reply_req_id: str, body: Dict[str, Any], *, is_final: bool = False, skip_if_pending: bool = False,
- ) -> Dict[str, Any]:
- """Send a reply via aibot_respond_msg with per-req_id ack tracking.
+def _elapsed(since: Optional[float]) -> float:
+ return time.monotonic() - (since or time.monotonic())
- is_final: wait for any pending ack before sending, then await our own ack.
- skip_if_pending: return ``{"skipped": True}`` if a prior frame's ack is pending.
- """
- if not self._ws or self._ws.closed:
- raise RuntimeError("WeCom websocket is not connected")
- normalized = str(reply_req_id or "").strip()
- if not normalized:
- raise ValueError("reply_req_id is required")
- queue = self._reply_queues.get(normalized)
- if queue is None:
- queue = ReplyQueue(normalized)
- self._reply_queues[normalized] = queue
+class WeComStreamMixin:
+ """Native streaming mixed into WeComAdapter (uses its ws transport, registries and ``_stream_*`` config)."""
+ MAX_STREAM_CONTENT_LENGTH = MAX_STREAM_CONTENT_LENGTH
+ _REPLY_ACK_TIMEOUT = 15.0 # official REPLY_SEND_TIMEOUT_MS; shorter widened the double-send race
+
+ async def _send_reply_queued(self, reply_req_id: str, body: Dict[str, Any], *, is_final: bool = False, skip_if_pending: bool = False) -> Dict[str, Any]:
+ """aibot_respond_msg with per-req_id ack tracking: is_final drains the pending ack then awaits its own;
+ skip_if_pending returns ``{"skipped": True}`` while a prior ack is pending."""
+ self._require_ws()
+ normalized = self._require_reply_req_id(reply_req_id)
+ queue = self._reply_queues.setdefault(normalized, ReplyQueue(normalized))
if skip_if_pending and queue.pending_ack is not None:
return {"skipped": True, "errcode": 0, "errmsg": "pending_ack"}
-
if is_final and queue.pending_ack is not None:
- pending_frame = queue.pending_ack
- _pending_stream = _stream_of(pending_frame.body)
- pending_desc = (self.name, normalized, _pending_stream.get("id", "N/A"), _pending_stream.get("finish", "N/A"))
- logger.debug(
- "[%s] _send_reply_queued: final waiting for pending ack drain — "
- "req_id=%s pending_stream_id=%s pending_finish=%s pending_sent_at=%.1fs_ago",
- *pending_desc, time.monotonic() - (pending_frame.sent_at or time.monotonic()),
- )
- try:
- await asyncio.wait_for(asyncio.shield(pending_frame.future), timeout=self._REPLY_ACK_TIMEOUT)
- except asyncio.TimeoutError:
- logger.warning(
- "[%s] Reply ack timeout waiting for pending (req_id=%s) — "
- "pending_stream_id=%s pending_finish=%s elapsed=%.1fs. "
- "Possible causes: ack cmd filtered, ack req_id mismatch, or WeCom did not ack.",
- *pending_desc, time.monotonic() - (pending_frame.sent_at or time.monotonic()),
- )
- except Exception:
- pass
- queue.pending_ack = None # resolved or timed out either way
-
+ await self._drain_pending_ack(queue, normalized)
future: asyncio.Future = asyncio.get_running_loop().create_future()
- frame = ReplyFrame(body=body, future=future, is_final=is_final)
- frame.sent_at = time.monotonic()
- # Register pending BEFORE sending so an ack arriving mid-send is routed.
- # Re-attach `queue` too: while the final frame awaited the drain above, the
- # intermediate ack may have popped the whole queue out of _reply_queues,
- # leaving our local reference orphaned (its ack would then be Unrouted →
- # 15s timeout).
+ frame = ReplyFrame(body=body, future=future, is_final=is_final, sent_at=time.monotonic())
+ # Register BEFORE sending so a mid-send ack routes; re-attach `queue` because the drain
+ # above may have let the intermediate ack pop it out of _reply_queues (orphan → timeout).
self._reply_queues[normalized] = queue
queue.pending_ack = frame
-
- _stream_info = _stream_of(body)
logger.debug(
- "[%s] _send_reply_queued: req_id=%s is_final=%s skip_if_pending=%s stream_id=%s finish=%s content_len=%d",
- self.name, normalized, is_final, skip_if_pending,
- _stream_info.get("id", "N/A"), _stream_info.get("finish", "N/A"), len(_stream_info.get("content", "") or ""),
+ "[%s] _send_reply_queued: req_id=%s is_final=%s skip_if_pending=%s stream_id=%s finish=%s content_len=%d", self.name, normalized, is_final, skip_if_pending, *_stream_desc(body), len(_stream_of(body).get("content", "") or ""),
)
-
try:
await self._send_json({"cmd": APP_CMD_RESPONSE, "headers": {"req_id": normalized}, "body": body})
except Exception:
- # Nobody awaits the future on this branch — cancel it rather than
- # leave a "Future exception was never retrieved" log.
- if queue.pending_ack is frame:
- queue.pending_ack = None
- self._reply_queues.pop(normalized, None)
+ # Nobody awaits the future here — cancel it rather than log "exception never retrieved".
+ self._release_pending(queue, normalized, frame)
if not future.done():
future.cancel()
raise
-
- if not is_final:
- # Fire-and-forget; pending_ack stays registered so later frames can skip.
+ if not is_final: # fire-and-forget; pending_ack stays registered so later frames can skip
return {"errcode": 0, "errmsg": "sent_nonblocking"}
try:
return await asyncio.wait_for(future, timeout=self._REPLY_ACK_TIMEOUT)
except asyncio.TimeoutError:
- # The bytes went out (send did not raise) but the ack is late — in
- # practice WeCom has already rendered the message. Raising here made
- # the upper layer fall back to a markdown send and produced duplicates;
- # match the official plugin: warn and treat as delivered.
- logger.warning(
- "[%s] Final frame ack timeout (req_id=%s) — treating as "
- "delivered (matches official wecom-openclaw-plugin "
- "behaviour). No fallback send.",
- self.name, normalized,
- )
+ # Bytes went out, ack is late — WeCom already rendered it; raising caused duplicates.
+ logger.warning("[%s] Final frame ack timeout (req_id=%s) — treating as delivered (matches official wecom-openclaw-plugin behaviour). No fallback send.", self.name, normalized)
return {"errcode": 0, "errmsg": "ack_timeout_assumed_delivered", "ack_pending": True}
finally:
self._release_pending(queue, normalized, frame)
+ async def _drain_pending_ack(self, queue: ReplyQueue, req_id: str) -> None:
+ """Before a final frame: wait (bounded) for the pending intermediate's ack, then clear it."""
+ pending_frame = queue.pending_ack
+ pending_desc = (self.name, req_id, *_stream_desc(pending_frame.body))
+ logger.debug("[%s] _send_reply_queued: final waiting for pending ack drain — req_id=%s pending_stream_id=%s pending_finish=%s pending_sent_at=%.1fs_ago", *pending_desc, _elapsed(pending_frame.sent_at))
+ try:
+ await asyncio.wait_for(asyncio.shield(pending_frame.future), timeout=self._REPLY_ACK_TIMEOUT)
+ except asyncio.TimeoutError:
+ logger.warning(
+ "[%s] Reply ack timeout waiting for pending (req_id=%s) — pending_stream_id=%s pending_finish=%s elapsed=%.1fs. Possible causes: ack cmd filtered, ack req_id mismatch, or WeCom did not ack.",
+ *pending_desc, _elapsed(pending_frame.sent_at),
+ )
+ except Exception:
+ pass
+ queue.pending_ack = None # resolved or timed out either way
+
def _release_pending(self, queue: ReplyQueue, req_id: str, frame: ReplyFrame) -> None:
"""Clear ``frame`` if it is still the pending ack; drop the queue once empty."""
if queue.pending_ack is frame:
@@ -224,41 +157,29 @@ class WeComStreamMixin:
frame = queue.pending_ack
if not frame.future.done():
_body = payload.get("body", {}) if isinstance(payload.get("body"), dict) else {}
- logger.debug(
- "[%s] _resolve_reply_ack: resolved req_id=%s is_final=%s "
- "elapsed=%.2fs errcode=%s",
- self.name, req_id, frame.is_final,
- time.monotonic() - (frame.sent_at or time.monotonic()),
- _body.get("errcode", "N/A"),
- )
+ logger.debug("[%s] _resolve_reply_ack: resolved req_id=%s is_final=%s elapsed=%.2fs errcode=%s", self.name, req_id, frame.is_final, _elapsed(frame.sent_at), _body.get("errcode", "N/A"))
frame.future.set_result(payload)
self._release_pending(queue, req_id, frame)
return True
def _fail_reply_queues(self, error: Exception) -> None:
- """Fail all pending reply acks (disconnect/error)."""
for queue in list(self._reply_queues.values()):
if queue.pending_ack and not queue.pending_ack.future.done():
queue.pending_ack.future.set_exception(error)
self._reply_queues.clear()
- # ── Turn registry ────────────────────────────────────────────────────
-
def _resolve_stream_req_id(self, chat_id: str, reply_to: Optional[str]) -> Optional[str]:
"""Explicit ``reply_to`` (cached message id) → last inbound req_id for the chat → None."""
- req_id = self._reply_req_id_for_message(reply_to)
- if req_id:
- return req_id
- return self._last_chat_req_ids.get(str(chat_id or "").strip()) or None
+ return self._reply_req_id_for_message(reply_to) or self._last_chat_req_ids.get(str(chat_id or "").strip()) or None
@staticmethod
def _cancel_keepalive(turn: StreamTurn) -> None:
- if turn.keepalive_handle is not None:
+ handle, turn.keepalive_handle = turn.keepalive_handle, None
+ if handle is not None:
try:
- turn.keepalive_handle.cancel()
+ handle.cancel()
except Exception:
pass
- turn.keepalive_handle = None
def _retire_turn(self, turn: StreamTurn, turn_id: Optional[str]) -> None:
"""Single choke point for "turn is dead": cancel the timer, then drop it from the registry."""
@@ -271,47 +192,30 @@ class WeComStreamMixin:
self._stream_expired_chats.add(turn.chat_id)
def _find_active_turn_for_chat(self, chat_id: str) -> Optional[StreamTurn]:
- for turn in self._stream_turns.values():
- if turn.chat_id == chat_id and not turn.finalized:
- return turn
- return None
-
- # ── Stream-level keep-alive (Layer 1) ────────────────────────────────
+ return next((t for t in self._stream_turns.values() if t.chat_id == chat_id and not t.finalized), None)
def _arm_keepalive(self, turn: StreamTurn, *, turn_id: Optional[str]) -> None:
"""Arm the keep-alive timer if enabled and not already armed (idempotent)."""
- if not self._stream_keepalive_enabled or turn.finalized or turn.expired:
- return
- if turn.keepalive_handle is not None:
+ if not self._stream_keepalive_enabled or turn.finalized or turn.expired or turn.keepalive_handle is not None:
return
try:
- loop = asyncio.get_running_loop()
+ turn.keepalive_handle = asyncio.get_running_loop().call_later(self._stream_keepalive_interval_seconds, self._on_keepalive_fire, turn, turn_id)
except RuntimeError:
- return
- turn.keepalive_handle = loop.call_later(
- self._stream_keepalive_interval_seconds, self._on_keepalive_fire, turn, turn_id,
- )
+ pass
def _on_keepalive_fire(self, turn: StreamTurn, turn_id: Optional[str]) -> None:
turn.keepalive_handle = None
- if turn.finalized or turn.expired:
- return
- try:
- asyncio.ensure_future(self._keepalive_send(turn, turn_id))
- except RuntimeError:
- pass
+ if not (turn.finalized or turn.expired):
+ try:
+ asyncio.ensure_future(self._keepalive_send(turn, turn_id))
+ except RuntimeError:
+ pass
async def _keepalive_send(self, turn: StreamTurn, turn_id: Optional[str]) -> None:
- """Re-send the accumulated text as finish=false to refresh the server window, then re-arm.
-
- Never sends a placeholder: with no accumulated text the tick is skipped
- (Layer 2 handles content-less turns). On 846604/846608 the turn is
- retired so finalize takes the Layer 2 fallback; no re-arm.
- """
- if turn.finalized or turn.expired:
- return
- if turn._intermediate_frames_sent >= MAX_INTERMEDIATE_FRAMES:
- return # no room left for intermediates; let finalize / Layer 2 run
+ """Re-send accumulated text as finish=false to refresh the window, then re-arm. Never a placeholder
+ (empty text skips); on 846604/846608 the turn is retired for Layer 2."""
+ if turn.finalized or turn.expired or turn._intermediate_frames_sent >= MAX_INTERMEDIATE_FRAMES:
+ return # cap reached: no room for intermediates; let finalize / Layer 2 run
content = turn.accumulated_text or ""
if not content.strip():
self._arm_keepalive(turn, turn_id=turn_id)
@@ -322,241 +226,145 @@ class WeComStreamMixin:
self._expire_turn(turn, turn_id)
return
except Exception as exc:
- logger.debug(
- "[%s] keep-alive send failed (chat=%s, turn=%s): %s",
- self.name, turn.chat_id, turn.stream_id, exc,
- )
+ logger.debug("[%s] keep-alive send failed (chat=%s, turn=%s): %s", self.name, turn.chat_id, turn.stream_id, exc)
self._arm_keepalive(turn, turn_id=turn_id) # transient — retry next interval
return
turn.last_sent_content = content
self._arm_keepalive(turn, turn_id=turn_id)
- # ── Frame sending ────────────────────────────────────────────────────
-
@staticmethod
def _truncate_stream_content(content: str, limit: int) -> str:
"""Truncate to ``limit`` UTF-8 bytes (WeCom caps frames by bytes, not codepoints)."""
encoded = content.encode("utf-8")
- if len(encoded) <= limit:
- return content
- return encoded[:limit].decode("utf-8", errors="ignore")
-
- async def _send_stream_reply(
- self, reply_req_id: str, stream_id: str, content: str, finish: bool = False,
- ) -> Dict[str, Any]:
- """Send one ``msgtype: "stream"`` frame.
-
- Intermediate frames are non-blocking with skip-if-pending (cumulative
- text means nothing is lost). The final frame drains any pending ack
- first, then awaits its own ack so 846608/6000 are detected reliably.
- Raises WeComStreamExpiredError on 846608/846604.
- """
+ return content if len(encoded) <= limit else encoded[:limit].decode("utf-8", errors="ignore")
+
+ async def _send_stream_reply(self, reply_req_id: str, stream_id: str, content: str, finish: bool = False) -> Dict[str, Any]:
+ """Send one ``msgtype: "stream"`` frame: intermediates non-blocking/skip-if-pending, the final frame awaits
+ its ack so 846608/6000 are detected. Raises WeComStreamExpiredError on expiry."""
truncated = self._truncate_stream_content(content or "", self.MAX_STREAM_CONTENT_LENGTH)
if len(content or "") != len(truncated):
logger.warning("[%s] Stream content truncated for stream_id=%s", self.name, stream_id)
body: Dict[str, Any] = {"msgtype": "stream", "stream": {"id": stream_id, "finish": bool(finish), "content": truncated}}
if not finish:
return await self._send_reply_queued(reply_req_id, body, is_final=False, skip_if_pending=True)
-
response = await self._send_reply_queued(reply_req_id, body, is_final=True, skip_if_pending=False)
errcode = response.get("errcode", 0)
if errcode in (STREAM_EXPIRED_ERRCODE, STREAM_REQUEST_EXPIRED_ERRCODE):
raise WeComStreamExpiredError(errcode=errcode, errmsg=str(response.get("errmsg") or ""))
if errcode == STREAM_VERSION_CONFLICT_ERRCODE:
- # Content is already on screen; raising would pop the turn and cause
- # a duplicate standalone send(). Absorbing makes finalize retry safe.
- logger.info(
- "[%s] finalize hit errcode 6000 (version conflict) — bubble "
- "already replaced by a newer frame; treating as delivered.",
- self.name,
- )
+ # Content is already on screen; raising would pop the turn and duplicate via send().
+ logger.info("[%s] finalize hit errcode 6000 (version conflict) — bubble already replaced by a newer frame; treating as delivered.", self.name)
return response
self._raise_for_wecom_error(response, "send stream reply")
return response
- async def send_stream_frame(
- self, text: str, *, finalize: bool = False, chat_id: Optional[str] = None, reply_to: Optional[str] = None, **kwargs,
- ) -> bool:
- """Entry point for the gateway streaming consumer.
-
- First call for a turn resolves the req_id, creates the StreamTurn and
- seeds the typing bubble; later calls push cumulative text (not deltas);
- ``finalize=True`` closes the stream and drops turn state. ``turn_id``
- (kwarg) keys the turn by (chat, turn_id) so concurrent consumers
- (/background, subagents) never share a stream.
-
- Returns False when the stream is unavailable (no req_id, expired,
- transport error) — the caller should fall back to :meth:`send`.
- """
+ async def send_stream_frame(self, text: str, *, finalize: bool = False, chat_id: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> bool:
+ """Gateway streaming entry point: first call seeds the turn, later calls push cumulative text, ``finalize=True``
+ closes it; ``turn_id`` kwarg keys concurrent turns. Returns False when unavailable — caller falls back to send()."""
chat = (chat_id or "").strip()
if not chat:
logger.warning("[%s] send_stream_frame: chat_id required", self.name)
return False
turn_id = kwargs.get("turn_id")
- # Chat-level expiry only blocks NEW turn creation; a known turn_id may
- # still finalize after another turn in the chat expired.
+ # Chat-level expiry only blocks NEW turn creation; a known turn_id may still finalize.
if not turn_id and chat in self._stream_expired_chats:
return False
- if finalize:
- # Finalize counts toward 30/min — control lane so it is never blocked.
- return await self._enqueue_chat_send(
- chat,
- lambda: self._send_stream_frame_inner(text, chat=chat, reply_to=reply_to, finalize=True, turn_id=turn_id),
- is_control=True,
- )
- # Intermediate frames don't count toward the quota: no queue, no rate limit.
- return await self._send_stream_frame_inner(text, chat=chat, reply_to=reply_to, finalize=False, turn_id=turn_id)
-
- def _locate_turn(
- self, chat: str, reply_to: Optional[str], finalize: bool, turn_id: Optional[str],
- ) -> Optional[StreamTurn]:
- """Find or create the StreamTurn for a frame; None means "stream unavailable".
+ inner = lambda: self._send_stream_frame_inner(text, chat=chat, reply_to=reply_to, finalize=finalize, turn_id=turn_id) # noqa: E731
+ # Finalize counts toward 30/min → control lane; intermediates are unmetered (no queue).
+ return await self._enqueue_chat_send(chat, inner, is_control=True) if finalize else await inner()
- A turn locks to its req_id at creation even if ``_last_chat_req_ids``
- changes mid-turn (e.g. the user sends /approve).
- """
+ def _locate_turn(self, chat: str, reply_to: Optional[str], finalize: bool, turn_id: Optional[str]) -> Optional[StreamTurn]:
+ """Find or create the StreamTurn (None = unavailable); a turn locks to its creation req_id."""
if turn_id:
turn = self._stream_turns.get(f"{chat}:{turn_id}")
if turn:
return turn
- # finalize must NOT create a turn: if it was cleaned up (e.g. 6000) the
- # caller should fall back rather than send a fresh seed + finish.
- if finalize:
- logger.debug(
- "[%s] send_stream_frame: cannot finalize non-existent turn (turn_id=%s, chat=%s)",
- self.name, turn_id, chat,
- )
+ if finalize: # never create a turn on finalize: caller must fall back, not seed+finish
+ logger.debug("[%s] send_stream_frame: cannot finalize non-existent turn (turn_id=%s, chat=%s)", self.name, turn_id, chat)
return None
- else:
- # No turn_id (direct callers): reuse the chat's active turn if any.
- existing_turn = self._find_active_turn_for_chat(chat)
- if existing_turn and not existing_turn.finalized:
- logger.debug(
- "[%s] send_stream_frame: reusing existing turn %s for chat %s",
- self.name, existing_turn.stream_id, chat,
- )
- return existing_turn
-
+ elif existing_turn := self._find_active_turn_for_chat(chat): # direct callers without turn_id reuse the chat's active (unfinalized) turn
+ logger.debug("[%s] send_stream_frame: reusing existing turn %s for chat %s", self.name, existing_turn.stream_id, chat)
+ return existing_turn
suffix = f" (turn_id={turn_id})" if turn_id else ""
- if chat in self._stream_expired_chats:
- logger.debug("[%s] send_stream_frame: chat %s is expired, cannot create new turn%s", self.name, chat, suffix)
- return None
- req_id = self._resolve_stream_req_id(chat, reply_to)
+ req_id = None if chat in self._stream_expired_chats else self._resolve_stream_req_id(chat, reply_to)
if not req_id:
- logger.debug("[%s] send_stream_frame: no req_id available for chat %s%s", self.name, chat, suffix)
+ why = "chat %s is expired, cannot create new turn%s" if chat in self._stream_expired_chats else "no req_id available for chat %s%s"
+ logger.debug("[%s] send_stream_frame: " + why, self.name, chat, suffix)
return None
key = f"{chat}:{turn_id or req_id}"
turn = (None if turn_id else self._stream_turns.get(key)) or StreamTurn(chat, req_id)
self._stream_turns[key] = turn
- logger.debug(
- "[%s] send_stream_frame: created new turn %s (%s) for chat %s",
- self.name, turn.stream_id, f"turn_id={turn_id}, req_id={req_id}" if turn_id else f"req_id={req_id}", chat,
- )
+ logger.debug("[%s] send_stream_frame: created new turn %s (%s) for chat %s", self.name, turn.stream_id, f"turn_id={turn_id}, req_id={req_id}" if turn_id else f"req_id={req_id}", chat)
return turn
- async def _send_stream_frame_inner(
- self, text: str, *, chat: str, reply_to: Optional[str] = None, finalize: bool = False, turn_id: Optional[str] = None,
- ) -> bool:
- """Stream frame logic with per-turn state (see ``send_stream_frame``)."""
+ async def _finalize_turn(self, turn: StreamTurn, text: str, chat: str, turn_id: Optional[str]) -> bool:
+ """Send the finish=true frame (or decline via the Layer 2 clock fallback)."""
+ # Layer 2: an old stream would hit 846604/846608 on finish=true, so decline up front and let
+ # send() deliver once. Skipped with Layer 1 on: the heartbeat refreshed the window.
+ if not self._stream_keepalive_enabled:
+ stream_age = time.monotonic() - turn.start_time
+ if stream_age >= self._stream_safe_duration_seconds:
+ logger.info(
+ "[%s] Stream age %.0fs >= safe duration %.0fs for chat %s — declining finalize frame, falling back to proactive send (Layer 2 clock fallback).",
+ self.name, stream_age, self._stream_safe_duration_seconds, chat,
+ )
+ self._expire_turn(turn, turn_id)
+ return False
+ self._cancel_keepalive(turn)
+ # A final frame identical to the last intermediate is silently dropped — differ via ZWSP.
+ final_text = text + "\u200b" if text and text == turn.last_sent_content else text
+ await self._send_stream_reply(turn.req_id, turn.stream_id, final_text, finish=True)
+ turn.finalized = True
+ self._stream_turns.pop(f"{chat}:{turn_id or turn.req_id}", None)
+ return True
+
+ async def _send_stream_frame_inner(self, text: str, *, chat: str, reply_to: Optional[str] = None, finalize: bool = False, turn_id: Optional[str] = None) -> bool:
turn: Optional[StreamTurn] = None
try:
turn = self._locate_turn(chat, reply_to, finalize, turn_id)
if turn is None or turn.expired:
return False
-
if not turn.seeded and not turn.finalized:
- # Seed with the official plugin's THINKING_MESSAGE (<think></think>)
- # so the client shows a reasoning turn; the seeded flag prevents a
- # double seed (errcode 6000) since the consumer seeds too.
+ # Official THINKING_MESSAGE seed; `seeded` prevents a double seed (6000).
await self._send_stream_reply(turn.req_id, turn.stream_id, "<think></think>", finish=False)
turn.seeded = True
self._arm_keepalive(turn, turn_id=turn_id)
if not text and not finalize:
return True # consumer's explicit seed call — nothing more to send
-
if finalize:
- # Layer 2 clock fallback: an old stream would almost certainly hit
- # 846604/846608 on finish=true, so decline up front and let the
- # consumer's send() fallback deliver exactly once. SKIPPED when
- # Layer 1 keep-alive is on — the heartbeat has been refreshing the
- # window, so age alone does not mean dead, and declining a live
- # stream would re-deliver content already on screen. A truly dead
- # stream still raises WeComStreamExpiredError below.
- if not self._stream_keepalive_enabled:
- stream_age = time.monotonic() - turn.start_time
- if stream_age >= self._stream_safe_duration_seconds:
- logger.info(
- "[%s] Stream age %.0fs >= safe duration %.0fs for chat "
- "%s — declining finalize frame, falling back to "
- "proactive send (Layer 2 clock fallback).",
- self.name, stream_age,
- self._stream_safe_duration_seconds, chat,
- )
- self._expire_turn(turn, turn_id)
- return False
-
- self._cancel_keepalive(turn)
- # WeCom silently drops (no ack) a final frame identical to the last
- # intermediate — append a zero-width space so the content differs.
- final_text = text
- if text and text == turn.last_sent_content:
- final_text = text + "\u200b"
- await self._send_stream_reply(turn.req_id, turn.stream_id, final_text, finish=True)
- turn.finalized = True
- self._stream_turns.pop(f"{chat}:{turn_id or turn.req_id}", None)
- else:
- # Fire-and-forget: the gateway decides when to push (identity dedup
- # in stream_consumer.py); no adapter-side buffering.
- turn.accumulated_text = text
- if turn._intermediate_frames_sent >= MAX_INTERMEDIATE_FRAMES:
- return True # cap reached — drop intermediates; finalize drains the rest
- if text == turn.last_sent_content:
- return True
- await self._send_stream_reply(turn.req_id, turn.stream_id, text, finish=False)
- turn._intermediate_frames_sent += 1
- turn.last_sent_content = text
+ return await self._finalize_turn(turn, text, chat, turn_id)
+ # Fire-and-forget: the gateway decides when to push (identity dedup in stream_consumer.py).
+ turn.accumulated_text = text
+ if turn._intermediate_frames_sent >= MAX_INTERMEDIATE_FRAMES or text == turn.last_sent_content:
+ return True # cap reached (finalize drains the rest) or nothing new
+ await self._send_stream_reply(turn.req_id, turn.stream_id, text, finish=False)
+ turn._intermediate_frames_sent += 1
+ turn.last_sent_content = text
return True
-
except WeComStreamExpiredError:
- # An intermediate frame is overwritten by the next cumulative/final
- # frame anyway; flipping the turn expired here would trip the
- # consumer's send() fallback and duplicate the bubble. Only a FINAL
- # frame's expiry means content is genuinely missing.
+ # Intermediates are overwritten by the next frame anyway; expiring here would duplicate.
if not finalize:
- logger.info(
- "[%s] Intermediate stream frame expired (errcode=%d) for chat %s — dropping frame, stream stays live",
- self.name, STREAM_EXPIRED_ERRCODE, chat,
- )
+ logger.info("[%s] Intermediate stream frame expired (errcode=%d) for chat %s — dropping frame, stream stays live", self.name, STREAM_EXPIRED_ERRCODE, chat)
return True
- logger.info(
- "[%s] Stream expired (errcode=%d) for chat %s — switching to proactive send",
- self.name, STREAM_EXPIRED_ERRCODE, chat,
- )
- if turn is not None:
- self._expire_turn(turn, turn_id)
- else:
+ logger.info("[%s] Stream expired (errcode=%d) for chat %s — switching to proactive send", self.name, STREAM_EXPIRED_ERRCODE, chat)
+ if turn is None:
self._stream_expired_chats.add(chat)
- return False
+ else:
+ self._expire_turn(turn, turn_id)
except Exception as exc:
if not finalize: # same intermediate/final split as above
- logger.info(
- "[%s] Intermediate stream frame failed (chat=%s): %s — dropping frame, stream stays live",
- self.name, chat, exc,
- )
+ logger.info("[%s] Intermediate stream frame failed (chat=%s): %s — dropping frame, stream stays live", self.name, chat, exc)
return True
logger.warning("[%s] Stream frame failed (chat=%s): %s", self.name, chat, exc)
if turn is not None:
self._retire_turn(turn, turn_id)
- return False
+ return False
- def supports_native_streaming(
- self, chat_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
- ) -> bool:
+ def supports_native_streaming(self, chat_type: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> bool:
"""Stream frames work in DMs and groups alike (groups just need a cached inbound req_id)."""
del chat_type, metadata
return True
async def send_typing(self, chat_id: str, metadata=None) -> None:
- """No-op: the stream consumer's seed frame triggers WeCom typing; repeated
- send_typing calls would open orphan streams."""
+ """No-op: the stream consumer's seed frame triggers WeCom typing; repeated calls would open orphan streams."""
del chat_id, metadata
diff --git a/plugins/platforms/wecom/wecom_crypto.py b/plugins/platforms/wecom/wecom_crypto.py
index f984ca80c3e..5e09fa419f0 100644
--- a/plugins/platforms/wecom/wecom_crypto.py
+++ b/plugins/platforms/wecom/wecom_crypto.py
@@ -1,8 +1,4 @@
-"""WeCom BizMsgCrypt-compatible AES-CBC encryption for callback mode.
-
-Implements the same wire format as Tencent's official ``WXBizMsgCrypt``
-SDK so that WeCom can verify, encrypt, and decrypt callback payloads.
-"""
+"""WeCom callback-mode AES-CBC crypto, wire-compatible with Tencent's official ``WXBizMsgCrypt`` SDK."""
from __future__ import annotations
@@ -23,16 +19,13 @@ class WeComCryptoError(Exception):
pass
-class SignatureError(WeComCryptoError):
- pass
+class SignatureError(WeComCryptoError): pass
-class DecryptError(WeComCryptoError):
- pass
+class DecryptError(WeComCryptoError): pass
-class EncryptError(WeComCryptoError):
- pass
+class EncryptError(WeComCryptoError): pass
class PKCS7Encoder:
@@ -40,11 +33,8 @@ class PKCS7Encoder:
@classmethod
def encode(cls, text: bytes) -> bytes:
- amount_to_pad = cls.block_size - (len(text) % cls.block_size)
- if amount_to_pad == 0:
- amount_to_pad = cls.block_size
- pad = bytes([amount_to_pad]) * amount_to_pad
- return text + pad
+ amount_to_pad = cls.block_size - (len(text) % cls.block_size) or cls.block_size
+ return text + bytes([amount_to_pad]) * amount_to_pad
@classmethod
def decode(cls, decrypted: bytes) -> bytes:
@@ -59,54 +49,45 @@ class PKCS7Encoder:
def _sha1_signature(token: str, timestamp: str, nonce: str, encrypt: str) -> str:
- parts = sorted([token, timestamp, nonce, encrypt])
- return hashlib.sha1("".join(parts).encode("utf-8")).hexdigest()
+ return hashlib.sha1("".join(sorted([token, timestamp, nonce, encrypt])).encode("utf-8")).hexdigest()
class WXBizMsgCrypt:
"""Minimal WeCom callback crypto helper compatible with BizMsgCrypt semantics."""
def __init__(self, token: str, encoding_aes_key: str, receive_id: str):
- if not token:
- raise ValueError("token is required")
- if not encoding_aes_key:
- raise ValueError("encoding_aes_key is required")
- if len(encoding_aes_key) != 43:
- raise ValueError("encoding_aes_key must be 43 chars")
- if not receive_id:
- raise ValueError("receive_id is required")
-
- self.token = token
- self.receive_id = receive_id
+ for bad, message in (
+ (not token, "token is required"), (not encoding_aes_key, "encoding_aes_key is required"),
+ (len(encoding_aes_key) != 43, "encoding_aes_key must be 43 chars"), (not receive_id, "receive_id is required"),
+ ):
+ if bad:
+ raise ValueError(message)
+ self.token, self.receive_id = token, receive_id
self.key = base64.b64decode(encoding_aes_key + "=")
self.iv = self.key[:16]
+ def _cipher(self) -> Cipher:
+ return Cipher(algorithms.AES(self.key), modes.CBC(self.iv), backend=default_backend())
+
def verify_url(self, msg_signature: str, timestamp: str, nonce: str, echostr: str) -> str:
- plain = self.decrypt(msg_signature, timestamp, nonce, echostr)
- return plain.decode("utf-8")
+ return self.decrypt(msg_signature, timestamp, nonce, echostr).decode("utf-8")
def decrypt(self, msg_signature: str, timestamp: str, nonce: str, encrypt: str) -> bytes:
- expected = _sha1_signature(self.token, timestamp, nonce, encrypt)
- if expected != msg_signature:
+ if _sha1_signature(self.token, timestamp, nonce, encrypt) != msg_signature:
raise SignatureError("signature mismatch")
try:
cipher_text = base64.b64decode(encrypt)
except Exception as exc:
raise DecryptError(f"invalid base64 payload: {exc}") from exc
try:
- cipher = Cipher(algorithms.AES(self.key), modes.CBC(self.iv), backend=default_backend())
- decryptor = cipher.decryptor()
- padded = decryptor.update(cipher_text) + decryptor.finalize()
- plain = PKCS7Encoder.decode(padded)
- content = plain[16:] # skip 16-byte random prefix
+ decryptor = self._cipher().decryptor()
+ content = PKCS7Encoder.decode(decryptor.update(cipher_text) + decryptor.finalize())[16:] # skip 16-byte random prefix
xml_length = socket.ntohl(struct.unpack("I", content[:4])[0])
- xml_content = content[4:4 + xml_length]
- receive_id = content[4 + xml_length:].decode("utf-8")
+ xml_content, receive_id = content[4:4 + xml_length], content[4 + xml_length:].decode("utf-8")
except WeComCryptoError:
raise
except Exception as exc:
raise DecryptError(f"decrypt failed: {exc}") from exc
-
if receive_id != self.receive_id:
raise DecryptError("receive_id mismatch")
return xml_content
@@ -115,28 +96,19 @@ class WXBizMsgCrypt:
nonce = nonce or self._random_nonce()
timestamp = timestamp or str(int(__import__("time").time()))
encrypt = self._encrypt_bytes(plaintext.encode("utf-8"))
- signature = _sha1_signature(self.token, timestamp, nonce, encrypt)
root = ET.Element("xml")
- ET.SubElement(root, "Encrypt").text = encrypt
- ET.SubElement(root, "MsgSignature").text = signature
- ET.SubElement(root, "TimeStamp").text = timestamp
- ET.SubElement(root, "Nonce").text = nonce
+ for tag, text in (("Encrypt", encrypt), ("MsgSignature", _sha1_signature(self.token, timestamp, nonce, encrypt)), ("TimeStamp", timestamp), ("Nonce", nonce)):
+ ET.SubElement(root, tag).text = text
return ET.tostring(root, encoding="unicode")
def _encrypt_bytes(self, raw: bytes) -> str:
try:
- random_prefix = os.urandom(16)
- msg_len = struct.pack("I", socket.htonl(len(raw)))
- payload = random_prefix + msg_len + raw + self.receive_id.encode("utf-8")
- padded = PKCS7Encoder.encode(payload)
- cipher = Cipher(algorithms.AES(self.key), modes.CBC(self.iv), backend=default_backend())
- encryptor = cipher.encryptor()
- encrypted = encryptor.update(padded) + encryptor.finalize()
- return base64.b64encode(encrypted).decode("utf-8")
+ payload = os.urandom(16) + struct.pack("I", socket.htonl(len(raw))) + raw + self.receive_id.encode("utf-8")
+ encryptor = self._cipher().encryptor()
+ return base64.b64encode(encryptor.update(PKCS7Encoder.encode(payload)) + encryptor.finalize()).decode("utf-8")
except Exception as exc:
raise EncryptError(f"encrypt failed: {exc}") from exc
@staticmethod
def _random_nonce(length: int = 10) -> str:
- alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
- return "".join(secrets.choice(alphabet) for _ in range(length))
+ return "".join(secrets.choice("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") for _ in range(length))
diff --git a/plugins/platforms/whatsapp/adapter.py b/plugins/platforms/whatsapp/adapter.py
index b2ccd398925..e6181966877 100644
--- a/plugins/platforms/whatsapp/adapter.py
+++ b/plugins/platforms/whatsapp/adapter.py
@@ -1,9 +1,5 @@
-"""
-WhatsApp platform adapter (Baileys bridge).
-
-A Node.js bridge process runs the WhatsApp Web client; messages are polled over a
-local HTTP API and responses are posted back through the bridge.
-"""
+"""WhatsApp platform adapter (Baileys bridge): a Node.js bridge process runs the WhatsApp Web
+client; messages are polled over a local HTTP API and responses are posted back through it."""
import asyncio
import logging
@@ -12,6 +8,8 @@ import platform
import re
import signal
import subprocess
+from contextlib import suppress
+from functools import wraps
from pathlib import Path
from typing import Dict, Optional, Any
@@ -23,213 +21,138 @@ _IS_WINDOWS = platform.system() == "Windows"
def _wenv(name: str, default: str = "") -> str:
- """WHATSAPP_* env read through the profile secret scope (multiplexed profiles see
- their own .env; os.getenv would return the process-global value)."""
+ """WHATSAPP_* env via the profile secret scope (multiplexed profiles see their own .env, not the process-global value)."""
return get_scoped_secret(name, default)
logger = logging.getLogger(__name__)
-# Inbound owner-typed WhatsApp text is prefixed at MessageEvent construction so
-# transcripts stay disambiguated even if downstream plugins fail before silent_ingest.
+# Owner-typed inbound text is prefixed at MessageEvent construction so transcripts stay disambiguated before silent_ingest.
_OWNER_REPLY_PREFIX = "[owner reply] "
_RUN_TEXT = dict(capture_output=True, text=True, encoding='utf-8', errors='replace', stdin=subprocess.DEVNULL)
def _listener_pids_on_port(port: int) -> list:
- """PIDs of processes *listening* on ``port`` (POSIX) — never clients.
-
- A bare ``lsof -i :PORT`` also returns clients whose connection involves that
- port (e.g. a browser tab on a local dev server); SIGTERMing those closed the
- user's browser. Restricting to LISTEN state never touches an unrelated client.
- """
+ """PIDs *listening* on ``port`` (POSIX), never clients — a bare ``lsof -i :PORT`` once killed the user's browser."""
pids: list = []
- try:
- result = subprocess.run(["lsof", "-ti", f"tcp:{port}", "-sTCP:LISTEN"], timeout=5, **_RUN_TEXT)
- for line in result.stdout.strip().splitlines():
- try:
- pids.append(int(line))
- except ValueError:
- pass
+ with suppress(FileNotFoundError): # lsof not installed — fall through to ss
+ pids = _safe_ints(subprocess.run(["lsof", "-ti", f"tcp:{port}", "-sTCP:LISTEN"], timeout=5, **_RUN_TEXT).stdout.strip().splitlines())
if pids:
return pids
- except FileNotFoundError:
- pass # lsof not installed — fall through to ss
- try:
- result = subprocess.run(["ss", "-ltnHp", f"sport = :{port}"], timeout=5, **_RUN_TEXT)
- for m in re.finditer(r"pid=(\d+)", result.stdout):
- pids.append(int(m.group(1)))
- except FileNotFoundError:
- pass
+ with suppress(FileNotFoundError):
+ pids.extend(int(m.group(1)) for m in re.finditer(r"pid=(\d+)", subprocess.run(["ss", "-ltnHp", f"sport = :{port}"], timeout=5, **_RUN_TEXT).stdout))
return pids
-def _pid_looks_like_node_bridge(pid: int) -> bool:
- """Fail-closed check that *pid* is plausibly a stale node bridge.
+def _safe_ints(tokens) -> list:
+ out: list = []
+ for tok in tokens:
+ try:
+ out.append(int(tok))
+ except ValueError:
+ pass
+ return out
+
+
+def _windows_listener_pids(port: int) -> list:
+ """PIDs in LISTENING state on ``port`` via netstat (Windows)."""
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ result = subprocess.run(["netstat", "-ano", "-p", "TCP"], timeout=5, creationflags=windows_hide_flags(), **_RUN_TEXT)
+ rows = (line.split() for line in result.stdout.splitlines())
+ return _safe_ints(p[4] for p in rows if len(p) >= 5 and p[3] == "LISTENING" and p[1].endswith(f":{port}"))
+
- A scan-time PID can name a stranger (even a critical system process) by the
- time we kill it; require the live process to be a ``node`` executable. Any
- ambiguity (process gone, unreadable cmdline) refuses the kill.
- """
+def _pid_looks_like_node_bridge(pid: int) -> bool:
+ """Fail-closed: the live process must be a ``node`` executable (a scan-time PID can be a stranger by kill time)."""
try:
import psutil
proc = psutil.Process(pid)
- name = (proc.name() or "").lower()
- cmdline = " ".join(proc.cmdline() or []).lower()
- return "node" in name or "node" in cmdline.split(" ", 1)[0]
+ return "node" in (proc.name() or "").lower() or "node" in " ".join(proc.cmdline() or []).lower().split(" ", 1)[0]
except Exception:
return False
-def _warn_not_bridge(pid: int, port: int) -> None:
- logger.warning(
- "[whatsapp] Not killing PID %s on port %d: process is not a node bridge "
- "(or identity unverifiable)", pid, port)
-
-
def _kill_port_process(port: int) -> None:
- """Kill any node bridge *listening* on the given TCP port (never a client)."""
- try:
- if _IS_WINDOWS:
- from hermes_cli._subprocess_compat import windows_hide_flags
- result = subprocess.run(
- ["netstat", "-ano", "-p", "TCP"], timeout=5, creationflags=windows_hide_flags(), **_RUN_TEXT,
- )
- for line in result.stdout.splitlines():
- parts = line.split()
- if len(parts) >= 5 and parts[3] == "LISTENING" and parts[1].endswith(f":{port}"):
- try:
- pid = int(parts[4])
- except ValueError:
- continue
- # taskkill /F on a mistyped or recycled PID is unrecoverable — verify first.
- if pid <= 0 or not _pid_looks_like_node_bridge(pid):
- _warn_not_bridge(pid, port)
- continue
- try:
- subprocess.run(
- ["taskkill", "/PID", str(pid), "/F"],
- capture_output=True, timeout=5, creationflags=windows_hide_flags(),
- )
- except subprocess.SubprocessError:
- pass
- else:
- for pid in _listener_pids_on_port(port):
- if not _pid_looks_like_node_bridge(pid):
- _warn_not_bridge(pid, port)
- continue
- try:
+ """Kill any node bridge *listening* on the given TCP port (never a client); SIGTERM on POSIX, taskkill /F on Windows."""
+ with suppress(Exception):
+ for pid in (_windows_listener_pids(port) if _IS_WINDOWS else _listener_pids_on_port(port)):
+ # Killing a mistyped or recycled PID is unrecoverable — verify first.
+ if pid <= 0 or not _pid_looks_like_node_bridge(pid):
+ logger.warning("[whatsapp] Not killing PID %s on port %d: process is not a node bridge (or identity unverifiable)", pid, port)
+ continue
+ with suppress(subprocess.SubprocessError, OSError): # ProcessLookupError/PermissionError are OSError subclasses
+ if not _IS_WINDOWS:
os.kill(pid, signal.SIGTERM)
- except (ProcessLookupError, PermissionError, OSError):
- pass
- except Exception:
- pass
+ continue
+ from hermes_cli._subprocess_compat import windows_hide_flags
+ subprocess.run(["taskkill", "/PID", str(pid), "/F"], capture_output=True, timeout=5, creationflags=windows_hide_flags())
def _bridge_pid_is_ours(pid: int, session_path: Path, expected_start) -> bool:
- """True only if ``pid`` is alive AND still our node bridge for this session.
-
- The kernel can recycle a pidfile's PID onto an unrelated process (seen landing
- on a desktop browser, which a bare-liveness kill then closed). Identity is the
- recorded kernel start time (definitive); legacy pidfiles without one fall back
- to a cmdline containing ``node`` and this session's unique path.
- """
- from gateway.status import _pid_exists
- if not _pid_exists(pid):
+ """``pid`` alive AND still our bridge: kernel start time (definitive), else legacy ``node`` + session path in cmdline."""
+ from gateway import status
+ if not status._pid_exists(pid):
return False
if expected_start is not None:
- from gateway.status import get_process_start_time
- return get_process_start_time(pid) == expected_start
- from gateway.status import _read_process_cmdline
- cmdline = _read_process_cmdline(pid)
- if not cmdline:
- return False
- return ("node" in cmdline) and (str(session_path) in cmdline)
+ return status.get_process_start_time(pid) == expected_start
+ cmdline = status._read_process_cmdline(pid)
+ return bool(cmdline) and ("node" in cmdline) and (str(session_path) in cmdline)
-def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:
- """Kill an orphaned bridge recorded in ``bridge.pid`` from a previous run.
+def _unlink_quietly(path: Path) -> None:
+ with suppress(OSError):
+ path.unlink()
+
- The PID is re-validated via :func:`_bridge_pid_is_ours` before any signal.
- """
+def _kill_stale_bridge_by_pidfile(session_path: Path) -> None:
+ """Kill an orphaned bridge recorded in ``bridge.pid``, after :func:`_bridge_pid_is_ours`."""
+ from gateway.status import _pid_exists
pid_file = session_path / "bridge.pid"
if not pid_file.exists():
return
- pid = None
- recorded_start = None
- try:
- # Line 1 = pid, optional line 2 = kernel start time (legacy files: pid only).
- lines = pid_file.read_text(encoding="utf-8").split("\n")
- pid = int(lines[0].strip())
- if len(lines) > 1 and lines[1].strip():
- recorded_start = int(lines[1].strip())
+ try: # Line 1 = pid, optional line 2 = kernel start time (legacy files: pid only).
+ lines = [ln.strip() for ln in pid_file.read_text(encoding="utf-8").split("\n")]
+ pid = int(lines[0])
+ recorded_start = int(lines[1]) if len(lines) > 1 and lines[1] else None
except (ValueError, OSError, TypeError, IndexError):
- try:
- pid_file.unlink()
- except OSError:
- pass
+ _unlink_quietly(pid_file)
return
if _bridge_pid_is_ours(pid, session_path, recorded_start):
- try:
+ with suppress(OSError): # ProcessLookupError / PermissionError included
os.kill(pid, signal.SIGTERM)
logger.info("[whatsapp] Killed stale bridge PID %d from pidfile", pid)
- except (ProcessLookupError, PermissionError, OSError):
- pass
- else:
- from gateway.status import _pid_exists
- if _pid_exists(pid):
- logger.warning(
- "[whatsapp] Not killing pidfile PID %d: it is no longer the "
- "bridge (recycled onto an unrelated process); skipping to avoid "
- "killing a stranger.", pid,
- )
- try:
- pid_file.unlink()
- except OSError:
- pass
+ elif _pid_exists(pid):
+ logger.warning("[whatsapp] Not killing pidfile PID %d: it is no longer the bridge (recycled onto an unrelated process); "
+ "skipping to avoid killing a stranger.", pid)
+ _unlink_quietly(pid_file)
def _write_bridge_pidfile(session_path: Path, pid: int) -> None:
- """Write the bridge PID plus its kernel start time (line 2) for later identity-checked cleanup."""
- try:
+ """Write the bridge PID plus its kernel start time (line 2) for identity-checked cleanup."""
+ with suppress(OSError):
from gateway.status import get_process_start_time
start = get_process_start_time(pid)
- text = str(pid) if start is None else "{}\n{}".format(pid, start)
- (session_path / "bridge.pid").write_text(text, encoding="utf-8")
- except OSError:
- pass
+ (session_path / "bridge.pid").write_text(str(pid) if start is None else f"{pid}\n{start}", encoding="utf-8")
def _terminate_bridge_process(proc, *, force: bool = False) -> None:
"""Terminate the bridge process using process-tree semantics where possible."""
+ action = "kill" if force else "terminate"
if _IS_WINDOWS:
- cmd = ["taskkill", "/PID", str(proc.pid), "/T"]
- if force:
- cmd.append("/F")
try:
- result = subprocess.run(cmd, timeout=10, **_RUN_TEXT)
+ result = subprocess.run(["taskkill", "/PID", str(proc.pid), "/T"] + (["/F"] if force else []), timeout=10, **_RUN_TEXT)
except FileNotFoundError:
- if force:
- proc.kill()
- else:
- proc.terminate()
- return
+ return getattr(proc, action)()
if result.returncode != 0:
- details = (result.stderr or result.stdout or "").strip()
- raise OSError(details or f"taskkill failed for PID {proc.pid}")
+ raise OSError((result.stderr or result.stdout or "").strip() or f"taskkill failed for PID {proc.pid}")
return
import psutil
- action = "kill" if force else "terminate"
- try:
+ with suppress(psutil.NoSuchProcess):
parent = psutil.Process(proc.pid)
for child in parent.children(recursive=True):
- try:
+ with suppress(psutil.NoSuchProcess):
getattr(child, action)()
- except psutil.NoSuchProcess:
- pass
getattr(parent, action)()
- except psutil.NoSuchProcess:
- return
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
@@ -238,50 +161,32 @@ from gateway.config import Platform, PlatformConfig
from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin
from gateway.whatsapp_identity import to_whatsapp_jid
from gateway.platforms.base import (
- BasePlatformAdapter,
- MessageEvent,
- MessageType,
- SendResult,
- SUPPORTED_DOCUMENT_TYPES,
- cache_image_from_url,
- cache_audio_from_url,
+ BasePlatformAdapter, MessageEvent, MessageType, SendResult, SUPPORTED_DOCUMENT_TYPES, cache_image_from_url, cache_audio_from_url,
)
from utils import env_int
-def _is_allowed_bridge_path(url: str) -> bool:
- """True only when an absolute bridge path resolves inside a Hermes media cache dir.
+def _cache_dirs() -> tuple:
+ """``(image, audio, video, document)`` cache dirs, resolved per call so a profile override's cache matches."""
+ from gateway.platforms.base import get_audio_cache_dir, get_document_cache_dir, get_image_cache_dir, get_video_cache_dir
+ return get_image_cache_dir(), get_audio_cache_dir(), get_video_cache_dir(), get_document_cache_dir()
- A compromised or buggy bridge could hand back ``/etc/passwd``; resolve
- symlinks and require one of the real cache roots (canonical ``cache/<kind>``
- or legacy ``<kind>_cache`` layout).
- """
+
+def _is_allowed_bridge_path(url: str) -> bool:
+ """Absolute bridge path resolves (symlinks included) inside a Hermes cache dir — a rogue bridge could hand back /etc/passwd."""
try:
resolved = Path(url).resolve()
except (OSError, ValueError):
return False
- # Per-call getters (not import-time constants) so a profile override's cache matches.
- from gateway.platforms.base import (
- get_audio_cache_dir,
- get_document_cache_dir,
- get_image_cache_dir,
- get_video_cache_dir,
- )
- for root in (get_image_cache_dir(), get_audio_cache_dir(), get_video_cache_dir(), get_document_cache_dir()):
- try:
+ for root in _cache_dirs():
+ with suppress(OSError, ValueError):
if resolved.is_relative_to(Path(root).resolve()):
return True
- except (OSError, ValueError):
- continue
return False
def _file_content_hash(path: Path) -> str:
- """First 16 hex chars of SHA-256 of *path* ("" if unreadable).
-
- bridge.js reports its own hash in ``/health`` (``scriptHash``); a mismatch with
- the on-disk file means a long-lived bridge is serving pre-update code.
- """
+ """First 16 hex chars of SHA-256 of *path* ("" if unreadable); bridge.js reports its own as ``/health`` ``scriptHash``."""
import hashlib
try:
return hashlib.sha256(path.read_bytes()).hexdigest()[:16]
@@ -292,49 +197,44 @@ def _file_content_hash(path: Path) -> str:
def check_whatsapp_requirements() -> bool:
"""Node.js (Hermes-managed first, so a bad system Node on PATH can't break Windows) is available."""
_node = find_node_executable("node")
- if not _node:
- return False
try:
- result = subprocess.run([_node, "--version"], timeout=5, **_RUN_TEXT)
- return result.returncode == 0
+ return bool(_node) and subprocess.run([_node, "--version"], timeout=5, **_RUN_TEXT).returncode == 0
except Exception:
return False
-# Env vars bridge.js consumes. Under multiplexing the subprocess gets a copy of
-# os.environ without the secondary profile's .env, so the resolved values are injected.
+# Env vars bridge.js consumes; injected because a multiplexed subprocess's os.environ lacks the secondary profile's .env.
_BRIDGE_PASSTHROUGH_ENV = (
- "WHATSAPP_ALLOWED_USERS", "WHATSAPP_ALLOW_FROM",
- "WHATSAPP_DM_POLICY", "WHATSAPP_GROUP_POLICY",
- "WHATSAPP_GROUP_ALLOWED_USERS", "WHATSAPP_GROUP_ALLOW_FROM",
- "WHATSAPP_REQUIRE_MENTION", "WHATSAPP_MENTION_PATTERNS",
- "WHATSAPP_FREE_RESPONSE_CHATS",
- "WHATSAPP_DEBUG", "WHATSAPP_FORWARD_OWNER_MESSAGES",
- "WHATSAPP_REPLY_PREFIX", "WHATSAPP_MAX_MESSAGE_LENGTH",
+ "WHATSAPP_ALLOWED_USERS", "WHATSAPP_ALLOW_FROM", "WHATSAPP_DM_POLICY", "WHATSAPP_GROUP_POLICY",
+ "WHATSAPP_GROUP_ALLOWED_USERS", "WHATSAPP_GROUP_ALLOW_FROM", "WHATSAPP_REQUIRE_MENTION",
+ "WHATSAPP_MENTION_PATTERNS", "WHATSAPP_FREE_RESPONSE_CHATS", "WHATSAPP_DEBUG",
+ "WHATSAPP_FORWARD_OWNER_MESSAGES", "WHATSAPP_REPLY_PREFIX", "WHATSAPP_MAX_MESSAGE_LENGTH",
"WHATSAPP_CHUNK_DELAY_MS", "WHATSAPP_SEND_TIMEOUT_MS",
)
_TEXT_INJECT_EXTS = {".txt", ".md", ".csv", ".json", ".xml", ".yaml", ".yml", ".log", ".py", ".js", ".ts", ".html", ".css"}
_MAX_TEXT_INJECT_BYTES = 100 * 1024 # matches Telegram/Discord/Slack
-_MEDIA_LABEL = {
- MessageType.PHOTO: "image", MessageType.VOICE: "audio", MessageType.AUDIO: "audio",
- MessageType.DOCUMENT: "document", MessageType.VIDEO: "video",
-}
-_MEDIA_DEFAULT_MIME = {
- MessageType.PHOTO: "image/jpeg", MessageType.VOICE: "audio/ogg",
- MessageType.AUDIO: "audio/mpeg", MessageType.VIDEO: "video/mp4",
+_NATIVE_MEDIA_TYPES = {"location": MessageType.LOCATION, "live_location": MessageType.LOCATION, "sticker": MessageType.STICKER}
+# Inbound mediaType substring → kind; ptt = WhatsApp voice note, so "ptt" must precede "audio".
+_MEDIA_NEEDLES = (("image", MessageType.PHOTO), ("video", MessageType.VIDEO), ("ptt", MessageType.VOICE), ("audio", MessageType.AUDIO))
+# MessageType → (bridge label, default mime); documents take their mime from SUPPORTED_DOCUMENT_TYPES instead.
+_MEDIA_INFO = {
+ MessageType.PHOTO: ("image", "image/jpeg"), MessageType.VOICE: ("audio", "audio/ogg"), MessageType.AUDIO: ("audio", "audio/mpeg"),
+ MessageType.VIDEO: ("video", "video/mp4"), MessageType.DOCUMENT: ("document", ""),
}
-class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
- """WhatsApp adapter over a local Node.js (Baileys) HTTP bridge; behavior comes
- from ``WhatsAppBehaviorMixin``, only transport lives here.
+def _needs_bridge(method):
+ """Adapter-method decorator: return ``SendResult(error=...)`` when ``_bridge_unavailable()`` says so."""
+ @wraps(method)
+ async def _guarded(self, *args, **kwargs):
+ unavailable = await self._bridge_unavailable()
+ return SendResult(success=False, error=unavailable) if unavailable else await method(self, *args, **kwargs)
+ return _guarded
- Configuration (config.extra):
- - bridge_script / bridge_port (default 3000) / session_path
- - dm_policy, group_policy: "open" | "allowlist" | "disabled" | "pairing" (default "pairing")
- - allow_from / group_allow_from: IDs allowed when the policy is "allowlist"
- - send_read_receipts: Mark accepted inbound WhatsApp messages as read
- """
+
+class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
+ """Transport over a local Node.js (Baileys) HTTP bridge; behavior lives in ``WhatsAppBehaviorMixin``. config.extra: bridge_script /
+ bridge_port (3000) / session_path, dm_policy / group_policy (open|allowlist|disabled|pairing), allow_from / group_allow_from, send_read_receipts."""
_DEFAULT_BRIDGE_DIR = None # resolved in __init__
splits_long_messages = True # send() chunks via truncate_message()
@@ -344,38 +244,24 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
if WhatsAppAdapter._DEFAULT_BRIDGE_DIR is None:
from gateway.platforms.whatsapp_common import resolve_whatsapp_bridge_dir
WhatsAppAdapter._DEFAULT_BRIDGE_DIR = resolve_whatsapp_bridge_dir()
+ extra = config.extra
self._bridge_process: Optional[subprocess.Popen] = None
- self._bridge_port: int = config.extra.get("bridge_port", 3000)
- self._bridge_script: Optional[str] = config.extra.get(
- "bridge_script", str(self._DEFAULT_BRIDGE_DIR / "bridge.js"),
- )
- self._session_path: Path = Path(config.extra.get(
- "session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")
- ))
- self._reply_prefix: Optional[str] = config.extra.get("reply_prefix")
- self._dm_policy = str(config.extra.get("dm_policy") or _wenv("WHATSAPP_DM_POLICY", "pairing")).strip().lower()
- allow_raw = self._select_dm_allowlist(config.extra, ("WHATSAPP_ALLOWED_USERS",), _wenv)
- self._allow_from = self._coerce_allow_list(allow_raw)
- self._group_policy = str(config.extra.get("group_policy") or _wenv("WHATSAPP_GROUP_POLICY", "pairing")).strip().lower()
- self._group_allow_from = self._coerce_allow_list(config.extra.get("group_allow_from") or config.extra.get("groupAllowFrom"))
- read_receipts = config.extra.get("send_read_receipts", False)
- self._send_read_receipts = (
- read_receipts if isinstance(read_receipts, bool)
- else str(read_receipts or "").strip().lower() in {"1", "true", "yes", "on"}
- )
+ self._bridge_port: int = extra.get("bridge_port", 3000)
+ self._bridge_script: str = extra.get("bridge_script", str(self._DEFAULT_BRIDGE_DIR / "bridge.js"))
+ self._session_path = Path(extra.get("session_path", get_hermes_dir("platforms/whatsapp/session", "whatsapp/session")))
+ self._reply_prefix: Optional[str] = extra.get("reply_prefix")
+ self._dm_policy = str(extra.get("dm_policy") or _wenv("WHATSAPP_DM_POLICY", "pairing")).strip().lower()
+ self._allow_from = self._coerce_allow_list(self._select_dm_allowlist(extra, ("WHATSAPP_ALLOWED_USERS",), _wenv))
+ self._group_policy = str(extra.get("group_policy") or _wenv("WHATSAPP_GROUP_POLICY", "pairing")).strip().lower()
+ self._group_allow_from = self._coerce_allow_list(extra.get("group_allow_from") or extra.get("groupAllowFrom"))
+ rr = extra.get("send_read_receipts", False)
+ self._send_read_receipts = rr if isinstance(rr, bool) else str(rr or "").strip().lower() in {"1", "true", "yes", "on"}
self._mention_patterns = self._compile_mention_patterns()
self._message_queue: asyncio.Queue = asyncio.Queue()
- self._bridge_log_fh = None
- self._bridge_log: Optional[Path] = None
- self._poll_task: Optional[asyncio.Task] = None
- self._http_session: Optional["aiohttp.ClientSession"] = None
- # Set by disconnect() before SIGTERMing the child so _check_managed_bridge_exit()
- # can tell an intentional exit (-15 / -2 / 0) from a crash.
- self._shutting_down: bool = False
-
- # Text debounce batching: WhatsApp delivers rapid bursts (forwards,
- # paste-splits); without debounce each triggers a separate agent turn.
- # Tunable via extra.text_batch_delay_seconds / text_batch_split_delay_seconds.
+ self._bridge_log_fh = self._bridge_log = self._poll_task = self._http_session = None
+ # Set by disconnect() before SIGTERMing so _check_managed_bridge_exit() can tell an intentional exit (-15/-2/0) from a crash.
+ self._shutting_down = False
+ # Text debounce batching: rapid bursts (forwards, paste-splits) would otherwise each trigger a separate agent turn.
self._text_batch_delay_seconds = self._coerce_float_extra("text_batch_delay_seconds", 5.0)
self._text_batch_split_delay_seconds = self._coerce_float_extra("text_batch_split_delay_seconds", 10.0)
self._pending_text_batches: Dict[str, MessageEvent] = {}
@@ -384,82 +270,60 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
def _coerce_float_extra(self, key: str, default: float) -> float:
"""Read a float from ``config.extra``; NaN/Inf/negative/unparseable → ``default`` (fed to asyncio.sleep)."""
import math
- value = self.config.extra.get(key) if getattr(self.config, "extra", None) else None
- if value is None:
- return float(default)
- try:
- parsed = float(value)
+ try: # float(None) → TypeError → default
+ parsed = float(self.config.extra.get(key) if getattr(self.config, "extra", None) else None)
except (TypeError, ValueError):
return float(default)
- if not math.isfinite(parsed) or parsed < 0:
- return float(default)
- return parsed
-
- # ── bridge lifecycle ─────────────────────────────────────────────
+ return parsed if math.isfinite(parsed) and parsed >= 0 else float(default)
def _bridge_url(self, path: str) -> str:
return f"http://127.0.0.1:{self._bridge_port}/{path}"
+ def _bridge_req(self, method: str, path: str, timeout: float, **kwargs):
+ """``session.<method>`` context manager for a bridge endpoint (caller must ``async with``)."""
+ import aiohttp
+ return getattr(self._http_session, method)(self._bridge_url(path), **kwargs, timeout=aiohttp.ClientTimeout(total=timeout))
+
async def _probe_bridge_health(self) -> tuple[bool, Any]:
- """GET /health with a fresh session. Returns ``(http_200, json)``; a 200 with
- an unparseable body yields ``(True, None)``. Connection errors propagate."""
+ """GET /health with a fresh session → ``(http_200, json)``; unparseable 200 body → ``(True, None)``; connection errors propagate."""
import aiohttp
- async with aiohttp.ClientSession() as session:
- async with session.get(self._bridge_url("health"), timeout=aiohttp.ClientTimeout(total=2)) as resp:
- if resp.status != 200:
- return False, None
- try:
- return True, await resp.json()
- except Exception:
- return True, None
+ async with aiohttp.ClientSession() as session, session.get(self._bridge_url("health"), timeout=aiohttp.ClientTimeout(total=2)) as resp:
+ if resp.status != 200:
+ return False, None
+ try:
+ return True, await resp.json()
+ except Exception:
+ return True, None
def _ensure_bridge_deps(self, bridge_dir: Path) -> bool:
- """npm install when node_modules is missing OR package.json changed since the
- last install (stamp file holds the package.json hash). False = fatal error set."""
- _pkg_json = bridge_dir / "package.json"
- _dep_stamp = bridge_dir / "node_modules" / ".hermes-pkg-hash"
- _pkg_hash = _file_content_hash(_pkg_json)
- _deps_fresh = False
- if (bridge_dir / "node_modules").exists():
- try:
- _deps_fresh = (_dep_stamp.read_text(encoding="utf-8").strip() == _pkg_hash) and bool(_pkg_hash)
- except OSError:
- _deps_fresh = False
- if _deps_fresh:
- return True
+ """npm install when node_modules is missing OR package.json hash != stamp file. False = fatal error set."""
+ _dep_stamp = bridge_dir / "node_modules" / ".hermes-pkg-hash" # holds the package.json hash of the last install
+ _pkg_hash = _file_content_hash(bridge_dir / "package.json")
+ try:
+ if (bridge_dir / "node_modules").exists() and _dep_stamp.read_text(encoding="utf-8").strip() == _pkg_hash and bool(_pkg_hash):
+ return True
+ except OSError:
+ pass
print(f"[{self.name}] Installing WhatsApp bridge dependencies...")
# Hermes-managed portable Node's npm.cmd first (Windows), then PATH.
_npm_bin = find_node_executable("npm") or "npm"
- try:
- # Default 300s accommodates slow systems like an Unraid NAS.
- npm_install_timeout = env_int("WHATSAPP_NPM_INSTALL_TIMEOUT", 300)
- install_result = subprocess.run(
- [_npm_bin, "install", "--silent"],
- cwd=str(bridge_dir), timeout=npm_install_timeout, env=with_hermes_node_path(), **_RUN_TEXT,
- )
- if install_result.returncode != 0:
- print(f"[{self.name}] npm install failed: {install_result.stderr}")
- self._set_fatal_error(
- "whatsapp_npm_install_failed",
- f"WhatsApp bridge npm install failed. Run `cd {bridge_dir} && {_npm_bin} install` manually, then restart `hermes gateway`.",
- retryable=False,
- )
- return False
- print(f"[{self.name}] Dependencies installed")
- if _pkg_hash:
- try:
- _dep_stamp.write_text(_pkg_hash, encoding="utf-8")
- except OSError:
- pass # Stamp is an optimization; install still succeeded
+ detail = ""
+ try: # Default 300s accommodates slow systems like an Unraid NAS.
+ install_result = subprocess.run([_npm_bin, "install", "--silent"], cwd=str(bridge_dir), timeout=env_int("WHATSAPP_NPM_INSTALL_TIMEOUT", 300),
+ env=with_hermes_node_path(), **_RUN_TEXT)
+ if install_result.returncode == 0:
+ print(f"[{self.name}] Dependencies installed")
+ with suppress(OSError): # Stamp is an optimization; install still succeeded
+ if _pkg_hash:
+ _dep_stamp.write_text(_pkg_hash, encoding="utf-8")
+ return True
+ print(f"[{self.name}] npm install failed: {install_result.stderr}")
except Exception as e:
print(f"[{self.name}] Failed to install dependencies: {e}")
- self._set_fatal_error(
- "whatsapp_npm_install_failed",
- f"WhatsApp bridge npm install failed ({e}). Run `cd {bridge_dir} && {_npm_bin} install` manually, then restart `hermes gateway`.",
- retryable=False,
- )
- return False
- return True
+ detail = f" ({e})"
+ self._set_fatal_error("whatsapp_npm_install_failed", f"WhatsApp bridge npm install failed{detail}. Run `cd {bridge_dir} && {_npm_bin} install` "
+ "manually, then restart `hermes gateway`.", retryable=False)
+ return False
def _attach_to_bridge(self, managed_process) -> None:
import aiohttp
@@ -468,35 +332,24 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
self._poll_task = asyncio.create_task(self._poll_messages())
async def _reuse_running_bridge(self, bridge_path: Path) -> bool:
- """Adopt an already-connected bridge if it serves the on-disk bridge.js and
- the same read-receipt config; otherwise report why it will be restarted.
-
- A long-lived bridge survives gateway restarts AND `hermes update`, so a
- hash mismatch (or no ``scriptHash`` at all) is stale by definition.
- """
+ """Adopt a connected bridge serving the on-disk bridge.js + same read-receipt config; else say why it restarts."""
try:
ok, data = await self._probe_bridge_health()
- if ok and data is not None:
- bridge_status = data.get("status", "unknown")
- if bridge_status == "connected":
- running_hash = data.get("scriptHash", "")
- disk_hash = _file_content_hash(bridge_path)
- running_read_receipts = bool(data.get("sendReadReceipts", False))
- config_matches = running_read_receipts == self._send_read_receipts
- if running_hash and disk_hash and running_hash == disk_hash and config_matches:
- print(f"[{self.name}] Using existing bridge (status: {bridge_status})")
- self._mark_connected()
- self._attach_to_bridge(None) # Not managed by us
- self._wire_plugin_handlers(None)
- return True
- stale_reason = (
- f"running={running_hash or 'unversioned'}, disk={disk_hash}"
- if running_hash != disk_hash
- else "send_read_receipts config changed"
- )
- print(f"[{self.name}] Running bridge is stale ({stale_reason}), restarting")
- else:
- print(f"[{self.name}] Bridge found but not connected (status: {bridge_status}), restarting")
+ if not ok or data is None:
+ return False
+ bridge_status = data.get("status", "unknown")
+ if bridge_status != "connected":
+ print(f"[{self.name}] Bridge found but not connected (status: {bridge_status}), restarting")
+ return False
+ running_hash, disk_hash = data.get("scriptHash", ""), _file_content_hash(bridge_path)
+ if running_hash and disk_hash and running_hash == disk_hash and bool(data.get("sendReadReceipts", False)) == self._send_read_receipts:
+ print(f"[{self.name}] Using existing bridge (status: {bridge_status})")
+ self._mark_connected()
+ self._attach_to_bridge(None) # Not managed by us
+ self._wire_plugin_handlers(None)
+ return True
+ stale_reason = f"running={running_hash or 'unversioned'}, disk={disk_hash}" if running_hash != disk_hash else "send_read_receipts config changed"
+ print(f"[{self.name}] Running bridge is stale ({stale_reason}), restarting")
except Exception:
pass # Bridge not running, start a new one
return False
@@ -508,23 +361,12 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
if self._reply_prefix is not None:
bridge_env["WHATSAPP_REPLY_PREFIX"] = self._reply_prefix
bridge_env["WHATSAPP_SEND_READ_RECEIPTS"] = "true" if self._send_read_receipts else "false"
- _profile_wa_mode = _wenv("WHATSAPP_MODE", "self-chat")
- if _profile_wa_mode:
- bridge_env["WHATSAPP_MODE"] = _profile_wa_mode
- for _key in _BRIDGE_PASSTHROUGH_ENV:
- _v = _wenv(_key)
+ for _key, _v in [("WHATSAPP_MODE", _wenv("WHATSAPP_MODE", "self-chat"))] + [(k, _wenv(k)) for k in _BRIDGE_PASSTHROUGH_ENV]:
if _v:
bridge_env[_key] = _v
- # Without these the bridge hardcodes ~/.hermes/{image,audio,document}_cache,
- # which diverges under HERMES_HOME overrides, profiles, and the cache/ layout.
- from gateway.platforms.base import (
- get_audio_cache_dir as _get_audio_dir,
- get_document_cache_dir as _get_doc_dir,
- get_image_cache_dir as _get_img_dir,
- )
- bridge_env["HERMES_IMAGE_CACHE_DIR"] = str(_get_img_dir())
- bridge_env["HERMES_AUDIO_CACHE_DIR"] = str(_get_audio_dir())
- bridge_env["HERMES_DOCUMENT_CACHE_DIR"] = str(_get_doc_dir())
+ # Without these the bridge hardcodes ~/.hermes/{image,audio,document}_cache (wrong under HERMES_HOME/profiles/cache layout).
+ img_dir, audio_dir, _video_dir, doc_dir = _cache_dirs()
+ 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:
@@ -534,8 +376,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
return False
async def _poll_bridge_health(self, died_msg: str) -> tuple[Optional[bool], bool, dict]:
- """Poll /health up to 15×1s. Returns ``(connected, http_ready, data)``; ``connected``
- is False when the process died (already reported), None when time ran out."""
+ """Poll /health up to 15×1s → ``(connected, http_ready, data)``; connected False = process died (reported), None = timeout."""
http_ready = False
data: dict = {}
for attempt in range(15):
@@ -556,8 +397,7 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
return None, http_ready, data
async def _wait_for_bridge(self) -> bool:
- """Phase 1: HTTP server up (≤15s). Phase 2: WhatsApp ``status: connected`` (≤15s more;
- proceeds with a warning if still connecting — the bridge may auto-reconnect later)."""
+ """Phase 1: HTTP up (≤15s). Phase 2: ``status: connected`` (≤15s more; warns but proceeds if still connecting)."""
connected, http_ready, data = await self._poll_bridge_health("Bridge process died (exit code {code})")
if connected is False:
return False
@@ -574,43 +414,32 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
print(f"[{self.name}] If session expired, re-pair: hermes whatsapp")
return True
+ def _preflight(self) -> bool:
+ """Node + bridge script + creds.json present, else a non-retryable fatal error (an unpaired bridge only prints QR codes; retries would pay 30s each)."""
+ bridge_path = Path(self._bridge_script)
+ creds_path = self._session_path / "creds.json"
+ checks = (
+ (check_whatsapp_requirements, ("[%s] Node.js not found. WhatsApp requires Node.js.", self.name),
+ "whatsapp_node_missing", "Node.js is not installed — install Node.js and re-run `hermes gateway`."),
+ (bridge_path.exists, ("[%s] Bridge script not found: %s", self.name, bridge_path),
+ "whatsapp_bridge_missing", f"WhatsApp bridge script missing at {bridge_path}."),
+ (creds_path.exists, ("[%s] WhatsApp is enabled but not paired (no creds.json at %s). Pair from the dashboard or run "
+ "`hermes whatsapp`; remove WHATSAPP_ENABLED from your .env to disable.", self.name, creds_path),
+ "whatsapp_not_paired", "WhatsApp enabled but not paired — pair from the dashboard or run `hermes whatsapp`."),
+ )
+ for ok, warn_args, code, message in checks:
+ if not ok():
+ logger.warning(*warn_args)
+ self._set_fatal_error(code, message, retryable=False)
+ return False
+ logger.info("[%s] Bridge found at %s", self.name, bridge_path)
+ return True
+
async def connect(self, *, is_reconnect: bool = False) -> bool:
"""Start (or adopt) the Node.js bridge and wait for it to be ready."""
- if not check_whatsapp_requirements():
- logger.warning("[%s] Node.js not found. WhatsApp requires Node.js.", self.name)
- self._set_fatal_error(
- "whatsapp_node_missing",
- "Node.js is not installed — install Node.js and re-run `hermes gateway`.",
- retryable=False,
- )
+ if not self._preflight():
return False
bridge_path = Path(self._bridge_script)
- if not bridge_path.exists():
- logger.warning("[%s] Bridge script not found: %s", self.name, bridge_path)
- self._set_fatal_error(
- "whatsapp_bridge_missing",
- f"WhatsApp bridge script missing at {bridge_path}.",
- retryable=False,
- )
- return False
-
- # Without creds.json the bridge only prints QR codes and never connects, so
- # every restart would pay the 30s timeout; fail non-retryable with a clear message.
- creds_path = self._session_path / "creds.json"
- if not creds_path.exists():
- logger.warning(
- "[%s] WhatsApp is enabled but not paired (no creds.json at %s). "
- "Pair from the dashboard or run `hermes whatsapp`; remove "
- "WHATSAPP_ENABLED from your .env to disable.",
- self.name, creds_path,
- )
- self._set_fatal_error(
- "whatsapp_not_paired",
- "WhatsApp enabled but not paired — pair from the dashboard or run `hermes whatsapp`.",
- retryable=False,
- )
- return False
- logger.info("[%s] Bridge found at %s", self.name, bridge_path)
lock_acquired = False
try:
if not self._acquire_platform_lock('whatsapp-session', str(self._session_path), 'WhatsApp session'):
@@ -627,27 +456,12 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
_kill_stale_bridge_by_pidfile(self._session_path)
_kill_port_process(self._bridge_port)
await asyncio.sleep(1)
-
- # Bridge output goes to a log file so QR codes, errors, and reconnection
- # messages are preserved for troubleshooting.
- whatsapp_mode = _wenv("WHATSAPP_MODE", "self-chat")
+ # Bridge output goes to a log file so QR codes, errors, and reconnection messages survive for troubleshooting.
self._bridge_log = self._session_path.parent / "bridge.log"
- bridge_log_fh = open(self._bridge_log, "a", encoding="utf-8")
- self._bridge_log_fh = bridge_log_fh
- bridge_env = self._bridge_env()
+ self._bridge_log_fh = bridge_log_fh = open(self._bridge_log, "a", encoding="utf-8")
self._bridge_process = subprocess.Popen(
- [
- find_node_executable("node") or "node",
- str(bridge_path),
- "--port", str(self._bridge_port),
- "--session", str(self._session_path),
- "--mode", whatsapp_mode,
- ],
- stdout=bridge_log_fh,
- stderr=bridge_log_fh,
- env=bridge_env,
- **windows_detach_popen_kwargs(),
- )
+ [find_node_executable("node") or "node", str(bridge_path), "--port", str(self._bridge_port), "--session", str(self._session_path),
+ "--mode", _wenv("WHATSAPP_MODE", "self-chat")], stdout=bridge_log_fh, stderr=bridge_log_fh, env=self._bridge_env(), **windows_detach_popen_kwargs())
_write_bridge_pidfile(self._session_path, self._bridge_process.pid)
if not await self._wait_for_bridge():
return False
@@ -666,22 +480,15 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
self._close_bridge_log()
def _close_bridge_log(self) -> None:
- """Close the bridge log file handle if open."""
if self._bridge_log_fh:
- try:
+ with suppress(Exception):
self._bridge_log_fh.close()
- except Exception:
- pass
self._bridge_log_fh = None
async def _check_managed_bridge_exit(self) -> Optional[str]:
- """Return a fatal error message if the managed bridge child exited."""
- if self._bridge_process is None:
- return None
- returncode = self._bridge_process.poll()
+ returncode = self._bridge_process.poll() if self._bridge_process is not None else None
if returncode is None:
return None
-
# getattr-with-default: tests build the adapter via ``__new__`` without __init__.
if getattr(self, "_shutting_down", False) and returncode in {0, -2, -15}:
logger.info("[%s] Bridge exited during shutdown (code %d).", self.name, returncode)
@@ -694,213 +501,124 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
await self._notify_fatal_error()
return self.fatal_error_message or message
+ def _terminate_bridge(self, *, force: bool) -> None:
+ try:
+ _terminate_bridge_process(self._bridge_process, force=force)
+ except (ProcessLookupError, PermissionError):
+ getattr(self._bridge_process, "kill" if force else "terminate")()
+
async def disconnect(self) -> None:
"""Stop the WhatsApp bridge and clean up any orphaned processes."""
- # Flip BEFORE signalling so the exit-check path (send(), poll loop) doesn't
- # report the intentional termination as fatal.
- self._shutting_down = True
- if self._bridge_process:
+ self._shutting_down = True # flip BEFORE signalling so send()/poll loop don't report the intentional exit as fatal
+ if not self._bridge_process:
+ print(f"[{self.name}] Disconnecting (external bridge left running)")
+ else:
try:
- try:
- _terminate_bridge_process(self._bridge_process, force=False)
- except (ProcessLookupError, PermissionError):
- self._bridge_process.terminate()
+ self._terminate_bridge(force=False)
await asyncio.sleep(1)
if self._bridge_process.poll() is None:
- try:
- _terminate_bridge_process(self._bridge_process, force=True)
- except (ProcessLookupError, PermissionError):
- self._bridge_process.kill()
+ self._terminate_bridge(force=True)
except Exception as e:
print(f"[{self.name}] Error stopping bridge: {e}")
- else:
- print(f"[{self.name}] Disconnecting (external bridge left running)")
- try:
- (self._session_path / "bridge.pid").unlink(missing_ok=True)
- except OSError:
- pass
+ _unlink_quietly(self._session_path / "bridge.pid")
if self._poll_task and not self._poll_task.done():
self._poll_task.cancel()
- try:
+ with suppress(asyncio.CancelledError, Exception):
await self._poll_task
- except (asyncio.CancelledError, Exception):
- pass
- self._poll_task = None
if self._http_session and not self._http_session.closed:
await self._http_session.close()
- self._http_session = None
+ self._poll_task = self._http_session = self._bridge_process = None
self._release_platform_lock()
self._mark_disconnected()
- self._bridge_process = None
self._close_bridge_log()
print(f"[{self.name}] Disconnected")
- # ── outbound ─────────────────────────────────────────────────────
-
async def _bridge_unavailable(self) -> Optional[str]:
- """Error string when the bridge can't take a request, else None."""
- if not self._running or not self._http_session:
- return "Not connected"
- return await self._check_managed_bridge_exit() or None
+ return "Not connected" if not self._running or not self._http_session else (await self._check_managed_bridge_exit() or None)
async def _post_bridge_message(self, path: str, payload: Dict[str, Any], *, timeout: float) -> SendResult:
"""POST to the bridge; 200 → SendResult(messageId, raw_response), else the error text."""
try:
- import aiohttp
- async with self._http_session.post(
- self._bridge_url(path), json=payload, timeout=aiohttp.ClientTimeout(total=timeout),
- ) as resp:
+ async with self._bridge_req("post", path, timeout, json=payload) as resp:
if resp.status == 200:
data = await resp.json()
return SendResult(success=True, message_id=data.get("messageId"), raw_response=data)
- error = await resp.text()
- return SendResult(success=False, error=error)
+ return SendResult(success=False, error=await resp.text())
except Exception as e:
return SendResult(success=False, error=str(e))
- async def send(
- self,
- chat_id: str,
- content: str,
- reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None
- ) -> SendResult:
+ @_needs_bridge
+ async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
"""Format markdown for WhatsApp, chunk preserving code blocks, send sequentially."""
- unavailable = await self._bridge_unavailable()
- if unavailable:
- return SendResult(success=False, error=unavailable)
if not content or not content.strip():
return SendResult(success=True, message_id=None)
chat_id = to_whatsapp_jid(chat_id)
try:
- formatted = self.format_message(content)
- chunks = self.truncate_message(formatted, self._outgoing_chunk_limit())
+ chunks = self.truncate_message(self.format_message(content), self._outgoing_chunk_limit())
sent_message_ids: list[str] = []
last_message_id = None
for idx, chunk in enumerate(chunks):
payload: Dict[str, Any] = {"chatId": chat_id, "message": chunk}
if reply_to and idx == 0:
- # Reply-to on the first chunk only.
- payload["replyTo"] = reply_to
+ payload["replyTo"] = reply_to # Reply-to on the first chunk only.
result = await self._post_bridge_message("send", payload, timeout=30)
if not result.success:
return SendResult(success=False, error=result.error)
last_message_id = result.message_id
if last_message_id:
sent_message_ids.append(str(last_message_id))
- # Small delay between chunks to avoid rate limiting
if len(chunks) > 1:
- await asyncio.sleep(0.3)
- return SendResult(
- success=True,
- message_id=last_message_id,
- continuation_message_ids=tuple(sent_message_ids[:-1]),
- raw_response={"message_ids": sent_message_ids},
- )
+ await asyncio.sleep(0.3) # avoid rate limiting between chunks
+ return SendResult(success=True, message_id=last_message_id, continuation_message_ids=tuple(sent_message_ids[:-1]),
+ raw_response={"message_ids": sent_message_ids})
except Exception as e:
return SendResult(success=False, error=str(e))
- async def edit_message(
- self, chat_id: str, message_id: str, content: str, *, finalize: bool = False,
- ) -> SendResult:
- """Edit a previously sent message via the WhatsApp bridge."""
- unavailable = await self._bridge_unavailable()
- if unavailable:
- return SendResult(success=False, error=unavailable)
+ @_needs_bridge
+ async def edit_message(self, chat_id: str, message_id: str, content: str, *, finalize: bool = False) -> SendResult:
try:
- import aiohttp
- async with self._http_session.post(
- self._bridge_url("edit"),
- json={"chatId": to_whatsapp_jid(chat_id), "messageId": message_id, "message": content},
- timeout=aiohttp.ClientTimeout(total=15)
- ) as resp:
- if resp.status == 200:
- return SendResult(success=True, message_id=message_id)
- error = await resp.text()
- return SendResult(success=False, error=error)
+ async with self._bridge_req("post", "edit", 15, json={"chatId": to_whatsapp_jid(chat_id), "messageId": message_id, "message": content}) as resp:
+ return SendResult(success=True, message_id=message_id) if resp.status == 200 else SendResult(success=False, error=await resp.text())
except Exception as e:
return SendResult(success=False, error=str(e))
- async def _send_media_to_bridge(
- self, chat_id: str, file_path: str, media_type: str, caption: Optional[str] = None,
- file_name: Optional[str] = None,
- ) -> SendResult:
- """Send any media file via bridge /send-media endpoint."""
- unavailable = await self._bridge_unavailable()
- if unavailable:
- return SendResult(success=False, error=unavailable)
+ @_needs_bridge
+ async def _send_media_to_bridge(self, chat_id: str, file_path: str, media_type: str, caption: Optional[str] = None, file_name: Optional[str] = None) -> SendResult:
if not os.path.exists(file_path):
return SendResult(success=False, error=f"File not found: {file_path}")
payload: Dict[str, Any] = {"chatId": to_whatsapp_jid(chat_id), "filePath": file_path, "mediaType": media_type}
- if caption:
- payload["caption"] = caption
- if file_name:
- payload["fileName"] = file_name
+ payload.update({k: v for k, v in (("caption", caption), ("fileName", file_name)) if v})
return await self._post_bridge_message("send-media", payload, timeout=120)
- async def send_poll(
- self, chat_id: str, question: str, options: list[str], *, selectable_count: int = 1,
- ) -> SendResult:
+ @_needs_bridge
+ async def send_poll(self, chat_id: str, question: str, options: list[str], *, selectable_count: int = 1) -> SendResult:
"""Native WhatsApp poll (low-level transport primitive; approval UX stays gateway-owned)."""
- unavailable = await self._bridge_unavailable()
- if unavailable:
- return SendResult(success=False, error=unavailable)
- payload: Dict[str, Any] = {
- "chatId": to_whatsapp_jid(chat_id),
- "question": question,
- "options": list(options or []),
- "selectableCount": selectable_count,
- }
+ payload: Dict[str, Any] = {"chatId": to_whatsapp_jid(chat_id), "question": question, "options": list(options or []), "selectableCount": selectable_count}
return await self._post_bridge_message("send-poll", payload, timeout=30)
- async def send_clarify(
- self, chat_id: str, question: str, choices: Optional[list], clarify_id: str,
- session_key: str, metadata: Optional[Dict[str, Any]] = None,
- ) -> SendResult:
- """Multiple-choice clarify as a native poll; Baileys emits the selected option
- as message text, which the normal clarify text-intercept resolves. Open-ended
- (or failed poll) falls back to the text prompt."""
+ async def send_clarify(self, chat_id: str, question: str, choices: Optional[list], clarify_id: str, session_key: str,
+ metadata: Optional[Dict[str, Any]] = None) -> SendResult:
+ """Multiple-choice clarify as a native poll (the pick arrives as message text for the normal intercept); else text prompt."""
clean_choices = [str(choice).strip() for choice in (choices or []) if str(choice).strip()]
if 2 <= len(clean_choices) <= 12:
result = await self.send_poll(chat_id, str(question or "").strip(), clean_choices, selectable_count=1)
if result.success:
return result
- logger.warning(
- "[%s] Native WhatsApp clarify poll failed; falling back to text: %s",
- self.name, result.error,
- )
- return await super().send_clarify(
- chat_id=chat_id, question=question, choices=choices,
- clarify_id=clarify_id, session_key=session_key, metadata=metadata,
- )
+ logger.warning("[%s] Native WhatsApp clarify poll failed; falling back to text: %s", self.name, result.error)
+ return await super().send_clarify(chat_id=chat_id, question=question, choices=choices, clarify_id=clarify_id, session_key=session_key, metadata=metadata)
- async def send_location(
- self, chat_id: str, latitude: float, longitude: float, *, name: Optional[str] = None,
- address: Optional[str] = None, reply_to: Optional[str] = None,
- metadata: Optional[Dict[str, Any]] = None,
- ) -> SendResult:
- """Send a native WhatsApp location pin via the Baileys bridge."""
- unavailable = await self._bridge_unavailable()
- if unavailable:
- return SendResult(success=False, error=unavailable)
+ @_needs_bridge
+ async def send_location(self, chat_id: str, latitude: float, longitude: float, *, name: Optional[str] = None, address: Optional[str] = None,
+ reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None) -> SendResult:
try:
- payload: Dict[str, Any] = {
- "chatId": to_whatsapp_jid(chat_id),
- "latitude": float(latitude),
- "longitude": float(longitude),
- }
+ payload: Dict[str, Any] = {"chatId": to_whatsapp_jid(chat_id), "latitude": float(latitude), "longitude": float(longitude)}
except Exception as e:
return SendResult(success=False, error=str(e))
- if name:
- payload["name"] = name
- if address:
- payload["address"] = address
+ payload.update({k: v for k, v in (("name", name), ("address", address)) if v})
return await self._post_bridge_message("send-location", payload, timeout=30)
- async def send_image(
- self, chat_id: str, image_url: str, caption: Optional[str] = None,
- reply_to: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None,
- ) -> SendResult:
+ async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None,
+ metadata: Optional[Dict[str, Any]] = None) -> SendResult:
"""Download image URL to cache, send natively via bridge (``metadata`` honors the base contract)."""
try:
local_path = await cache_image_from_url(image_url)
@@ -908,92 +626,55 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
except Exception:
return await super().send_image(chat_id, image_url, caption, reply_to, metadata)
- async def send_image_file(
- self, chat_id: str, image_path: str, caption: Optional[str] = None,
- reply_to: Optional[str] = None, **kwargs,
- ) -> SendResult:
+ async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:
return await self._send_media_to_bridge(chat_id, image_path, "image", caption)
- async def send_video(
- self, chat_id: str, video_path: str, caption: Optional[str] = None,
- reply_to: Optional[str] = None, **kwargs,
- ) -> SendResult:
+ async def send_video(self, chat_id: str, video_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:
return await self._send_media_to_bridge(chat_id, video_path, "video", caption)
- async def send_voice(
- self, chat_id: str, audio_path: str, caption: Optional[str] = None,
- reply_to: Optional[str] = None, **kwargs,
- ) -> SendResult:
+ async def send_voice(self, chat_id: str, audio_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, **kwargs) -> SendResult:
return await self._send_media_to_bridge(chat_id, audio_path, "audio", caption)
- async def send_document(
- self, chat_id: str, file_path: str, caption: Optional[str] = None,
- file_name: Optional[str] = None, reply_to: Optional[str] = None, **kwargs,
- ) -> SendResult:
- return await self._send_media_to_bridge(
- chat_id, file_path, "document", caption, file_name or os.path.basename(file_path),
- )
+ async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None,
+ reply_to: Optional[str] = None, **kwargs) -> SendResult:
+ return await self._send_media_to_bridge(chat_id, file_path, "document", caption, file_name or os.path.basename(file_path))
async def send_typing(self, chat_id: str, metadata=None) -> None:
- """Send typing indicator via bridge (failures ignored)."""
if await self._bridge_unavailable():
return
- try:
+ with suppress(Exception):
import aiohttp
-
- # ``async with`` — a bare ``await session.post(...)`` leaves the response
- # alive until GC, holding its socket in CLOSE_WAIT.
- async with self._http_session.post(
- self._bridge_url("typing"),
- json={"chatId": to_whatsapp_jid(chat_id)},
- timeout=aiohttp.ClientTimeout(total=5)
- ):
+ # ``async with`` — a bare ``await session.post(...)`` leaves the response (and its CLOSE_WAIT socket) alive until GC.
+ async with self._http_session.post(self._bridge_url("typing"), json={"chatId": to_whatsapp_jid(chat_id)}, timeout=aiohttp.ClientTimeout(total=5)):
pass
- except Exception:
- pass
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
- """Get information about a WhatsApp chat."""
if not self._running or not self._http_session:
return {"name": "Unknown", "type": "dm"}
- if await self._check_managed_bridge_exit():
- return {"name": chat_id, "type": "dm"}
- try:
- import aiohttp
- async with self._http_session.get(
- self._bridge_url(f"chat/{to_whatsapp_jid(chat_id)}"),
- timeout=aiohttp.ClientTimeout(total=10)
- ) as resp:
- if resp.status == 200:
- data = await resp.json()
- return {
- "name": data.get("name", chat_id),
- "type": "group" if data.get("isGroup") else "dm",
- "participants": data.get("participants", []),
- }
- except Exception as e:
- logger.debug("Could not get WhatsApp chat info for %s: %s", chat_id, e)
+ if not await self._check_managed_bridge_exit():
+ try:
+ async with self._bridge_req("get", f"chat/{to_whatsapp_jid(chat_id)}", 10) as resp:
+ if resp.status == 200:
+ data = await resp.json()
+ return {"name": data.get("name", chat_id), "type": "group" if data.get("isGroup") else "dm", "participants": data.get("participants", [])}
+ except Exception as e:
+ logger.debug("Could not get WhatsApp chat info for %s: %s", chat_id, e)
return {"name": chat_id, "type": "dm"}
- # ── inbound ──────────────────────────────────────────────────────
+ async def _report_bridge_exit(self) -> bool:
+ bridge_exit = await self._check_managed_bridge_exit()
+ if bridge_exit:
+ print(f"[{self.name}] {bridge_exit}")
+ return bool(bridge_exit)
async def _poll_messages(self) -> None:
- """Poll the bridge for incoming messages."""
- import aiohttp
while self._running:
- if not self._http_session:
- break
- bridge_exit = await self._check_managed_bridge_exit()
- if bridge_exit:
- print(f"[{self.name}] {bridge_exit}")
+ if not self._http_session or await self._report_bridge_exit():
break
try:
- async with self._http_session.get(
- self._bridge_url("messages"), timeout=aiohttp.ClientTimeout(total=30)
- ) as resp:
+ async with self._bridge_req("get", "messages", 30) as resp:
if resp.status == 200:
- messages = await resp.json()
- for msg_data in messages:
+ for msg_data in await resp.json():
event = await self._build_message_event(msg_data)
if event:
# Fire-and-forget: a slow bridge /read must not delay dispatch.
@@ -1005,50 +686,34 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
except asyncio.CancelledError:
break
except Exception as e:
- bridge_exit = await self._check_managed_bridge_exit()
- if bridge_exit:
- print(f"[{self.name}] {bridge_exit}")
+ if await self._report_bridge_exit():
break
print(f"[{self.name}] Poll error: {e}")
await asyncio.sleep(5)
await asyncio.sleep(1) # Poll interval
async def _send_read_receipt(self, data: Dict[str, Any]) -> None:
- """Mark a policy-accepted inbound message as read via the bridge."""
- if not self._send_read_receipts or not self._http_session:
- return
key = data.get("readReceiptKey")
- if not isinstance(key, dict):
+ if not self._send_read_receipts or not self._http_session or not isinstance(key, dict):
return
try:
- import aiohttp
- async with self._http_session.post(
- self._bridge_url("read"), json={"key": key}, timeout=aiohttp.ClientTimeout(total=5),
- ) as resp:
+ async with self._bridge_req("post", "read", 5, json={"key": key}) as resp:
if resp.status != 200:
logger.warning("[%s] WhatsApp read receipt failed with HTTP %s", self.name, resp.status)
except Exception as exc:
logger.warning("[%s] WhatsApp read receipt failed: %s", self.name, exc)
- # ── Text debounce batching ──────────────────────────────────────
-
_SPLIT_THRESHOLD = 6000 # WhatsApp supports ~65K chars; generous threshold
async def _flush_text_batch(self, key: str) -> None:
- """Wait for quiet period then dispatch aggregated text."""
current_task = asyncio.current_task()
try:
pending = self._pending_text_batches.get(key)
last_len = getattr(pending, "_last_chunk_len", 0) if pending else 0
- if last_len >= self._SPLIT_THRESHOLD:
- delay = self._text_batch_split_delay_seconds
- else:
- delay = self._text_batch_delay_seconds
- await asyncio.sleep(delay)
+ await asyncio.sleep(self._text_batch_split_delay_seconds if last_len >= self._SPLIT_THRESHOLD else self._text_batch_delay_seconds)
event = self._pending_text_batches.pop(key, None)
- if not event:
- return
- await self.handle_message(event)
+ if event:
+ await self.handle_message(event)
finally:
if self._pending_text_batch_tasks.get(key) is current_task:
self._pending_text_batch_tasks.pop(key, None)
@@ -1056,84 +721,51 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
@staticmethod
def _classify_bridge_message(data: Dict[str, Any]) -> MessageType:
media_type = str(data.get("mediaType", "") or "")
- if media_type in {"location", "live_location"}:
- return MessageType.LOCATION
- if media_type == "sticker":
- return MessageType.STICKER
- if data.get("hasMedia"):
- if "image" in media_type:
- return MessageType.PHOTO
- if "video" in media_type:
- return MessageType.VIDEO
- if "ptt" in media_type: # ptt = WhatsApp voice note
- return MessageType.VOICE
- if "audio" in media_type:
- return MessageType.AUDIO
- return MessageType.DOCUMENT
- return MessageType.TEXT
-
- async def _collect_bridge_media(
- self, data: Dict[str, Any], msg_type: MessageType
- ) -> tuple[list, list]:
- """Resolve bridge ``mediaUrls`` into ``(cached_urls, media_types)``.
-
- Remote image/audio URLs are downloaded to the local cache; absolute paths the
- bridge already downloaded are accepted only inside a Hermes cache dir.
- """
- cached_urls = []
- media_types = []
- label = _MEDIA_LABEL.get(msg_type)
+ if media_type in _NATIVE_MEDIA_TYPES:
+ return _NATIVE_MEDIA_TYPES[media_type]
+ if not data.get("hasMedia"):
+ return MessageType.TEXT
+ return next((kind for needle, kind in _MEDIA_NEEDLES if needle in media_type), MessageType.DOCUMENT)
+
+ async def _collect_bridge_media(self, data: Dict[str, Any], msg_type: MessageType) -> tuple[list, list]:
+ """``mediaUrls`` → ``(cached_urls, media_types)``: remote image/audio cached locally; absolute paths only inside a cache dir."""
+ accepted: list[tuple] = [] # (url_or_path, mime)
+ label, default_mime = _MEDIA_INFO.get(msg_type, (None, ""))
+ bridge_mime = str(data.get("mime") or "").strip()
for url in data.get("mediaUrls", []):
- bridge_mime = str(data.get("mime") or "").strip()
- is_http = url.startswith(("http://", "https://"))
- if msg_type == MessageType.DOCUMENT:
- mime = bridge_mime or SUPPORTED_DOCUMENT_TYPES.get(Path(url).suffix.lower(), "application/octet-stream")
- else:
- mime = bridge_mime or _MEDIA_DEFAULT_MIME.get(msg_type, "")
- if is_http and msg_type in {MessageType.PHOTO, MessageType.VOICE, MessageType.AUDIO}:
- cacher, ext = (
- (cache_image_from_url, ".jpg") if msg_type == MessageType.PHOTO else (cache_audio_from_url, ".ogg")
- )
+ mime = bridge_mime or (SUPPORTED_DOCUMENT_TYPES.get(Path(url).suffix.lower(), "application/octet-stream") if msg_type == MessageType.DOCUMENT else default_mime)
+ if url.startswith(("http://", "https://")) and msg_type in {MessageType.PHOTO, MessageType.VOICE, MessageType.AUDIO}:
+ cacher, ext = (cache_image_from_url, ".jpg") if msg_type == MessageType.PHOTO else (cache_audio_from_url, ".ogg")
try:
- cached_path = await cacher(url, ext=ext)
- cached_urls.append(cached_path)
- media_types.append(mime)
- print(f"[{self.name}] Cached user {label}: {cached_path}", flush=True)
+ url = await cacher(url, ext=ext)
+ print(f"[{self.name}] Cached user {label}: {url}", flush=True)
except Exception as e:
print(f"[{self.name}] Failed to cache {label}: {e}", flush=True)
- cached_urls.append(url)
- media_types.append(mime)
+ accepted.append((url, mime))
elif label is not None and os.path.isabs(url):
if _is_allowed_bridge_path(url):
- cached_urls.append(url)
- media_types.append(mime)
+ accepted.append((url, mime))
print(f"[{self.name}] Using bridge-cached {label}: {url}", flush=True)
else:
print(f"[{self.name}] Rejected bridge {label} path outside cache dir: {url}", flush=True)
else:
- cached_urls.append(url)
- media_types.append("unknown")
- return cached_urls, media_types
+ accepted.append((url, "unknown"))
+ return [u for u, _ in accepted], [m for _, m in accepted]
def _inject_document_text(self, cached_urls: list, body: str) -> str:
"""Prepend text-readable document contents (≤100KB) so the agent reads them inline."""
for doc_path in cached_urls:
- if Path(doc_path).suffix.lower() not in _TEXT_INJECT_EXTS:
+ p = Path(doc_path)
+ if p.suffix.lower() not in _TEXT_INJECT_EXTS:
continue
try:
- file_size = Path(doc_path).stat().st_size
+ file_size = p.stat().st_size
if file_size > _MAX_TEXT_INJECT_BYTES:
print(f"[{self.name}] Skipping text injection for {doc_path} ({file_size} bytes > {_MAX_TEXT_INJECT_BYTES})", flush=True)
continue
- content = Path(doc_path).read_text(encoding="utf-8", errors="replace")
- fname = Path(doc_path).name
- # Remove the doc_<hex>_ prefix for display
- display_name = fname
- if "_" in fname:
- parts = fname.split("_", 2)
- if len(parts) >= 3:
- display_name = parts[2]
- injection = f"[Content of {display_name}]:\n{content}"
+ content = p.read_text(encoding="utf-8", errors="replace")
+ parts = p.name.split("_", 2) # strip the doc_<hex>_ prefix for display
+ injection = f"[Content of {parts[2] if len(parts) >= 3 else p.name}]:\n{content}"
body = f"{injection}\n\n{body}" if body else injection
print(f"[{self.name}] Injected text content from: {doc_path}", flush=True)
except Exception as e:
@@ -1146,177 +778,101 @@ class WhatsAppAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
if 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",
- user_id=data.get("senderId"),
- user_name=data.get("senderName"),
- )
+ source = self.build_source(chat_id=data.get("chatId", ""), chat_name=data.get("chatName"), chat_type="group" if data.get("isGroup", False) else "dm",
+ user_id=data.get("senderId"), user_name=data.get("senderName"))
cached_urls, media_types = await self._collect_bridge_media(data, msg_type)
body = data.get("body", "")
if data.get("isGroup"):
body = self._clean_bot_mention_text(body, data)
- if (
- msg_type == MessageType.VOICE
- and cached_urls
- and str(body).strip().lower() == "[ptt received]"
- ):
- # Bridge placeholder for captionless voice notes; the audio is the payload.
- body = ""
-
- # Quoted message stays in structured fields only — GatewayRunner renders
- # the "[Replying to: ...]" pointer for every platform.
- quoted_text = str(data.get("quotedText") or "").strip()
- reply_to_text = quoted_text or None
- reply_to_message_id = None
- reply_to_author_id = None
- reply_to_is_own_message = False
- if data.get("hasQuotedMessage"):
- raw_reply_id = data.get("quotedMessageId")
- if raw_reply_id is not None:
- reply_to_message_id = str(raw_reply_id)
- quoted_participant = self._normalize_whatsapp_id(data.get("quotedParticipant"))
- if quoted_participant:
- reply_to_author_id = quoted_participant
- reply_to_is_own_message = self._message_is_reply_to_bot(data)
+ if msg_type == MessageType.VOICE and cached_urls and str(body).strip().lower() == "[ptt received]":
+ body = "" # Bridge placeholder for captionless voice notes; the audio is the payload.
+ # Quoted message stays in structured fields only — GatewayRunner renders the "[Replying to: ...]" pointer.
+ quoted = bool(data.get("hasQuotedMessage"))
+ raw_reply_id = data.get("quotedMessageId") if quoted else None
if msg_type == MessageType.DOCUMENT and cached_urls:
body = self._inject_document_text(cached_urls, body)
- metadata: Dict[str, Any] = {}
- native_type = str(data.get("nativeType") or "").strip()
native_metadata = data.get("nativeMetadata")
- if native_type:
- metadata["whatsapp_native_type"] = native_type
- if isinstance(native_metadata, dict) and native_metadata:
- metadata["whatsapp_native"] = native_metadata
- # ``fromOwner`` = owner-typed inbound fromMe (linked device), gated by
- # WHATSAPP_FORWARD_OWNER_MESSAGES at the bridge. Surfaced as metadata AND
- # a text prefix so the marker survives downstream failures before silent_ingest.
+ metadata: Dict[str, Any] = {k: v for k, v in (
+ ("whatsapp_native_type", str(data.get("nativeType") or "").strip()),
+ ("whatsapp_native", native_metadata if isinstance(native_metadata, dict) else None),
+ ) if v}
+ # ``fromOwner`` = owner-typed inbound fromMe (gated by WHATSAPP_FORWARD_OWNER_MESSAGES at the bridge); surfaced as
+ # metadata AND a text prefix so the marker survives downstream failures before silent_ingest.
if data.get("fromOwner"):
metadata["whatsapp_from_owner"] = True
if not body.startswith(_OWNER_REPLY_PREFIX):
body = f"{_OWNER_REPLY_PREFIX}{body}"
return MessageEvent(
- text=body,
- message_type=msg_type,
- source=source,
- raw_message=data,
- message_id=data.get("messageId"),
- media_urls=cached_urls,
- media_types=media_types,
- metadata=metadata,
- reply_to_message_id=reply_to_message_id,
- reply_to_text=reply_to_text,
- reply_to_author_id=reply_to_author_id,
- reply_to_is_own_message=reply_to_is_own_message,
+ text=body, message_type=msg_type, source=source, raw_message=data, message_id=data.get("messageId"),
+ media_urls=cached_urls, media_types=media_types, metadata=metadata,
+ reply_to_message_id=str(raw_reply_id) if raw_reply_id is not None else None,
+ reply_to_text=str(data.get("quotedText") or "").strip() or None,
+ reply_to_author_id=(self._normalize_whatsapp_id(data.get("quotedParticipant")) or None) if quoted else None,
+ reply_to_is_own_message=self._message_is_reply_to_bot(data) if quoted else False,
)
except Exception as e:
print(f"[{self.name}] Error building event: {e}")
return None
-# ──────────────────────────────────────────────────────────────────────────
-# Plugin glue: register(ctx) plus the hook implementations that replaced the
-# per-platform core touchpoints (gateway/run.py, gateway/config.py,
-# hermes_cli/gateway.py, tools/send_message_tool.py).
-# ──────────────────────────────────────────────────────────────────────────
-
+# ── Plugin glue: register(ctx) plus the hooks for gateway/run.py, gateway/config.py, hermes_cli/gateway.py, send_message_tool.py.
-_WA_IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".gif"}
-_WA_VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"}
-_WA_AUDIO_EXTS = {".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac"}
+_WA_EXT_MEDIA_TYPE = {
+ **dict.fromkeys((".jpg", ".jpeg", ".png", ".webp", ".gif"), "image"),
+ **dict.fromkeys((".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp"), "video"),
+ **dict.fromkeys((".ogg", ".opus", ".mp3", ".wav", ".m4a", ".flac"), "audio"),
+}
def _bridge_media_type(file_path: str, is_voice: bool, force_document: bool) -> str:
- """Map a local file to the bridge ``mediaType`` (image|video|audio|document).
-
- ``force_document`` (the [[as_document]] directive) forces ``document``.
- """
- if force_document:
- return "document"
- ext = os.path.splitext(file_path)[1].lower()
- if is_voice or ext in _WA_AUDIO_EXTS:
- return "audio"
- if ext in _WA_IMAGE_EXTS:
- return "image"
- if ext in _WA_VIDEO_EXTS:
- return "video"
- return "document"
-
-
-async def _standalone_send(
- pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False,
- caption=None,
-):
- """Out-of-process WhatsApp delivery via the bridge HTTP API (standalone_sender_fn
- contract, so deliver=whatsapp cron jobs work when cron runs apart from the gateway).
-
- With ``caption`` (single-file ``MEDIA:<path> caption`` send) the text rides on
- the media bubble's native caption instead of a separate ``/send``.
- """
- extra = getattr(pconfig, "extra", {}) or {}
+ """Local file → bridge ``mediaType`` (image|video|audio|document); ``force_document`` = the [[as_document]] directive."""
+ return "document" if force_document else "audio" if is_voice else _WA_EXT_MEDIA_TYPE.get(os.path.splitext(file_path)[1].lower(), "document")
+
+
+async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False, caption=None):
+ """Out-of-process delivery via the bridge HTTP API (standalone_sender_fn: cron apart from the gateway); ``caption`` rides on the media bubble."""
try:
import aiohttp
except ImportError:
return {"error": "aiohttp not installed. Run: pip install aiohttp"}
try:
- bridge_port = extra.get("bridge_port", 3000)
+ bridge_port = (getattr(pconfig, "extra", {}) or {}).get("bridge_port", 3000)
normalized_chat_id = to_whatsapp_jid(chat_id)
media = media_files or []
- text = message or ""
# A caption only applies to a single media file — never repeat it across a multi-file send.
media_caption = caption if (caption and len(media) == 1) else None
last_message_id = None
async with aiohttp.ClientSession() as session:
- def _post(path, payload, total):
- return session.post(
- f"http://localhost:{bridge_port}/{path}", json=payload, timeout=aiohttp.ClientTimeout(total=total),
- )
-
+ async def _post(path, payload, total, error_label=None):
+ """``(messageId, None)`` on 200, else ``(None, error_dict)`` (body read only when labelled)."""
+ url = f"http://localhost:{bridge_port}/{path}"
+ async with session.post(url, json=payload, timeout=aiohttp.ClientTimeout(total=total)) as resp:
+ if resp.status == 200:
+ return (await resp.json()).get("messageId"), None
+ return None, {} if error_label is None else {"error": f"WhatsApp {error_label} error ({resp.status}): {await resp.text()}"}
# 1) Text first (skipped when media-only or when the text rides as the caption).
- if text.strip() and not media_caption:
- async with _post("send", {"chatId": normalized_chat_id, "message": text}, 30) as resp:
- if resp.status != 200:
- body = await resp.text()
- return {"error": f"WhatsApp bridge error ({resp.status}): {body}"}
- data = await resp.json()
- last_message_id = data.get("messageId")
-
+ if (message or "").strip() and not media_caption:
+ last_message_id, err = await _post("send", {"chatId": normalized_chat_id, "message": message}, 30, "bridge")
+ if err:
+ return err
# 2) Each media file as a native attachment (mediaType picks the WhatsApp kind).
for media_path, is_voice in media:
if not os.path.exists(media_path):
- # In caption mode the words would be lost with the missing file —
- # deliver the caption as a plain message so nothing silently disappears.
+ # In caption mode the words would vanish with the missing file — deliver the caption as a plain message.
if media_caption:
try:
- async with _post("send", {"chatId": normalized_chat_id, "message": media_caption}, 30) as resp:
- if resp.status == 200:
- last_message_id = (await resp.json()).get("messageId")
+ await _post("send", {"chatId": normalized_chat_id, "message": media_caption}, 30)
except Exception:
logger.warning("WhatsApp caption-fallback send failed for missing media")
return {"error": f"WhatsApp media file not found: {media_path}"}
media_type = _bridge_media_type(media_path, is_voice, force_document)
- payload: Dict[str, Any] = {
- "chatId": normalized_chat_id,
- "filePath": media_path,
- "mediaType": media_type,
- }
- if media_type == "document":
- payload["fileName"] = os.path.basename(media_path)
- if media_caption:
- payload["caption"] = media_caption
- async with _post("send-media", payload, 120) as resp:
- if resp.status != 200:
- body = await resp.text()
- return {"error": f"WhatsApp media error ({resp.status}): {body}"}
- data = await resp.json()
- last_message_id = data.get("messageId") or last_message_id
- return {
- "success": True,
- "platform": "whatsapp",
- "chat_id": normalized_chat_id,
- "message_id": last_message_id,
- }
+ payload: Dict[str, Any] = {"chatId": normalized_chat_id, "filePath": media_path, "mediaType": media_type}
+ payload.update({k: v for k, v in (("fileName", os.path.basename(media_path) if media_type == "document" else None), ("caption", media_caption)) if v})
+ mid, err = await _post("send-media", payload, 120, "media")
+ if err:
+ return err
+ last_message_id = mid or last_message_id
+ return {"success": True, "platform": "whatsapp", "chat_id": normalized_chat_id, "message_id": last_message_id}
except Exception as e:
return {"error": f"WhatsApp send failed: {e}"}
@@ -1324,28 +880,20 @@ async def _standalone_send(
def interactive_setup() -> None:
"""Guide the user through WhatsApp setup (CLI helpers lazy-imported)."""
from hermes_cli.config import get_env_value, remove_env_value, save_env_value
- from hermes_cli.cli_output import (
- prompt,
- prompt_yes_no,
- print_header,
- print_info,
- print_success,
- )
+ from hermes_cli.cli_output import prompt, prompt_yes_no, print_header, print_info, print_success
print_header("WhatsApp")
print_info("WhatsApp uses a local Node.js bridge (WhatsApp Web client).")
print_info("Start the bridge separately; the gateway connects to it over HTTP.")
- existing = get_env_value("WHATSAPP_ENABLED")
- if existing and existing.lower() in {"true", "1", "yes"}:
+ if (get_env_value("WHATSAPP_ENABLED") or "").lower() in {"true", "1", "yes"}:
print_info("WhatsApp: already enabled")
if not prompt_yes_no("Reconfigure WhatsApp?", False):
return
- if prompt_yes_no("Enable WhatsApp?", True):
- save_env_value("WHATSAPP_ENABLED", "true")
- print_success("WhatsApp enabled")
- else:
+ if not prompt_yes_no("Enable WhatsApp?", True):
save_env_value("WHATSAPP_ENABLED", "false")
print_info("WhatsApp left disabled")
return
+ save_env_value("WHATSAPP_ENABLED", "true")
+ print_success("WhatsApp enabled")
allowed_users = prompt("Allowed user IDs (comma-separated, leave empty for no allowlist)")
if allowed_users:
save_env_value("WHATSAPP_ALLOWED_USERS", allowed_users.replace(" ", ""))
@@ -1353,29 +901,17 @@ def interactive_setup() -> None:
home_channel = prompt("Home chat ID for cron delivery (leave empty to skip)").strip()
if home_channel:
save_env_value("WHATSAPP_HOME_CHANNEL", home_channel)
- else:
- if remove_env_value("WHATSAPP_HOME_CHANNEL"):
- print_info("Home channel cleared.")
+ elif remove_env_value("WHATSAPP_HOME_CHANNEL"):
+ print_info("Home channel cleared.")
# config.yaml whatsapp: key → env var. Env vars take precedence over YAML.
-_YAML_LOWERCASE_KEYS = (
- ("require_mention", "WHATSAPP_REQUIRE_MENTION"),
- ("dm_policy", "WHATSAPP_DM_POLICY"),
- ("group_policy", "WHATSAPP_GROUP_POLICY"),
-)
-_YAML_LIST_KEYS = (
- ("free_response_chats", "WHATSAPP_FREE_RESPONSE_CHATS"),
- ("allow_from", "WHATSAPP_ALLOWED_USERS"),
- ("group_allow_from", "WHATSAPP_GROUP_ALLOWED_USERS"),
-)
+_YAML_LOWERCASE_KEYS = (("require_mention", "WHATSAPP_REQUIRE_MENTION"), ("dm_policy", "WHATSAPP_DM_POLICY"), ("group_policy", "WHATSAPP_GROUP_POLICY"))
+_YAML_LIST_KEYS = (("free_response_chats", "WHATSAPP_FREE_RESPONSE_CHATS"), ("allow_from", "WHATSAPP_ALLOWED_USERS"), ("group_allow_from", "WHATSAPP_GROUP_ALLOWED_USERS"))
def _apply_yaml_config(yaml_cfg: dict, whatsapp_cfg: dict) -> dict | None:
- """Translate config.yaml whatsapp: keys into WHATSAPP_* env vars (apply_yaml_config_fn contract).
-
- Returns None — everything flows through env.
- """
+ """config.yaml whatsapp: keys → WHATSAPP_* env vars (apply_yaml_config_fn contract; returns None)."""
import json as _json
for key, env in _YAML_LOWERCASE_KEYS:
if key in whatsapp_cfg and not os.getenv(env):
@@ -1385,50 +921,29 @@ def _apply_yaml_config(yaml_cfg: dict, whatsapp_cfg: dict) -> dict | None:
for key, env in _YAML_LIST_KEYS:
val = whatsapp_cfg.get(key)
if val is not None and not os.getenv(env):
- if isinstance(val, list):
- val = ",".join(str(v) for v in val)
- os.environ[env] = str(val)
+ os.environ[env] = ",".join(str(v) for v in val) if isinstance(val, list) else str(val)
return None
def _is_connected(config) -> bool:
- """Connected == explicitly enabled via WHATSAPP_ENABLED (or an enabled PlatformConfig with extras).
-
- Auth is handled by the Node.js bridge, so the opt-in flag is the signal; an
- unconditional True would show WhatsApp as configured in ``hermes setup`` always.
- """
- extra = getattr(config, "extra", {}) or {}
- if config is not None and getattr(config, "enabled", False) and extra:
+ """Connected == WHATSAPP_ENABLED opt-in (or an enabled PlatformConfig with extras); auth lives in the bridge."""
+ if config is not None and getattr(config, "enabled", False) and (getattr(config, "extra", {}) or {}):
return True
- # Via hermes_cli.gateway.get_env_value (not os.getenv) so setup-status callers
- # that patch get_env_value observe the same value.
+ # Via hermes_cli.gateway.get_env_value (not os.getenv) so setup-status callers that patch it observe the same value.
import hermes_cli.gateway as gateway_mod
- val = (gateway_mod.get_env_value("WHATSAPP_ENABLED") or "").strip().lower()
- return val in {"true", "1", "yes"}
+ return (gateway_mod.get_env_value("WHATSAPP_ENABLED") or "").strip().lower() in {"true", "1", "yes"}
def _build_adapter(config):
- """Factory wrapper that constructs WhatsAppAdapter from a PlatformConfig."""
return WhatsAppAdapter(config)
def register(ctx) -> None:
- """Plugin entry point — called by the Hermes plugin system."""
ctx.register_platform(
- name="whatsapp",
- label="WhatsApp",
- adapter_factory=_build_adapter,
- check_fn=check_whatsapp_requirements,
- is_connected=_is_connected,
- required_env=["WHATSAPP_ENABLED"],
+ name="whatsapp", label="WhatsApp", adapter_factory=_build_adapter, check_fn=check_whatsapp_requirements,
+ is_connected=_is_connected, required_env=["WHATSAPP_ENABLED"],
install_hint="WhatsApp requires a Node.js bridge — see the WhatsApp messaging docs",
- setup_fn=interactive_setup,
- apply_yaml_config_fn=_apply_yaml_config,
- allowed_users_env="WHATSAPP_ALLOWED_USERS",
- allow_all_env="WHATSAPP_ALLOW_ALL_USERS",
- cron_deliver_env_var="WHATSAPP_HOME_CHANNEL",
- standalone_sender_fn=_standalone_send,
- max_message_length=4096,
- emoji="💬",
- allow_update_command=True,
+ setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, allowed_users_env="WHATSAPP_ALLOWED_USERS",
+ allow_all_env="WHATSAPP_ALLOW_ALL_USERS", cron_deliver_env_var="WHATSAPP_HOME_CHANNEL",
+ standalone_sender_fn=_standalone_send, max_message_length=4096, emoji="💬", allow_update_command=True,
)