@botharness/im-provider 4.32.0-botharness.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (412) hide show
  1. package/LICENSE +21 -0
  2. package/PROVENANCE.json +25 -0
  3. package/README.en.md +445 -0
  4. package/README.md +448 -0
  5. package/THIRD_PARTY_NOTICES.md +93 -0
  6. package/assets/dingtalk-menu-template.json +6 -0
  7. package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
  8. package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
  9. package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
  10. package/assets/logo-icon.png +0 -0
  11. package/assets/logo-plugin-message-link-gradient.webp +0 -0
  12. package/assets/logo-plugin-phone.png +0 -0
  13. package/assets/logo.png +0 -0
  14. package/assets/logo_cn.png +0 -0
  15. package/assets/screenshot-menu-card.png +0 -0
  16. package/cordis.patch.yml +3 -0
  17. package/lib/client.js +20330 -0
  18. package/lib/index.js +602 -0
  19. package/locale/en.json +5 -0
  20. package/locale/zh.json +5 -0
  21. package/package.json +181 -0
  22. package/plugin-src/client/access-policy-settings.js +362 -0
  23. package/plugin-src/client/agent-preset.js +119 -0
  24. package/plugin-src/client/bot-alias.js +169 -0
  25. package/plugin-src/client/build.mjs +38 -0
  26. package/plugin-src/client/channel-card-meta.js +132 -0
  27. package/plugin-src/client/channel-logos.js +190 -0
  28. package/plugin-src/client/channels/dingtalk/api.js +267 -0
  29. package/plugin-src/client/channels/dingtalk/index.js +954 -0
  30. package/plugin-src/client/channels/dingtalk/styles.js +136 -0
  31. package/plugin-src/client/channels/discord/api.js +11 -0
  32. package/plugin-src/client/channels/discord/index.js +25 -0
  33. package/plugin-src/client/channels/discord/styles.js +19 -0
  34. package/plugin-src/client/channels/email/api.js +52 -0
  35. package/plugin-src/client/channels/email/index.js +728 -0
  36. package/plugin-src/client/channels/email/styles.js +51 -0
  37. package/plugin-src/client/channels/feishu/api.js +405 -0
  38. package/plugin-src/client/channels/feishu/group-settings.js +581 -0
  39. package/plugin-src/client/channels/feishu/index.js +1583 -0
  40. package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
  41. package/plugin-src/client/channels/feishu/styles.js +573 -0
  42. package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
  43. package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
  44. package/plugin-src/client/channels/imessage/api.js +12 -0
  45. package/plugin-src/client/channels/imessage/index.js +46 -0
  46. package/plugin-src/client/channels/imessage/styles.js +19 -0
  47. package/plugin-src/client/channels/matrix/api.js +11 -0
  48. package/plugin-src/client/channels/matrix/index.js +151 -0
  49. package/plugin-src/client/channels/matrix/styles.js +36 -0
  50. package/plugin-src/client/channels/office/api.js +46 -0
  51. package/plugin-src/client/channels/office/index.js +153 -0
  52. package/plugin-src/client/channels/office/styles.js +50 -0
  53. package/plugin-src/client/channels/qq/api.js +171 -0
  54. package/plugin-src/client/channels/qq/index.js +593 -0
  55. package/plugin-src/client/channels/qq/styles.js +19 -0
  56. package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
  57. package/plugin-src/client/channels/shared/token-api.js +124 -0
  58. package/plugin-src/client/channels/shared/token-channel.js +495 -0
  59. package/plugin-src/client/channels/slack/api.js +11 -0
  60. package/plugin-src/client/channels/slack/index.js +131 -0
  61. package/plugin-src/client/channels/slack/styles.js +34 -0
  62. package/plugin-src/client/channels/telegram/api.js +11 -0
  63. package/plugin-src/client/channels/telegram/index.js +28 -0
  64. package/plugin-src/client/channels/telegram/styles.js +31 -0
  65. package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
  66. package/plugin-src/client/channels/wecom/api.js +160 -0
  67. package/plugin-src/client/channels/wecom/index.js +625 -0
  68. package/plugin-src/client/channels/wecom/styles.js +19 -0
  69. package/plugin-src/client/channels/wecom-app/api.js +132 -0
  70. package/plugin-src/client/channels/wecom-app/index.js +634 -0
  71. package/plugin-src/client/channels/wecom-app/styles.js +25 -0
  72. package/plugin-src/client/channels/weixin/api.js +211 -0
  73. package/plugin-src/client/channels/weixin/connection-error.js +1 -0
  74. package/plugin-src/client/channels/weixin/index.js +801 -0
  75. package/plugin-src/client/channels/weixin/styles.js +115 -0
  76. package/plugin-src/client/channels/whatsapp/api.js +152 -0
  77. package/plugin-src/client/channels/whatsapp/index.js +609 -0
  78. package/plugin-src/client/channels/whatsapp/styles.js +19 -0
  79. package/plugin-src/client/connection-error.js +87 -0
  80. package/plugin-src/client/context-enhancement.js +415 -0
  81. package/plugin-src/client/credential-binding.js +118 -0
  82. package/plugin-src/client/delivery-settings.js +905 -0
  83. package/plugin-src/client/global-settings.js +433 -0
  84. package/plugin-src/client/i18n.js +1314 -0
  85. package/plugin-src/client/index.js +624 -0
  86. package/plugin-src/client/interface-language.js +89 -0
  87. package/plugin-src/client/last-message-error.js +18 -0
  88. package/plugin-src/client/lifecycle.js +86 -0
  89. package/plugin-src/client/loopback-recovery.js +75 -0
  90. package/plugin-src/client/model-setting.js +172 -0
  91. package/plugin-src/client/panel-error-boundary.js +21 -0
  92. package/plugin-src/client/plugin-page.js +51 -0
  93. package/plugin-src/client/session-channel-logos.js +243 -0
  94. package/plugin-src/client/styles.js +770 -0
  95. package/plugin-src/client/update-panel.js +14 -0
  96. package/plugin-src/client/workspace-directory-picker.js +280 -0
  97. package/plugin-src/client/workspace-editor.js +69 -0
  98. package/plugin-src/client/workspace-snapshot-fence.js +28 -0
  99. package/plugin-src/host/build.mjs +52 -0
  100. package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
  101. package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
  102. package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
  103. package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
  104. package/plugin-src/host/channels/discord/index.mjs +33 -0
  105. package/plugin-src/host/channels/discord/production.mjs +17 -0
  106. package/plugin-src/host/channels/discord/rpc.mjs +21 -0
  107. package/plugin-src/host/channels/email/availability.mjs +60 -0
  108. package/plugin-src/host/channels/email/index.mjs +36 -0
  109. package/plugin-src/host/channels/email/production.mjs +58 -0
  110. package/plugin-src/host/channels/email/rpc.mjs +163 -0
  111. package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
  112. package/plugin-src/host/channels/feishu/controller.mjs +172 -0
  113. package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
  114. package/plugin-src/host/channels/feishu/index.mjs +69 -0
  115. package/plugin-src/host/channels/feishu/production.mjs +318 -0
  116. package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
  117. package/plugin-src/host/channels/imessage/index.mjs +21 -0
  118. package/plugin-src/host/channels/imessage/production.mjs +13 -0
  119. package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
  120. package/plugin-src/host/channels/matrix/index.mjs +31 -0
  121. package/plugin-src/host/channels/matrix/production.mjs +241 -0
  122. package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
  123. package/plugin-src/host/channels/office/index.mjs +14 -0
  124. package/plugin-src/host/channels/office/production.mjs +45 -0
  125. package/plugin-src/host/channels/office/rpc.mjs +51 -0
  126. package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
  127. package/plugin-src/host/channels/qq/index.mjs +28 -0
  128. package/plugin-src/host/channels/qq/production.mjs +181 -0
  129. package/plugin-src/host/channels/qq/rpc.mjs +250 -0
  130. package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
  131. package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
  132. package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
  133. package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
  134. package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
  135. package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
  136. package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
  137. package/plugin-src/host/channels/shared/production.mjs +237 -0
  138. package/plugin-src/host/channels/shared/rpc.mjs +226 -0
  139. package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
  140. package/plugin-src/host/channels/shared/startup.mjs +76 -0
  141. package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
  142. package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
  143. package/plugin-src/host/channels/slack/index.mjs +31 -0
  144. package/plugin-src/host/channels/slack/production.mjs +176 -0
  145. package/plugin-src/host/channels/slack/rpc.mjs +221 -0
  146. package/plugin-src/host/channels/telegram/index.mjs +33 -0
  147. package/plugin-src/host/channels/telegram/production.mjs +19 -0
  148. package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
  149. package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
  150. package/plugin-src/host/channels/wecom/index.mjs +34 -0
  151. package/plugin-src/host/channels/wecom/production.mjs +187 -0
  152. package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
  153. package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
  154. package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
  155. package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
  156. package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
  157. package/plugin-src/host/channels/weixin/index.mjs +44 -0
  158. package/plugin-src/host/channels/weixin/production.mjs +257 -0
  159. package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
  160. package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
  161. package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
  162. package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
  163. package/plugin-src/host/delivery-adapter.mjs +388 -0
  164. package/plugin-src/host/delivery-http.mjs +132 -0
  165. package/plugin-src/host/delivery-rpc.mjs +173 -0
  166. package/plugin-src/host/delivery-service.mjs +552 -0
  167. package/plugin-src/host/delivery-suggestions.mjs +198 -0
  168. package/plugin-src/host/harness-command-executor.mjs +48 -0
  169. package/plugin-src/host/harness-connection.mjs +20 -0
  170. package/plugin-src/host/harness-session-coordinator.mjs +183 -0
  171. package/plugin-src/host/host-language-rpc.mjs +71 -0
  172. package/plugin-src/host/host-language.mjs +157 -0
  173. package/plugin-src/host/image-input-rpc.mjs +24 -0
  174. package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
  175. package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
  176. package/plugin-src/host/inbound-ttl-service.mjs +179 -0
  177. package/plugin-src/host/index.mjs +224 -0
  178. package/plugin-src/host/injected-context.mjs +104 -0
  179. package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
  180. package/plugin-src/host/modern-harness-api.mjs +738 -0
  181. package/plugin-src/host/rpc-authority.mjs +12 -0
  182. package/plugin-src/host/session-sync-coordinator.mjs +233 -0
  183. package/plugin-src/host/session-title-prefix.mjs +122 -0
  184. package/plugin-src/host/update-policy.mjs +31 -0
  185. package/plugin-src/host/update-rpc.mjs +16 -0
  186. package/plugin-src/host/update-runtime.mjs +339 -0
  187. package/plugin-src/host/update-service.mjs +392 -0
  188. package/plugin-src/management-rpc.mjs +87 -0
  189. package/src/channels/dingtalk/config-store.mjs +284 -0
  190. package/src/channels/dingtalk/connection-error.mjs +292 -0
  191. package/src/channels/dingtalk/device-auth.mjs +240 -0
  192. package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
  193. package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
  194. package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
  195. package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
  196. package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
  197. package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
  198. package/src/channels/dingtalk/harness-client.mjs +19 -0
  199. package/src/channels/dingtalk/state-store.mjs +325 -0
  200. package/src/channels/discord/config-store.mjs +25 -0
  201. package/src/channels/discord/discord-api.mjs +347 -0
  202. package/src/channels/discord/discord-bridge.mjs +16 -0
  203. package/src/channels/discord/discord-controller.mjs +16 -0
  204. package/src/channels/discord/discord-runtime.mjs +974 -0
  205. package/src/channels/discord/harness-client.mjs +11 -0
  206. package/src/channels/discord/state-store.mjs +3 -0
  207. package/src/channels/email/config-store.mjs +194 -0
  208. package/src/channels/email/email-api.mjs +20 -0
  209. package/src/channels/email/email-bridge.mjs +17 -0
  210. package/src/channels/email/email-controller.mjs +824 -0
  211. package/src/channels/email/email-runtime.mjs +699 -0
  212. package/src/channels/email/harness-client.mjs +7 -0
  213. package/src/channels/email/mail-format.mjs +91 -0
  214. package/src/channels/email/state-store.mjs +176 -0
  215. package/src/channels/email/transport.mjs +64 -0
  216. package/src/channels/email/transports/agent-mail.mjs +604 -0
  217. package/src/channels/email/transports/agently-cli.mjs +288 -0
  218. package/src/channels/email/transports/imap-smtp.mjs +165 -0
  219. package/src/channels/feishu/bridge.mjs +6286 -0
  220. package/src/channels/feishu/config.mjs +71 -0
  221. package/src/channels/feishu/external-consumer.mjs +77 -0
  222. package/src/channels/feishu/external-files.mjs +111 -0
  223. package/src/channels/feishu/feishu-app.mjs +54 -0
  224. package/src/channels/feishu/feishu-cards.mjs +1285 -0
  225. package/src/channels/feishu/feishu-channel.mjs +651 -0
  226. package/src/channels/feishu/feishu-runtime.mjs +950 -0
  227. package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
  228. package/src/channels/feishu/group-response-mode.mjs +15 -0
  229. package/src/channels/feishu/harness-client.mjs +19 -0
  230. package/src/channels/feishu/history-reader.mjs +77 -0
  231. package/src/channels/feishu/live-cot.mjs +260 -0
  232. package/src/channels/feishu/message-utils.mjs +613 -0
  233. package/src/channels/feishu/multi-bot-controller.mjs +1588 -0
  234. package/src/channels/feishu/nearby-history.mjs +72 -0
  235. package/src/channels/feishu/plugin-config-store.mjs +216 -0
  236. package/src/channels/feishu/plugin-controller.mjs +254 -0
  237. package/src/channels/feishu/registration-manager.mjs +349 -0
  238. package/src/channels/feishu/repair-manager.mjs +138 -0
  239. package/src/channels/feishu/reply-context.mjs +22 -0
  240. package/src/channels/feishu/slash-command-panel.mjs +155 -0
  241. package/src/channels/feishu/slash-command-registry.mjs +495 -0
  242. package/src/channels/feishu/state-store.mjs +214 -0
  243. package/src/channels/feishu/step-push-mode.mjs +25 -0
  244. package/src/channels/feishu/voice-config.mjs +34 -0
  245. package/src/channels/feishu/voice.mjs +134 -0
  246. package/src/channels/imessage/config-store.mjs +24 -0
  247. package/src/channels/imessage/controller.mjs +37 -0
  248. package/src/channels/imessage/harness-client.mjs +7 -0
  249. package/src/channels/imessage/imessage-api.mjs +194 -0
  250. package/src/channels/imessage/imessage-bridge.mjs +16 -0
  251. package/src/channels/imessage/runtime.mjs +102 -0
  252. package/src/channels/imessage/state-store.mjs +3 -0
  253. package/src/channels/matrix/matrix-api.mjs +696 -0
  254. package/src/channels/matrix/matrix-bridge.mjs +20 -0
  255. package/src/channels/matrix/matrix-config-store.mjs +368 -0
  256. package/src/channels/matrix/matrix-controller.mjs +404 -0
  257. package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
  258. package/src/channels/matrix/matrix-crypto.mjs +1014 -0
  259. package/src/channels/matrix/matrix-harness-client.mjs +11 -0
  260. package/src/channels/matrix/matrix-normalize.mjs +357 -0
  261. package/src/channels/matrix/matrix-rich-text.mjs +313 -0
  262. package/src/channels/matrix/matrix-room-history.mjs +316 -0
  263. package/src/channels/matrix/matrix-runtime.mjs +1014 -0
  264. package/src/channels/office/config-store.mjs +107 -0
  265. package/src/channels/office/office-controller.mjs +178 -0
  266. package/src/channels/office/office-job-executor.mjs +391 -0
  267. package/src/channels/office/office-runtime.mjs +175 -0
  268. package/src/channels/office/office-transport.mjs +171 -0
  269. package/src/channels/office/protocol.mjs +43 -0
  270. package/src/channels/qq/config-store.mjs +173 -0
  271. package/src/channels/qq/harness-client.mjs +11 -0
  272. package/src/channels/qq/markdown-reply.mjs +446 -0
  273. package/src/channels/qq/qq-bridge.mjs +1507 -0
  274. package/src/channels/qq/qq-controller.mjs +514 -0
  275. package/src/channels/qq/qq-menu.mjs +208 -0
  276. package/src/channels/qq/qq-runtime.mjs +303 -0
  277. package/src/channels/qq/qr-auth.mjs +24 -0
  278. package/src/channels/qq/state-error.mjs +17 -0
  279. package/src/channels/qq/state-store.mjs +143 -0
  280. package/src/channels/shared/access-policy.mjs +210 -0
  281. package/src/channels/shared/agent-preset.mjs +76 -0
  282. package/src/channels/shared/batch-input.mjs +229 -0
  283. package/src/channels/shared/bot-alias.mjs +29 -0
  284. package/src/channels/shared/bot-workspace-store.mjs +2383 -0
  285. package/src/channels/shared/command-catalog.mjs +107 -0
  286. package/src/channels/shared/command-permission.mjs +32 -0
  287. package/src/channels/shared/compact-command.mjs +109 -0
  288. package/src/channels/shared/config-read-error.mjs +24 -0
  289. package/src/channels/shared/connection-error.mjs +191 -0
  290. package/src/channels/shared/connection-test.mjs +58 -0
  291. package/src/channels/shared/context-enhancement.mjs +372 -0
  292. package/src/channels/shared/control-command.mjs +111 -0
  293. package/src/channels/shared/conversation-state-store.mjs +165 -0
  294. package/src/channels/shared/default-workspace.mjs +31 -0
  295. package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
  296. package/src/channels/shared/deferred-delivery.mjs +161 -0
  297. package/src/channels/shared/deferred-state.mjs +53 -0
  298. package/src/channels/shared/diagnostic-details.mjs +95 -0
  299. package/src/channels/shared/editable-message-stream.mjs +100 -0
  300. package/src/channels/shared/exclusive-inbound-consumers.mjs +71 -0
  301. package/src/channels/shared/file-download.mjs +64 -0
  302. package/src/channels/shared/harness-approval.mjs +508 -0
  303. package/src/channels/shared/harness-client.mjs +2143 -0
  304. package/src/channels/shared/harness-mux.mjs +123 -0
  305. package/src/channels/shared/harness-question.mjs +95 -0
  306. package/src/channels/shared/harness-session-binding.mjs +119 -0
  307. package/src/channels/shared/history-command.mjs +193 -0
  308. package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
  309. package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
  310. package/src/channels/shared/i18n-en/discord.mjs +10 -0
  311. package/src/channels/shared/i18n-en/email.mjs +25 -0
  312. package/src/channels/shared/i18n-en/feishu.mjs +404 -0
  313. package/src/channels/shared/i18n-en/image-input.mjs +18 -0
  314. package/src/channels/shared/i18n-en/matrix.mjs +85 -0
  315. package/src/channels/shared/i18n-en/office.mjs +23 -0
  316. package/src/channels/shared/i18n-en/qq.mjs +96 -0
  317. package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
  318. package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
  319. package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
  320. package/src/channels/shared/i18n-en/slack.mjs +27 -0
  321. package/src/channels/shared/i18n-en/telegram.mjs +27 -0
  322. package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
  323. package/src/channels/shared/i18n-en/wecom.mjs +62 -0
  324. package/src/channels/shared/i18n-en/weixin.mjs +88 -0
  325. package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
  326. package/src/channels/shared/i18n-en.mjs +45 -0
  327. package/src/channels/shared/i18n.mjs +78 -0
  328. package/src/channels/shared/im-source-guidance.mjs +65 -0
  329. package/src/channels/shared/image-input-policy.mjs +35 -0
  330. package/src/channels/shared/image-input-settings-store.mjs +60 -0
  331. package/src/channels/shared/image-input.mjs +124 -0
  332. package/src/channels/shared/image-prompt.mjs +360 -0
  333. package/src/channels/shared/inbound-access.mjs +43 -0
  334. package/src/channels/shared/inbound-file.mjs +323 -0
  335. package/src/channels/shared/inbound-ttl-store.mjs +110 -0
  336. package/src/channels/shared/inbound-ttl.mjs +22 -0
  337. package/src/channels/shared/injected-context.mjs +362 -0
  338. package/src/channels/shared/interface-language-store.mjs +127 -0
  339. package/src/channels/shared/interface-language.mjs +51 -0
  340. package/src/channels/shared/message-failure.mjs +257 -0
  341. package/src/channels/shared/model-command.mjs +741 -0
  342. package/src/channels/shared/model-setting.mjs +145 -0
  343. package/src/channels/shared/preset-command.mjs +308 -0
  344. package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
  345. package/src/channels/shared/semantic/artifact.mjs +750 -0
  346. package/src/channels/shared/semantic/delivery.mjs +193 -0
  347. package/src/channels/shared/semantic/reply-reference.mjs +148 -0
  348. package/src/channels/shared/session-binding-lock.mjs +40 -0
  349. package/src/channels/shared/session-channel-labels.mjs +28 -0
  350. package/src/channels/shared/session-reply-recovery.mjs +104 -0
  351. package/src/channels/shared/session-sync-registry.mjs +22 -0
  352. package/src/channels/shared/session-title.mjs +74 -0
  353. package/src/channels/shared/status-reaction.mjs +107 -0
  354. package/src/channels/shared/text-harness-bridge.mjs +1623 -0
  355. package/src/channels/shared/token-bot-controller.mjs +417 -0
  356. package/src/channels/shared/token-config-store.mjs +208 -0
  357. package/src/channels/shared/workspace-command.mjs +532 -0
  358. package/src/channels/shared/workspace-session.mjs +196 -0
  359. package/src/channels/slack/config-store.mjs +177 -0
  360. package/src/channels/slack/external-consumer.mjs +80 -0
  361. package/src/channels/slack/external-files.mjs +90 -0
  362. package/src/channels/slack/harness-client.mjs +11 -0
  363. package/src/channels/slack/history-reader.mjs +203 -0
  364. package/src/channels/slack/manifest.mjs +37 -0
  365. package/src/channels/slack/slack-api.mjs +636 -0
  366. package/src/channels/slack/slack-bridge.mjs +20 -0
  367. package/src/channels/slack/slack-controller.mjs +468 -0
  368. package/src/channels/slack/slack-runtime.mjs +879 -0
  369. package/src/channels/slack/state-store.mjs +3 -0
  370. package/src/channels/telegram/config-store.mjs +89 -0
  371. package/src/channels/telegram/harness-client.mjs +11 -0
  372. package/src/channels/telegram/state-store.mjs +3 -0
  373. package/src/channels/telegram/telegram-api.mjs +486 -0
  374. package/src/channels/telegram/telegram-bridge.mjs +81 -0
  375. package/src/channels/telegram/telegram-controller.mjs +52 -0
  376. package/src/channels/telegram/telegram-http.mjs +21 -0
  377. package/src/channels/telegram/telegram-rich-message.mjs +149 -0
  378. package/src/channels/telegram/telegram-runtime.mjs +1471 -0
  379. package/src/channels/wecom/config-store.mjs +172 -0
  380. package/src/channels/wecom/harness-client.mjs +11 -0
  381. package/src/channels/wecom/qr-auth.mjs +95 -0
  382. package/src/channels/wecom/send-error.mjs +31 -0
  383. package/src/channels/wecom/state-store.mjs +107 -0
  384. package/src/channels/wecom/wecom-bridge.mjs +1833 -0
  385. package/src/channels/wecom/wecom-cards.mjs +101 -0
  386. package/src/channels/wecom/wecom-controller.mjs +530 -0
  387. package/src/channels/wecom/wecom-runtime.mjs +269 -0
  388. package/src/channels/wecom-app/callback-server.mjs +471 -0
  389. package/src/channels/wecom-app/config-store.mjs +242 -0
  390. package/src/channels/wecom-app/harness-client.mjs +11 -0
  391. package/src/channels/wecom-app/state-store.mjs +107 -0
  392. package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
  393. package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
  394. package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
  395. package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
  396. package/src/channels/weixin/config-store.mjs +192 -0
  397. package/src/channels/weixin/connection-error.en.mjs +137 -0
  398. package/src/channels/weixin/connection-error.mjs +153 -0
  399. package/src/channels/weixin/diagnostic-details.mjs +1 -0
  400. package/src/channels/weixin/harness-client.mjs +19 -0
  401. package/src/channels/weixin/state-store.mjs +291 -0
  402. package/src/channels/weixin/weixin-api.mjs +949 -0
  403. package/src/channels/weixin/weixin-bridge.mjs +1537 -0
  404. package/src/channels/weixin/weixin-controller.mjs +669 -0
  405. package/src/channels/weixin/weixin-runtime.mjs +416 -0
  406. package/src/channels/whatsapp/config-store.mjs +210 -0
  407. package/src/channels/whatsapp/harness-client.mjs +11 -0
  408. package/src/channels/whatsapp/state-store.mjs +3 -0
  409. package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
  410. package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
  411. package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
  412. package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
