adapter.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887
  1. """WeCom (Enterprise WeChat) AI Bot adapter over the ``openws`` WebSocket gateway.
  2. Streaming lives in ``streaming.py``, media in ``media.py``, per-chat send queue in ``send_queue.py``.
  3. Config (``platforms.wecom.extra``): ``bot_id``/``secret`` (or WECOM_BOT_ID / WECOM_SECRET), ``websocket_url``,
  4. ``dm_policy``/``group_policy`` (open|allowlist|disabled|pairing), ``allow_from``, ``group_allow_from``,
  5. ``groups: {<group_id>: {allow_from: [...]}}``."""
  6. from __future__ import annotations
  7. from pm import install_hint
  8. import asyncio
  9. import json
  10. import logging
  11. import re
  12. import time
  13. import uuid
  14. from datetime import datetime, timezone, UTC
  15. from typing import Any, Dict, List, Optional, Tuple
  16. try:
  17. import aiohttp
  18. except ImportError:
  19. aiohttp = None # type: ignore[assignment]
  20. try:
  21. import httpx
  22. except ImportError:
  23. httpx = None # type: ignore[assignment]
  24. AIOHTTP_AVAILABLE = aiohttp is not None
  25. HTTPX_AVAILABLE = httpx is not None
  26. from gateway.config import Platform, PlatformConfig
  27. from gateway.platforms.helpers import MessageDeduplicator, bounded_put, send_chunks
  28. from gateway.platforms.access_policy_mixin import OwnAccessPolicyMixin
  29. from gateway.platforms.base import gateway_trust_env, BasePlatformAdapter, SendResult
  30. from gateway.platforms.event import MessageEvent, MessageType
  31. from utils import env_float
  32. from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret, send_error
  33. from gateway.platforms.send_targets import StandaloneSendPolicy, parse_nonempty
  34. from plugins.platforms.wecom.send_queue import ChatSendQueueMixin
  35. from plugins.platforms.wecom.media import WeComMediaMixin, APP_CMD_SEND
  36. from plugins.platforms.wecom.streaming import (
  37. WeComStreamMixin, ReplyQueue, StreamTurn, APP_CMD_RESPONSE,
  38. STREAM_NOT_SUBSCRIBED_ERRCODE, MAX_STREAM_CONTENT_LENGTH,
  39. STREAM_SAFE_DURATION_SECONDS, STREAM_KEEPALIVE_INTERVAL_SECONDS, STREAM_KEEPALIVE_ENABLED_DEFAULT,
  40. )
  41. logger = logging.getLogger(__name__)
  42. DEFAULT_WS_URL = "wss://openws.work.weixin.qq.com"
  43. APP_CMD_SUBSCRIBE = "aibot_subscribe"
  44. APP_CMD_CALLBACK = "aibot_msg_callback"
  45. APP_CMD_LEGACY_CALLBACK = "aibot_callback"
  46. APP_CMD_EVENT_CALLBACK = "aibot_event_callback"
  47. APP_CMD_PING = "ping"
  48. CALLBACK_COMMANDS = {APP_CMD_CALLBACK, APP_CMD_LEGACY_CALLBACK}
  49. NON_RESPONSE_COMMANDS = CALLBACK_COMMANDS | {APP_CMD_EVENT_CALLBACK}
  50. MAX_MESSAGE_LENGTH = 4000
  51. CONNECT_TIMEOUT_SECONDS = 20.0
  52. REQUEST_TIMEOUT_SECONDS = 15.0
  53. HEARTBEAT_INTERVAL_SECONDS = 30.0
  54. RECONNECT_BACKOFF = [2, 5, 10, 30, 60]
  55. DEDUP_MAX_SIZE = 1000
  56. def check_wecom_requirements() -> bool:
  57. return AIOHTTP_AVAILABLE and HTTPX_AVAILABLE
  58. def _coerce_list(value: Any) -> list[str]:
  59. """Coerce config values (None | "a, b" | iterable | scalar) into a trimmed, non-empty string list."""
  60. if isinstance(value, str):
  61. value = value.split(",")
  62. elif not isinstance(value, (list, tuple, set)):
  63. value = [] if value is None else [value]
  64. return [item for item in (str(item).strip() for item in value) if item]
  65. def _normalize_entry(raw: str) -> str:
  66. """Normalize allowlist entries such as ``wecom:user:foo``."""
  67. value = re.sub(r"^wecom:", "", str(raw).strip(), flags=re.IGNORECASE)
  68. return re.sub(r"^(user|group):", "", value, flags=re.IGNORECASE).strip()
  69. def _entry_matches(entries: list[str], target: str) -> bool:
  70. """Case-insensitive allowlist match with ``*`` support."""
  71. normalized_target = str(target).strip().lower()
  72. return any(_normalize_entry(e).lower() in ("*", normalized_target) for e in entries)
  73. def _dict_or_empty(container: dict[str, Any], key: str) -> dict[str, Any]:
  74. return container.get(key) if isinstance(container.get(key), dict) else {}
  75. def _content_of(container: dict[str, Any], key: str) -> str:
  76. return str(_dict_or_empty(container, key).get("content") or "").strip()
  77. class WeComAdapter(WeComStreamMixin, WeComMediaMixin, ChatSendQueueMixin, OwnAccessPolicyMixin, BasePlatformAdapter):
  78. """WeCom AI Bot adapter backed by a persistent WebSocket connection."""
  79. ALLOW_ALL_ENV_PREFIX = "WECOM"
  80. MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
  81. SUPPORTS_MESSAGE_EDITING = False
  82. SUPPORTS_NATIVE_STREAMING = True # msgtype "stream" via aibot_respond_msg, not edit-based
  83. MAX_STREAM_CONTENT_LENGTH = MAX_STREAM_CONTENT_LENGTH
  84. splits_long_messages = True # send() chunks via truncate_message(MAX_MESSAGE_LENGTH)
  85. _SPLIT_THRESHOLD = 3900 # chunks near the 4000-char client split are almost certainly continued
  86. serial_receive_loop = True # _read_events awaits each frame before reading the next
  87. def __init__(self, config: PlatformConfig):
  88. super().__init__(config, Platform.WECOM)
  89. extra = config.extra or {}
  90. def _extra_float(key: str, default: float) -> float:
  91. try:
  92. return float(extra.get(key, default))
  93. except (TypeError, ValueError):
  94. return default
  95. def _setting(*keys: str, env: str = "", default: str = "") -> str:
  96. return str(next((extra[k] for k in keys if extra.get(k)), None) or (_get_scoped_secret(env, default) if env else "")).strip()
  97. self._bot_id = _setting("bot_id", env="WECOM_BOT_ID")
  98. self._secret = _setting("secret", env="WECOM_SECRET")
  99. self._ws_url = _setting("websocket_url", "websocketUrl", env="WECOM_WEBSOCKET_URL", default=DEFAULT_WS_URL) or DEFAULT_WS_URL
  100. self._dm_policy = _setting("dm_policy", env="WECOM_DM_POLICY", default="pairing").lower()
  101. # WECOM_ALLOWED_USERS fallback: env-only allowlist setups otherwise drop every DM at intake.
  102. self._allow_from = _coerce_list(extra.get("allow_from") or extra.get("allowFrom") or _get_scoped_secret("WECOM_ALLOWED_USERS", ""))
  103. self._group_policy = _setting("group_policy", env="WECOM_GROUP_POLICY", default="pairing").lower()
  104. self._group_allow_from = _coerce_list(extra.get("group_allow_from") or extra.get("groupAllowFrom"))
  105. self._groups = extra.get("groups") if isinstance(extra.get("groups"), dict) else {}
  106. self._session = self._ws = self._http_client = self._listen_task = self._heartbeat_task = None
  107. self._pending_responses: dict[str, asyncio.Future] = {}
  108. self._reply_queues: dict[str, ReplyQueue] = {}
  109. self._dedup, self._reply_req_ids = MessageDeduplicator(max_size=DEDUP_MAX_SIZE), {}
  110. # Text batching (clients split long messages ~4000 chars); attachment-only frames are held
  111. # for the merge window so the trailing text callback joins the same event (official: 800ms).
  112. self._text_batch_delay_seconds = env_float("HERMES_WECOM_TEXT_BATCH_DELAY_SECONDS", 0.6)
  113. self._text_batch_split_delay_seconds = env_float("HERMES_WECOM_TEXT_BATCH_SPLIT_DELAY_SECONDS", 2.0)
  114. self._attachment_text_merge_delay_seconds = _extra_float("attachment_text_merge_delay_seconds", 0.8)
  115. # Stream keep-alive config (see streaming.py STREAM_* constants).
  116. self._stream_safe_duration_seconds = _extra_float("stream_safe_duration_seconds", STREAM_SAFE_DURATION_SECONDS)
  117. self._stream_keepalive_enabled = bool(extra.get("stream_keepalive_enabled", STREAM_KEEPALIVE_ENABLED_DEFAULT))
  118. self._stream_keepalive_interval_seconds = _extra_float("stream_keepalive_interval_seconds", STREAM_KEEPALIVE_INTERVAL_SECONDS)
  119. self._device_id = uuid.uuid4().hex
  120. self._last_chat_req_ids: dict[str, str] = {}
  121. # Turns keyed f"{chat_id}:{req_id|turn_id}"; expired chats clear on the next inbound req_id.
  122. self._stream_turns: dict[str, StreamTurn] = {}
  123. self._stream_expired_chats, self._group_chat_ids = set(), set() # groups can't receive proactive APP_CMD_SEND
  124. # Per-chat FIFO send queues (normal + control lanes) + token buckets — see send_queue.py.
  125. self._chat_queues, self._chat_workers, self._control_queues, self._control_workers, self._chat_token_usage = {}, {}, {}, {}, {}
  126. def _startup_failure(self, code: str, message: str, log_msg: str, *args: Any) -> bool:
  127. self._set_fatal_error(code, message, retryable=True)
  128. logger.warning(log_msg, self.name, message, *args)
  129. return False
  130. async def connect(self, *, is_reconnect: bool = False) -> bool:
  131. for available, dep in ((AIOHTTP_AVAILABLE, "aiohttp"), (HTTPX_AVAILABLE, "httpx")):
  132. if not available:
  133. return self._startup_failure("wecom_missing_dependency", f"WeCom startup failed: {dep} not installed", "[%s] %s. Run: pip install %s", dep)
  134. if not self._bot_id or not self._secret:
  135. return self._startup_failure("wecom_missing_credentials", "WeCom startup failed: WECOM_BOT_ID and WECOM_SECRET are required", "[%s] %s")
  136. try:
  137. # Tighter keepalive so idle CLOSE_WAIT drains promptly.
  138. # See #18451.
  139. from gateway.platforms.helpers import platform_http_client
  140. self._http_client = platform_http_client()
  141. await self._open_connection()
  142. self._mark_connected()
  143. self._listen_task, self._heartbeat_task = asyncio.create_task(self._listen_loop()), asyncio.create_task(self._heartbeat_loop())
  144. logger.info("[%s] Connected to %s", self.name, self._ws_url)
  145. self._wire_plugin_handlers(None) # ctx.register_platform_handler hooks
  146. return True
  147. except Exception as exc:
  148. self._set_fatal_error("wecom_connect_error", f"WeCom startup failed: {exc}", retryable=True)
  149. logger.error("[%s] Failed to connect: %s", self.name, exc, exc_info=True)
  150. await self._teardown()
  151. return False
  152. async def disconnect(self) -> None:
  153. self._running = False
  154. self._mark_disconnected()
  155. for task in list(self._chat_workers.values()) + list(self._control_workers.values()):
  156. task.cancel()
  157. for registry in (self._chat_workers, self._control_workers, self._chat_queues, self._control_queues):
  158. registry.clear()
  159. for attr in ("_listen_task", "_heartbeat_task"):
  160. task = getattr(self, attr)
  161. if task:
  162. task.cancel()
  163. try:
  164. await task
  165. except asyncio.CancelledError:
  166. pass
  167. setattr(self, attr, None)
  168. self._fail_all(RuntimeError("WeCom adapter disconnected"))
  169. await self._teardown()
  170. self._dedup.clear()
  171. logger.info("[%s] Disconnected", self.name)
  172. def _fail_all(self, exc: Exception) -> None:
  173. self._fail_pending_responses(exc)
  174. self._fail_reply_queues(exc)
  175. async def _cleanup_ws(self) -> None:
  176. """Close the live websocket, then its session, if any."""
  177. for attr in ("_ws", "_session"):
  178. live = getattr(self, attr)
  179. if live and not live.closed:
  180. await live.close()
  181. setattr(self, attr, None)
  182. async def _teardown(self) -> None:
  183. """_cleanup_ws, then close the httpx client."""
  184. await self._cleanup_ws()
  185. if self._http_client:
  186. await self._http_client.aclose()
  187. self._http_client = None
  188. async def _open_connection(self) -> None:
  189. await self._cleanup_ws()
  190. # certifi's CA bundle so aiohttp trusts the same roots as urllib/requests (macOS stale OpenSSL path),
  191. # re-derived when an install-environment rotation deleted the imported one (#137255).
  192. import ssl as _ssl
  193. from agent.ssl_verify import certifi_bundle_path
  194. cafile = certifi_bundle_path()
  195. _ssl_ctx = _ssl.create_default_context(cafile=cafile)
  196. self._session = aiohttp.ClientSession(trust_env=gateway_trust_env(), connector=aiohttp.TCPConnector(ssl=_ssl_ctx))
  197. self._ws = await self._session.ws_connect(self._ws_url, heartbeat=HEARTBEAT_INTERVAL_SECONDS * 2, timeout=CONNECT_TIMEOUT_SECONDS)
  198. req_id = self._new_req_id("subscribe")
  199. 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}})
  200. auth_payload = await self._wait_for_handshake(req_id)
  201. errcode = auth_payload.get("errcode", 0)
  202. if errcode not in {0, None}:
  203. raise RuntimeError(f"{auth_payload.get('errmsg', 'authentication failed')} (errcode={errcode})")
  204. async def _wait_for_handshake(self, req_id: str) -> dict[str, Any]:
  205. if not self._ws:
  206. raise RuntimeError("WebSocket not initialized")
  207. loop = asyncio.get_running_loop()
  208. deadline = loop.time() + CONNECT_TIMEOUT_SECONDS
  209. while (remaining := deadline - loop.time()) > 0:
  210. msg = await asyncio.wait_for(self._ws.receive(), timeout=remaining)
  211. if msg.type == aiohttp.WSMsgType.TEXT:
  212. payload = self._parse_json(msg.data)
  213. if not payload or payload.get("cmd") == APP_CMD_PING:
  214. continue
  215. if self._payload_req_id(payload) == req_id:
  216. return payload
  217. logger.debug("[%s] Ignoring pre-auth payload: %s", self.name, payload.get("cmd"))
  218. elif msg.type in {aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.ERROR}:
  219. raise RuntimeError("WeCom websocket closed during authentication")
  220. raise TimeoutError("Timed out waiting for WeCom subscribe acknowledgement")
  221. async def _listen_loop(self) -> None:
  222. backoff_idx = 0
  223. while self._running:
  224. try:
  225. await self._read_events()
  226. backoff_idx = 0
  227. except asyncio.CancelledError:
  228. return
  229. except Exception as exc:
  230. if not self._running:
  231. return
  232. logger.warning("[%s] WebSocket error: %s", self.name, exc)
  233. self._fail_all(RuntimeError("WeCom connection interrupted"))
  234. await asyncio.sleep(RECONNECT_BACKOFF[min(backoff_idx, len(RECONNECT_BACKOFF) - 1)])
  235. backoff_idx += 1
  236. try:
  237. await self._open_connection()
  238. backoff_idx = 0
  239. self._mark_connected()
  240. logger.info("[%s] Reconnected", self.name)
  241. except Exception as reconnect_exc:
  242. logger.warning("[%s] Reconnect failed: %s", self.name, reconnect_exc)
  243. async def _read_events(self) -> None:
  244. if not self._ws:
  245. raise RuntimeError("WebSocket not connected")
  246. while self._running and self._ws and not self._ws.closed:
  247. msg = await self._ws.receive()
  248. if msg.type in (aiohttp.WSMsgType.TEXT, aiohttp.WSMsgType.BINARY):
  249. await self._handle_frame(msg.data, msg.type == aiohttp.WSMsgType.BINARY)
  250. elif msg.type in {aiohttp.WSMsgType.CLOSE, aiohttp.WSMsgType.CLOSED, aiohttp.WSMsgType.ERROR, aiohttp.WSMsgType.CLOSING}:
  251. raise RuntimeError("WeCom websocket closed")
  252. else:
  253. logger.info("[%s] Inbound frame ignored: WSMsgType=%s", self.name, msg.type)
  254. async def _handle_frame(self, data: Any, is_binary: bool) -> None:
  255. """Parse one TEXT/BINARY frame and dispatch it; every drop is logged at INFO."""
  256. data_len = len(data) if isinstance(data, (str, bytes, bytearray)) else -1
  257. if is_binary: # WeCom should send TEXT; log a preview so an unhandled transport isn't silently dropped
  258. decoded = data.decode("utf-8", errors="replace") if isinstance(data, (bytes, bytearray)) else "<undecodable>"
  259. logger.info("[%s] Inbound BINARY frame received (len=%d) head=%r — attempting JSON parse", self.name, data_len, decoded[:200])
  260. payload = self._parse_json(data)
  261. if payload:
  262. await self._dispatch_payload(payload)
  263. elif is_binary:
  264. logger.info("[%s] BINARY frame not parseable as JSON — dropped", self.name)
  265. else: # _parse_json logged the detail; make the DROP itself visible at INFO
  266. logger.info("[%s] Inbound TEXT frame dropped (unparseable/non-dict) len=%d", self.name, data_len)
  267. async def _heartbeat_loop(self) -> None:
  268. try:
  269. while self._running:
  270. await asyncio.sleep(HEARTBEAT_INTERVAL_SECONDS)
  271. try:
  272. if self._ws and not self._ws.closed:
  273. await self._send_json({"cmd": APP_CMD_PING, "headers": {"req_id": self._new_req_id("ping")}, "body": {}})
  274. except Exception as exc:
  275. logger.debug("[%s] Heartbeat send failed: %s", self.name, exc)
  276. except asyncio.CancelledError:
  277. pass
  278. async def _dispatch_payload(self, payload: dict[str, Any]) -> None:
  279. req_id = self._payload_req_id(payload)
  280. cmd = str(payload.get("cmd") or "")
  281. body_dict = payload.get("body") if isinstance(payload.get("body"), dict) else None
  282. if self._reply_queues and cmd != APP_CMD_PING:
  283. 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()))
  284. if req_id and self._reply_queues.get(req_id):
  285. logger.debug(
  286. "[%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,
  287. 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()),
  288. )
  289. # Reply-queue acks (inbound req_id, no/other cmd) MUST win over _pending_responses.
  290. if req_id and cmd not in NON_RESPONSE_COMMANDS:
  291. if self._resolve_reply_ack(req_id, payload):
  292. return
  293. if req_id in self._pending_responses:
  294. future = self._pending_responses[req_id]
  295. if future and not future.done():
  296. future.set_result(payload)
  297. return
  298. if cmd in CALLBACK_COMMANDS:
  299. await self._on_message(payload)
  300. elif cmd == APP_CMD_EVENT_CALLBACK:
  301. # Kicked by server (another connection exists): suppress reconnect like the official SDK.
  302. if str((payload.get("body") or {}).get("event_type") or "") == "disconnected_event":
  303. logger.warning("[%s] Kicked by server (another WS connection established). Suppressing reconnect to avoid mutual kicking. Check for duplicate gateway instances.", self.name)
  304. self._running = False
  305. elif cmd != APP_CMD_PING:
  306. 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)
  307. def _fail_pending_responses(self, exc: Exception) -> None:
  308. for req_id, future in list(self._pending_responses.items()):
  309. if not future.done():
  310. future.set_exception(exc)
  311. self._pending_responses.pop(req_id, None)
  312. def _require_ws(self) -> None:
  313. if not self._ws or self._ws.closed:
  314. raise RuntimeError("WeCom websocket is not connected")
  315. async def _send_json(self, payload: dict[str, Any]) -> None:
  316. self._require_ws()
  317. await self._ws.send_json(payload)
  318. async def _request(self, cmd: str, req_id: str, body: dict[str, Any], timeout: float) -> dict[str, Any]:
  319. future = self._pending_responses[req_id] = asyncio.get_running_loop().create_future()
  320. try:
  321. await self._send_json({"cmd": cmd, "headers": {"req_id": req_id}, "body": body})
  322. return await asyncio.wait_for(future, timeout=timeout)
  323. finally:
  324. self._pending_responses.pop(req_id, None)
  325. async def _send_request(self, cmd: str, body: dict[str, Any], timeout: float = REQUEST_TIMEOUT_SECONDS) -> dict[str, Any]:
  326. self._require_ws()
  327. return await self._request(cmd, self._new_req_id(cmd), body, timeout)
  328. 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]:
  329. """Send a reply frame correlated to an inbound callback req_id."""
  330. self._require_ws()
  331. return await self._request(cmd, self._require_reply_req_id(reply_req_id), body, timeout)
  332. @staticmethod
  333. def _require_reply_req_id(reply_req_id: str) -> str:
  334. normalized = str(reply_req_id or "").strip()
  335. if not normalized:
  336. raise ValueError("reply_req_id is required")
  337. return normalized
  338. @staticmethod
  339. def _new_req_id(prefix: str) -> str:
  340. return f"{prefix}-{uuid.uuid4().hex}"
  341. @staticmethod
  342. def _payload_req_id(payload: dict[str, Any]) -> str:
  343. headers = payload.get("headers")
  344. return str(headers.get("req_id") or "") if isinstance(headers, dict) else ""
  345. @staticmethod
  346. def _parse_json(raw: Any) -> Optional[dict[str, Any]]:
  347. raw_len = len(raw) if isinstance(raw, (str, bytes)) else -1
  348. try:
  349. payload = json.loads(raw)
  350. except json.JSONDecodeError:
  351. # WeCom sometimes sends raw control chars inside JSON strings; strict=False accepts them.
  352. try:
  353. text = raw if isinstance(raw, str) else raw.decode("utf-8", errors="replace")
  354. payload = json.JSONDecoder(strict=False).decode(text)
  355. logger.info("WeCom payload required strict=False fallback (len=%d)", raw_len)
  356. except Exception as exc2:
  357. tail = raw[-100:] if isinstance(raw, (str, bytes)) and len(raw) > 100 else raw
  358. logger.warning("Failed to parse WeCom payload (strict=False also failed): error=%s len=%d tail=%r", exc2, raw_len, tail)
  359. return None
  360. except Exception as exc:
  361. logger.warning("Failed to parse WeCom payload: error=%s len=%d", exc, raw_len)
  362. return None
  363. return payload if isinstance(payload, dict) else None
  364. async def _on_message(self, payload: dict[str, Any]) -> None:
  365. body = payload.get("body")
  366. if not isinstance(body, dict):
  367. return
  368. req_id = self._payload_req_id(payload)
  369. msg_id = str(body.get("msgid") or req_id or uuid.uuid4().hex)
  370. sender = _dict_or_empty(body, "from")
  371. sender_id = str(sender.get("userid") or "").strip()
  372. if self._dedup.is_duplicate(msg_id):
  373. # INFO: a msgid redelivered after a processing exception is dropped for the TTL.
  374. 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"))
  375. return
  376. if req_id:
  377. bounded_put(self._reply_req_ids, msg_id, req_id, DEDUP_MAX_SIZE)
  378. chat_id = str(body.get("chatid") or sender_id).strip()
  379. 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")))
  380. if not chat_id:
  381. logger.info("[%s] Missing chat id, skipping message; body_keys=%s", self.name, list(body.keys()))
  382. return
  383. is_group = str(body.get("chattype") or "").lower() == "group"
  384. if not self._admit_inbound(is_group, chat_id, sender_id):
  385. return
  386. # Post-policy: cache req_id so sends can fall back to passive reply (required in groups).
  387. self._remember_chat_req_id(chat_id, req_id)
  388. text, reply_text = self._extract_text(body)
  389. if is_group and text:
  390. text = re.sub(r"^@\S+\s*", "", text).strip() # "@Bot /approve" -> "/approve"
  391. media_urls, media_types = await self._extract_media(body)
  392. message_type = self._derive_message_type(body, text, media_types)
  393. has_reply_context = bool(reply_text and (text or media_urls))
  394. if reply_text and not has_reply_context: # quote-only message: the quote becomes the text
  395. text = reply_text
  396. if not text and not media_urls:
  397. logger.info("[%s] Empty WeCom message skipped: is_group=%s chat=%s msgtype=%r", self.name, is_group, chat_id, body.get("msgtype"))
  398. return
  399. 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,
  400. message_id=msg_id)
  401. event = MessageEvent(
  402. text=text, message_type=message_type, source=source, raw_message=payload, message_id=msg_id, media_urls=media_urls, media_types=media_types,
  403. 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=UTC),
  404. )
  405. # Only plain text is batched, EXCEPT attachment-only messages, which are held so the
  406. # trailing text callback merges instead of "interrupting" a run the attachment spawned.
  407. has_pending_batch = self._text_batch_key(event) in self._pending_text_batches
  408. is_attachment_only = bool(media_urls) and not (text or "").strip()
  409. 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):
  410. self._enqueue_text_event(event)
  411. else:
  412. await self.handle_message(event)
  413. def _admit_inbound(self, is_group: bool, chat_id: str, sender_id: str) -> bool:
  414. """Apply group_policy / dm_policy at intake; logs and returns False when dropped."""
  415. if not is_group:
  416. allowed = self._is_dm_intake_allowed(sender_id)
  417. if not allowed:
  418. logger.info("[%s] DM sender %s blocked by policy", self.name, sender_id)
  419. return allowed
  420. self._group_chat_ids.add(chat_id)
  421. allowed = self._is_group_allowed(chat_id, sender_id)
  422. if not allowed:
  423. logger.info(
  424. "[%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)",
  425. self.name, chat_id, sender_id, self._group_policy,
  426. )
  427. return allowed
  428. def _enqueue_text_event(self, event: MessageEvent) -> None:
  429. """Buffer + reset the flush timer; real text joining a buffered attachment promotes it to TEXT and inherits the quote context."""
  430. existing = self._pending_text_batches.get(self._text_batch_key(event))
  431. super()._enqueue_text_event(event) # merge text/media + restart the flush timer
  432. if existing is not None and event.text and event.text.strip():
  433. existing.message_type = MessageType.TEXT
  434. if event.reply_to_text and not existing.reply_to_text:
  435. existing.reply_to_text = event.reply_to_text
  436. existing.reply_to_message_id = event.reply_to_message_id
  437. def _text_batch_delay_for(self, pending: Optional[MessageEvent]) -> float:
  438. if pending is not None and pending.media_urls and not (pending.text or "").strip():
  439. return self._attachment_text_merge_delay_seconds # attachment-only: wait for the text frame
  440. return super()._text_batch_delay_for(pending)
  441. @staticmethod
  442. def _extract_text(body: dict[str, Any]) -> tuple[str, Optional[str]]:
  443. msgtype = str(body.get("msgtype") or "").lower()
  444. if msgtype == "mixed":
  445. items = _dict_or_empty(body, "mixed").get("msg_item")
  446. 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"]
  447. else: # voice transcript / appmsg attachment title (filename) follow the text; empties drop below
  448. text_parts = [
  449. _content_of(body, "text"), _content_of(body, "voice") if msgtype == "voice" else "",
  450. str(_dict_or_empty(body, "appmsg").get("title") or "").strip() if msgtype == "appmsg" else "",
  451. ]
  452. quote = _dict_or_empty(body, "quote")
  453. quote_type = str(quote.get("msgtype") or "").lower()
  454. reply_text = _content_of(quote, quote_type) or None if quote_type in ("text", "voice") else None
  455. return "\n".join(part for part in text_parts if part).strip(), reply_text
  456. @staticmethod
  457. def _derive_message_type(body: dict[str, Any], text: str, media_types: list[str]) -> MessageType:
  458. if any(mtype.startswith(("application/", "text/")) for mtype in media_types):
  459. return MessageType.DOCUMENT
  460. if any(mtype.startswith("image/") for mtype in media_types):
  461. return MessageType.TEXT if text else MessageType.PHOTO
  462. if str(body.get("msgtype") or "").lower() == "voice":
  463. return MessageType.VOICE
  464. return MessageType.TEXT
  465. def _entry_matches(self, entries: list[str], target: str) -> bool:
  466. return _entry_matches(entries, target)
  467. def _is_group_allowed(self, chat_id: str, sender_id: str) -> bool:
  468. """Per-group ``groups.<id>.allow_from`` restricts senders on top of the chat-level policy."""
  469. if not super()._is_group_allowed(chat_id):
  470. return False
  471. group_cfg = self._resolve_group_cfg(chat_id)
  472. sender_allow = _coerce_list(group_cfg.get("allow_from") or group_cfg.get("allowFrom"))
  473. return _entry_matches(sender_allow, sender_id) if sender_allow else True
  474. def _resolve_group_cfg(self, chat_id: str) -> dict[str, Any]:
  475. """Exact key, then case-insensitive key, then ``"*"``; only dict values count."""
  476. if not isinstance(self._groups, dict):
  477. return {}
  478. lowered = chat_id.lower()
  479. 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("*"))
  480. return next((c for c in candidates if isinstance(c, dict)), {})
  481. def _remember_chat_req_id(self, chat_id: str, req_id: str) -> None:
  482. """Cache the chat's latest inbound req_id; a fresh one also resurrects its stream channel."""
  483. chat_id, req_id = str(chat_id or "").strip(), str(req_id or "").strip()
  484. if chat_id and req_id:
  485. bounded_put(self._last_chat_req_ids, chat_id, req_id, DEDUP_MAX_SIZE)
  486. self._stream_expired_chats.discard(chat_id)
  487. def _reply_req_id_for_message(self, reply_to: Optional[str]) -> Optional[str]:
  488. normalized = str(reply_to or "").strip()
  489. return None if not normalized or normalized.startswith("quote:") else self._reply_req_ids.get(normalized)
  490. def _cached_reply_req_id(self, chat_id: str, reply_to: Optional[str]) -> Optional[str]:
  491. """Explicit reply_to mapping, else the chat's last inbound req_id."""
  492. return self._reply_req_id_for_message(reply_to) or self._last_chat_req_ids.get(chat_id)
  493. async def _force_reconnect_on_stale_subscription(self, errcode: int) -> None:
  494. """On 846609 (subscription lost) drop req_ids bound to the dead session. Do NOT close the
  495. WS: a second connection gets kicked and invalidates the first (infinite kick loop)."""
  496. if errcode != STREAM_NOT_SUBSCRIBED_ERRCODE:
  497. return
  498. logger.warning("[%s] Got errcode %d (subscription lost) — clearing stale state", self.name, errcode)
  499. self._last_chat_req_ids.clear()
  500. self._reply_req_ids.clear()
  501. @staticmethod
  502. def _response_error(response: dict[str, Any]) -> Optional[str]:
  503. errcode = response.get("errcode", 0)
  504. return None if errcode in {0, None} else f"WeCom errcode {errcode}: {response.get('errmsg') or 'unknown error'}"
  505. @classmethod
  506. def _raise_for_wecom_error(cls, response: dict[str, Any], operation: str) -> None:
  507. error = cls._response_error(response)
  508. if error:
  509. raise RuntimeError(f"{operation} failed: {error}")
  510. def _markdown_body(self, content: str) -> dict[str, Any]:
  511. return {"msgtype": "markdown", "markdown": {"content": content[:self.MAX_MESSAGE_LENGTH]}}
  512. async def _send_reply_markdown(self, reply_req_id: str, content: str) -> dict[str, Any]:
  513. response = await self._send_reply_request(reply_req_id, self._markdown_body(content))
  514. self._raise_for_wecom_error(response, "send reply markdown")
  515. return response
  516. async def _send_proactive_markdown(self, chat_id: str, content: str) -> dict[str, Any]:
  517. return await self._send_request(APP_CMD_SEND, {"chatid": chat_id, **self._markdown_body(content)})
  518. async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None) -> SendResult:
  519. """Send standalone markdown (never touches active streams); serialized per chat for the 30 msgs/min
  520. limit (846607). ``metadata["is_approval_prompt"]`` uses the control lane."""
  521. if not chat_id:
  522. return SendResult(success=False, error="chat_id is required")
  523. metadata = metadata or {} # pops mutate the caller's dict on purpose (consumed flags)
  524. is_control = metadata.pop("is_approval_prompt", False)
  525. # Approval *confirmations* must not consume the req_id the stream consumer still needs.
  526. force_proactive = bool(metadata.pop("force_proactive_send", False))
  527. # One queued send per chunk so each one draws a token from the 30 msgs/min bucket.
  528. return await send_chunks(self.truncate_message(content, self.MAX_MESSAGE_LENGTH), lambda chunk: self._enqueue_chat_send(
  529. chat_id, lambda: self._send_inner(chat_id, chunk, reply_to, force_proactive=force_proactive), is_control=is_control))
  530. async def _send_inner(self, chat_id: str, content: str, reply_to: Optional[str] = None, *, force_proactive: bool = False) -> SendResult:
  531. """Send under the per-chat queue; force_proactive skips passive reply except in groups."""
  532. try:
  533. 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)
  534. if reply_req_id:
  535. try:
  536. response = await self._send_reply_markdown(reply_req_id, content)
  537. except (TimeoutError, RuntimeError) as passive_err:
  538. # req_id may be stale after a reconnect — proactive send needs none.
  539. logger.warning("[%s] Passive reply failed (%s), falling back to proactive send", self.name, passive_err)
  540. response = await self._send_proactive_markdown(chat_id, content)
  541. elif chat_id in self._group_chat_ids:
  542. logger.warning("[%s] No cached req_id for group chat %s — cannot send (groups require passive reply via req_id)", self.name, chat_id)
  543. return SendResult(success=False, error="No req_id available for group chat (passive reply required)")
  544. else:
  545. response = await self._send_proactive_markdown(chat_id, content)
  546. except TimeoutError:
  547. return SendResult(success=False, error="Timeout sending message to WeCom")
  548. except Exception as exc:
  549. logger.error("[%s] Send failed: %s", self.name, exc)
  550. return self._send_failure(str(exc), str(STREAM_NOT_SUBSCRIBED_ERRCODE) in str(exc))
  551. if error := self._response_error(response):
  552. return self._send_failure(error, response.get("errcode", 0) == STREAM_NOT_SUBSCRIBED_ERRCODE)
  553. return SendResult(success=True, message_id=self._payload_req_id(response) or uuid.uuid4().hex[:12], raw_response=response)
  554. def _send_failure(self, error: str, subscription_lost: bool) -> SendResult:
  555. """Failed SendResult; on 846609 schedule the stale-req_id purge so later sends recover."""
  556. if subscription_lost:
  557. asyncio.ensure_future(self._force_reconnect_on_stale_subscription(STREAM_NOT_SUBSCRIBED_ERRCODE))
  558. return SendResult(success=False, error=error)
  559. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  560. return {"name": chat_id, "type": "group" if chat_id and chat_id.lower().startswith("group") else "dm"}
  561. _QR_GENERATE_URL = "https://work.weixin.qq.com/ai/qc/generate"
  562. _QR_QUERY_URL = "https://work.weixin.qq.com/ai/qc/query_result"
  563. _QR_CODE_PAGE = "https://work.weixin.qq.com/ai/qc/gen?source=hermes&scode="
  564. _QR_POLL_INTERVAL, _QR_POLL_TIMEOUT = 3, 300 # seconds (poll every 3s, give up after 5 minutes)
  565. def qr_scan_for_bot_info(*, timeout_seconds: int = _QR_POLL_TIMEOUT) -> Optional[dict[str, str]]:
  566. """Fetch a WeCom QR code, render it, poll until scanned or timeout; ``{"bot_id", "secret"}`` or None.
  567. The ``ai/qc/*`` endpoints back the admin console, not the public API, and may change."""
  568. import urllib.request
  569. import urllib.parse
  570. def _get_json(url: str, timeout: int) -> dict[str, Any]:
  571. req = urllib.request.Request(url, headers={"User-Agent": "HermesAgent/1.0"})
  572. with urllib.request.urlopen(req, timeout=timeout) as resp:
  573. return json.loads(resp.read().decode("utf-8"))
  574. def _fail(log_msg: str, detail: Any, shown: Any) -> None:
  575. logger.error(log_msg, detail)
  576. print(f" failed: {shown}")
  577. print(" Connecting to WeCom...", end="", flush=True)
  578. try:
  579. raw = _get_json(f"{_QR_GENERATE_URL}?source=hermes", 15)
  580. except Exception as exc:
  581. return _fail("WeCom QR: failed to fetch QR code: %s", exc, exc)
  582. scode, auth_url = (str((raw.get("data") or {}).get(k) or "").strip() for k in ("scode", "auth_url"))
  583. if not scode or not auth_url:
  584. return _fail("WeCom QR: unexpected response format: %s", raw, "unexpected response format")
  585. print(" done.\n")
  586. page_url = f"{_QR_CODE_PAGE}{urllib.parse.quote(scode)}"
  587. try:
  588. import qrcode as _qrcode
  589. qr = _qrcode.QRCode()
  590. qr.add_data(auth_url)
  591. qr.make(fit=True)
  592. qr.print_ascii(invert=True)
  593. print(f"\n Scan the QR code above, or open this URL directly:\n {page_url}")
  594. except Exception:
  595. print(f" Open this URL in WeCom on your phone:\n\n {page_url}\n")
  596. print(" Tip: from the Hermes environment, run: "
  597. f"{install_hint('messaging')} "
  598. "to display a scannable QR code here next time")
  599. print("\n Fetching configuration results...", end="", flush=True)
  600. deadline = time.monotonic() + timeout_seconds
  601. query_url = f"{_QR_QUERY_URL}?scode={urllib.parse.quote(scode)}"
  602. while time.monotonic() < deadline:
  603. try:
  604. result = _get_json(query_url, 10)
  605. print(".", end="", flush=True) # progress dot on every poll
  606. except Exception as exc:
  607. logger.debug("WeCom QR poll error: %s", exc)
  608. result = {}
  609. result_data = result.get("data") or {}
  610. if str(result_data.get("status") or "").lower() != "success":
  611. time.sleep(_QR_POLL_INTERVAL)
  612. continue
  613. bot_info = result_data.get("bot_info") or {}
  614. bot_id, secret = str(bot_info.get("botid") or bot_info.get("bot_id") or "").strip(), str(bot_info.get("secret") or "").strip()
  615. if bot_id and secret:
  616. print()
  617. return {"bot_id": bot_id, "secret": secret}
  618. logger.warning("WeCom QR: scan reported success but bot_info missing or incomplete: %s", result_data)
  619. 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.")
  620. return None
  621. print(f"\n QR scan timed out ({timeout_seconds // 60} minutes). Please try again.")
  622. return None
  623. async def _send_via(adapter, chat_id, message, *, live: bool):
  624. try:
  625. result = await adapter.send(chat_id, message)
  626. except Exception as e:
  627. return send_error(f"WeCom live adapter send failed: {e}" if live else f"WeCom send failed: {e}")
  628. if result.success:
  629. return {"success": True, "platform": "wecom", "chat_id": chat_id, "message_id": result.message_id}
  630. return send_error(f"WeCom send failed: {result.error}")
  631. async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):
  632. """Reuse the live gateway adapter in-process, else connect ephemerally (WeCom allows ONE
  633. WebSocket per bot — a second connection kicks the first). The live adapter is the ACTIVE
  634. PROFILE's (``_live_adapter``): a bare ``runner.adapters`` hit is the default profile's bot under
  635. multiplex, so a secondary profile's send would leave with the wrong identity."""
  636. try:
  637. from tools.send_message_senders import _live_adapter
  638. _, adapter = _live_adapter(Platform.WECOM)
  639. except Exception:
  640. adapter = None
  641. if adapter is not None:
  642. return await _send_via(adapter, chat_id, message, live=True)
  643. if not check_wecom_requirements():
  644. return send_error("WeCom requirements not met. Need aiohttp + WECOM_BOT_ID/SECRET.")
  645. try:
  646. adapter = WeComAdapter(pconfig)
  647. if not await adapter.connect():
  648. return send_error(f"WeCom: failed to connect - {getattr(adapter, 'fatal_error_message', None) or 'unknown error'}")
  649. try:
  650. return await _send_via(adapter, chat_id, message, live=False)
  651. finally:
  652. await adapter.disconnect()
  653. except Exception as e:
  654. return send_error(f"WeCom send failed: {e}")
  655. _MANUAL_SETUP_STEPS = (
  656. "1. Go to WeCom Application → Workspace → Smart Robot -> Create smart robots",
  657. "2. Select API Mode",
  658. "3. Copy the Bot ID and Secret from the bot's credentials info",
  659. "4. The bot connects via WebSocket — no public endpoint needed",
  660. )
  661. # (menu label, env saves, (print level, message)...) per unauthorized-user choice; index 3 = skip
  662. _ACCESS_CHOICES = (
  663. ("Enable open access (anyone can message the bot)", (("WECOM_DM_POLICY", "open"), ("GATEWAY_ALLOW_ALL_USERS", "true")),
  664. (("warning", "Open access enabled — anyone can use your bot!"),)),
  665. ("Use DM pairing (unknown users request access, you approve with 'hermes pairing approve')", (("WECOM_DM_POLICY", "pairing"),),
  666. (("success", "DM pairing mode — users will receive a code to request access."), ("info", "Approve with: hermes pairing approve <platform> <code>"))),
  667. ("Disable direct messages", (("WECOM_DM_POLICY", "disabled"),), (("warning", "Direct messages disabled."),)),
  668. ("Skip for now (bot will deny all users until configured)", (), (("info", "Skipped — configure later with 'hermes gateway setup'"),)),
  669. )
  670. def interactive_setup() -> None:
  671. from hermes_cli.config import remove_env_value, save_env_value
  672. from hermes_cli.setup import prompt_choice
  673. from hermes_cli.cli_output import prompt, print_header, print_info, print_success, print_warning
  674. from hermes_cli.setup_platforms import declines_reconfigure
  675. print_header("WeCom (Enterprise WeChat)")
  676. if declines_reconfigure("WeCom", "Reconfigure WeCom?", "WECOM_BOT_ID"):
  677. return
  678. 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)
  679. bot_id = secret = None
  680. if method_idx == 0:
  681. try:
  682. credentials = qr_scan_for_bot_info() or {}
  683. except KeyboardInterrupt:
  684. print_warning("WeCom setup cancelled.")
  685. return
  686. except Exception as exc:
  687. print_warning(f"QR scan failed: {exc}")
  688. credentials = {}
  689. if credentials:
  690. bot_id, secret = credentials.get("bot_id", ""), credentials.get("secret", "")
  691. print_success("✔ QR scan successful! Bot ID and Secret obtained.")
  692. if not bot_id or not secret:
  693. print_info("QR scan did not complete. Continuing with manual input.")
  694. bot_id = secret = None
  695. if not bot_id or not secret:
  696. for line in _MANUAL_SETUP_STEPS:
  697. print_info(line)
  698. creds = []
  699. for label, password in (("Bot ID", False), ("Secret", True)):
  700. creds.append(prompt(label, password=password))
  701. if not creds[-1]:
  702. print_warning(f"Skipped — WeCom won't work without a {label}.")
  703. return
  704. bot_id, secret = creds
  705. save_env_value("WECOM_BOT_ID", bot_id)
  706. save_env_value("WECOM_SECRET", secret)
  707. print_info("The gateway DENIES all users by default for security.")
  708. print_info("Enter user IDs to create an allowlist, or leave empty.")
  709. allowed = prompt("Allowed user IDs (comma-separated, or empty)", password=False)
  710. if allowed:
  711. save_env_value("WECOM_ALLOWED_USERS", allowed.replace(" ", ""))
  712. print_success("Saved — only these users can interact with the bot.")
  713. else:
  714. access_idx = prompt_choice("How should unauthorized users be handled?", [label for label, _, _ in _ACCESS_CHOICES], 1)
  715. _, saves, messages = _ACCESS_CHOICES[access_idx if access_idx in (0, 1, 2) else 3]
  716. for key, value in saves:
  717. save_env_value(key, value)
  718. for level, message in messages:
  719. {"warning": print_warning, "success": print_success, "info": print_info}[level](message)
  720. if home := prompt("Home chat ID (optional, for cron/notifications)", password=False).strip():
  721. save_env_value("WECOM_HOME_CHANNEL", home)
  722. print_success(f"Home channel set to {home}")
  723. elif remove_env_value("WECOM_HOME_CHANNEL"):
  724. print_info("Home channel cleared.")
  725. print_success("💬 WeCom configured!")
  726. def _is_connected(config) -> bool:
  727. return bool((getattr(config, "extra", {}) or {}).get("bot_id"))
  728. def _callback_is_connected(config) -> bool:
  729. """Callback mode: corp_id or a multi-app `apps` block."""
  730. extra = getattr(config, "extra", {}) or {}
  731. return bool(extra.get("corp_id") or extra.get("apps"))
  732. def _build_callback_adapter(config):
  733. from plugins.platforms.wecom.callback_adapter import WecomCallbackAdapter
  734. return WecomCallbackAdapter(config)
  735. # System-prompt platform hint (PlatformEntry.platform_hint); cached-prompt bytes, keep stable.
  736. _WECOM_PLATFORM_HINT = (
  737. "You are on WeCom (\u4f01\u4e1a\u5fae\u4fe1). Markdown is supported. "
  738. "You can send files natively: write MEDIA:/absolute/path/to/file in your response. "
  739. "Images (.jpg, .png, .webp) send as photos (\u226410 MB), other files as documents (\u226420 MB), videos "
  740. "(.mp4) play inline. Voice messages must be AMR \u2014 other audio formats send as file attachments. Image "
  741. "URLs via ![alt](url) are downloaded and sent as photos. Never claim you lack file-sending."
  742. )
  743. def register(ctx) -> None:
  744. common = dict(install_hint="Run `hermes setup` to install WeCom support.", emoji="💼", allow_update_command=True)
  745. from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)
  746. ctx.register_platform(
  747. target_ref_syntax_fn=parse_nonempty,
  748. standalone_send=StandaloneSendPolicy(text_direct=True),
  749. name="wecom", label="WeCom (Enterprise WeChat)", adapter_factory=WeComAdapter, check_fn=check_wecom_requirements,
  750. dashboard_label="WeCom (group bot)",
  751. dashboard_description="Send-only WeCom group bot via webhook.",
  752. docs_url="https://developer.work.weixin.qq.com/document/path/91770",
  753. dashboard_env_vars=("WECOM_BOT_ID", "WECOM_SECRET"),
  754. dashboard_required_env=("WECOM_BOT_ID",),
  755. is_connected=_is_connected, validate_config=_is_connected, required_env=["WECOM_BOT_ID", "WECOM_SECRET"],
  756. setup_fn=interactive_setup,
  757. cron_deliver_env_var="WECOM_HOME_CHANNEL", standalone_sender_fn=_standalone_send, max_message_length=4000, **common,
  758. platform_hint=_WECOM_PLATFORM_HINT,
  759. display_tier="low",
  760. # Non-editable, but its native "stream" msgtype gives a typing animation + cumulative updates.
  761. display_overrides={"streaming": True},
  762. env_overrides=gateway_env.ENV_OVERRIDES,
  763. env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS, **gateway_env.AUTHZ,
  764. )
  765. from plugins.platforms.wecom.callback_adapter import check_wecom_callback_requirements, ensure_wecom_callback_requirements
  766. ctx.register_platform(
  767. name="wecom_callback", label="WeCom Callback (self-built apps)", adapter_factory=_build_callback_adapter,
  768. dashboard_label="WeCom (app)",
  769. dashboard_description="Two-way WeCom integration via callback app.",
  770. docs_url="https://developer.work.weixin.qq.com/document/path/90930",
  771. dashboard_env_vars=(
  772. "WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET", "WECOM_CALLBACK_AGENT_ID",
  773. "WECOM_CALLBACK_TOKEN", "WECOM_CALLBACK_ENCODING_AES_KEY",
  774. ),
  775. dashboard_required_env=(
  776. "WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET", "WECOM_CALLBACK_AGENT_ID",
  777. ),
  778. check_fn=check_wecom_callback_requirements, ensure_deps_fn=ensure_wecom_callback_requirements,
  779. is_connected=_callback_is_connected, validate_config=_callback_is_connected,
  780. required_env=["WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET"], **common,
  781. display_tier="low",
  782. env_overrides=gateway_env.CALLBACK_ENV_OVERRIDES,
  783. env_enable_credentials=gateway_env.CALLBACK_ENV_ENABLE_CREDENTIALS, **gateway_env.CALLBACK_AUTHZ,
  784. )