adapter.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. """DingTalk platform adapter (Stream Mode via dingtalk-stream >=0.20; replies via session webhook markdown or AI Cards).
  2. Requires ``pip install "dingtalk-stream>=0.20" httpx``. config.yaml ``platforms.dingtalk``: ``enabled``, group gating
  3. (``require_mention``, ``free_response_chats``, ``mention_patterns``, ``allowed_users``/``allowed_chats``) and
  4. ``extra.client_id`` / ``extra.client_secret`` (or DINGTALK_CLIENT_ID / DINGTALK_CLIENT_SECRET)."""
  5. import asyncio
  6. import json
  7. import logging
  8. import re
  9. import time
  10. import traceback
  11. import uuid
  12. from datetime import datetime, timezone, UTC
  13. from typing import Any, Dict, List, Optional, Set
  14. # Optional SDKs: catch broad Exception, not just ImportError — their transitive cryptography
  15. # dependency can raise AttributeError on version skew; a broken optional SDK must degrade gracefully.
  16. try:
  17. import dingtalk_stream
  18. from dingtalk_stream import ChatbotMessage
  19. from dingtalk_stream.frames import CallbackMessage, AckMessage
  20. DINGTALK_STREAM_AVAILABLE = True
  21. except Exception:
  22. DINGTALK_STREAM_AVAILABLE = False
  23. dingtalk_stream = ChatbotMessage = CallbackMessage = None # type: ignore[assignment]
  24. AckMessage = type("AckMessage", (), {"STATUS_OK": 200, "STATUS_SYSTEM_EXCEPTION": 500}) # type: ignore[assignment]
  25. try:
  26. import httpx
  27. HTTPX_AVAILABLE = True
  28. except ImportError:
  29. HTTPX_AVAILABLE = False
  30. httpx = None # type: ignore[assignment]
  31. try:
  32. from alibabacloud_dingtalk.card_1_0 import client as dingtalk_card_client, models as dingtalk_card_models
  33. from alibabacloud_dingtalk.robot_1_0 import client as dingtalk_robot_client, models as dingtalk_robot_models
  34. from alibabacloud_tea_openapi import models as open_api_models
  35. from alibabacloud_tea_util import models as tea_util_models
  36. CARD_SDK_AVAILABLE = True
  37. except Exception:
  38. CARD_SDK_AVAILABLE = False
  39. dingtalk_card_client = dingtalk_card_models = dingtalk_robot_client = dingtalk_robot_models = None
  40. open_api_models = tea_util_models = None
  41. from gateway.config import Platform, PlatformConfig
  42. from gateway.platforms.helpers import MessageDeduplicator, compile_mention_patterns
  43. from agent.i18n import t
  44. from gateway.platforms.base import BasePlatformAdapter, SendResult
  45. from gateway.platforms.event import MessageEvent
  46. from gateway.platforms._shared import (
  47. apply_yaml_bridge as _apply_yaml_bridge, decode_json_list_literal as _decode_json_list_literal,
  48. extra_or_secret as _extra_or_secret, get_scoped_secret as _get_scoped_secret, send_error
  49. )
  50. from gateway.platforms.send_targets import StandaloneSendPolicy
  51. from plugins.platforms.dingtalk.inbound import collect_download_codes, extract_media, extract_text
  52. logger = logging.getLogger(__name__)
  53. MAX_MESSAGE_LENGTH = 20000
  54. RECONNECT_BACKOFF = [2, 5, 10, 30, 60]
  55. RECONNECT_CIRCUIT_BREAKER_TRIPS = 5 # identical errors escaping start() before the breaker trips
  56. RECONNECT_CIRCUIT_BREAKER_DELAY = 300 # seconds between attempts while tripped (matches the runner's cap)
  57. _SDK_LOG_REPEAT_WINDOW = 300.0 # identical dingtalk_stream.client records are collapsed within this window
  58. def _is_sdk_incompat(exc: BaseException | None) -> bool:
  59. """True for #24851: ``websockets.connect`` is not an async CM for this dingtalk-stream.
  60. The SDK may surface it as the bare TypeError, or as an AttributeError (its ``except``
  61. clause touches the unloaded ``websockets.exceptions``) chained on that TypeError.
  62. """
  63. for _ in range(4):
  64. if exc is None:
  65. return False
  66. if isinstance(exc, TypeError) and "asynchronous context manager" in str(exc):
  67. return True
  68. exc = exc.__cause__ or exc.__context__
  69. return False
  70. class _SdkLogGuard(logging.Filter):
  71. """Collapse repeated dingtalk_stream.client records; never raises on bad format args.
  72. dingtalk-stream 0.24.3 logs ``logger.exception('unknown exception', e)`` every 3 s from its
  73. retry loop — a malformed call that also triggers stdlib "--- Logging error ---" tracebacks.
  74. """
  75. def __init__(self, on_exception=None, window: float = _SDK_LOG_REPEAT_WINDOW):
  76. super().__init__()
  77. self._on_exception, self._window = on_exception, window
  78. self._seen: dict[tuple, list] = {} # key -> [last_emitted_monotonic, suppressed_count]
  79. def filter(self, record: logging.LogRecord) -> bool:
  80. try:
  81. try:
  82. msg = record.getMessage()
  83. except Exception:
  84. args = record.args if isinstance(record.args, tuple) else (record.args,)
  85. msg = " ".join(str(x) for x in (record.msg, *args))
  86. record.msg, record.args = msg, ()
  87. exc = record.exc_info[1] if record.exc_info else None
  88. if exc is not None and self._on_exception is not None:
  89. self._on_exception(exc)
  90. key = (record.levelno, msg[:500], type(exc).__name__ if exc is not None else None)
  91. now = time.monotonic()
  92. entry = self._seen.get(key)
  93. if entry is not None and now - entry[0] < self._window:
  94. entry[1] += 1
  95. return False
  96. if entry is not None and entry[1]:
  97. record.msg, record.args = f"{msg} (suppressed {entry[1]} identical repeats)", ()
  98. if len(self._seen) >= 256:
  99. self._seen.clear()
  100. self._seen[key] = [now, 0]
  101. except Exception:
  102. pass # a logging filter must never break the caller
  103. return True
  104. _SESSION_WEBHOOKS_MAX = 500
  105. _DINGTALK_WEBHOOK_RE = re.compile(r'^https://(?:api|oapi)\.dingtalk\.com/')
  106. _TRUTHY = {"true", "1", "yes", "on"}
  107. _EMOTION_ID = "2659900"
  108. _EMOTION_BG = "im_bg_1"
  109. # recall? -> (TextEmotion model, Request model, Headers model, robot SDK method), resolved on ``dingtalk_robot_models`` at call time.
  110. _EMOTION_SDK = {recall: (f"Robot{v}EmotionRequestTextEmotion", f"Robot{v}EmotionRequest", f"Robot{v}EmotionHeaders", f"robot_{v.lower()}_emotion_with_options_async")
  111. for recall, v in ((True, "Recall"), (False, "Reply"))}
  112. _NUMBERED_RE = re.compile(r"^\d+\.\s")
  113. _NO_LOCAL_UPLOAD = "DingTalk session webhook replies do not support local %s. Only markdown/text replies are supported without OpenAPI %s."
  114. def _csv_set(raw: Any) -> set[str]:
  115. """Split a list, JSON-list string or comma-separated string into a set of stripped, non-empty items."""
  116. raw = _decode_json_list_literal(raw)
  117. parts = raw if isinstance(raw, list) else str(raw).split(",")
  118. return {str(part).strip() for part in parts if str(part).strip()}
  119. def dingtalk_deps_present() -> bool:
  120. """PASSIVE registry ``check_fn`` — must never install; credentials are gated separately.
  121. Registry ``check_fn`` — called from status displays and config loading, so it must never install
  122. anything. The ACTIVE lazy-installer (``check_dingtalk_requirements``) is registered as
  123. ``ensure_deps_fn`` and runs from ``create_adapter()`` when this returns False (#79812).
  124. """
  125. return DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE
  126. def ensure_dingtalk_deps() -> bool:
  127. """ACTIVE deps-only installer (registry ``ensure_deps_fn``); rebinds module globals. Deliberately does NOT
  128. check credentials: an ``extra``-configured platform would otherwise be vetoed before ever installing (deadlock).
  129. Lazy-installs dingtalk-stream/httpx and rebinds module globals. Deliberately does NOT check credentials
  130. — ``ensure_deps_fn``'s contract is deps-only ("Returns True once deps are importable"); credentials are
  131. gated by ``is_connected``/``validate_config``. Otherwise a platform configured via
  132. ``PlatformConfig.extra`` (which ``_is_connected`` accepts) would pass enablement, reach
  133. ``create_adapter()``, and have the installer veto on env-var grounds before ever installing —
  134. re-creating the #79812 deadlock for extra-configured setups.
  135. """
  136. global DINGTALK_STREAM_AVAILABLE, dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, HTTPX_AVAILABLE, httpx
  137. if DINGTALK_STREAM_AVAILABLE and HTTPX_AVAILABLE:
  138. return True
  139. try:
  140. from pm.extras import ensure_import
  141. ensure_import("dingtalk")
  142. import dingtalk_stream as _ds, httpx as _httpx
  143. from dingtalk_stream import ChatbotMessage as _CM
  144. from dingtalk_stream.frames import CallbackMessage as _CBM, AckMessage as _AM
  145. except Exception:
  146. return False
  147. dingtalk_stream, ChatbotMessage, CallbackMessage, AckMessage, httpx = _ds, _CM, _CBM, _AM, _httpx
  148. DINGTALK_STREAM_AVAILABLE = HTTPX_AVAILABLE = True
  149. return True
  150. def _credentials(extra: Optional[dict]) -> tuple:
  151. """(client_id, client_secret) from PlatformConfig.extra first, then env / scoped secret."""
  152. extra = extra or {}
  153. # client_id goes through the same scoped reader as the secret: os.environ holds the DEFAULT
  154. # profile's app id under multiplex, and pairing it with a secondary's secret authenticates as the wrong app.
  155. return (extra.get("client_id") or _get_scoped_secret("DINGTALK_CLIENT_ID", ""),
  156. extra.get("client_secret") or _get_scoped_secret("DINGTALK_CLIENT_SECRET", ""))
  157. def check_dingtalk_requirements() -> bool:
  158. """Combined deps (lazy-installed) + credentials check for setup/status callers."""
  159. return ensure_dingtalk_deps() and all(_credentials(None))
  160. class DingTalkAdapter(BasePlatformAdapter):
  161. """Stream Mode adapter: the SDK keeps a long-lived WebSocket and messages arrive via a ChatbotHandler
  162. callback; replies go through the message's session_webhook (httpx) or, with ``card_template_id``, AI Cards."""
  163. MAX_MESSAGE_LENGTH = MAX_MESSAGE_LENGTH
  164. @property
  165. def SUPPORTS_MESSAGE_EDITING(self) -> bool:
  166. """Edits only exist with AI Cards; the gateway gates streaming cursor/edit on this."""
  167. return bool(self._card_template_id and self._card_sdk)
  168. REQUIRES_EDIT_FINALIZE = SUPPORTS_MESSAGE_EDITING # AI Cards need an explicit ``finalize=True`` edit to close the streaming indicator
  169. def __init__(self, config: PlatformConfig):
  170. super().__init__(config, Platform.DINGTALK)
  171. extra = config.extra or {}
  172. self._client_id, self._client_secret = _credentials(extra)
  173. # Group-chat gating; mention state is the SDK's structured ``is_in_at_list``, not text parsing.
  174. self._mention_patterns: list[re.Pattern] = self._compile_mention_patterns()
  175. self._allowed_users: set[str] = {item.lower() for item in self._csv_setting("allowed_users", "DINGTALK_ALLOWED_USERS")}
  176. self._stream_client = self._stream_task = self._http_client = self._card_sdk = self._robot_sdk = None
  177. self._robot_code: str = extra.get("robot_code") or self._client_id
  178. self._dedup = MessageDeduplicator(max_size=1000)
  179. self._session_webhooks: dict[str, tuple[str, int]] = {} # chat_id -> (webhook, expired_time_ms)
  180. self._message_contexts: dict[str, Any] = {} # chat_id -> last inbound ChatbotMessage (per-chat: no clobber)
  181. self._card_template_id: Optional[str] = extra.get("card_template_id")
  182. self._done_emoji_fired: set[str] = set() # chats whose Done reaction fired this turn; reset per inbound
  183. # Open streaming cards: chat_id -> {out_track_id: last_content}. ``edit_message(finalize=False)``
  184. # re-opens a finalized card, so we track them and auto-close as siblings on the next ``send()``.
  185. self._streaming_cards: dict[str, dict[str, str]] = {}
  186. self._bg_tasks: set[asyncio.Task] = set() # fire-and-forget emoji tasks, kept referenced (GC) + cancellable
  187. async def connect(self, *, is_reconnect: bool = False) -> bool:
  188. """Connect to DingTalk via Stream Mode."""
  189. for ok, problem in ((DINGTALK_STREAM_AVAILABLE, "dingtalk-stream not installed. Run: pip install 'dingtalk-stream>=0.20'"),
  190. (HTTPX_AVAILABLE, "httpx not installed. Run: pip install httpx"),
  191. (self._client_id and self._client_secret, "DINGTALK_CLIENT_ID and DINGTALK_CLIENT_SECRET required")):
  192. if not ok:
  193. logger.warning("[%s] " + problem, self.name)
  194. return False
  195. try:
  196. from gateway.platforms._http_client_limits import platform_httpx_limits # tighter keepalive: idle CLOSE_WAIT drains promptly
  197. self._http_client = httpx.AsyncClient(timeout=30.0, limits=platform_httpx_limits())
  198. self._stream_client = dingtalk_stream.DingTalkStreamClient(dingtalk_stream.Credential(self._client_id, self._client_secret))
  199. if CARD_SDK_AVAILABLE:
  200. sdk_config = open_api_models.Config()
  201. sdk_config.protocol, sdk_config.region_id = "https", "central"
  202. if self._card_template_id:
  203. self._card_sdk = dingtalk_card_client.Client(sdk_config)
  204. self._robot_sdk = dingtalk_robot_client.Client(sdk_config) # needed for media download even without cards
  205. if self._card_template_id:
  206. logger.info("[%s] Card SDK initialized with template: %s", self.name, self._card_template_id)
  207. else:
  208. logger.info("[%s] Robot SDK initialized (media download)", self.name)
  209. self._stream_client.register_callback_handler(dingtalk_stream.ChatbotMessage.TOPIC, _IncomingHandler(self, asyncio.get_running_loop()))
  210. self._stream_task = asyncio.create_task(self._run_stream())
  211. self._mark_connected()
  212. logger.info("[%s] Connected via Stream Mode", self.name)
  213. self._wire_plugin_handlers(self._stream_client) # plugin-registered native handlers
  214. return True
  215. except Exception as e:
  216. logger.error("[%s] Failed to connect: %s", self.name, e)
  217. return False
  218. async def _run_stream(self) -> None:
  219. """Run the SDK stream client with auto-reconnection.
  220. dingtalk-stream's ``start()`` runs its own catch-all retry loop, so most
  221. errors never reach us: ``_SdkLogGuard`` collapses that loop's repeated
  222. log records, and a dingtalk-stream/websockets incompatibility (#24851)
  223. is handed to the gateway's reconnect watcher via ``_set_fatal_error``
  224. instead of retrying forever. For errors that do escape ``start()``,
  225. exponential backoff (RECONNECT_BACKOFF) applies; after
  226. RECONNECT_CIRCUIT_BREAKER_TRIPS identical errors in a row the breaker
  227. trips and stays tripped (silent, RECONNECT_CIRCUIT_BREAKER_DELAY between
  228. attempts) until the error type changes.
  229. """
  230. self._sdk_loop_task = asyncio.current_task()
  231. sdk_logger = getattr(self._stream_client, "logger", None)
  232. if not isinstance(sdk_logger, logging.Logger):
  233. sdk_logger = logging.getLogger("dingtalk_stream.client")
  234. guard = _SdkLogGuard(self._on_sdk_error)
  235. sdk_logger.addFilter(guard)
  236. try:
  237. await self._run_stream_loop()
  238. finally:
  239. sdk_logger.removeFilter(guard)
  240. async def _run_stream_loop(self) -> None:
  241. backoff_idx = 0
  242. consecutive_same_error = 0
  243. last_error_type: type | None = None
  244. while self._running:
  245. try:
  246. logger.debug("[%s] Starting stream client...", self.name)
  247. await self._stream_client.start()
  248. except asyncio.CancelledError:
  249. if getattr(self, "_fatal_error_code", None) == "dingtalk_stream_error":
  250. await self._notify_fatal_error()
  251. return
  252. except Exception as e:
  253. if not self._running:
  254. return
  255. if _is_sdk_incompat(e):
  256. self._on_sdk_error(e, cancel=False)
  257. await self._notify_fatal_error()
  258. return
  259. error_type = type(e)
  260. if error_type is last_error_type:
  261. consecutive_same_error += 1
  262. else:
  263. consecutive_same_error = 1
  264. last_error_type = error_type
  265. if consecutive_same_error <= RECONNECT_CIRCUIT_BREAKER_TRIPS:
  266. logger.warning("[%s] Stream client error: %s", self.name, e)
  267. elif consecutive_same_error == RECONNECT_CIRCUIT_BREAKER_TRIPS + 1:
  268. logger.error(
  269. "[%s] Stream client error repeated %d times: %s — circuit breaker tripped; "
  270. "retrying every %ds silently until the error changes.",
  271. self.name, consecutive_same_error, e, RECONNECT_CIRCUIT_BREAKER_DELAY,
  272. )
  273. if not self._running:
  274. return
  275. if consecutive_same_error > RECONNECT_CIRCUIT_BREAKER_TRIPS:
  276. await asyncio.sleep(RECONNECT_CIRCUIT_BREAKER_DELAY)
  277. else:
  278. delay = RECONNECT_BACKOFF[min(backoff_idx, len(RECONNECT_BACKOFF) - 1)]
  279. logger.info("[%s] Reconnecting in %ds...", self.name, delay)
  280. await asyncio.sleep(delay)
  281. backoff_idx += 1
  282. def _on_sdk_error(self, exc: BaseException, *, cancel: bool = True) -> None:
  283. """Called (sync, possibly from the SDK logger) with an SDK exception; hands off on incompat."""
  284. if not _is_sdk_incompat(exc) or getattr(self, "_fatal_error_code", None) == "dingtalk_stream_error":
  285. return
  286. msg = (f"dingtalk-stream cannot open its websocket with the installed websockets package ({exc}). "
  287. "Hermes pins dingtalk-stream==0.24.3 with websockets==15.0.1; reinstall the dingtalk extra "
  288. "so those versions are used (e.g. `pip install 'hermes-agent[dingtalk]'`).")
  289. logger.error("[%s] %s", self.name, msg)
  290. # Not retryable: only a reinstall + restart fixes it, and connect() returns True before the
  291. # socket exists, so a gateway reconnect would re-fail every watcher tick forever.
  292. self._set_fatal_error("dingtalk_stream_error", msg, retryable=False)
  293. task = getattr(self, "_sdk_loop_task", None)
  294. if cancel and task is not None and not task.done():
  295. task.cancel() # SDK's own retry loop never exits; lands on its next await
  296. async def _quiet(self, coro, debug_fmt: str = "", *args) -> None:
  297. """Await *coro*, swallowing any exception (logged at debug as ``debug_fmt % (name, *args, exc)`` when given)."""
  298. try:
  299. await coro
  300. except Exception as e:
  301. if debug_fmt:
  302. logger.debug(debug_fmt, self.name, *args, e)
  303. async def disconnect(self) -> None:
  304. """Disconnect from DingTalk."""
  305. self._running = False
  306. self._mark_disconnected()
  307. # Close the websocket first so the stream task sees the disconnect instead of awaiting frames that never arrive.
  308. websocket = getattr(self._stream_client, "websocket", None) if self._stream_client else None
  309. if websocket is not None:
  310. await self._quiet(websocket.close(), "[%s] websocket close during disconnect failed: %s")
  311. if self._stream_task:
  312. if hasattr(self._stream_client, "close"):
  313. await self._quiet(asyncio.to_thread(self._stream_client.close)) # sync close() may block on I/O
  314. self._stream_task.cancel()
  315. try:
  316. await asyncio.wait_for(self._stream_task, timeout=5.0)
  317. except (TimeoutError, asyncio.CancelledError):
  318. logger.debug("[%s] stream task did not exit cleanly during disconnect", self.name)
  319. self._stream_task = None
  320. for task in list(self._bg_tasks):
  321. task.cancel()
  322. if self._bg_tasks:
  323. await asyncio.gather(*self._bg_tasks, return_exceptions=True)
  324. # Finalize open streaming cards BEFORE the HTTP client closes so they don't stay stuck
  325. # in streaming state after a gateway restart. Outer try guards the token fetch.
  326. for _chat_id in list(self._streaming_cards):
  327. await self._quiet(self._close_streaming_siblings(_chat_id), "[%s] Failed to finalize streaming card on disconnect for %s: %s", _chat_id)
  328. if self._http_client:
  329. await self._http_client.aclose()
  330. self._http_client = self._stream_client = None
  331. for store in (self._session_webhooks, self._message_contexts, self._streaming_cards, self._done_emoji_fired, self._dedup, self._bg_tasks):
  332. store.clear()
  333. logger.info("[%s] Disconnected", self.name)
  334. def _csv_setting(self, key: str, env_name: str) -> set[str]:
  335. """List/CSV setting from config.extra[key], falling back to the env var."""
  336. return _csv_set(_extra_or_secret(self.config.extra, key, env_name, blank_is_unset=False))
  337. def _dingtalk_require_mention(self) -> bool:
  338. """Whether group chats require an explicit bot trigger."""
  339. configured = _extra_or_secret(self.config.extra, "require_mention", "DINGTALK_REQUIRE_MENTION", "false", blank_is_unset=False)
  340. return configured.lower() in _TRUTHY if isinstance(configured, str) else bool(configured)
  341. def _dingtalk_allowed_chats(self) -> set[str]:
  342. """Group chat whitelist; non-empty = hard gate even when @mentioned. DMs never filtered."""
  343. return self._csv_setting("allowed_chats", "DINGTALK_ALLOWED_CHATS")
  344. def _compile_mention_patterns(self) -> list[re.Pattern]:
  345. """Compile optional regex wake-word patterns (config list, or env as JSON / lines / CSV)."""
  346. patterns = (self.config.extra or {}).get("mention_patterns")
  347. if patterns is None and (raw := str(_get_scoped_secret("DINGTALK_MENTION_PATTERNS", "") or "").strip()):
  348. try:
  349. patterns = json.loads(raw)
  350. except Exception:
  351. patterns = [part.strip() for part in raw.splitlines() if part.strip()]
  352. if not patterns:
  353. patterns = [part.strip() for part in raw.split(",") if part.strip()]
  354. if patterns is None: # return before touching ``self.name`` on the no-patterns path (historical parity)
  355. return []
  356. return compile_mention_patterns(patterns, log_prefix=self.name, platform_label="dingtalk", display_label="DingTalk", logger_=logger)
  357. def _is_user_allowed(self, sender_id: str, sender_staff_id: str) -> bool:
  358. if not self._allowed_users or "*" in self._allowed_users:
  359. return True
  360. return bool(({(sender_id or "").lower(), (sender_staff_id or "").lower()} - {""}) & self._allowed_users)
  361. def _message_matches_mention_patterns(self, text: str) -> bool:
  362. return bool(text and self._mention_patterns) and any(p.search(text) for p in self._mention_patterns)
  363. def _should_process_message(self, message: ChatbotMessage, text: str, is_group: bool, chat_id: str) -> bool:
  364. """Group trigger rules (DMs always pass; ``allowed_users`` is enforced earlier): ``allowed_chats`` is a hard
  365. gate, then any of free_response_chats / require_mention off / @mentioned (SDK ``is_in_at_list``) / wake-word."""
  366. if not is_group:
  367. return True
  368. allowed = self._dingtalk_allowed_chats()
  369. if allowed and chat_id and chat_id not in allowed:
  370. return False
  371. return (
  372. bool(chat_id and chat_id in self._csv_setting("free_response_chats", "DINGTALK_FREE_RESPONSE_CHATS"))
  373. or not self._dingtalk_require_mention()
  374. or bool(getattr(message, "is_in_at_list", False))
  375. or self._message_matches_mention_patterns(text)
  376. )
  377. def _spawn_bg(self, coro) -> None:
  378. """Start a fire-and-forget coroutine and track it for cleanup."""
  379. self._bg_tasks.add(task := asyncio.create_task(coro))
  380. task.add_done_callback(self._bg_tasks.discard)
  381. async def _close_streaming_siblings(self, chat_id: str) -> None:
  382. """Finalize open streaming cards for this chat at the start of every ``send()`` — the gateway has no "turn end" signal, so this is what closes lingering tool-progress cards."""
  383. cards = self._streaming_cards.pop(chat_id, None)
  384. token = await self._get_access_token() if cards else None
  385. for out_track_id, last_content in list(cards.items()) if token else ():
  386. try:
  387. await self._stream_card_content(out_track_id, token, last_content, finalize=True)
  388. logger.debug("[%s] AI Card sibling closed: %s", self.name, out_track_id)
  389. except Exception as e:
  390. logger.debug("[%s] Sibling close failed for %s: %s", self.name, out_track_id, e)
  391. def _fire_done_reaction(self, chat_id: str) -> None:
  392. """Swap 🤔Thinking → 🥳Done on the original user message; idempotent per chat_id."""
  393. if chat_id in self._done_emoji_fired:
  394. return
  395. self._done_emoji_fired.add(chat_id)
  396. msg = self._message_contexts.get(chat_id)
  397. msg_id, conversation_id = (getattr(msg, "message_id", None) or "", getattr(msg, "conversation_id", None) or "") if msg else ("", "")
  398. if not (msg_id and conversation_id):
  399. return
  400. async def _swap() -> None:
  401. await self._send_emotion(msg_id, conversation_id, t("platform.dingtalk.emotion.thinking"), recall=True)
  402. await self._send_emotion(msg_id, conversation_id, t("platform.dingtalk.emotion.done"), recall=False)
  403. self._spawn_bg(_swap())
  404. async def _on_message(self, message: ChatbotMessage) -> None:
  405. """Process an incoming DingTalk chatbot message."""
  406. msg_id = getattr(message, "message_id", None) or uuid.uuid4().hex
  407. if self._dedup.is_duplicate(msg_id):
  408. return logger.debug("[%s] Duplicate message %s, skipping", self.name, msg_id)
  409. conversation_id, sender_id, sender_nick, sender_staff_id = (getattr(message, k, "") or "" for k in ("conversation_id", "sender_id", "sender_nick", "sender_staff_id"))
  410. is_group = str(getattr(message, "conversation_type", "1")) == "2"
  411. sender_nick = sender_nick or sender_id
  412. chat_id = conversation_id or sender_id
  413. if not self._is_user_allowed(sender_id, sender_staff_id):
  414. return logger.debug("[%s] Dropping message from non-allowlisted user staff_id=%s sender_id=%s", self.name, sender_staff_id, sender_id)
  415. if not self._should_process_message(message, self._extract_text(message) or "", is_group, chat_id): # wake-word gate needs text early
  416. return logger.debug("[%s] Dropping group message that failed mention gate message_id=%s chat_id=%s", self.name, msg_id, chat_id)
  417. # Per-chat context; reset the Done marker so this message gets its own Thinking→Done cycle.
  418. if chat_id:
  419. self._message_contexts[chat_id] = message
  420. self._done_emoji_fired.discard(chat_id)
  421. session_webhook = getattr(message, "session_webhook", None) or ""
  422. if session_webhook and chat_id and _DINGTALK_WEBHOOK_RE.match(session_webhook):
  423. if len(self._session_webhooks) >= _SESSION_WEBHOOKS_MAX:
  424. self._session_webhooks.pop(next(iter(self._session_webhooks))) # evict oldest (dict is non-empty here)
  425. self._session_webhooks[chat_id] = (session_webhook, getattr(message, "session_webhook_expired_time", 0) or 0)
  426. await self._resolve_media_codes(message) # download codes -> URLs so vision tools can use them
  427. text = self._extract_text(message)
  428. msg_type, media_urls, media_types = self._extract_media(message)
  429. if not text and not media_urls:
  430. return logger.debug("[%s] Empty message, skipping", self.name)
  431. source = self.build_source(chat_id=chat_id, chat_name=getattr(message, "conversation_title", None), chat_type="group" if is_group else "dm",
  432. user_id=sender_id, user_name=sender_nick, user_id_alt=sender_staff_id if sender_staff_id else None,
  433. message_id=msg_id)
  434. create_at = getattr(message, "create_at", None)
  435. try:
  436. timestamp = datetime.fromtimestamp(int(create_at) / 1000, tz=UTC) if create_at else datetime.now(tz=UTC)
  437. except (ValueError, OSError, TypeError):
  438. timestamp = datetime.now(tz=UTC)
  439. logger.debug("[%s] Message from %s in %s: %s", self.name, sender_nick, chat_id[:20] if chat_id else "?", text[:80] if text else "(media)")
  440. await self.handle_message(MessageEvent(text=text, message_type=msg_type, source=source, message_id=msg_id, raw_message=message,
  441. media_urls=media_urls, media_types=media_types, timestamp=timestamp))
  442. _extract_text = staticmethod(extract_text)
  443. def _extract_media(self, message: ChatbotMessage):
  444. return extract_media(message)
  445. async def send(self, chat_id: str, content: str, reply_to: Optional[str] = None, metadata: Optional[dict[str, Any]] = None) -> SendResult:
  446. """Send a reply via AI Card (when configured) or DingTalk session webhook markdown."""
  447. metadata = metadata or {}
  448. logger.debug("[%s] send() chat_id=%s card_enabled=%s", self.name, chat_id, bool(self._card_template_id and self._card_sdk))
  449. session_webhook = metadata.get("session_webhook") or (self._get_valid_webhook(chat_id) or ("",))[0]
  450. if not session_webhook:
  451. logger.warning("[%s] No valid session_webhook for chat_id=%s", self.name, chat_id)
  452. return SendResult(success=False, error="No valid session_webhook available. Reply must follow an incoming message.")
  453. if not self._http_client:
  454. return SendResult(success=False, error="HTTP client not initialized")
  455. current_message = self._message_contexts.get(chat_id)
  456. # ``reply_to`` is only set by base.py:_send_with_retry for the FINAL reply to an inbound message;
  457. # tool-progress, commentary and stream first-sends leave it None. It decides (1) finalize-on-create
  458. # (intermediate cards stay open so edits don't flicker) and (2) whether to fire the Done reaction.
  459. is_final_reply = reply_to is not None
  460. if self._card_template_id and current_message and self._card_sdk:
  461. await self._close_streaming_siblings(chat_id) # close lingering tool-progress cards before creating a new one
  462. result = await self._create_and_stream_card(chat_id, current_message, content, finalize=is_final_reply)
  463. if result and result.success:
  464. if is_final_reply:
  465. self._fire_done_reaction(chat_id)
  466. else: # keep open + track so the next send() auto-closes it, or edit_message(finalize=True) does
  467. self._streaming_cards.setdefault(chat_id, {})[result.message_id] = content
  468. return result
  469. logger.warning("[%s] AI Card send failed, falling back to webhook", self.name)
  470. logger.debug("[%s] Sending via webhook", self.name)
  471. payload = {"msgtype": "markdown", "markdown": {"title": "Hermes", "text": self._normalize_markdown(content[: self.MAX_MESSAGE_LENGTH])}}
  472. try:
  473. resp = await self._http_client.post(session_webhook, json=payload, timeout=15.0)
  474. if resp.status_code < 300:
  475. if is_final_reply:
  476. self._fire_done_reaction(chat_id)
  477. return SendResult(success=True, message_id=uuid.uuid4().hex[:12])
  478. logger.warning("[%s] Send failed HTTP %d: %s", self.name, resp.status_code, resp.text[:200])
  479. return SendResult(success=False, error=f"HTTP {resp.status_code}: {resp.text[:200]}")
  480. except httpx.TimeoutException:
  481. return SendResult(success=False, error="Timeout sending message to DingTalk")
  482. except Exception as e:
  483. logger.error("[%s] Send error: %s", self.name, e)
  484. return SendResult(success=False, error=str(e))
  485. async def send_typing(self, chat_id: str, metadata=None) -> None:
  486. """DingTalk does not support typing indicators."""
  487. async def send_image(self, chat_id: str, image_url: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata=None) -> SendResult:
  488. """Render a remote image inline via markdown (session webhook has no native attachments)."""
  489. image_block = f"![image]({image_url})"
  490. return await self.send(chat_id=chat_id, content=f"{caption}\n\n{image_block}" if caption else image_block, reply_to=reply_to, metadata=metadata)
  491. async def send_image_file(self, chat_id: str, image_path: str, caption: Optional[str] = None, reply_to: Optional[str] = None, metadata=None, **kwargs) -> SendResult:
  492. """Webhook replies cannot upload local images."""
  493. return SendResult(success=False, error=_NO_LOCAL_UPLOAD % ("image uploads", "media upload"))
  494. async def send_document(self, chat_id: str, file_path: str, caption: Optional[str] = None, file_name: Optional[str] = None, reply_to=None, metadata=None, **kwargs) -> SendResult:
  495. """Webhook replies cannot upload local files."""
  496. return SendResult(success=False, error=_NO_LOCAL_UPLOAD % ("file attachments", "message send"))
  497. async def get_chat_info(self, chat_id: str) -> dict[str, Any]:
  498. """Return basic info about a DingTalk conversation."""
  499. return {"name": chat_id, "type": "group" if "group" in chat_id.lower() else "dm"}
  500. def _get_valid_webhook(self, chat_id: str) -> Optional[tuple[str, int]]:
  501. """Get a non-expired session webhook for chat_id (5-minute safety margin)."""
  502. info = self._session_webhooks.get(chat_id)
  503. expired_time_ms = info[1] if info else 0
  504. if expired_time_ms and expired_time_ms > 0 and int(datetime.now(tz=UTC).timestamp() * 1000) + 5 * 60 * 1000 >= expired_time_ms:
  505. self._session_webhooks.pop(chat_id, None)
  506. return None
  507. return info or None
  508. async def _create_and_stream_card(self, chat_id: str, message: Any, content: str, *, finalize: bool = True) -> Optional[SendResult]:
  509. """Create, deliver and stream an AI Card; ``finalize=False`` leaves it open for ``edit_message`` by out_track_id."""
  510. try:
  511. token = await self._get_access_token()
  512. if not token:
  513. return None
  514. out_track_id, models = f"hermes_{uuid.uuid4().hex[:12]}", dingtalk_card_models
  515. is_group = str(getattr(message, "conversation_type", "1")) == "2"
  516. sender_staff_id = getattr(message, "sender_staff_id", "") or ""
  517. create_request = models.CreateCardRequest(
  518. card_template_id=self._card_template_id, out_track_id=out_track_id, callback_type="STREAM",
  519. card_data=models.CreateCardRequestCardData(card_param_map={"content": ""}),
  520. im_group_open_space_model=models.CreateCardRequestImGroupOpenSpaceModel(support_forward=True),
  521. im_robot_open_space_model=models.CreateCardRequestImRobotOpenSpaceModel(support_forward=True))
  522. await self._sdk_call(self._card_sdk.create_card_with_options_async, create_request, models.CreateCardHeaders, token)
  523. if is_group:
  524. open_space_id = f"dtv1.card//IM_GROUP.{getattr(message, 'conversation_id', '') or ''}"
  525. deliver_model = {"im_group_open_deliver_model": models.DeliverCardRequestImGroupOpenDeliverModel(robot_code=self._robot_code)}
  526. elif sender_staff_id:
  527. open_space_id = f"dtv1.card//IM_ROBOT.{sender_staff_id}"
  528. deliver_model = {"im_robot_open_deliver_model": models.DeliverCardRequestImRobotOpenDeliverModel(space_type="IM_ROBOT")}
  529. else:
  530. return logger.warning("[%s] AI Card skipped: missing sender_staff_id for DM", self.name)
  531. deliver_request = models.DeliverCardRequest(out_track_id=out_track_id, user_id_type=1, open_space_id=open_space_id, **deliver_model)
  532. await self._sdk_call(self._card_sdk.deliver_card_with_options_async, deliver_request, models.DeliverCardHeaders, token)
  533. await self._stream_card_content(out_track_id, token, content, finalize=finalize)
  534. logger.info("[%s] AI Card %s: %s", self.name, "created+finalized" if finalize else "created (streaming)", out_track_id)
  535. return SendResult(success=True, message_id=out_track_id)
  536. except Exception as e:
  537. logger.warning("[%s] AI Card create failed: %s\n%s", self.name, e, traceback.format_exc())
  538. return None
  539. async def edit_message(self, chat_id: str, message_id: str, content: str, *, finalize: bool = False) -> SendResult:
  540. """Stream updated content to an AI Card; ``message_id`` is the creating ``send()``'s out_track_id (callers track their own ids so parallel flows on one chat don't interfere)."""
  541. if not self.SUPPORTS_MESSAGE_EDITING:
  542. return SendResult(success=False, error="AI Cards are not configured for message editing")
  543. token = await self._get_access_token() if message_id else None
  544. if not token:
  545. return SendResult(success=False, error="message_id required" if not message_id else "No access token")
  546. try:
  547. await self._stream_card_content(message_id, token, content, finalize=finalize)
  548. if finalize: # canonical "response ended" signal from the stream consumer's final edit
  549. self._streaming_cards.get(chat_id, {}).pop(message_id, None)
  550. if not self._streaming_cards.get(chat_id):
  551. self._streaming_cards.pop(chat_id, None)
  552. logger.debug("[%s] AI Card finalized (edit): %s", self.name, message_id)
  553. self._fire_done_reaction(chat_id)
  554. else: # non-final edit reopens the card into streaming state — track for sibling close
  555. self._streaming_cards.setdefault(chat_id, {})[message_id] = content
  556. return SendResult(success=True, message_id=message_id)
  557. except Exception as e:
  558. logger.warning("[%s] Card edit failed: %s", self.name, e)
  559. return SendResult(success=False, error=str(e))
  560. @staticmethod
  561. async def _sdk_call(method, request, headers_cls, token: str):
  562. """``await method(request, headers_cls(token), RuntimeOptions())`` — the alibabacloud SDK call shape."""
  563. return await method(request, headers_cls(x_acs_dingtalk_access_token=token), tea_util_models.RuntimeOptions())
  564. async def _stream_card_content(self, out_track_id: str, token: str, content: str, finalize: bool = False) -> None:
  565. """Stream content to an existing AI Card."""
  566. stream_request = dingtalk_card_models.StreamingUpdateRequest(
  567. out_track_id=out_track_id, guid=str(uuid.uuid4()), key="content", content=content[: self.MAX_MESSAGE_LENGTH],
  568. is_full=True, is_finalize=finalize, is_error=False,
  569. )
  570. await self._sdk_call(self._card_sdk.streaming_update_with_options_async, stream_request, dingtalk_card_models.StreamingUpdateHeaders, token)
  571. async def _get_access_token(self) -> Optional[str]:
  572. """Get access token via the SDK's cached (sync, requests-based) getter."""
  573. if not self._stream_client:
  574. return None
  575. try:
  576. return await asyncio.to_thread(self._stream_client.get_access_token)
  577. except Exception as e:
  578. logger.error("[%s] Failed to get access token: %s", self.name, e)
  579. return None
  580. async def _send_emotion(self, open_msg_id: str, open_conversation_id: str, emoji_name: str, *, recall: bool = False) -> None:
  581. """Add (or recall) an emoji reaction on a message."""
  582. if not self._robot_sdk or not open_msg_id or not open_conversation_id:
  583. return
  584. action = "recall" if recall else "reply"
  585. try:
  586. token = await self._get_access_token()
  587. if not token:
  588. return
  589. text_emotion_cls, request_cls, headers_cls, sdk_method = _EMOTION_SDK[recall]
  590. text_emotion = getattr(dingtalk_robot_models, text_emotion_cls)(emotion_id=_EMOTION_ID, emotion_name=emoji_name, text=emoji_name, background_id=_EMOTION_BG)
  591. request = getattr(dingtalk_robot_models, request_cls)(robot_code=self._robot_code, open_msg_id=open_msg_id, open_conversation_id=open_conversation_id,
  592. emotion_type=2, emotion_name=emoji_name, text_emotion=text_emotion)
  593. await self._sdk_call(getattr(self._robot_sdk, sdk_method), request, getattr(dingtalk_robot_models, headers_cls), token)
  594. logger.info("[%s] _send_emotion: %s %s on msg=%s", self.name, action, emoji_name, open_msg_id[:24])
  595. except Exception:
  596. logger.debug("[%s] _send_emotion %s failed", self.name, action, exc_info=True)
  597. async def _resolve_media_codes(self, message: ChatbotMessage) -> None:
  598. """Resolve download codes in the message to real URLs (in place, in parallel)."""
  599. token = await self._get_access_token()
  600. if not token:
  601. return
  602. robot_code = getattr(message, "robot_code", None) or self._client_id
  603. pairs = [(getattr(obj, key, None) if hasattr(obj, key) else obj.get(key), obj, key) for obj, key in collect_download_codes(message)]
  604. tasks = [self._fetch_download_url(code, robot_code, token, obj, key) for code, obj, key in pairs if code]
  605. if tasks:
  606. await asyncio.gather(*tasks, return_exceptions=True)
  607. async def _fetch_download_url(self, code: str, robot_code: str, token: str, obj, key: str) -> None:
  608. """Fetch the download URL for one code via the robot SDK and write it back to ``obj[key]``."""
  609. if not self._robot_sdk:
  610. return logger.warning("[%s] Robot SDK not initialized, cannot resolve media code", self.name)
  611. try:
  612. response = await self._sdk_call(self._robot_sdk.robot_message_file_download_with_options_async,
  613. dingtalk_robot_models.RobotMessageFileDownloadRequest(download_code=code, robot_code=robot_code),
  614. dingtalk_robot_models.RobotMessageFileDownloadHeaders, token)
  615. body = response.body if response else None
  616. url = getattr(body, "download_url", None) if body else None
  617. if not body:
  618. logger.warning("[%s] Failed to download media: empty response for code %s", self.name, code)
  619. elif url and hasattr(obj, key):
  620. setattr(obj, key, url)
  621. elif url and isinstance(obj, dict):
  622. obj[key] = url
  623. except Exception as e:
  624. logger.error("[%s] Error resolving media code %s: %s", self.name, code, e)
  625. @staticmethod
  626. def _normalize_markdown(text: str) -> str:
  627. """Work around DingTalk renderer quirks: blank line before numbered lists, dedent ``` fences."""
  628. lines = text.split("\n")
  629. out = []
  630. for i, line in enumerate(lines):
  631. prev = lines[i - 1].strip() if i > 0 else ""
  632. if prev and _NUMBERED_RE.match(line.strip()) and not _NUMBERED_RE.match(prev):
  633. out.append("")
  634. out.append(line.lstrip() if line.strip().startswith("```") else line)
  635. return "\n".join(out)
  636. class _IncomingHandler(dingtalk_stream.ChatbotHandler if DINGTALK_STREAM_AVAILABLE else object):
  637. """ChatbotHandler forwarding to the adapter (SDK >= 0.20: async ``process()`` gets a CallbackMessage ``.data`` dict)."""
  638. def __init__(self, adapter: DingTalkAdapter, loop: Optional[asyncio.AbstractEventLoop] = None):
  639. if DINGTALK_STREAM_AVAILABLE:
  640. super().__init__()
  641. self._adapter, self._loop = adapter, loop
  642. def pre_start(self) -> None:
  643. """No-op hook the SDK calls on every handler before opening the WebSocket (missing → AttributeError)."""
  644. return
  645. async def process(self, message: CallbackMessage):
  646. """Convert to ChatbotMessage, dispatch as a background task, ACK immediately (blocking would stall SDK heartbeats)."""
  647. try:
  648. data = json.loads(message.data) if isinstance(message.data, str) else message.data
  649. chatbot_msg = ChatbotMessage.from_dict(data)
  650. data = data if isinstance(data, dict) else {} # backfill fields from_dict() may not map (names vary across SDK versions)
  651. webhook = data.get("sessionWebhook") or data.get("session_webhook") or ""
  652. if webhook and not getattr(chatbot_msg, "session_webhook", None):
  653. chatbot_msg.session_webhook = webhook
  654. if not getattr(chatbot_msg, "is_in_at_list", False) and data.get("isInAtList"):
  655. chatbot_msg.is_in_at_list = True
  656. msg_id, conversation_id = getattr(chatbot_msg, "message_id", None) or "", getattr(chatbot_msg, "conversation_id", None) or ""
  657. if msg_id and conversation_id:
  658. self._adapter._spawn_bg(self._adapter._send_emotion(msg_id, conversation_id, t("platform.dingtalk.emotion.thinking"), recall=False))
  659. asyncio.create_task(self._safe_on_message(chatbot_msg)) # surfaces exceptions in logs instead of losing them
  660. except Exception:
  661. logger.exception("[%s] Error preparing incoming message", self._adapter.name)
  662. return AckMessage.STATUS_SYSTEM_EXCEPTION, "error"
  663. return AckMessage.STATUS_OK, "OK"
  664. async def _safe_on_message(self, chatbot_msg: ChatbotMessage) -> None:
  665. try:
  666. await self._adapter._on_message(chatbot_msg)
  667. except Exception:
  668. logger.exception("[%s] Error processing incoming message", self._adapter.name)
  669. async def _standalone_send(pconfig, chat_id, message, *, thread_id=None, media_files=None, force_document=False):
  670. """Out-of-process delivery (standalone_sender_fn) via the static robot webhook (DINGTALK_WEBHOOK_URL / extra
  671. ``webhook_url``) — per-session webhooks aren't available to cron jobs."""
  672. try:
  673. import httpx
  674. except ImportError:
  675. return send_error("httpx not installed")
  676. # Scoped: the webhook URL carries the robot's access_token and IS the delivery target — a raw
  677. # environ read would post a secondary profile's cron output to the default profile's robot.
  678. webhook_url = (getattr(pconfig, "extra", {}) or {}).get("webhook_url") or _get_scoped_secret("DINGTALK_WEBHOOK_URL", "")
  679. if not webhook_url:
  680. return send_error("DingTalk not configured. Set DINGTALK_WEBHOOK_URL env var or webhook_url in dingtalk platform extra config.")
  681. try:
  682. async with httpx.AsyncClient(timeout=30.0) as client:
  683. resp = await client.post(webhook_url, json={"msgtype": "text", "text": {"content": message}})
  684. resp.raise_for_status()
  685. data = resp.json()
  686. if data.get("errcode", 0) != 0:
  687. return send_error(f"DingTalk API error: {data.get('errmsg', 'unknown')}")
  688. return {"success": True, "platform": "dingtalk", "chat_id": chat_id}
  689. except Exception as e:
  690. try: # send_message_tool._error redacts access_token from webhook URLs (lazy import avoids a circular)
  691. from tools.send_message_tool import _error as _redact_error
  692. return _redact_error(f"DingTalk send failed: {e}")
  693. except Exception:
  694. return send_error(f"DingTalk send failed: {e}")
  695. def interactive_setup() -> None:
  696. """Configure DingTalk — QR scan (recommended) or manual credential entry."""
  697. from hermes_cli.config import save_env_value
  698. from hermes_cli.setup import prompt_choice
  699. from hermes_cli.cli_output import prompt, print_header, print_success, print_warning
  700. from hermes_cli.setup_platforms import declines_reconfigure
  701. print_header("DingTalk")
  702. if declines_reconfigure("DingTalk", "Reconfigure DingTalk?", "DINGTALK_CLIENT_ID"):
  703. return
  704. choices = ["QR Code Scan (Recommended, auto-obtain Client ID and Client Secret)", "Manual Input (Client ID and Client Secret)"]
  705. result = None
  706. if prompt_choice("Choose setup method", choices, default=0) == 0:
  707. try:
  708. from hermes_cli.dingtalk_auth import dingtalk_qr_auth
  709. result = dingtalk_qr_auth()
  710. if result is None:
  711. print_warning("QR auth incomplete, falling back to manual input.")
  712. except ImportError as exc:
  713. print_warning(f"QR auth module failed to load ({exc}), falling back to manual input.")
  714. if result is not None:
  715. for key, value in zip(("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"), result):
  716. save_env_value(key, value)
  717. return print_success("DingTalk configured via QR scan!")
  718. _manual_credential_entry(prompt, save_env_value, print_success)
  719. def _manual_credential_entry(prompt, save_env_value, print_success) -> None:
  720. client_id = prompt("DingTalk Client ID (app key)")
  721. if not client_id:
  722. return
  723. save_env_value("DINGTALK_CLIENT_ID", client_id)
  724. if client_secret := prompt("DingTalk Client Secret", password=True):
  725. save_env_value("DINGTALK_CLIENT_SECRET", client_secret)
  726. print_success("DingTalk credentials saved")
  727. def _nested_allowed_users(yaml_cfg: dict, dingtalk_cfg: dict):
  728. """Allowlist from ``extra.allowed_users``: this block's own extra first, then ``gateway.platforms.dingtalk.extra`` and ``platforms.dingtalk.extra``."""
  729. _gw = yaml_cfg.get("gateway")
  730. containers = (_gw.get("platforms") if isinstance(_gw, dict) else None, yaml_cfg.get("platforms"))
  731. for holder in (dingtalk_cfg, *(c.get("dingtalk") if isinstance(c, dict) else None for c in containers)):
  732. _extra = holder.get("extra") if isinstance(holder, dict) else None
  733. if isinstance(_extra, dict) and _extra.get("allowed_users") is not None:
  734. return _extra.get("allowed_users")
  735. return None
  736. _YAML_BRIDGE = ( # (yaml key, env var, kind) for apply_yaml_bridge
  737. ("require_mention", "DINGTALK_REQUIRE_MENTION", "lower"), ("mention_patterns", "DINGTALK_MENTION_PATTERNS", "json"),
  738. ("free_response_chats", "DINGTALK_FREE_RESPONSE_CHATS", "csv"), ("allowed_chats", "DINGTALK_ALLOWED_CHATS", "csv"),
  739. ("allowed_users", "DINGTALK_ALLOWED_USERS", "csv"),
  740. )
  741. def _apply_yaml_config(yaml_cfg: dict, dingtalk_cfg: dict) -> dict | None:
  742. """``apply_yaml_config_fn`` (#24849): config.yaml dingtalk: keys → DINGTALK_* env (env wins; skipped under a
  743. multiplexed secondary profile's scope) + ``PlatformConfig.extra``. The docs put the allowlist at
  744. ``gateway.platforms.dingtalk.extra.allowed_users`` but gateway authz only consults DINGTALK_ALLOWED_USERS,
  745. so nested-only allowlists are bridged too."""
  746. cfg = dict(dingtalk_cfg)
  747. if cfg.get("allowed_users") is None:
  748. cfg["allowed_users"] = _nested_allowed_users(yaml_cfg, dingtalk_cfg)
  749. return _apply_yaml_bridge(cfg, _YAML_BRIDGE)
  750. def _is_connected(config) -> bool:
  751. """Connected when client_id + client_secret are present (PlatformConfig.extra first, then env)."""
  752. return all(_credentials(getattr(config, "extra", {})))
  753. def register(ctx) -> None:
  754. """Plugin entry point — called by the Hermes plugin system."""
  755. from . import gateway_env # env -> GatewayConfig bridge (gateway.config_env)
  756. ctx.register_platform(
  757. standalone_send=StandaloneSendPolicy(text_direct=True),
  758. name="dingtalk", label="DingTalk", adapter_factory=DingTalkAdapter, check_fn=dingtalk_deps_present,
  759. dashboard_description="Connect Hermes to DingTalk groups (钉钉).",
  760. docs_url="https://open.dingtalk.com/document/orgapp/the-robot-development-process",
  761. dashboard_env_vars=("DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"),
  762. ensure_deps_fn=ensure_dingtalk_deps, is_connected=_is_connected, validate_config=_is_connected,
  763. required_env=["DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET"], install_hint="pip install 'dingtalk-stream>=0.20' httpx",
  764. setup_fn=interactive_setup, apply_yaml_config_fn=_apply_yaml_config, cron_deliver_env_var="DINGTALK_HOME_CHANNEL",
  765. standalone_sender_fn=_standalone_send, emoji="🐳", allow_update_command=True,
  766. display_tier="low",
  767. env_overrides=gateway_env.ENV_OVERRIDES,
  768. env_enable_credentials=gateway_env.ENV_ENABLE_CREDENTIALS, **gateway_env.AUTHZ,
  769. )