@@ -0,0 +1,1889 @@
1
+ import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
2
+ import {
3
+ DINGTALK_DONE_REACTION_NAME,
4
+ DINGTALK_ERROR_REACTION_NAME,
5
+ DINGTALK_THINKING_REACTION_NAME,
6
+ normalizeDingtalkSessionWebhook,
7
+ splitDingtalkText,
8
+ } from './dingtalk-api.mjs';
9
+ import { createDingTalkCardStream } from './dingtalk-card-stream.mjs';
10
+ import { dingtalkMenuSnapshot, dingtalkMenuCommand, isDingtalkMenuCommand } from './dingtalk-menu.mjs';
11
+ import {
12
+ harnessAnswerForQuestion,
13
+ harnessQuestionText,
14
+ validHarnessQuestion,
15
+ } from '../shared/harness-question.mjs';
16
+ import { HarnessApprovalQueue } from '../shared/harness-approval.mjs';
17
+ import { runCompactCommand } from '../shared/compact-command.mjs';
18
+ import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
19
+ import {
20
+ isControlCommand,
21
+ runControlCommand,
22
+ } from '../shared/control-command.mjs';
23
+ import {
24
+ isModelCommand,
25
+ runModelCommand,
26
+ } from '../shared/model-command.mjs';
27
+ import {
28
+ isPresetCommand,
29
+ runPresetCommand,
30
+ } from '../shared/preset-command.mjs';
31
+ import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
32
+ import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
33
+ import {
34
+ captureContextEnhancement,
35
+ captureContextEnhancementSource,
36
+ enhanceContextContent,
37
+ } from '../shared/context-enhancement.mjs';
38
+ import {
39
+ BatchInputManager,
40
+ batchInputBusyMessage,
41
+ batchInputGroupUnsupportedMessage,
42
+ isBatchInputCommand,
43
+ } from '../shared/batch-input.mjs';
44
+ import {
45
+ hasInboundImages,
46
+ imagePromptDiagnostic,
47
+ imagePromptUserMessage,
48
+ } from '../shared/image-prompt.mjs';
49
+ import {
50
+ InboundFileError,
51
+ hasInboundFiles,
52
+ inboundFileUserMessage,
53
+ prefetchInboundFiles,
54
+ } from '../shared/inbound-file.mjs';
55
+ import { rememberConnectionTestTarget } from '../shared/connection-test.mjs';
56
+ import { deliverOutboundArtifacts } from '../shared/semantic/artifact-delivery.mjs';
57
+ import {
58
+ hasReplyReference,
59
+ promptContentForInboundMessage,
60
+ } from '../shared/semantic/reply-reference.mjs';
61
+ import {
62
+ createDeliveryReceipt,
63
+ providerMessageIdsFor,
64
+ } from '../shared/semantic/delivery.mjs';
65
+ import { recoverAssistantTextByTimestamp } from '../shared/session-reply-recovery.mjs';
66
+ import { DINGTALK_RECENT_OUTBOUND_MATCH_TOLERANCE_MS } from './state-store.mjs';
67
+ import {
68
+ messageFailureDiagnostic,
69
+ channelDeliveryFailure,
70
+ clearLastMessageFailure,
71
+ messageFailureText,
72
+ setLastMessageFailure,
73
+ } from '../shared/message-failure.mjs';
74
+ import {
75
+ COMMAND_PERMISSION_DENIED_MESSAGE,
76
+ evaluateInboundAccess,
77
+ } from '../shared/inbound-access.mjs';
78
+ import { t } from '../shared/i18n.mjs';
79
+
80
+ const CARD_INITIAL_TEXT = '已连接 DeepSeek Harness,正在思考…';
81
+ const INTERACTION_RESOLVED_TEXT = '这个问题已在其他客户端处理,无需再次回答。';
82
+
83
+ const HELP_TEXT_LINES = [
84
+ '钉钉机器人已连接 DeepSeek Harness。',
85
+ '',
86
+ '直接发送文字、图片或文件即可继续当前会话。',
87
+ '/m 或 /menu 打开下拉操作菜单',
88
+ '/new 开启一个全新会话',
89
+ '/compact 压缩当前会话的较早上下文',
90
+ '/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)',
91
+ '/workspace 工作区序号或绝对路径 切换工作区',
92
+ '/workspacelist 列出工作区绝对路径',
93
+ '/ws、/wsl、/workspaces 工作区命令别名',
94
+ '/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题',
95
+ '/sessionlist --limit N 仅列出当前工作区前 N 个会话',
96
+ '/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话',
97
+ '/models 按序号列出所有可用模型',
98
+ '/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级',
99
+ '/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级',
100
+ '/model [序号或完整模型ID] [推理等级ID] 查看或切换当前会话模型',
101
+ '示例:先发 /models,再发 /model 2 [推理等级ID]',
102
+ '/presetlist 或 /presets 按序号列出可用 Agent Preset',
103
+ '/preset [序号或完整ID] 查看或设置当前机器人 Agent Preset',
104
+ '纯数字 ID:/preset id:<ID>',
105
+ '/preset --default 跟随 Host 默认',
106
+ '/stop 停止当前任务',
107
+ '/steer 补充指令 纠偏当前任务',
108
+ '/batch 开始批量输入(仅私聊,最多 10 条文字)',
109
+ '/send 提交当前批次',
110
+ '/cancel 取消当前批次',
111
+ '/status 检查连接状态',
112
+ '/version 查看插件版本',
113
+ '/help 显示本帮助',
114
+ ];
115
+
116
+ function helpText() {
117
+ return HELP_TEXT_LINES.map((line) => t(line)).join('\n');
118
+ }
119
+
120
+ function nonEmptyString(value) {
121
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
122
+ }
123
+
124
+ function dingtalkFileProviderIds(result) {
125
+ const ids = providerMessageIdsFor(result);
126
+ const processQueryKey = nonEmptyString(result?.processQueryKey);
127
+ if (processQueryKey && !ids.includes(processQueryKey)) ids.push(processQueryKey);
128
+ return ids;
129
+ }
130
+
131
+ function safeErrorDiagnostic(error) {
132
+ const chain = [];
133
+ const seen = new Set();
134
+ let current = error;
135
+ while (current && typeof current === 'object' && chain.length < 3 && !seen.has(current)) {
136
+ seen.add(current);
137
+ const name = nonEmptyString(current.name)?.slice(0, 80);
138
+ const code = nonEmptyString(current.code)?.slice(0, 80);
139
+ const providerCode = nonEmptyString(current.providerCode)?.slice(0, 160);
140
+ const status = Number.isInteger(current.status) ? current.status : undefined;
141
+ chain.push({
142
+ ...(name ? { name } : {}),
143
+ ...(code ? { code } : {}),
144
+ ...(providerCode ? { providerCode } : {}),
145
+ ...(status ? { status } : {}),
146
+ });
147
+ current = current.cause;
148
+ }
149
+ return chain;
150
+ }
151
+
152
+ function dingtalkImageErrorUserMessage(error) {
153
+ let current = error;
154
+ const seen = new Set();
155
+ while (current && typeof current === 'object' && !seen.has(current)) {
156
+ seen.add(current);
157
+ if (current.code === 'image-download-address-failed') {
158
+ return t('钉钉未能换取图片下载地址,请重新发送;若持续失败,请检查机器人的“企业内机器人发送消息权限”。');
159
+ }
160
+ if (current.code === 'invalid-image-download') {
161
+ return t('钉钉没有返回图片下载地址,请重新发送。');
162
+ }
163
+ if (current.code === 'image-content-download-failed') {
164
+ return t('钉钉返回的图片临时地址无法读取,请重新发送。');
165
+ }
166
+ current = current.cause;
167
+ }
168
+ return imagePromptUserMessage(error);
169
+ }
170
+
171
+ function senderStaffId(message) {
172
+ return nonEmptyString(message?.senderStaffId) ?? nonEmptyString(message?.senderId);
173
+ }
174
+
175
+ function parsedMessageContent(message) {
176
+ if (message?.content && typeof message.content === 'object') return message.content;
177
+ if (typeof message?.content !== 'string') return null;
178
+ try {
179
+ const parsed = JSON.parse(message.content);
180
+ return parsed && typeof parsed === 'object' ? parsed : null;
181
+ } catch {
182
+ return null;
183
+ }
184
+ }
185
+
186
+ function richTextEntries(content) {
187
+ const entries = content?.richText ?? content?.rich_text;
188
+ return Array.isArray(entries) ? entries : [];
189
+ }
190
+
191
+ function richTextEntryText(entry) {
192
+ if (typeof entry?.text === 'string') return nonEmptyString(entry.text);
193
+ if (typeof entry?.text?.content === 'string') return nonEmptyString(entry.text.content);
194
+ if (String(entry?.type).toLowerCase() === 'text' && typeof entry?.content === 'string') {
195
+ return nonEmptyString(entry.content);
196
+ }
197
+ return null;
198
+ }
199
+
200
+ function downloadCodeFor(value) {
201
+ return nonEmptyString(value?.downloadCode) ?? nonEmptyString(value?.pictureDownloadCode);
202
+ }
203
+
204
+ function dingtalkImageEntries(msgtype, content) {
205
+ if (msgtype === 'picture') return [content];
206
+ if (msgtype !== 'richtext') return [];
207
+ return richTextEntries(content)
208
+ .filter((entry) => String(entry?.type ?? '').toLowerCase() === 'picture');
209
+ }
210
+
211
+ function dingtalkTimestampMs(value) {
212
+ const number = typeof value === 'string' && value.trim() ? Number(value) : value;
213
+ if (!Number.isFinite(number) || number < 0) return null;
214
+ return Math.trunc(number < 10_000_000_000 ? number * 1_000 : number);
215
+ }
216
+
217
+ function usefulReplyText(value) {
218
+ const text = nonEmptyString(value);
219
+ return text && !/^\[interactive card message\]$/iu.test(text) ? text : null;
220
+ }
221
+
222
+ function dingtalkReplyMessage(message) {
223
+ if (message?.text?.isReplyMsg !== true) return null;
224
+ const replied = message.text.repliedMsg;
225
+ if (!replied || typeof replied !== 'object') return null;
226
+ const msgtype = nonEmptyString(replied.msgType ?? replied.msgtype)?.toLowerCase() ?? '';
227
+ const repliedContent = parsedMessageContent({ content: replied.content }) ?? {};
228
+ // Quoted richText entries use msgType instead of the direct callback's type.
229
+ const content = msgtype === 'richtext' ? {
230
+ ...repliedContent,
231
+ richText: richTextEntries(repliedContent).map((entry) => ({
232
+ ...entry, type: entry?.type ?? entry?.msgType ?? entry?.msgtype,
233
+ })),
234
+ } : repliedContent;
235
+ return {
236
+ msgtype,
237
+ robotCode: message.robotCode,
238
+ text: {
239
+ content: nonEmptyString(repliedContent.text)
240
+ ?? (typeof replied.content === 'string' ? replied.content : ''),
241
+ },
242
+ content,
243
+ };
244
+ }
245
+
246
+ function dingtalkReplyReference(message, options) {
247
+ if (message?.text?.isReplyMsg !== true) return null;
248
+ const pseudoMessage = dingtalkReplyMessage(message);
249
+ if (!pseudoMessage) return { unavailableReason: 'not-delivered' };
250
+ const replied = message.text.repliedMsg;
251
+ const { msgtype, content: repliedContent } = pseudoMessage;
252
+ const normalized = dingtalkInboundMessage(pseudoMessage, options);
253
+ let attachments = [];
254
+ if (msgtype === 'picture') {
255
+ attachments = [{ kind: 'image' }];
256
+ } else if (msgtype === 'file') {
257
+ const name = nonEmptyString(repliedContent.fileName ?? repliedContent.file_name);
258
+ attachments = [{ kind: 'file', ...(name ? { name } : {}) }];
259
+ } else if (msgtype === 'richtext') {
260
+ attachments = dingtalkImageEntries(msgtype, repliedContent)
261
+ .map(() => ({ kind: 'image' }));
262
+ } else if (msgtype === 'voice' || msgtype === 'audio') {
263
+ attachments = [{ kind: 'audio' }];
264
+ } else if (msgtype === 'video') {
265
+ attachments = [{ kind: 'video' }];
266
+ }
267
+
268
+ const messageId = nonEmptyString(replied.msgId ?? replied.messageId);
269
+ const authorId = nonEmptyString(replied.senderId ?? replied.senderStaffId);
270
+ const authorName = nonEmptyString(replied.senderNick ?? replied.senderName);
271
+ const content = usefulReplyText(normalized.content)
272
+ ?? usefulReplyText(repliedContent.text)
273
+ ?? usefulReplyText(repliedContent.summary)
274
+ ?? usefulReplyText(repliedContent.title);
275
+ const processQueryKey = nonEmptyString(
276
+ message?.originalProcessQueryKey ?? repliedContent.processQueryKey,
277
+ );
278
+ const createdAt = dingtalkTimestampMs(replied.createdAt ?? replied.createTime);
279
+ const load = !content && attachments.length === 0
280
+ && typeof options?.loadReplyContent === 'function'
281
+ ? ({ signal } = {}) => options.loadReplyContent({
282
+ ...(messageId ? { messageId } : {}),
283
+ ...(processQueryKey ? { processQueryKey } : {}),
284
+ ...(createdAt === null ? {} : { createdAt }),
285
+ }, { signal })
286
+ : null;
287
+ const supported = [
288
+ 'text', 'picture', 'file', 'richtext', 'voice', 'audio', 'video',
289
+ 'interactivecard', 'chatrecord',
290
+ ]
291
+ .includes(msgtype);
292
+ return {
293
+ ...(messageId ? { messageId } : {}),
294
+ ...(authorId ? { authorId } : {}),
295
+ ...(authorName ? { authorName } : {}),
296
+ ...(content ? { content } : {}),
297
+ ...(attachments.length > 0 ? { attachments } : {}),
298
+ ...(load ? { load } : {}),
299
+ ...(!content && attachments.length === 0 && !load
300
+ ? { unavailableReason: supported ? 'not-delivered' : 'unsupported' }
301
+ : {}),
302
+ };
303
+ }
304
+
305
+ // Resolve only the immediate quote, after command/interaction routing has finished.
306
+ function prepareDingtalkReplyAttachments(message, promptMessage, options) {
307
+ const quoted = dingtalkReplyMessage(message);
308
+ if (!quoted) return promptMessage;
309
+ if (['audio', 'voice', 'video'].includes(quoted.msgtype)) quoted.msgtype = 'file';
310
+ const imageCodes = dingtalkImageEntries(quoted.msgtype, quoted.content).map(downloadCodeFor);
311
+ const fileCodes = quoted.msgtype === 'file' ? [downloadCodeFor(quoted.content)] : [];
312
+ if ([...imageCodes, ...fileCodes].some((code) => !code)) {
313
+ throw new InboundFileError(
314
+ 'dingtalk-quoted-attachment-unavailable',
315
+ 'DingTalk did not deliver a download reference for the quoted attachment.',
316
+ t('钉钉未提供引用附件的下载信息,无法读取原附件。请直接重新发送附件后再提问。'),
317
+ );
318
+ }
319
+ if (imageCodes.length === 0 && fileCodes.length === 0) return promptMessage;
320
+ const currentType = String(message?.msgtype ?? '').toLowerCase();
321
+ const currentContent = parsedMessageContent(message);
322
+ const seen = new Set([
323
+ ...dingtalkImageEntries(currentType, currentContent).map(downloadCodeFor),
324
+ ...(currentType === 'file' ? [downloadCodeFor(currentContent)] : []),
325
+ ].filter(Boolean));
326
+ const take = (code) => {
327
+ if (seen.has(code)) return false;
328
+ seen.add(code);
329
+ return true;
330
+ };
331
+ const normalized = dingtalkInboundMessage(quoted, options);
332
+ const images = normalized.images.filter((_, index) => take(imageCodes[index]));
333
+ const files = normalized.files.filter((_, index) => take(fileCodes[index]));
334
+ const prefetched = prefetchInboundFiles({ files }, { signal: options.signal });
335
+ return {
336
+ ...promptMessage,
337
+ images: [...promptMessage.images, ...images],
338
+ files: [...promptMessage.files, ...prefetched.files],
339
+ };
340
+ }
341
+
342
+ /** Normalize DingTalk picture and richText callbacks into lazy image references. */
343
+ export function dingtalkInboundMessage(message, {
344
+ api,
345
+ clientId,
346
+ clientSecret,
347
+ loadReplyContent,
348
+ } = {}) {
349
+ const msgtype = String(message?.msgtype ?? '').toLowerCase();
350
+ const content = parsedMessageContent(message);
351
+ const richEntries = msgtype === 'richtext' ? richTextEntries(content) : [];
352
+ const text = msgtype === 'text'
353
+ ? nonEmptyString(message?.text?.content) ?? ''
354
+ : richEntries.map(richTextEntryText).filter(Boolean).join('\n');
355
+ const imageCodes = dingtalkImageEntries(msgtype, content).map(downloadCodeFor).filter(Boolean);
356
+ const fileCode = msgtype === 'file' ? downloadCodeFor(content) : null;
357
+ const replyTo = dingtalkReplyReference(message, {
358
+ api,
359
+ clientId,
360
+ clientSecret,
361
+ loadReplyContent,
362
+ });
363
+ return {
364
+ content: text,
365
+ images: imageCodes.map((downloadCode, index) => ({
366
+ name: index === 0 ? 'image' : `image-${index + 1}`,
367
+ load: ({ signal, maxBytes }) => {
368
+ if (typeof api?.downloadImage !== 'function') {
369
+ throw new Error('DingTalk API does not support image downloads');
370
+ }
371
+ return api.downloadImage({
372
+ clientId,
373
+ clientSecret,
374
+ robotCode: message?.robotCode,
375
+ downloadCode,
376
+ signal,
377
+ maxBytes,
378
+ });
379
+ },
380
+ })),
381
+ files: fileCode ? [{
382
+ name: nonEmptyString(content?.fileName ?? content?.file_name) ?? 'file',
383
+ load: ({ signal } = {}) => {
384
+ if (typeof api?.downloadFile !== 'function') {
385
+ throw new Error('DingTalk API does not support file downloads');
386
+ }
387
+ return api.downloadFile({
388
+ clientId,
389
+ clientSecret,
390
+ robotCode: message?.robotCode,
391
+ downloadCode: fileCode,
392
+ signal,
393
+ });
394
+ },
395
+ }] : [],
396
+ ...(replyTo ? { replyTo } : {}),
397
+ };
398
+ }
399
+
400
+ function conversationKey(message, sender) {
401
+ if (String(message?.conversationType) === '2') {
402
+ const conversationId = nonEmptyString(message?.conversationId);
403
+ if (!conversationId) throw new Error('DingTalk group message has no conversation id');
404
+ return `group:${conversationId}`;
405
+ }
406
+ return `p2p:${sender}`;
407
+ }
408
+
409
+ function cardTarget(message, sender) {
410
+ if (String(message?.conversationType) === '2') {
411
+ return {
412
+ type: 'group',
413
+ openConversationId: nonEmptyString(message?.conversationId),
414
+ atUserIds: { [sender]: nonEmptyString(message?.senderNick) ?? sender },
415
+ };
416
+ }
417
+ return { type: 'user', userId: sender };
418
+ }
419
+
420
+ function fileTarget(message, sender, clientId) {
421
+ const robotCode = nonEmptyString(message?.robotCode) ?? clientId;
422
+ if (String(message?.conversationType) === '2') {
423
+ return {
424
+ type: 'group',
425
+ openConversationId: nonEmptyString(message?.conversationId),
426
+ robotCode,
427
+ };
428
+ }
429
+ return { type: 'user', userId: sender, robotCode };
430
+ }
431
+
432
+ function artifactFailureText(fileName, error) {
433
+ const name = String(fileName ?? t('结果文件')).replace(/[\r\n]+/g, ' ').trim() || t('结果文件');
434
+ switch (error?.code) {
435
+ case 'artifact-delivery-uncertain':
436
+ return t('结果文件「{name}」发送结果未能确认,请先检查聊天内是否已收到,不要立即重试。', { name });
437
+ case 'artifact-permission-required':
438
+ return t('结果文件「{name}」已生成,但钉钉应用或机器人缺少文件消息权限。请开通应用 qyapi_base 权限,并确认机器人具备文件消息发送能力。', { name });
439
+ case 'artifact-too-large':
440
+ return t('结果文件「{name}」超过当前钉钉机器人可发送的文件大小,未发送。', { name });
441
+ case 'artifact-rate-limited':
442
+ return t('结果文件「{name}」暂时被钉钉限流,未能发送,请稍后重试。', { name });
443
+ case 'artifact-provider-rejected':
444
+ return t('结果文件「{name}」已生成,但钉钉拒绝了该文件消息,请检查文件类型和机器人文件消息配置。', { name });
445
+ case 'artifact-invalid':
446
+ case 'artifact-changed':
447
+ case 'artifact-unavailable':
448
+ return t('结果文件「{name}」暂时无法读取或准备发送,请确认文件仍可访问后重试。', { name });
449
+ default:
450
+ return t('结果文件「{name}」已生成,但暂时未能通过钉钉发送,请稍后重试。', { name });
451
+ }
452
+ }
453
+
454
+ function progressText(update) {
455
+ if (update?.type === 'text' && nonEmptyString(update.text)) return update.text;
456
+ if (update?.type === 'tool') {
457
+ if (update.name === 'web_search') return t('_正在搜索网络并整理信息…_');
458
+ return t('_正在使用 {name}…_', { name: nonEmptyString(update.name) ?? t('工具') });
459
+ }
460
+ return t('_{text}_', { text: nonEmptyString(update?.text) ?? t('正在处理…') });
461
+ }
462
+
463
+ function canClaimInteractionReply(message, pending, sender) {
464
+ if (pending.needsPresentation || !pending.questions[pending.index]) return false;
465
+ if (pending.actor !== sender) return false;
466
+ if (String(message?.conversationType) === '2' && message?.isInAtList !== true) return false;
467
+ if (message?.msgtype !== 'text' || !nonEmptyString(message?.text?.content)) return false;
468
+ try {
469
+ normalizeDingtalkSessionWebhook(message.sessionWebhook);
470
+ return true;
471
+ } catch {
472
+ return false;
473
+ }
474
+ }
475
+
476
+ function ensureStats(status) {
477
+ status.stats ??= {};
478
+ for (const key of [
479
+ 'messagesReceived',
480
+ 'messagesReplied',
481
+ 'messagesRejected',
482
+ 'messagesIgnored',
483
+ 'reactionsAdded',
484
+ 'reactionsRemoved',
485
+ 'reactionErrors',
486
+ ]) {
487
+ status[key] ??= 0;
488
+ status.stats[key] = status[key];
489
+ }
490
+ status.pendingSenders ??= [];
491
+ }
492
+
493
+ function increment(status, key) {
494
+ status[key] = (status[key] ?? 0) + 1;
495
+ status.stats ??= {};
496
+ status.stats[key] = status[key];
497
+ }
498
+
499
+ export function createDingtalkBridgeStatus({ pendingSenders = [] } = {}) {
500
+ return {
501
+ messagesReceived: 0,
502
+ messagesReplied: 0,
503
+ messagesRejected: 0,
504
+ messagesIgnored: 0,
505
+ reactionsAdded: 0,
506
+ reactionsRemoved: 0,
507
+ reactionErrors: 0,
508
+ lastMessageAt: null,
509
+ lastReplyAt: null,
510
+ lastRejectedAt: null,
511
+ lastError: null,
512
+ lastMessageError: null,
513
+ pendingSenders: structuredClone(pendingSenders),
514
+ stats: {
515
+ messagesReceived: 0,
516
+ messagesReplied: 0,
517
+ messagesRejected: 0,
518
+ messagesIgnored: 0,
519
+ reactionsAdded: 0,
520
+ reactionsRemoved: 0,
521
+ reactionErrors: 0,
522
+ },
523
+ };
524
+ }
525
+
526
+ export class DingtalkHarnessBridge {
527
+ #api;
528
+ #clientId;
529
+ #clientSecret;
530
+ #harness;
531
+ #state;
532
+ #deferred;
533
+ #contextEnhancement;
534
+ #accessPolicy;
535
+ #status;
536
+ #logger;
537
+ #replyTimeoutMs;
538
+ #reactionTimeoutMs;
539
+ #maxMessageChars;
540
+ #signal;
541
+ #queues = new Map();
542
+ #pendingInteractions = new Map();
543
+ #interactionKeys = new Map();
544
+ #interactionTasks = new Set();
545
+ #commandTasks = new Set();
546
+ #menus = new Map();
547
+ // Keep the accepted configuration through the existing queue/reply lifecycle.
548
+ #acceptedMessageIds = new Map();
549
+ #approvals;
550
+ #batchInputs = new BatchInputManager();
551
+
552
+ constructor({
553
+ api,
554
+ clientId,
555
+ clientSecret,
556
+ harness,
557
+ state,
558
+ contextEnhancement,
559
+ accessPolicy,
560
+ status = createDingtalkBridgeStatus(),
561
+ logger = console,
562
+ replyTimeoutMs = 600_000,
563
+ reactionTimeoutMs = 5_000,
564
+ maxMessageChars = 4_000,
565
+ signal,
566
+ }) {
567
+ if (!api || typeof api.sendText !== 'function') throw new TypeError('DingTalk API is required');
568
+ if (!nonEmptyString(clientId) || !nonEmptyString(clientSecret)) {
569
+ throw new TypeError('DingTalk app credentials are required');
570
+ }
571
+ if (!harness || !state) throw new TypeError('Harness client and state store are required');
572
+ this.#api = api;
573
+ this.#clientId = clientId.trim();
574
+ this.#clientSecret = clientSecret.trim();
575
+ this.#harness = harness;
576
+ this.#state = state;
577
+ this.#contextEnhancement = contextEnhancement;
578
+ this.#accessPolicy = accessPolicy;
579
+ this.#status = status;
580
+ this.#logger = logger;
581
+ this.#approvals = new HarnessApprovalQueue({ label: 'DingTalk', logger });
582
+ this.#replyTimeoutMs = replyTimeoutMs;
583
+ this.#reactionTimeoutMs = Number.isFinite(reactionTimeoutMs) && reactionTimeoutMs > 0
584
+ ? Math.floor(reactionTimeoutMs)
585
+ : 5_000;
586
+ this.#maxMessageChars = maxMessageChars;
587
+ this.#signal = signal;
588
+ this.#deferred = createDeferredDeliveryCoordinator({ harness, state, signal, logger,
589
+ deliver: (entry, outcome) => this.#deliverDeferredOutcome(entry, outcome),
590
+ });
591
+ ensureStats(this.#status);
592
+ this.#refreshPendingSenders();
593
+ }
594
+
595
+ get status() {
596
+ this.#refreshPendingSenders();
597
+ return structuredClone(this.#status);
598
+ }
599
+
600
+ accept(message, { contextSnapshot } = {}) {
601
+ if (this.#signal?.aborted) return Promise.resolve();
602
+ const messageId = nonEmptyString(message?.msgId);
603
+ const sender = senderStaffId(message);
604
+ if (!messageId || !sender || this.#state.hasSeen(messageId)
605
+ || this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
606
+ const conversationType = String(message.conversationType) === '2' ? 'group'
607
+ : String(message.conversationType) === '1' ? 'direct' : null;
608
+
609
+ let key;
610
+ try {
611
+ key = conversationKey(message, sender);
612
+ } catch {
613
+ increment(this.#status, 'messagesRejected');
614
+ this.#status.lastRejectedAt = new Date().toISOString();
615
+ return Promise.resolve();
616
+ }
617
+
618
+ let sessionWebhook = null;
619
+ try {
620
+ sessionWebhook = normalizeDingtalkSessionWebhook(message.sessionWebhook);
621
+ } catch {
622
+ // An unsafe reply route must never be able to submit an approval.
623
+ }
624
+ const pending = this.#pendingInteractions.get(key);
625
+ const promptMessage = this.#inboundMessage(message, key);
626
+ const commandText = nonEmptyString(promptMessage.content) ?? '';
627
+ const addressed = String(message.conversationType) !== '2' || message?.isInAtList === true;
628
+ const direct = String(message.conversationType) !== '2';
629
+ if (addressed) {
630
+ const access = evaluateInboundAccess(this.#accessPolicy, {
631
+ conversationType,
632
+ senderIds: sender,
633
+ text: commandText,
634
+ hasImages: hasInboundImages(promptMessage),
635
+ hasFiles: hasInboundFiles(promptMessage),
636
+ ...(isDingtalkMenuCommand(commandText) ? { isCommand: true } : {}),
637
+ });
638
+ if (!access.allowed) {
639
+ this.#acceptedMessageIds.set(messageId, null);
640
+ return this.#finishAccessDecision(message, messageId, sessionWebhook, access);
641
+ }
642
+ }
643
+ this.#acceptedMessageIds.set(messageId, contextSnapshot === undefined ? captureContextEnhancement(
644
+ this.#contextEnhancement,
645
+ conversationType,
646
+ ) : contextSnapshot);
647
+ if (sessionWebhook && direct) {
648
+ rememberConnectionTestTarget(this.#state, { sessionWebhook });
649
+ }
650
+ const statusReaction = sessionWebhook && addressed ? this.#startStatusReaction(message) : null;
651
+ const finish = (task) => Promise.resolve(task).then(
652
+ (value) => {
653
+ this.#finishStatusReaction(
654
+ statusReaction,
655
+ this.#signal?.aborted ? 'clear' : 'success',
656
+ );
657
+ return value;
658
+ },
659
+ (error) => {
660
+ this.#finishStatusReaction(
661
+ statusReaction,
662
+ this.#signal?.aborted || error?.name === 'AbortError' || error?.code === 'turn-stopped'
663
+ ? 'clear'
664
+ : 'error',
665
+ );
666
+ throw error;
667
+ },
668
+ );
669
+ const batchCommand = String(message?.msgtype).toLowerCase() === 'text'
670
+ && isBatchInputCommand(commandText);
671
+ const batchStatus = this.#batchInputs.status(key);
672
+ if (batchCommand && !direct && sessionWebhook && addressed) {
673
+ return finish(this.#finishBatchResult(
674
+ messageId,
675
+ sessionWebhook,
676
+ { message: batchInputGroupUnsupportedMessage() },
677
+ statusReaction,
678
+ ));
679
+ }
680
+ if (direct && sessionWebhook && !isDingtalkMenuCommand(commandText)
681
+ && (batchCommand || batchStatus.phase === 'collecting')) {
682
+ const exactBatchStart = /^\/batch$/iu.test(commandText);
683
+ const result = exactBatchStart
684
+ && batchStatus.phase === 'idle'
685
+ && (this.#queues.has(key) || pending || this.#approvals.hasPending(key))
686
+ ? { handled: true, kind: 'busy', message: batchInputBusyMessage() }
687
+ : this.#batchInputs.handle(key, commandText, {
688
+ plainText: Boolean(commandText)
689
+ && String(message?.msgtype).toLowerCase() === 'text'
690
+ && !hasInboundFiles(promptMessage)
691
+ && !hasInboundImages(promptMessage)
692
+ && !hasReplyReference(promptMessage),
693
+ });
694
+ if (result.handled) {
695
+ if (result.kind === 'submit') {
696
+ return finish(this.#enqueueMessage(
697
+ {
698
+ ...message,
699
+ msgtype: 'text',
700
+ text: { content: result.prompt },
701
+ },
702
+ messageId,
703
+ sender,
704
+ key,
705
+ { batchSubmission: result, statusReaction },
706
+ ));
707
+ }
708
+ return finish(this.#finishBatchResult(
709
+ messageId,
710
+ sessionWebhook,
711
+ result,
712
+ statusReaction,
713
+ ));
714
+ }
715
+ }
716
+ const commandRunner = isDingtalkMenuCommand(commandText)
717
+ && !hasInboundFiles(promptMessage) && !hasInboundImages(promptMessage)
718
+ ? async () => { await this.#showMenu(message, key); }
719
+ : isHistoryCommand(commandText) ? runHistoryCommand
720
+ : hasInboundFiles(promptMessage) ? null : isControlCommand(commandText)
721
+ ? runControlCommand
722
+ : (isModelCommand(commandText)
723
+ ? runModelCommand
724
+ : (isPresetCommand(commandText) ? runPresetCommand : null));
725
+ if (commandRunner && sessionWebhook && addressed) {
726
+ let task;
727
+ task = this.#processFastCommand(
728
+ message,
729
+ messageId,
730
+ key,
731
+ sessionWebhook,
732
+ promptMessage,
733
+ commandRunner,
734
+ ).catch((error) => {
735
+ if (error?.code === 'turn-stopped' || this.#signal?.aborted) {
736
+ this.#finishStatusReaction(statusReaction, 'clear');
737
+ return;
738
+ }
739
+ this.#finishStatusReaction(statusReaction, 'error');
740
+ this.#status.lastError = error?.message ?? String(error);
741
+ const failure = setLastMessageFailure(this.#status, error);
742
+ this.#logger.error?.(
743
+ `[dsh-dingtalk] failed to process a command [${failure.referenceId}]`,
744
+ messageFailureDiagnostic(error, failure),
745
+ );
746
+ return this.#send(sessionWebhook, messageFailureText(failure), this.#atUsersFor(message)).catch(() => undefined);
747
+ }).finally(() => {
748
+ this.#acceptedMessageIds.delete(messageId);
749
+ this.#commandTasks.delete(task);
750
+ });
751
+ this.#commandTasks.add(task);
752
+ return finish(task);
753
+ }
754
+ const approvalReply = this.#approvals.claimReply({
755
+ key,
756
+ actor: sender,
757
+ messageId,
758
+ text: sessionWebhook && message?.msgtype === 'text'
759
+ ? nonEmptyString(message?.text?.content) ?? ''
760
+ : '',
761
+ addressed: String(message?.conversationType) !== '2' || message?.isInAtList === true,
762
+ hasPendingQuestion: Boolean(pending),
763
+ questionCompletion: pending?.submitting || pending?.claimedReplyMessageId
764
+ ? pending.queue
765
+ : null,
766
+ isQuestionPending: () => this.#pendingInteractions.has(key),
767
+ send: sessionWebhook
768
+ ? (reply) => this.#send(sessionWebhook, reply, this.#atUsersFor(message))
769
+ : async () => undefined,
770
+ });
771
+ if (approvalReply) {
772
+ let current;
773
+ current = approvalReply.process(async () => {
774
+ if (this.#state.hasSeen(messageId)) return false;
775
+ await this.#state.markSeen(messageId);
776
+ increment(this.#status, 'messagesReceived');
777
+ this.#status.lastMessageAt = new Date().toISOString();
778
+ if (!sessionWebhook) {
779
+ increment(this.#status, 'messagesRejected');
780
+ this.#status.lastRejectedAt = new Date().toISOString();
781
+ this.#status.lastError = t('钉钉消息没有安全的回复地址。');
782
+ }
783
+ return true;
784
+ })
785
+ .catch((error) => {
786
+ if (this.#signal?.aborted) {
787
+ this.#finishStatusReaction(statusReaction, 'clear');
788
+ return;
789
+ }
790
+ this.#finishStatusReaction(statusReaction, 'error');
791
+ this.#status.lastError = t('钉钉审批处理失败。');
792
+ this.#logger.error?.('[dsh-dingtalk] failed to process an approval reply', error);
793
+ })
794
+ .finally(() => {
795
+ this.#acceptedMessageIds.delete(messageId);
796
+ this.#interactionTasks.delete(current);
797
+ });
798
+ this.#interactionTasks.add(current);
799
+ return finish(current);
800
+ }
801
+
802
+ if (pending && pending.actor !== sender) {
803
+ return finish(this.#enqueueMessage(message, messageId, sender, key, { statusReaction }));
804
+ }
805
+ // Once one valid answer has been claimed, later messages are subsequent
806
+ // prompts even if the network submission eventually needs a retry. Invalid
807
+ // replies do not claim the question, so the next valid answer can still
808
+ // pass through this interaction queue.
809
+ if (pending?.submitting || pending?.claimedReplyMessageId) {
810
+ return finish(this.#enqueueMessage(message, messageId, sender, key, { statusReaction }));
811
+ }
812
+ if (pending) {
813
+ if (canClaimInteractionReply(message, pending, sender)) {
814
+ pending.claimedReplyMessageId = messageId;
815
+ }
816
+ const previous = pending.queue ?? Promise.resolve();
817
+ const current = previous
818
+ .catch(() => undefined)
819
+ .then(() => this.#processInteractionReply(
820
+ message,
821
+ messageId,
822
+ sender,
823
+ key,
824
+ pending,
825
+ statusReaction,
826
+ ))
827
+ .finally(() => {
828
+ this.#acceptedMessageIds.delete(messageId);
829
+ if (pending.claimedReplyMessageId === messageId) {
830
+ pending.claimedReplyMessageId = null;
831
+ }
832
+ if (pending.queue === current) pending.queue = null;
833
+ });
834
+ pending.queue = current;
835
+ return finish(current);
836
+ }
837
+ return finish(this.#enqueueMessage(message, messageId, sender, key, { statusReaction }));
838
+ }
839
+
840
+ async #showMenu(message, key) {
841
+ if (typeof this.#api.createMenuCard !== 'function') {
842
+ await this.#send(message.sessionWebhook, helpText(), this.#atUsersFor(message));
843
+ return;
844
+ }
845
+ const snapshot = await dingtalkMenuSnapshot(this.#harness, this.#state, key, this.#signal);
846
+ const now = Date.now();
847
+ for (const [id, entry] of this.#menus) {
848
+ if (entry.expiresAt <= now || entry.key === key) this.#menus.delete(id);
849
+ }
850
+ while (this.#menus.size >= 256) this.#menus.delete(this.#menus.keys().next().value);
851
+ const { cardInstanceId } = await this.#api.createMenuCard({
852
+ clientId: this.#clientId, clientSecret: this.#clientSecret,
853
+ target: cardTarget(message, senderStaffId(message)), data: snapshot.data, signal: this.#signal,
854
+ });
855
+ this.#menus.set(cardInstanceId, {
856
+ ...snapshot, key, message, cardInstanceId, expiresAt: now + 30 * 60_000, busy: false,
857
+ });
858
+ }
859
+
860
+ acceptCard(callback, messageId) {
861
+ if (this.#signal?.aborted || !nonEmptyString(messageId) || this.#state.hasSeen(messageId)) {
862
+ return Promise.resolve();
863
+ }
864
+ const entry = this.#menus.get(callback?.outTrackId);
865
+ if (!entry || entry.busy || entry.expiresAt <= Date.now()
866
+ || callback?.userId !== senderStaffId(entry.message)) return Promise.resolve();
867
+ const command = dingtalkMenuCommand(entry, callback);
868
+ if (!command) return Promise.resolve();
869
+ entry.busy = true;
870
+ let task;
871
+ task = this.#processMenuAction(entry, command, messageId).catch(async (error) => {
872
+ if (this.#signal?.aborted) return;
873
+ this.#status.lastError = error?.message ?? String(error);
874
+ this.#logger.warn?.('[dsh-dingtalk] menu action failed', safeErrorDiagnostic(error));
875
+ await this.#api.updateMenuCard({
876
+ clientId: this.#clientId, clientSecret: this.#clientSecret,
877
+ cardInstanceId: entry.cardInstanceId,
878
+ data: { notice: t('操作未完成,请重新发送 /m 后重试。') }, signal: this.#signal,
879
+ }).catch(() => undefined);
880
+ }).finally(() => { entry.busy = false; this.#commandTasks.delete(task); });
881
+ this.#commandTasks.add(task);
882
+ return task;
883
+ }
884
+
885
+ async #processMenuAction(entry, command, messageId) {
886
+ await this.#state.markSeen(messageId);
887
+ const { key, message } = entry;
888
+ const options = {
889
+ signal: this.#signal, isDirect: String(message.conversationType) === '1',
890
+ pendingInteraction: this.#pendingInteractions.has(key) || this.#approvals.hasPending(key),
891
+ control: { owner: this, key }, deferredDelivery: this.#deferred,
892
+ enhancement: captureContextEnhancementSource(
893
+ this.#contextEnhancement,
894
+ String(message.conversationType) === '1' ? 'direct' : 'group',
895
+ () => ({
896
+ channel: 'dingtalk',
897
+ senderId: senderStaffId(message),
898
+ senderName: message.senderNick,
899
+ conversationTitle: message.conversationTitle,
900
+ chatId: message.conversationId,
901
+ }),
902
+ ),
903
+ };
904
+ const access = evaluateInboundAccess(this.#accessPolicy, {
905
+ conversationType: options.isDirect ? 'direct' : 'group',
906
+ senderIds: senderStaffId(message), text: command, isCommand: true,
907
+ });
908
+ let result;
909
+ if (!access.allowed) {
910
+ await this.#api.updateMenuCard({
911
+ clientId: this.#clientId, clientSecret: this.#clientSecret,
912
+ cardInstanceId: entry.cardInstanceId,
913
+ data: { notice: t(COMMAND_PERMISSION_DENIED_MESSAGE) }, signal: this.#signal,
914
+ });
915
+ return;
916
+ }
917
+ const sessionWorkspace = typeof this.#harness.currentConversationWorkspace === 'function'
918
+ ? this.#harness.currentConversationWorkspace(key) : this.#harness.currentWorkspace?.();
919
+ if (entry.workspace !== this.#harness.currentWorkspace?.()
920
+ || entry.sessionWorkspace !== sessionWorkspace
921
+ || entry.sessionId !== this.#state.sessionFor(key)) {
922
+ result = { message: t('会话或工作区已变化,菜单已刷新,请重新选择。') };
923
+ } else if ((this.#queues.has(key) || options.pendingInteraction || this.#batchInputs.status(key).phase !== 'idle')
924
+ && !['/stop', '/help', '/status', '/history'].includes(command)) {
925
+ result = { message: t('当前任务尚未结束,请先停止任务或等待完成后再操作。') };
926
+ } else if (command === '/new') {
927
+ await this.#state.clearSession(key);
928
+ result = { message: t('已开启新会话。请发送你的问题。') };
929
+ } else if (command === '/status') {
930
+ await this.#harness.ensureRunning({ signal: this.#signal });
931
+ result = { message: t('钉钉机器人与 DeepSeek Harness 连接正常。') };
932
+ } else if (command === '/help') {
933
+ result = { message: helpText() };
934
+ } else {
935
+ result = await runWorkspaceCommand(command, this.#harness, key)
936
+ ?? await runCompactCommand(command, this.#harness, this.#state, key, options)
937
+ ?? await runControlCommand(command, this.#harness, this.#state, key, options)
938
+ ?? await runHistoryCommand(command, this.#harness, this.#state, key, options)
939
+ ?? await runModelCommand(command, this.#harness, this.#state, key, options)
940
+ ?? await runPresetCommand(command, this.#harness, this.#state, key, options);
941
+ }
942
+ if (result?.stopped) await Promise.allSettled([
943
+ this.#cancelPendingInteraction(key), this.#approvals.closeRoute(key),
944
+ ]);
945
+ const snapshot = await dingtalkMenuSnapshot(this.#harness, this.#state, key, this.#signal);
946
+ if (command === '/help' || command === '/history') {
947
+ for (const reply of result?.messages ?? [result?.message]) {
948
+ if (reply) await this.#send(message.sessionWebhook, reply, this.#atUsersFor(message));
949
+ }
950
+ } else snapshot.data.notice = (result?.message ?? '').slice(0, 300);
951
+ await this.#api.updateMenuCard({
952
+ clientId: this.#clientId, clientSecret: this.#clientSecret,
953
+ cardInstanceId: entry.cardInstanceId, data: snapshot.data, signal: this.#signal,
954
+ });
955
+ Object.assign(entry, snapshot);
956
+ this.#status.lastError = null;
957
+ }
958
+
959
+ #runReactionCall(method, target, reactionName, kind) {
960
+ const controller = new AbortController();
961
+ const operation = Promise.resolve().then(() => this.#api[method]({
962
+ clientId: this.#clientId,
963
+ clientSecret: this.#clientSecret,
964
+ ...target,
965
+ reactionName,
966
+ signal: controller.signal,
967
+ }));
968
+ let timer;
969
+ const timeout = new Promise((_, reject) => {
970
+ timer = setTimeout(() => {
971
+ const error = new DOMException('DingTalk reaction timed out', 'TimeoutError');
972
+ controller.abort(error);
973
+ reject(error);
974
+ }, this.#reactionTimeoutMs);
975
+ timer.unref?.();
976
+ });
977
+ return Promise.race([operation, timeout])
978
+ .then(() => {
979
+ increment(this.#status, kind === 'add' ? 'reactionsAdded' : 'reactionsRemoved');
980
+ return true;
981
+ })
982
+ .catch((error) => {
983
+ increment(this.#status, 'reactionErrors');
984
+ this.#logger.debug?.(`[dsh-dingtalk] ${method} failed`, safeErrorDiagnostic(error));
985
+ return false;
986
+ })
987
+ .finally(() => clearTimeout(timer));
988
+ }
989
+
990
+ #startStatusReaction(message) {
991
+ if (typeof this.#api.addReaction !== 'function'
992
+ || typeof this.#api.recallReaction !== 'function') return null;
993
+ const messageId = nonEmptyString(message?.msgId);
994
+ const conversationId = nonEmptyString(message?.conversationId);
995
+ if (!messageId || !conversationId) return null;
996
+ const target = {
997
+ messageId,
998
+ conversationId,
999
+ robotCode: nonEmptyString(message?.robotCode) ?? this.#clientId,
1000
+ };
1001
+ return {
1002
+ target,
1003
+ attached: this.#runReactionCall(
1004
+ 'addReaction',
1005
+ target,
1006
+ DINGTALK_THINKING_REACTION_NAME,
1007
+ 'add',
1008
+ ),
1009
+ terminal: false,
1010
+ };
1011
+ }
1012
+
1013
+ #finishStatusReaction(reaction, outcome) {
1014
+ if (!reaction || reaction.terminal) return;
1015
+ reaction.terminal = true;
1016
+ const terminalName = outcome === 'success'
1017
+ ? DINGTALK_DONE_REACTION_NAME
1018
+ : outcome === 'error' ? DINGTALK_ERROR_REACTION_NAME : null;
1019
+ // Preserve attach -> recall -> terminal ordering without extending the message task.
1020
+ void reaction.attached.then(async (attached) => {
1021
+ let cleaned = await this.#runReactionCall(
1022
+ 'recallReaction',
1023
+ reaction.target,
1024
+ DINGTALK_THINKING_REACTION_NAME,
1025
+ 'remove',
1026
+ );
1027
+ if (!attached || !cleaned) {
1028
+ await new Promise((resolve) => {
1029
+ const retry = setTimeout(resolve, Math.min(1_000, this.#reactionTimeoutMs));
1030
+ retry.unref?.();
1031
+ });
1032
+ cleaned = await this.#runReactionCall(
1033
+ 'recallReaction',
1034
+ reaction.target,
1035
+ DINGTALK_THINKING_REACTION_NAME,
1036
+ 'remove',
1037
+ ) || cleaned;
1038
+ }
1039
+ if (!cleaned || !terminalName || this.#signal?.aborted) return;
1040
+ await this.#runReactionCall('addReaction', reaction.target, terminalName, 'add');
1041
+ }).catch(() => undefined);
1042
+ }
1043
+
1044
+ #enqueueMessage(message, messageId, sender, key, {
1045
+ releaseMessageId = true,
1046
+ alreadyRecorded = false,
1047
+ batchSubmission = null,
1048
+ statusReaction = null,
1049
+ } = {}) {
1050
+ let hasSafeReplyRoute = false;
1051
+ try {
1052
+ normalizeDingtalkSessionWebhook(message.sessionWebhook);
1053
+ hasSafeReplyRoute = true;
1054
+ } catch {
1055
+ // Keep the existing rejection path without downloading an unusable file.
1056
+ }
1057
+ const addressed = String(message.conversationType) !== '2' || message.isInAtList === true;
1058
+ const preparedMessage = hasSafeReplyRoute && addressed
1059
+ ? prefetchInboundFiles(this.#inboundMessage(message, key), { signal: this.#signal })
1060
+ : undefined;
1061
+ const previous = this.#queues.get(key) ?? Promise.resolve();
1062
+ const current = previous
1063
+ .catch(() => undefined)
1064
+ .then(() => this.#process(message, messageId, sender, key, {
1065
+ alreadyRecorded,
1066
+ preparedMessage,
1067
+ batchSubmission,
1068
+ statusReaction,
1069
+ }))
1070
+ .finally(() => {
1071
+ if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
1072
+ if (this.#queues.get(key) === current) this.#queues.delete(key);
1073
+ });
1074
+ this.#queues.set(key, current);
1075
+ return current;
1076
+ }
1077
+
1078
+ #inboundMessage(message, key) {
1079
+ return dingtalkInboundMessage(message, {
1080
+ api: this.#api,
1081
+ clientId: this.#clientId,
1082
+ clientSecret: this.#clientSecret,
1083
+ loadReplyContent: (reference, options) => this.#loadReplyContent(key, reference, options),
1084
+ });
1085
+ }
1086
+
1087
+ async #loadReplyContent(key, reference, { signal } = {}) {
1088
+ const indexed = this.#state.recentOutboundTextFor?.({
1089
+ conversationKey: key,
1090
+ ...reference,
1091
+ });
1092
+ if (indexed) return { content: indexed };
1093
+ const quotedAt = dingtalkTimestampMs(reference?.createdAt);
1094
+ if (quotedAt === null) return { unavailableReason: 'not-delivered' };
1095
+ const sessionId = this.#state.sessionFor(key);
1096
+ const session = typeof sessionId === 'string' && sessionId
1097
+ ? this.#harness.workspaceSession?.(sessionId, key)
1098
+ : null;
1099
+ const text = await recoverAssistantTextByTimestamp({
1100
+ session,
1101
+ quotedAt,
1102
+ signal,
1103
+ toleranceMs: DINGTALK_RECENT_OUTBOUND_MATCH_TOLERANCE_MS,
1104
+ });
1105
+ if (!text) return { unavailableReason: 'not-delivered' };
1106
+ try {
1107
+ await this.#state.rememberOutboundMessage?.({
1108
+ conversationKey: key,
1109
+ text,
1110
+ sentAt: quotedAt,
1111
+ completedAt: quotedAt,
1112
+ providerMessageIds: [reference?.processQueryKey, reference?.messageId]
1113
+ .map(nonEmptyString)
1114
+ .filter(Boolean),
1115
+ });
1116
+ } catch (error) {
1117
+ this.#logger.warn?.('[dsh-dingtalk] failed to remember a recovered quote:', error);
1118
+ }
1119
+ return { content: text };
1120
+ }
1121
+
1122
+ async #deliverDeferredOutcome(entry, outcome) {
1123
+ const text = deferredOutcomeText(outcome);
1124
+ if (outcome.found && ['createAiCard', 'updateAiCard', 'finishAiCard'].every((name) => typeof this.#api[name] === 'function')) {
1125
+ const card = createDingTalkCardStream({ api: this.#api, clientId: this.#clientId,
1126
+ clientSecret: this.#clientSecret, target: entry.target, signal: this.#signal, logger: this.#logger });
1127
+ if (await card.start(t(CARD_INITIAL_TEXT)) && await card.finish(text)) return true;
1128
+ this.#logger.warn?.('[dsh-dingtalk] deferred card unavailable; sending robot text');
1129
+ }
1130
+ await this.#api.sendRobotText({ clientId: this.#clientId, clientSecret: this.#clientSecret,
1131
+ target: entry.target, text, signal: this.#signal });
1132
+ return true;
1133
+ }
1134
+
1135
+ async waitForIdle() {
1136
+ await Promise.allSettled([
1137
+ ...this.#queues.values(),
1138
+ ...[...this.#pendingInteractions.values()].flatMap((pending) => (
1139
+ pending.queue ? [pending.queue] : []
1140
+ )),
1141
+ ...this.#interactionTasks,
1142
+ ...this.#commandTasks,
1143
+ ]);
1144
+ await this.#deferred.whenIdle();
1145
+ }
1146
+
1147
+ async #processFastCommand(message, messageId, key, sessionWebhook, prompt, runner) {
1148
+ this.#signal?.throwIfAborted();
1149
+ if (this.#state.hasSeen(messageId)) return;
1150
+ await this.#state.markSeen(messageId);
1151
+ increment(this.#status, 'messagesReceived');
1152
+ this.#status.lastMessageAt = new Date().toISOString();
1153
+ const result = await runner(
1154
+ nonEmptyString(prompt.content) ?? '',
1155
+ this.#harness,
1156
+ this.#state,
1157
+ key,
1158
+ {
1159
+ signal: this.#signal,
1160
+ isDirect: String(message.conversationType) === '1',
1161
+ hasImages: hasInboundImages(prompt),
1162
+ hasFiles: hasInboundFiles(prompt),
1163
+ pendingInteraction: this.#pendingInteractions.has(key)
1164
+ || this.#approvals.hasPending(key),
1165
+ control: { owner: this, key },
1166
+ deferredDelivery: this.#deferred,
1167
+ enhancement: captureContextEnhancementSource(
1168
+ this.#contextEnhancement,
1169
+ String(message.conversationType) === '1' ? 'direct' : 'group',
1170
+ () => ({
1171
+ channel: 'dingtalk',
1172
+ senderId: senderStaffId(message),
1173
+ senderName: message.senderNick,
1174
+ conversationTitle: message.conversationTitle,
1175
+ chatId: message.conversationId,
1176
+ }),
1177
+ ),
1178
+ },
1179
+ );
1180
+ if (result?.stopped) {
1181
+ await Promise.allSettled([
1182
+ this.#cancelPendingInteraction(key),
1183
+ this.#approvals.closeRoute(key),
1184
+ ]);
1185
+ }
1186
+ for (const reply of result?.messages ?? [result?.message]) {
1187
+ if (reply) await this.#send(sessionWebhook, reply, this.#atUsersFor(message));
1188
+ }
1189
+ this.#status.lastError = null;
1190
+ }
1191
+
1192
+ #finishBatchResult(messageId, sessionWebhook, result, statusReaction) {
1193
+ let task;
1194
+ task = Promise.resolve().then(async () => {
1195
+ if (this.#state.hasSeen(messageId)) return;
1196
+ await this.#state.markSeen(messageId);
1197
+ increment(this.#status, 'messagesReceived');
1198
+ this.#status.lastMessageAt = new Date().toISOString();
1199
+ if (result.message) await this.#send(sessionWebhook, result.message);
1200
+ this.#status.lastError = null;
1201
+ }).catch(async (error) => {
1202
+ if (this.#signal?.aborted) {
1203
+ this.#finishStatusReaction(statusReaction, 'clear');
1204
+ return;
1205
+ }
1206
+ this.#finishStatusReaction(statusReaction, 'error');
1207
+ this.#status.lastError = error?.message ?? String(error);
1208
+ const failure = setLastMessageFailure(this.#status, error);
1209
+ this.#logger.error?.(
1210
+ `[dsh-dingtalk] failed to process a batch input message [${failure.referenceId}]`,
1211
+ messageFailureDiagnostic(error, failure),
1212
+ );
1213
+ await this.#send(sessionWebhook, messageFailureText(failure)).catch(() => undefined);
1214
+ }).finally(() => {
1215
+ this.#acceptedMessageIds.delete(messageId);
1216
+ this.#commandTasks.delete(task);
1217
+ });
1218
+ this.#commandTasks.add(task);
1219
+ return task;
1220
+ }
1221
+
1222
+ #finishAccessDecision(message, messageId, sessionWebhook, access) {
1223
+ let task;
1224
+ task = Promise.resolve().then(async () => {
1225
+ if (this.#state.hasSeen(messageId)) return;
1226
+ await this.#state.markSeen(messageId);
1227
+ if (access.reason === 'command-not-allowed' && sessionWebhook) {
1228
+ increment(this.#status, 'messagesReceived');
1229
+ this.#status.lastMessageAt = new Date().toISOString();
1230
+ await this.#send(
1231
+ sessionWebhook,
1232
+ t(COMMAND_PERMISSION_DENIED_MESSAGE),
1233
+ this.#atUsersFor(message),
1234
+ );
1235
+ increment(this.#status, 'messagesReplied');
1236
+ this.#status.lastReplyAt = new Date().toISOString();
1237
+ } else {
1238
+ increment(this.#status, 'messagesRejected');
1239
+ this.#status.lastRejectedAt = new Date().toISOString();
1240
+ }
1241
+ this.#status.lastError = null;
1242
+ }).catch((error) => {
1243
+ if (this.#signal?.aborted) return;
1244
+ this.#status.lastError = error?.message ?? String(error);
1245
+ this.#logger.error?.('[dsh-dingtalk] failed to apply inbound access policy', error);
1246
+ }).finally(() => {
1247
+ this.#acceptedMessageIds.delete(messageId);
1248
+ this.#commandTasks.delete(task);
1249
+ });
1250
+ this.#commandTasks.add(task);
1251
+ return task;
1252
+ }
1253
+
1254
+ async #process(message, messageId, sender, key, {
1255
+ alreadyRecorded = false,
1256
+ preparedMessage,
1257
+ batchSubmission = null,
1258
+ statusReaction = null,
1259
+ } = {}) {
1260
+ this.#signal?.throwIfAborted();
1261
+ if (!alreadyRecorded) {
1262
+ if (this.#state.hasSeen(messageId)) return;
1263
+ await this.#state.markSeen(messageId);
1264
+ increment(this.#status, 'messagesReceived');
1265
+ this.#status.lastMessageAt = new Date().toISOString();
1266
+ }
1267
+
1268
+ if (String(message.conversationType) === '2' && message.isInAtList !== true) {
1269
+ increment(this.#status, 'messagesIgnored');
1270
+ return;
1271
+ }
1272
+
1273
+ let sessionWebhook;
1274
+ try {
1275
+ sessionWebhook = normalizeDingtalkSessionWebhook(message.sessionWebhook);
1276
+ } catch {
1277
+ increment(this.#status, 'messagesRejected');
1278
+ this.#status.lastRejectedAt = new Date().toISOString();
1279
+ this.#status.lastError = t('钉钉消息没有安全的回复地址。');
1280
+ return;
1281
+ }
1282
+
1283
+ const promptMessage = preparedMessage ?? this.#inboundMessage(message, key);
1284
+ const text = promptMessage.content;
1285
+ const hasImages = hasInboundImages(promptMessage);
1286
+ const hasFiles = hasInboundFiles(promptMessage);
1287
+ const hasReply = hasReplyReference(promptMessage);
1288
+ const isPlainText = String(message?.msgtype).toLowerCase() === 'text';
1289
+ let cardStream = null;
1290
+ let cardStarted = false;
1291
+ let cardStartedAt = null;
1292
+ let batchSettled = batchSubmission === null;
1293
+ try {
1294
+ if (!text && !hasImages && !hasFiles && !hasReply) {
1295
+ await this.#send(sessionWebhook, t('目前支持文字、图片和文件消息。'), this.#atUsersFor(message));
1296
+ return;
1297
+ }
1298
+
1299
+ const command = text.toLowerCase();
1300
+ if (isPlainText && !hasImages && !hasFiles && command === '/help') {
1301
+ await this.#send(sessionWebhook, helpText(), this.#atUsersFor(message));
1302
+ return;
1303
+ }
1304
+ if (isPlainText && !hasImages && !hasFiles && command === '/status') {
1305
+ await this.#harness.ensureRunning({ signal: this.#signal });
1306
+ await this.#send(sessionWebhook, t('钉钉机器人与 DeepSeek Harness 连接正常。'), this.#atUsersFor(message));
1307
+ return;
1308
+ }
1309
+ if (isPlainText && !hasImages && !hasFiles && command === '/new') {
1310
+ await this.#state.clearSession(key);
1311
+ await this.#send(sessionWebhook, t('已开启新会话。请发送你的问题。'), this.#atUsersFor(message));
1312
+ return;
1313
+ }
1314
+ const workspaceCommand = isPlainText && !hasImages && !hasFiles
1315
+ ? await runWorkspaceCommand(text, this.#harness, key)
1316
+ : null;
1317
+ if (workspaceCommand) {
1318
+ for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
1319
+ await this.#send(sessionWebhook, reply, this.#atUsersFor(message));
1320
+ }
1321
+ return;
1322
+ }
1323
+ const compactCommand = isPlainText && !hasImages && !hasFiles
1324
+ ? await runCompactCommand(
1325
+ text,
1326
+ this.#harness,
1327
+ this.#state,
1328
+ key,
1329
+ { signal: this.#signal },
1330
+ )
1331
+ : null;
1332
+ if (compactCommand) {
1333
+ await this.#send(sessionWebhook, compactCommand.message, this.#atUsersFor(message));
1334
+ return;
1335
+ }
1336
+
1337
+ const modelMessage = prepareDingtalkReplyAttachments(message, promptMessage, {
1338
+ api: this.#api, clientId: this.#clientId, clientSecret: this.#clientSecret,
1339
+ signal: this.#signal,
1340
+ });
1341
+ let content = hasInboundImages(modelMessage) || hasReply
1342
+ ? await promptContentForInboundMessage(modelMessage, { signal: this.#signal, deferImages: true })
1343
+ : undefined;
1344
+ const snapshot = this.#acceptedMessageIds.get(messageId);
1345
+ let contextEnhanced = false;
1346
+ if (snapshot) {
1347
+ const originalContent = content ?? text;
1348
+ content = enhanceContextContent(originalContent, snapshot, () => ({
1349
+ channel: 'dingtalk',
1350
+ senderId: sender,
1351
+ senderName: message.senderNick,
1352
+ conversationTitle: message.conversationTitle,
1353
+ chatId: message.conversationId,
1354
+ }));
1355
+ contextEnhanced = content !== originalContent;
1356
+ }
1357
+ if (typeof this.#api.createAiCard === 'function'
1358
+ && typeof this.#api.updateAiCard === 'function'
1359
+ && typeof this.#api.finishAiCard === 'function') {
1360
+ cardStream = createDingTalkCardStream({
1361
+ api: this.#api,
1362
+ clientId: this.#clientId,
1363
+ clientSecret: this.#clientSecret,
1364
+ target: cardTarget(message, sender),
1365
+ signal: this.#signal,
1366
+ logger: this.#logger,
1367
+ });
1368
+ const startedAt = Date.now();
1369
+ cardStarted = await cardStream.start(t(CARD_INITIAL_TEXT));
1370
+ if (cardStarted) cardStartedAt = startedAt;
1371
+ }
1372
+ const { answer, artifacts = [] } = await askInWorkspaceSession({
1373
+ deferredDelivery: () => ({ coordinator: this.#deferred, target: { ...cardTarget(message, sender), robotCode: this.#clientId } }),
1374
+ harness: this.#harness,
1375
+ state: this.#state,
1376
+ key,
1377
+ text,
1378
+ content,
1379
+ titleText: batchSubmission?.title,
1380
+ sourceGuidance: snapshot?.config?.guidance,
1381
+ contextEnhanced,
1382
+ createOptions: { signal: this.#signal },
1383
+ existsOptions: { signal: this.#signal },
1384
+ askOptions: {
1385
+ timeoutMs: this.#replyTimeoutMs,
1386
+ signal: this.#signal,
1387
+ control: { owner: this, key },
1388
+ onUpdate: cardStarted
1389
+ ? (update) => cardStream.push(progressText(update))
1390
+ : undefined,
1391
+ onInteraction: (interaction) => this.#handleInteraction(interaction, {
1392
+ key,
1393
+ actor: sender,
1394
+ sessionWebhook,
1395
+ requiresMention: String(message.conversationType) === '2',
1396
+ }),
1397
+ onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
1398
+ files: modelMessage.files,
1399
+ images: modelMessage.images,
1400
+ },
1401
+ });
1402
+ if (batchSubmission) {
1403
+ this.#batchInputs.complete(key, batchSubmission.token);
1404
+ batchSettled = true;
1405
+ }
1406
+ const answerText = typeof answer === 'string' && answer.trim()
1407
+ ? answer
1408
+ : artifacts.length > 0 ? t('结果文件已生成。') : answer;
1409
+ let textDeliveryError = null;
1410
+ let textReceipt = null;
1411
+ let streamed = false;
1412
+ const deliveryStartedAt = cardStartedAt ?? Date.now();
1413
+ try {
1414
+ streamed = cardStarted && await cardStream.finish(answerText);
1415
+ if (streamed) {
1416
+ textReceipt = createDeliveryReceipt({
1417
+ deliveryId: messageId,
1418
+ presentation: 'dingtalk-card',
1419
+ providerMessageIds: cardStream.providerMessageIds,
1420
+ });
1421
+ } else {
1422
+ // Failed streams close the card with a notice pointing to a
1423
+ // follow-up message. Deliver the answer through that fallback.
1424
+ textReceipt = createDeliveryReceipt({
1425
+ deliveryId: messageId,
1426
+ presentation: 'dingtalk-text',
1427
+ providerMessageIds: await this.#send(sessionWebhook, answerText, this.#atUsersFor(message)),
1428
+ });
1429
+ }
1430
+ try {
1431
+ await this.#state.rememberOutboundMessage?.({
1432
+ conversationKey: key,
1433
+ text: answerText,
1434
+ sentAt: deliveryStartedAt,
1435
+ completedAt: Date.now(),
1436
+ providerMessageIds: providerMessageIdsFor(textReceipt),
1437
+ });
1438
+ } catch (error) {
1439
+ this.#logger.warn?.('[dsh-dingtalk] failed to remember an outbound message:', error);
1440
+ }
1441
+ } catch (error) {
1442
+ textDeliveryError = channelDeliveryFailure(error);
1443
+ }
1444
+ const delivery = await this.#deliverArtifacts(
1445
+ fileTarget(message, sender, this.#clientId),
1446
+ sessionWebhook,
1447
+ messageId,
1448
+ artifacts,
1449
+ textReceipt,
1450
+ );
1451
+ if (textDeliveryError && !delivery.userVisible) throw textDeliveryError;
1452
+ if (textDeliveryError && delivery.artifactSendErrors === 0) {
1453
+ setLastMessageFailure(this.#status, textDeliveryError);
1454
+ }
1455
+ increment(this.#status, 'messagesReplied');
1456
+ this.#status.lastReplyAt = new Date().toISOString();
1457
+ this.#status.lastError = null;
1458
+ if (!textDeliveryError && delivery.artifactSendErrors === 0) {
1459
+ clearLastMessageFailure(this.#status);
1460
+ }
1461
+ return delivery.receipt;
1462
+ } catch (error) {
1463
+ let batchFailureMessage = null;
1464
+ if (!batchSettled && batchSubmission) {
1465
+ if (error?.code === 'turn-stopped') {
1466
+ this.#batchInputs.complete(key, batchSubmission.token);
1467
+ } else {
1468
+ batchFailureMessage = this.#batchInputs.fail(key, batchSubmission.token).message ?? null;
1469
+ }
1470
+ batchSettled = true;
1471
+ }
1472
+ if (error?.code === 'turn-stopped') {
1473
+ this.#finishStatusReaction(statusReaction, 'clear');
1474
+ if (cardStarted) await cardStream.finish(t('已停止。')).catch(() => undefined);
1475
+ return;
1476
+ }
1477
+ if (this.#signal?.aborted) {
1478
+ this.#finishStatusReaction(statusReaction, 'clear');
1479
+ return;
1480
+ }
1481
+ this.#finishStatusReaction(statusReaction, 'error');
1482
+ this.#status.lastError = error?.message ?? String(error);
1483
+ const userMessage = inboundFileUserMessage(error)
1484
+ ?? dingtalkImageErrorUserMessage(error);
1485
+ const failure = setLastMessageFailure(this.#status, error, {
1486
+ userMessage,
1487
+ reason: imagePromptDiagnostic(error)?.reason,
1488
+ });
1489
+ this.#logger.error?.(
1490
+ `[dsh-dingtalk] failed to process an inbound message [${failure.referenceId}]`,
1491
+ messageFailureDiagnostic(error, failure),
1492
+ );
1493
+ try {
1494
+ const errorText = messageFailureText(failure);
1495
+ const visibleError = batchFailureMessage
1496
+ ? `${errorText}\n\n${batchFailureMessage}`
1497
+ : errorText;
1498
+ const streamed = cardStarted && await cardStream.finish(visibleError);
1499
+ if (!streamed) {
1500
+ await this.#send(sessionWebhook, visibleError, this.#atUsersFor(message));
1501
+ }
1502
+ } catch {
1503
+ this.#logger.error?.('[dsh-dingtalk] failed to send the safe error reply');
1504
+ }
1505
+ } finally {
1506
+ await this.#cancelPendingInteraction(key);
1507
+ await this.#approvals.closeRoute(key);
1508
+ }
1509
+ }
1510
+
1511
+ async #processInteractionReply(
1512
+ message,
1513
+ messageId,
1514
+ sender,
1515
+ key,
1516
+ expected,
1517
+ statusReaction,
1518
+ ) {
1519
+ this.#signal?.throwIfAborted();
1520
+ const current = this.#pendingInteractions.get(key);
1521
+ const claimed = expected.claimedReplyMessageId === messageId;
1522
+ if (!current || current !== expected || current.submitting) {
1523
+ if (claimed && (!current || current !== expected)) {
1524
+ return this.#discardResolvedInteractionReply(message, messageId);
1525
+ }
1526
+ return this.#enqueueMessage(message, messageId, sender, key, {
1527
+ releaseMessageId: false,
1528
+ statusReaction,
1529
+ });
1530
+ }
1531
+ if (this.#state.hasSeen(messageId)) return;
1532
+ await this.#state.markSeen(messageId);
1533
+ increment(this.#status, 'messagesReceived');
1534
+ this.#status.lastMessageAt = new Date().toISOString();
1535
+
1536
+ if (String(message.conversationType) === '2' && message.isInAtList !== true) {
1537
+ increment(this.#status, 'messagesIgnored');
1538
+ return;
1539
+ }
1540
+
1541
+ let sessionWebhook;
1542
+ try {
1543
+ sessionWebhook = normalizeDingtalkSessionWebhook(message.sessionWebhook);
1544
+ } catch {
1545
+ increment(this.#status, 'messagesRejected');
1546
+ this.#status.lastRejectedAt = new Date().toISOString();
1547
+ this.#status.lastError = t('钉钉消息没有安全的回复地址。');
1548
+ return;
1549
+ }
1550
+
1551
+ const text = message?.msgtype === 'text' ? nonEmptyString(message?.text?.content) : null;
1552
+ if (!text) {
1553
+ try {
1554
+ await this.#send(sessionWebhook, t('请用文字回答当前问题。'), this.#atUsersFor(message));
1555
+ } catch {
1556
+ this.#logger.error?.('[dsh-dingtalk] failed to reject a non-text interaction reply');
1557
+ }
1558
+ return;
1559
+ }
1560
+
1561
+ const pending = this.#pendingInteractions.get(key);
1562
+ if (!pending || pending !== expected || pending.submitting) {
1563
+ if (claimed && (!pending || pending !== expected)) {
1564
+ try {
1565
+ await this.#send(sessionWebhook, t(INTERACTION_RESOLVED_TEXT), this.#atUsersFor(message));
1566
+ } catch {
1567
+ this.#logger.error?.('[dsh-dingtalk] failed to send an expired interaction notice');
1568
+ }
1569
+ return;
1570
+ }
1571
+ return this.#enqueueMessage(message, messageId, sender, key, {
1572
+ releaseMessageId: false,
1573
+ alreadyRecorded: true,
1574
+ statusReaction,
1575
+ });
1576
+ }
1577
+ pending.sessionWebhook = sessionWebhook;
1578
+ if (pending.needsPresentation) {
1579
+ try {
1580
+ await this.#presentInteraction(pending);
1581
+ } catch {
1582
+ this.#finishStatusReaction(statusReaction, 'error');
1583
+ this.#status.lastError = t('钉钉交互问题发送失败。');
1584
+ this.#logger.error?.('[dsh-dingtalk] failed to retry an interaction question');
1585
+ pending.interaction.reconnect?.();
1586
+ }
1587
+ return;
1588
+ }
1589
+ const question = pending.questions[pending.index];
1590
+ if (!question) return;
1591
+
1592
+ pending.answers.push(harnessAnswerForQuestion(question, text));
1593
+ pending.index += 1;
1594
+ if (pending.index < pending.questions.length) {
1595
+ if (pending.claimedReplyMessageId === messageId) {
1596
+ pending.claimedReplyMessageId = null;
1597
+ }
1598
+ pending.needsPresentation = true;
1599
+ try {
1600
+ await this.#presentInteraction(pending);
1601
+ } catch {
1602
+ this.#finishStatusReaction(statusReaction, 'error');
1603
+ this.#status.lastError = t('钉钉交互问题发送失败。');
1604
+ this.#logger.error?.('[dsh-dingtalk] failed to send the next interaction question');
1605
+ pending.interaction.reconnect?.();
1606
+ }
1607
+ return;
1608
+ }
1609
+
1610
+ pending.submitting = true;
1611
+ try {
1612
+ await pending.interaction.respond({
1613
+ ok: true,
1614
+ value: {
1615
+ sessionId: pending.sessionId,
1616
+ answer: { answers: pending.answers },
1617
+ },
1618
+ });
1619
+ this.#clearPendingInteraction(key, pending.interactionId);
1620
+ this.#status.lastError = null;
1621
+ } catch (error) {
1622
+ if (this.#signal?.aborted) {
1623
+ this.#finishStatusReaction(statusReaction, 'clear');
1624
+ return;
1625
+ }
1626
+ if (this.#pendingInteractions.get(key) !== pending) return;
1627
+ if (error?.code === 'interaction-not-pending') {
1628
+ this.#clearPendingInteraction(key, pending.interactionId);
1629
+ try {
1630
+ await this.#send(sessionWebhook, t(INTERACTION_RESOLVED_TEXT), this.#atUsersFor(message));
1631
+ } catch {
1632
+ this.#logger.error?.('[dsh-dingtalk] failed to send an expired interaction notice');
1633
+ }
1634
+ return;
1635
+ }
1636
+ this.#finishStatusReaction(statusReaction, 'error');
1637
+ pending.submitting = false;
1638
+ pending.answers.pop();
1639
+ pending.index -= 1;
1640
+ this.#status.lastError = t('回答提交失败。');
1641
+ this.#logger.error?.('[dsh-dingtalk] failed to answer a Harness interaction');
1642
+ try {
1643
+ await this.#send(sessionWebhook, t('回答提交失败,请重新发送当前问题的答案。'), this.#atUsersFor(message));
1644
+ } catch {
1645
+ this.#logger.error?.('[dsh-dingtalk] failed to send an interaction retry notice');
1646
+ }
1647
+ }
1648
+ }
1649
+
1650
+ async #handleInteraction(interaction, {
1651
+ key,
1652
+ actor,
1653
+ sessionWebhook,
1654
+ requiresMention,
1655
+ }) {
1656
+ if (await this.#approvals.handleRequested(interaction, {
1657
+ key,
1658
+ actor,
1659
+ requiresMention,
1660
+ send: (text) => this.#send(sessionWebhook, text),
1661
+ })) return;
1662
+
1663
+ // Approval requests return above; the existing question state machine stays unchanged.
1664
+ if (interaction?.kind !== 'question') return;
1665
+ const questions = interaction?.payload?.questions;
1666
+ const interactionId = typeof interaction?.interactionId === 'string'
1667
+ ? interaction.interactionId
1668
+ : interaction?.rpcId;
1669
+ if (typeof interaction.rpcId !== 'string'
1670
+ || typeof interactionId !== 'string'
1671
+ || typeof interaction.sessionId !== 'string'
1672
+ || !Array.isArray(questions)
1673
+ || questions.length === 0
1674
+ || questions.some((question) => !validHarnessQuestion(question))) {
1675
+ this.#logger.warn?.('[dsh-dingtalk] ignored an invalid Harness question interaction');
1676
+ return;
1677
+ }
1678
+
1679
+ if (interaction.recovered === true) {
1680
+ await interaction.respond({
1681
+ ok: false,
1682
+ error: {
1683
+ code: 'cancelled',
1684
+ message: 'DingTalk safely cancelled an interaction left by an earlier client.',
1685
+ details: {},
1686
+ },
1687
+ });
1688
+ try {
1689
+ await this.#send(sessionWebhook, t('检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。'));
1690
+ } catch {
1691
+ this.#logger.error?.('[dsh-dingtalk] failed to send an interaction recovery notice');
1692
+ }
1693
+ return;
1694
+ }
1695
+
1696
+ const existing = this.#pendingInteractions.get(key);
1697
+ if (existing?.interactionId === interactionId) {
1698
+ existing.interaction = interaction;
1699
+ if (existing.needsPresentation) await this.#presentInteraction(existing);
1700
+ return;
1701
+ }
1702
+ if (this.#interactionKeys.has(interactionId)) return;
1703
+ if (existing) {
1704
+ this.#logger.warn?.('[dsh-dingtalk] cancelled a second pending Harness question');
1705
+ await interaction.respond({
1706
+ ok: false,
1707
+ error: {
1708
+ code: 'cancelled',
1709
+ message: 'DingTalk is already handling another user interaction.',
1710
+ details: {},
1711
+ },
1712
+ });
1713
+ return;
1714
+ }
1715
+
1716
+ const pending = {
1717
+ kind: 'question',
1718
+ interactionId,
1719
+ sessionId: interaction.sessionId,
1720
+ interaction,
1721
+ actor,
1722
+ requiresMention,
1723
+ questions,
1724
+ answers: [],
1725
+ index: 0,
1726
+ sessionWebhook,
1727
+ queue: null,
1728
+ claimedReplyMessageId: null,
1729
+ submitting: false,
1730
+ needsPresentation: true,
1731
+ };
1732
+ this.#pendingInteractions.set(key, pending);
1733
+ this.#interactionKeys.set(pending.interactionId, key);
1734
+ await this.#presentInteraction(pending);
1735
+ }
1736
+
1737
+ async #handleInteractionResolved(resolution) {
1738
+ if (await this.#approvals.handleResolved(resolution)) return;
1739
+ const interactionId = resolution?.interactionId;
1740
+ if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
1741
+ const key = this.#interactionKeys.get(interactionId);
1742
+ if (!key) return;
1743
+ this.#clearPendingInteraction(key, interactionId);
1744
+ }
1745
+
1746
+ async #presentInteraction(pending) {
1747
+ const question = pending.questions[pending.index];
1748
+ if (!question) return;
1749
+ await this.#send(
1750
+ pending.sessionWebhook,
1751
+ harnessQuestionText(
1752
+ question,
1753
+ pending.index,
1754
+ pending.questions.length,
1755
+ { requiresMention: pending.requiresMention },
1756
+ ),
1757
+ );
1758
+ pending.needsPresentation = false;
1759
+ }
1760
+
1761
+ async #discardResolvedInteractionReply(message, messageId) {
1762
+ if (this.#state.hasSeen(messageId)) return;
1763
+ await this.#state.markSeen(messageId);
1764
+ increment(this.#status, 'messagesReceived');
1765
+ this.#status.lastMessageAt = new Date().toISOString();
1766
+ let sessionWebhook;
1767
+ try {
1768
+ sessionWebhook = normalizeDingtalkSessionWebhook(message.sessionWebhook);
1769
+ } catch {
1770
+ increment(this.#status, 'messagesRejected');
1771
+ this.#status.lastRejectedAt = new Date().toISOString();
1772
+ return;
1773
+ }
1774
+ try {
1775
+ await this.#send(sessionWebhook, t(INTERACTION_RESOLVED_TEXT), this.#atUsersFor(message));
1776
+ } catch {
1777
+ this.#logger.error?.('[dsh-dingtalk] failed to send an expired interaction notice');
1778
+ }
1779
+ }
1780
+
1781
+ #takePendingInteraction(key, interactionId) {
1782
+ const pending = this.#pendingInteractions.get(key);
1783
+ if (!pending
1784
+ || (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
1785
+ this.#pendingInteractions.delete(key);
1786
+ this.#interactionKeys.delete(pending.interactionId);
1787
+ return pending;
1788
+ }
1789
+
1790
+ #clearPendingInteraction(key, interactionId) {
1791
+ return this.#takePendingInteraction(key, interactionId) !== null;
1792
+ }
1793
+
1794
+ async #cancelPendingInteraction(key) {
1795
+ const pending = this.#takePendingInteraction(key);
1796
+ if (!pending || pending.kind !== 'question') return;
1797
+ try {
1798
+ await pending.interaction.respond({
1799
+ ok: false,
1800
+ error: {
1801
+ code: 'cancelled',
1802
+ message: 'The DingTalk interaction ended before the user answered.',
1803
+ details: {},
1804
+ },
1805
+ }, { signal: AbortSignal.timeout(5_000) });
1806
+ } catch (error) {
1807
+ if (error?.code !== 'interaction-not-pending') {
1808
+ this.#logger.warn?.('[dsh-dingtalk] failed to cancel a pending Harness interaction');
1809
+ }
1810
+ }
1811
+ }
1812
+
1813
+ #refreshPendingSenders() {
1814
+ if (typeof this.#state.pendingSenders === 'function') {
1815
+ this.#status.pendingSenders = this.#state.pendingSenders();
1816
+ }
1817
+ }
1818
+
1819
+ #atUsersFor(message) {
1820
+ const sender = senderStaffId(message);
1821
+ return String(message?.conversationType) === '2' && sender
1822
+ ? { atUserIds: [sender] }
1823
+ : undefined;
1824
+ }
1825
+
1826
+ async #send(sessionWebhook, text, at) {
1827
+ const providerMessageIds = [];
1828
+ for (const chunk of splitDingtalkText(text, this.#maxMessageChars)) {
1829
+ this.#signal?.throwIfAborted();
1830
+ const result = await this.#api.sendText({
1831
+ clientId: this.#clientId,
1832
+ clientSecret: this.#clientSecret,
1833
+ sessionWebhook,
1834
+ text: chunk,
1835
+ at,
1836
+ signal: this.#signal,
1837
+ });
1838
+ providerMessageIds.push(...providerMessageIdsFor(result));
1839
+ }
1840
+ return providerMessageIds;
1841
+ }
1842
+
1843
+ async #deliverArtifacts(target, sessionWebhook, replyTo, artifacts, baseReceipt) {
1844
+ const sendArtifact = async (method, file) => dingtalkFileProviderIds(
1845
+ await this.#api[method]({
1846
+ clientId: this.#clientId,
1847
+ clientSecret: this.#clientSecret,
1848
+ target,
1849
+ file,
1850
+ signal: this.#signal,
1851
+ }),
1852
+ );
1853
+ const delivery = await deliverOutboundArtifacts({
1854
+ artifacts,
1855
+ baseReceipt,
1856
+ deliveryId: replyTo,
1857
+ aggregatePresentation: baseReceipt ? 'dingtalk-text-and-files' : 'dingtalk-files',
1858
+ channelKey: 'dingtalk',
1859
+ signal: this.#signal,
1860
+ sendImage: typeof this.#api.sendImage === 'function'
1861
+ ? (file) => sendArtifact('sendImage', file)
1862
+ : undefined,
1863
+ sendFile: typeof this.#api.sendFile === 'function'
1864
+ ? (file) => sendArtifact('sendFile', file)
1865
+ : undefined,
1866
+ onFailure: (artifact, error) => setLastMessageFailure(this.#status, error, {
1867
+ userMessage: artifactFailureText(artifact?.fileName, error),
1868
+ reason: error?.code,
1869
+ }),
1870
+ sendFailureNotice: (_artifact, _error, failure) => this.#send(
1871
+ sessionWebhook,
1872
+ messageFailureText(failure),
1873
+ ),
1874
+ logger: this.#logger,
1875
+ });
1876
+ this.#status.artifactsSent = (this.#status.artifactsSent ?? 0)
1877
+ + delivery.artifactsSent;
1878
+ this.#status.artifactSendErrors = (this.#status.artifactSendErrors ?? 0)
1879
+ + delivery.artifactSendErrors;
1880
+ return {
1881
+ receipt: delivery.receipt,
1882
+ userVisible: delivery.userVisible,
1883
+ artifactSendErrors: delivery.artifactSendErrors,
1884
+ };
1885
+ }
1886
+ }
1887
+
1888
+ export const DingTalkHarnessBridge = DingtalkHarnessBridge;
1889
+ export const createDingTalkBridgeStatus = createDingtalkBridgeStatus;