@botharness/im-provider 4.32.0-botharness.15

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 (423) 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 +604 -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 +18 -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 +319 -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 +239 -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 +258 -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 +411 -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 +618 -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 +229 -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 +28 -0
  201. package/src/channels/discord/discord-api.mjs +423 -0
  202. package/src/channels/discord/discord-bridge.mjs +16 -0
  203. package/src/channels/discord/discord-controller.mjs +29 -0
  204. package/src/channels/discord/discord-runtime.mjs +1091 -0
  205. package/src/channels/discord/external-consumer.mjs +199 -0
  206. package/src/channels/discord/external-files.mjs +97 -0
  207. package/src/channels/discord/harness-client.mjs +11 -0
  208. package/src/channels/discord/history-reader.mjs +142 -0
  209. package/src/channels/discord/nearby-history.mjs +112 -0
  210. package/src/channels/discord/state-store.mjs +3 -0
  211. package/src/channels/email/config-store.mjs +194 -0
  212. package/src/channels/email/email-api.mjs +20 -0
  213. package/src/channels/email/email-bridge.mjs +17 -0
  214. package/src/channels/email/email-controller.mjs +824 -0
  215. package/src/channels/email/email-runtime.mjs +699 -0
  216. package/src/channels/email/harness-client.mjs +7 -0
  217. package/src/channels/email/mail-format.mjs +91 -0
  218. package/src/channels/email/state-store.mjs +176 -0
  219. package/src/channels/email/transport.mjs +64 -0
  220. package/src/channels/email/transports/agent-mail.mjs +604 -0
  221. package/src/channels/email/transports/agently-cli.mjs +288 -0
  222. package/src/channels/email/transports/imap-smtp.mjs +165 -0
  223. package/src/channels/feishu/bridge.mjs +6286 -0
  224. package/src/channels/feishu/config.mjs +71 -0
  225. package/src/channels/feishu/external-cards.mjs +87 -0
  226. package/src/channels/feishu/external-consumer.mjs +89 -0
  227. package/src/channels/feishu/external-files.mjs +115 -0
  228. package/src/channels/feishu/external-images.mjs +50 -0
  229. package/src/channels/feishu/external-names.mjs +99 -0
  230. package/src/channels/feishu/feishu-app.mjs +54 -0
  231. package/src/channels/feishu/feishu-cards.mjs +1285 -0
  232. package/src/channels/feishu/feishu-channel.mjs +651 -0
  233. package/src/channels/feishu/feishu-runtime.mjs +982 -0
  234. package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
  235. package/src/channels/feishu/group-response-mode.mjs +15 -0
  236. package/src/channels/feishu/harness-client.mjs +19 -0
  237. package/src/channels/feishu/history-reader.mjs +77 -0
  238. package/src/channels/feishu/live-cot.mjs +260 -0
  239. package/src/channels/feishu/message-utils.mjs +613 -0
  240. package/src/channels/feishu/multi-bot-controller.mjs +1619 -0
  241. package/src/channels/feishu/nearby-history.mjs +72 -0
  242. package/src/channels/feishu/plugin-config-store.mjs +216 -0
  243. package/src/channels/feishu/plugin-controller.mjs +254 -0
  244. package/src/channels/feishu/registration-manager.mjs +349 -0
  245. package/src/channels/feishu/repair-manager.mjs +138 -0
  246. package/src/channels/feishu/reply-context.mjs +22 -0
  247. package/src/channels/feishu/slash-command-panel.mjs +155 -0
  248. package/src/channels/feishu/slash-command-registry.mjs +495 -0
  249. package/src/channels/feishu/state-store.mjs +214 -0
  250. package/src/channels/feishu/step-push-mode.mjs +25 -0
  251. package/src/channels/feishu/voice-config.mjs +34 -0
  252. package/src/channels/feishu/voice.mjs +134 -0
  253. package/src/channels/imessage/config-store.mjs +24 -0
  254. package/src/channels/imessage/controller.mjs +37 -0
  255. package/src/channels/imessage/harness-client.mjs +7 -0
  256. package/src/channels/imessage/imessage-api.mjs +194 -0
  257. package/src/channels/imessage/imessage-bridge.mjs +16 -0
  258. package/src/channels/imessage/runtime.mjs +102 -0
  259. package/src/channels/imessage/state-store.mjs +3 -0
  260. package/src/channels/matrix/matrix-api.mjs +696 -0
  261. package/src/channels/matrix/matrix-bridge.mjs +20 -0
  262. package/src/channels/matrix/matrix-config-store.mjs +368 -0
  263. package/src/channels/matrix/matrix-controller.mjs +404 -0
  264. package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
  265. package/src/channels/matrix/matrix-crypto.mjs +1014 -0
  266. package/src/channels/matrix/matrix-harness-client.mjs +11 -0
  267. package/src/channels/matrix/matrix-normalize.mjs +357 -0
  268. package/src/channels/matrix/matrix-rich-text.mjs +313 -0
  269. package/src/channels/matrix/matrix-room-history.mjs +316 -0
  270. package/src/channels/matrix/matrix-runtime.mjs +1014 -0
  271. package/src/channels/office/config-store.mjs +107 -0
  272. package/src/channels/office/office-controller.mjs +178 -0
  273. package/src/channels/office/office-job-executor.mjs +391 -0
  274. package/src/channels/office/office-runtime.mjs +175 -0
  275. package/src/channels/office/office-transport.mjs +171 -0
  276. package/src/channels/office/protocol.mjs +43 -0
  277. package/src/channels/qq/config-store.mjs +173 -0
  278. package/src/channels/qq/harness-client.mjs +11 -0
  279. package/src/channels/qq/markdown-reply.mjs +446 -0
  280. package/src/channels/qq/qq-bridge.mjs +1507 -0
  281. package/src/channels/qq/qq-controller.mjs +514 -0
  282. package/src/channels/qq/qq-menu.mjs +208 -0
  283. package/src/channels/qq/qq-runtime.mjs +303 -0
  284. package/src/channels/qq/qr-auth.mjs +24 -0
  285. package/src/channels/qq/state-error.mjs +17 -0
  286. package/src/channels/qq/state-store.mjs +143 -0
  287. package/src/channels/shared/access-policy.mjs +210 -0
  288. package/src/channels/shared/agent-preset.mjs +76 -0
  289. package/src/channels/shared/batch-input.mjs +229 -0
  290. package/src/channels/shared/bot-alias.mjs +29 -0
  291. package/src/channels/shared/bot-workspace-store.mjs +2383 -0
  292. package/src/channels/shared/command-catalog.mjs +107 -0
  293. package/src/channels/shared/command-permission.mjs +32 -0
  294. package/src/channels/shared/compact-command.mjs +109 -0
  295. package/src/channels/shared/config-read-error.mjs +24 -0
  296. package/src/channels/shared/connection-error.mjs +191 -0
  297. package/src/channels/shared/connection-test.mjs +58 -0
  298. package/src/channels/shared/context-enhancement.mjs +372 -0
  299. package/src/channels/shared/control-command.mjs +111 -0
  300. package/src/channels/shared/conversation-state-store.mjs +165 -0
  301. package/src/channels/shared/default-workspace.mjs +31 -0
  302. package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
  303. package/src/channels/shared/deferred-delivery.mjs +161 -0
  304. package/src/channels/shared/deferred-state.mjs +53 -0
  305. package/src/channels/shared/diagnostic-details.mjs +95 -0
  306. package/src/channels/shared/editable-message-stream.mjs +100 -0
  307. package/src/channels/shared/exclusive-inbound-consumers.mjs +91 -0
  308. package/src/channels/shared/file-download.mjs +64 -0
  309. package/src/channels/shared/harness-approval.mjs +508 -0
  310. package/src/channels/shared/harness-client.mjs +2143 -0
  311. package/src/channels/shared/harness-mux.mjs +123 -0
  312. package/src/channels/shared/harness-question.mjs +95 -0
  313. package/src/channels/shared/harness-session-binding.mjs +119 -0
  314. package/src/channels/shared/history-command.mjs +193 -0
  315. package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
  316. package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
  317. package/src/channels/shared/i18n-en/discord.mjs +10 -0
  318. package/src/channels/shared/i18n-en/email.mjs +25 -0
  319. package/src/channels/shared/i18n-en/feishu.mjs +404 -0
  320. package/src/channels/shared/i18n-en/image-input.mjs +18 -0
  321. package/src/channels/shared/i18n-en/matrix.mjs +85 -0
  322. package/src/channels/shared/i18n-en/office.mjs +23 -0
  323. package/src/channels/shared/i18n-en/qq.mjs +96 -0
  324. package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
  325. package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
  326. package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
  327. package/src/channels/shared/i18n-en/slack.mjs +27 -0
  328. package/src/channels/shared/i18n-en/telegram.mjs +27 -0
  329. package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
  330. package/src/channels/shared/i18n-en/wecom.mjs +62 -0
  331. package/src/channels/shared/i18n-en/weixin.mjs +88 -0
  332. package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
  333. package/src/channels/shared/i18n-en.mjs +45 -0
  334. package/src/channels/shared/i18n.mjs +78 -0
  335. package/src/channels/shared/im-source-guidance.mjs +65 -0
  336. package/src/channels/shared/image-input-policy.mjs +35 -0
  337. package/src/channels/shared/image-input-settings-store.mjs +60 -0
  338. package/src/channels/shared/image-input.mjs +124 -0
  339. package/src/channels/shared/image-prompt.mjs +360 -0
  340. package/src/channels/shared/inbound-access.mjs +43 -0
  341. package/src/channels/shared/inbound-file.mjs +323 -0
  342. package/src/channels/shared/inbound-ttl-store.mjs +110 -0
  343. package/src/channels/shared/inbound-ttl.mjs +22 -0
  344. package/src/channels/shared/injected-context.mjs +362 -0
  345. package/src/channels/shared/interface-language-store.mjs +127 -0
  346. package/src/channels/shared/interface-language.mjs +51 -0
  347. package/src/channels/shared/message-failure.mjs +257 -0
  348. package/src/channels/shared/model-command.mjs +741 -0
  349. package/src/channels/shared/model-setting.mjs +145 -0
  350. package/src/channels/shared/preset-command.mjs +308 -0
  351. package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
  352. package/src/channels/shared/semantic/artifact.mjs +750 -0
  353. package/src/channels/shared/semantic/delivery.mjs +193 -0
  354. package/src/channels/shared/semantic/reply-reference.mjs +148 -0
  355. package/src/channels/shared/session-binding-lock.mjs +40 -0
  356. package/src/channels/shared/session-channel-labels.mjs +28 -0
  357. package/src/channels/shared/session-reply-recovery.mjs +104 -0
  358. package/src/channels/shared/session-sync-registry.mjs +22 -0
  359. package/src/channels/shared/session-title.mjs +74 -0
  360. package/src/channels/shared/status-reaction.mjs +107 -0
  361. package/src/channels/shared/text-harness-bridge.mjs +1623 -0
  362. package/src/channels/shared/token-bot-controller.mjs +529 -0
  363. package/src/channels/shared/token-config-store.mjs +208 -0
  364. package/src/channels/shared/video-media.mjs +9 -0
  365. package/src/channels/shared/workspace-command.mjs +532 -0
  366. package/src/channels/shared/workspace-session.mjs +196 -0
  367. package/src/channels/slack/config-store.mjs +177 -0
  368. package/src/channels/slack/external-consumer.mjs +93 -0
  369. package/src/channels/slack/external-files.mjs +90 -0
  370. package/src/channels/slack/harness-client.mjs +11 -0
  371. package/src/channels/slack/history-reader.mjs +203 -0
  372. package/src/channels/slack/manifest.mjs +37 -0
  373. package/src/channels/slack/slack-api.mjs +644 -0
  374. package/src/channels/slack/slack-bridge.mjs +20 -0
  375. package/src/channels/slack/slack-controller.mjs +468 -0
  376. package/src/channels/slack/slack-runtime.mjs +895 -0
  377. package/src/channels/slack/state-store.mjs +3 -0
  378. package/src/channels/telegram/config-store.mjs +89 -0
  379. package/src/channels/telegram/harness-client.mjs +11 -0
  380. package/src/channels/telegram/state-store.mjs +3 -0
  381. package/src/channels/telegram/telegram-api.mjs +486 -0
  382. package/src/channels/telegram/telegram-bridge.mjs +81 -0
  383. package/src/channels/telegram/telegram-controller.mjs +52 -0
  384. package/src/channels/telegram/telegram-http.mjs +21 -0
  385. package/src/channels/telegram/telegram-rich-message.mjs +149 -0
  386. package/src/channels/telegram/telegram-runtime.mjs +1471 -0
  387. package/src/channels/wecom/config-store.mjs +172 -0
  388. package/src/channels/wecom/harness-client.mjs +11 -0
  389. package/src/channels/wecom/qr-auth.mjs +95 -0
  390. package/src/channels/wecom/send-error.mjs +31 -0
  391. package/src/channels/wecom/state-store.mjs +107 -0
  392. package/src/channels/wecom/wecom-bridge.mjs +1833 -0
  393. package/src/channels/wecom/wecom-cards.mjs +101 -0
  394. package/src/channels/wecom/wecom-controller.mjs +530 -0
  395. package/src/channels/wecom/wecom-runtime.mjs +269 -0
  396. package/src/channels/wecom-app/callback-server.mjs +471 -0
  397. package/src/channels/wecom-app/config-store.mjs +242 -0
  398. package/src/channels/wecom-app/harness-client.mjs +11 -0
  399. package/src/channels/wecom-app/state-store.mjs +107 -0
  400. package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
  401. package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
  402. package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
  403. package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
  404. package/src/channels/weixin/config-store.mjs +194 -0
  405. package/src/channels/weixin/connection-error.en.mjs +137 -0
  406. package/src/channels/weixin/connection-error.mjs +153 -0
  407. package/src/channels/weixin/diagnostic-details.mjs +1 -0
  408. package/src/channels/weixin/external-consumer.mjs +160 -0
  409. package/src/channels/weixin/external-files.mjs +84 -0
  410. package/src/channels/weixin/external-typing.mjs +120 -0
  411. package/src/channels/weixin/harness-client.mjs +19 -0
  412. package/src/channels/weixin/state-store.mjs +316 -0
  413. package/src/channels/weixin/weixin-api.mjs +1009 -0
  414. package/src/channels/weixin/weixin-bridge.mjs +1537 -0
  415. package/src/channels/weixin/weixin-controller.mjs +779 -0
  416. package/src/channels/weixin/weixin-runtime.mjs +507 -0
  417. package/src/channels/whatsapp/config-store.mjs +210 -0
  418. package/src/channels/whatsapp/harness-client.mjs +11 -0
  419. package/src/channels/whatsapp/state-store.mjs +3 -0
  420. package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
  421. package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
  422. package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
  423. package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
@@ -0,0 +1,1507 @@
1
+ import { createDeferredDeliveryCoordinator, deferredOutcomeText } from '../shared/deferred-delivery-coordinator.mjs';
2
+ import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
3
+ import { runCompactCommand } from '../shared/compact-command.mjs';
4
+ import { isHistoryCommand, runHistoryCommand } from '../shared/history-command.mjs';
5
+ import {
6
+ isControlCommand,
7
+ runControlCommand,
8
+ } from '../shared/control-command.mjs';
9
+ import { rememberConnectionTestTarget } from '../shared/connection-test.mjs';
10
+ import {
11
+ harnessAnswerForQuestion,
12
+ harnessQuestionText,
13
+ validHarnessQuestion,
14
+ } from '../shared/harness-question.mjs';
15
+ import { HarnessApprovalQueue } from '../shared/harness-approval.mjs';
16
+ import {
17
+ isModelCommand,
18
+ runModelCommand,
19
+ } from '../shared/model-command.mjs';
20
+ import {
21
+ isPresetCommand,
22
+ runPresetCommand,
23
+ } from '../shared/preset-command.mjs';
24
+ import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
25
+ import {
26
+ captureContextEnhancement,
27
+ captureContextEnhancementSource,
28
+ enhanceContextContent,
29
+ } from '../shared/context-enhancement.mjs';
30
+ import {
31
+ BatchInputManager,
32
+ batchInputBusyMessage,
33
+ batchInputGroupUnsupportedMessage,
34
+ isBatchInputCommand,
35
+ } from '../shared/batch-input.mjs';
36
+ import {
37
+ fetchImageBuffer,
38
+ hasInboundImages,
39
+ imagePromptDiagnostic,
40
+ imagePromptUserMessage,
41
+ } from '../shared/image-prompt.mjs';
42
+ import {
43
+ hasInboundFiles,
44
+ inboundFileUserMessage,
45
+ prefetchInboundFiles,
46
+ } from '../shared/inbound-file.mjs';
47
+ import {
48
+ trackOutboundArtifactProviderPromise,
49
+ } from '../shared/semantic/artifact.mjs';
50
+ import { deliverOutboundArtifacts } from '../shared/semantic/artifact-delivery.mjs';
51
+ import {
52
+ hasReplyReference,
53
+ promptContentForInboundMessage,
54
+ } from '../shared/semantic/reply-reference.mjs';
55
+ import {
56
+ createDeliveryReceipt,
57
+ providerMessageIdsFor,
58
+ } from '../shared/semantic/delivery.mjs';
59
+ import {
60
+ messageFailureDiagnostic,
61
+ channelDeliveryFailure,
62
+ clearLastMessageFailure,
63
+ messageFailureText,
64
+ setLastMessageFailure,
65
+ } from '../shared/message-failure.mjs';
66
+ import {
67
+ COMMAND_PERMISSION_DENIED_MESSAGE,
68
+ evaluateInboundAccess,
69
+ } from '../shared/inbound-access.mjs';
70
+ import { sendMarkdownReply } from './markdown-reply.mjs';
71
+ import {
72
+ isQqMenuCommand, parseQqMenuCommand, QqMenuStore,
73
+ qqMenuPage, qqMenuView, sendQqMenu,
74
+ } from './qq-menu.mjs';
75
+ import { withSessionBindingLock } from '../shared/session-binding-lock.mjs';
76
+ import { t } from '../shared/i18n.mjs';
77
+
78
+ function interactionResolvedText() {
79
+ return t('这个问题已在其他客户端处理,无需再次回答。');
80
+ }
81
+ const DEFAULT_FILE_UPLOAD_TIMEOUT_MS = 120_000;
82
+
83
+ export const QQ_IMAGE_HOSTS = Object.freeze([
84
+ '.myqcloud.com',
85
+ '.qpic.cn',
86
+ '.qq.com',
87
+ '.qq.com.cn',
88
+ '.tencentcos.com',
89
+ '.ugcimg.cn',
90
+ ]);
91
+
92
+ const QQ_IMAGE_FILENAME = /\.(?:gif|jpe?g|png|webp)$/i;
93
+
94
+ function helpText() {
95
+ return [
96
+ t('QQ 机器人已连接 DeepSeek Harness。'),
97
+ '',
98
+ t('直接发送文字、图片或文件即可继续当前会话。'),
99
+ t('/menu 或 /m 打开可点击的功能菜单'),
100
+ t('/new 开启一个全新会话'),
101
+ t('/compact 压缩当前会话的较早上下文'),
102
+ t('/history [数量] 查看最近历史消息(默认 3 条,最多 5 条)'),
103
+ t('/workspace 工作区序号或绝对路径 切换工作区'),
104
+ t('/workspacelist 列出工作区绝对路径'),
105
+ t('/ws、/wsl、/workspaces 工作区命令别名'),
106
+ t('/sessionlist 或 /sessions [工作区序号或绝对路径] 列出会话 ID 和标题'),
107
+ t('/sessionlist --limit N 仅列出当前工作区前 N 个会话'),
108
+ t('/session Session ID 或当前工作区序号 将当前聊天绑定到指定会话'),
109
+ t('/models 按序号列出所有可用模型'),
110
+ t('/reasoninglist 或 /reasonings 按序号列出当前模型可用推理等级'),
111
+ t('/reasoning [序号、等级ID或 --default] 查看或切换当前推理等级'),
112
+ t('/model [序号或完整模型ID] [推理等级ID] 查看或切换当前会话模型'),
113
+ t('示例:先发 /models,再发 /model 2 [推理等级ID]'),
114
+ t('/presetlist 或 /presets 按序号列出可用 Agent Preset'),
115
+ t('/preset [序号或完整ID] 查看或设置当前机器人 Agent Preset'),
116
+ t('纯数字 ID:/preset id:<ID>'),
117
+ t('/preset --default 跟随 Host 默认'),
118
+ t('/stop 停止当前任务'),
119
+ t('/steer 补充指令 纠偏当前任务'),
120
+ t('/batch 开始批量输入(仅私聊,最多 10 条文字)'),
121
+ t('/send 提交当前批次'),
122
+ t('/cancel 取消当前批次'),
123
+ t('/status 检查连接状态'),
124
+ t('/version 查看插件版本'),
125
+ t('/help 显示本帮助'),
126
+ ].join('\n');
127
+ }
128
+
129
+ function conversationKey(message) {
130
+ return `${message.kind}:${message.kind === 'group' ? message.groupOpenid : message.senderId}`;
131
+ }
132
+
133
+ function senderAllowed(message, ownerUserOpenid) {
134
+ return message?.kind === 'group'
135
+ || ownerUserOpenid === '*'
136
+ || message?.senderId === ownerUserOpenid;
137
+ }
138
+
139
+ function safeText(message) {
140
+ return typeof message?.content === 'string' ? message.content.trim() : '';
141
+ }
142
+
143
+ function attachmentMediaType(attachment) {
144
+ const value = nonEmptyString(attachment?.content_type ?? attachment?.contentType);
145
+ if (!value) return null;
146
+ return value.split(';', 1)[0].trim().toLowerCase();
147
+ }
148
+
149
+ function isQqImageAttachment(attachment) {
150
+ const mediaType = attachmentMediaType(attachment);
151
+ return mediaType?.startsWith('image/') === true
152
+ || QQ_IMAGE_FILENAME.test(nonEmptyString(attachment?.filename) ?? '');
153
+ }
154
+
155
+ function hasQqImageAttachments(message) {
156
+ return Array.isArray(message?.attachments)
157
+ && message.attachments.some(isQqImageAttachment);
158
+ }
159
+
160
+ function hasQqFileAttachments(message) {
161
+ return Array.isArray(message?.attachments)
162
+ && message.attachments.some((attachment) => !isQqImageAttachment(attachment));
163
+ }
164
+
165
+ function qqAttachmentKind(attachment) {
166
+ const mediaType = attachmentMediaType(attachment);
167
+ if (mediaType?.startsWith('image/')) return 'image';
168
+ if (mediaType?.startsWith('audio/')) return 'audio';
169
+ if (mediaType?.startsWith('video/')) return 'video';
170
+ return 'file';
171
+ }
172
+
173
+ function qqReplyReference(message) {
174
+ const refMsgIdx = nonEmptyString(message?.refMsgIdx);
175
+ if (!refMsgIdx) return null;
176
+ const element = Array.isArray(message?.msgElements) ? message.msgElements[0] : null;
177
+ const sourceAttachments = Array.isArray(element?.attachments) ? element.attachments : [];
178
+ const attachments = sourceAttachments.map((attachment) => {
179
+ const name = nonEmptyString(attachment?.filename);
180
+ return { kind: qqAttachmentKind(attachment), ...(name ? { name } : {}) };
181
+ });
182
+ const asrText = sourceAttachments
183
+ .filter((attachment) => qqAttachmentKind(attachment) === 'audio')
184
+ .map((attachment) => nonEmptyString(attachment?.asr_refer_text))
185
+ .filter(Boolean)
186
+ .join('\n');
187
+ const content = asrText || nonEmptyString(element?.content);
188
+ return {
189
+ messageId: refMsgIdx,
190
+ ...(content ? { content } : {}),
191
+ ...(attachments.length > 0 ? { attachments } : {}),
192
+ ...(!content && attachments.length === 0 ? { unavailableReason: 'not-delivered' } : {}),
193
+ };
194
+ }
195
+
196
+ async function fetchQqFileBuffer(url, { fetchImpl, signal }) {
197
+ const normalizedUrl = url.startsWith('//') ? `https:${url}` : url;
198
+ const response = await fetchImpl(new URL(normalizedUrl), {
199
+ method: 'GET',
200
+ signal,
201
+ redirect: 'follow',
202
+ });
203
+ if (!response?.ok) {
204
+ await response?.body?.cancel?.().catch?.(() => undefined);
205
+ throw new Error(`QQ file download failed with HTTP ${response?.status ?? 'unknown'}`);
206
+ }
207
+ return Buffer.from(await response.arrayBuffer());
208
+ }
209
+
210
+ /** Convert QQ's attachment metadata into lazily downloaded image references. */
211
+ export function qqInboundMessage(message, { fetchImpl = fetch } = {}) {
212
+ if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
213
+ const images = [];
214
+ const files = [];
215
+ for (const attachment of message?.attachments ?? []) {
216
+ const url = nonEmptyString(attachment?.url);
217
+ const name = nonEmptyString(attachment?.filename) ?? undefined;
218
+ const mediaType = attachmentMediaType(attachment);
219
+ const declaredSize = Number(attachment?.size);
220
+ if (isQqImageAttachment(attachment)) {
221
+ images.push({
222
+ ...(name ? { name } : {}),
223
+ ...(mediaType?.startsWith('image/') ? { mediaType } : {}),
224
+ ...(Number.isFinite(declaredSize) && declaredSize >= 0 ? { size: declaredSize } : {}),
225
+ load: ({ signal, maxBytes }) => {
226
+ if (!url) throw new Error('QQ image attachment has no download URL');
227
+ return fetchImageBuffer(url, {
228
+ fetchImpl,
229
+ signal,
230
+ maxBytes,
231
+ allowedHosts: QQ_IMAGE_HOSTS,
232
+ });
233
+ },
234
+ });
235
+ continue;
236
+ }
237
+ files.push({
238
+ name: name ?? (files.length === 0 ? 'file' : `file-${files.length + 1}`),
239
+ ...(mediaType?.includes('/') ? { mediaType } : {}),
240
+ ...(Number.isFinite(declaredSize) && declaredSize >= 0 ? { size: declaredSize } : {}),
241
+ load: ({ signal } = {}) => {
242
+ if (!url) throw new Error('QQ file attachment has no download URL');
243
+ return fetchQqFileBuffer(url, { fetchImpl, signal });
244
+ },
245
+ });
246
+ }
247
+ const replyTo = qqReplyReference(message);
248
+ return {
249
+ content: safeText(message),
250
+ images,
251
+ files,
252
+ ...(replyTo ? { replyTo } : {}),
253
+ };
254
+ }
255
+
256
+ function nonEmptyString(value) {
257
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
258
+ }
259
+
260
+ function artifactFailureText(fileName, error) {
261
+ const name = String(fileName ?? t('结果文件')).replace(/[\r\n]+/g, ' ').trim() || t('结果文件');
262
+ if (error?.name === 'UploadDailyLimitExceededError') {
263
+ return t('结果文件「{name}」已生成,但 QQ 今日文件上传额度已用完,请稍后重试。', { name });
264
+ }
265
+ switch (error?.code) {
266
+ case 'artifact-delivery-uncertain':
267
+ return t('结果文件「{name}」的发送结果未能确认,请先检查聊天内是否已收到,不要立即重试。', { name });
268
+ case 'artifact-permission-required':
269
+ return t('结果文件「{name}」已生成,但当前 QQ 机器人没有文件消息权限。', { name });
270
+ case 'artifact-too-large':
271
+ return t('结果文件「{name}」超过当前 QQ 机器人可发送的文件大小,未发送。', { name });
272
+ case 'artifact-empty':
273
+ return t('结果文件「{name}」为空,QQ 不允许发送空文件。', { name });
274
+ case 'artifact-changed':
275
+ case 'artifact-invalid':
276
+ case 'artifact-unavailable':
277
+ return t('结果文件「{name}」暂时无法读取或准备发送,请确认文件仍可访问后重试。', { name });
278
+ case 'artifact-rate-limited':
279
+ return t('结果文件「{name}」暂时被 QQ 限流,未能发送,请稍后重试。', { name });
280
+ case 'artifact-provider-rejected':
281
+ return t('结果文件「{name}」已生成,但 QQ 拒绝了该文件或文件消息。', { name });
282
+ default:
283
+ return t('结果文件「{name}」已生成,但暂时未能通过 QQ 发送,请稍后重试。', { name });
284
+ }
285
+ }
286
+
287
+ function answerTextForDelivery(answer, artifacts) {
288
+ if (typeof answer === 'string' && answer.trim()) return answer;
289
+ return artifacts.length > 0 ? t('结果文件已生成。') : answer;
290
+ }
291
+
292
+ function qqArtifactError(error, { dispatched = false } = {}) {
293
+ if (error?.code?.startsWith?.('artifact-')) {
294
+ return error;
295
+ }
296
+ if (error?.name === 'UploadDailyLimitExceededError') {
297
+ const wrapped = new Error('QQ daily file upload limit exceeded', { cause: error });
298
+ wrapped.name = error.name;
299
+ wrapped.code = 'artifact-rate-limited';
300
+ return wrapped;
301
+ }
302
+ const status = Number(error?.httpStatus);
303
+ const wrapped = new Error('QQ file delivery failed', { cause: error });
304
+ if (status === 401 || status === 403) wrapped.code = 'artifact-permission-required';
305
+ else if (status === 413) wrapped.code = 'artifact-too-large';
306
+ else if (status === 429) wrapped.code = 'artifact-rate-limited';
307
+ else if ([400, 404, 405, 406, 410, 415, 422].includes(status)) {
308
+ wrapped.code = 'artifact-provider-rejected';
309
+ } else {
310
+ wrapped.code = dispatched ? 'artifact-delivery-uncertain' : 'artifact-provider-failed';
311
+ }
312
+ return wrapped;
313
+ }
314
+
315
+ function abortReason(signal) {
316
+ return signal?.reason instanceof Error
317
+ ? signal.reason
318
+ : new DOMException('The operation was aborted', 'AbortError');
319
+ }
320
+
321
+ function waitWithSignal(promise, signal) {
322
+ if (!signal) return promise;
323
+ signal.throwIfAborted();
324
+ return new Promise((resolve, reject) => {
325
+ let settled = false;
326
+ const finish = (callback, value) => {
327
+ if (settled) return;
328
+ settled = true;
329
+ signal.removeEventListener('abort', onAbort);
330
+ callback(value);
331
+ };
332
+ const onAbort = () => finish(reject, abortReason(signal));
333
+ signal.addEventListener('abort', onAbort, { once: true });
334
+ Promise.resolve(promise).then(
335
+ (value) => finish(resolve, value),
336
+ (error) => finish(reject, error),
337
+ );
338
+ if (signal.aborted) onAbort();
339
+ });
340
+ }
341
+
342
+ /** Send one materialized artifact through QQ's native image message. */
343
+ export async function sendQqImage(
344
+ bot,
345
+ target,
346
+ file,
347
+ { signal, timeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS } = {},
348
+ ) {
349
+ signal?.throwIfAborted();
350
+ if (typeof bot?.sendImage !== 'function') {
351
+ const unavailable = new Error('QQ image delivery is unavailable');
352
+ unavailable.code = 'artifact-provider-unavailable';
353
+ throw unavailable;
354
+ }
355
+
356
+ try {
357
+ const timeout = AbortSignal.timeout(timeoutMs);
358
+ const waitSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
359
+ const pending = bot.sendImage(
360
+ target,
361
+ { buffer: file.bytes },
362
+ { onProgress: () => signal?.throwIfAborted() },
363
+ );
364
+ trackOutboundArtifactProviderPromise(file, pending);
365
+ return await waitWithSignal(pending, waitSignal);
366
+ } catch (error) {
367
+ if (signal?.aborted) throw abortReason(signal);
368
+ throw qqArtifactError(error, { dispatched: true });
369
+ }
370
+ }
371
+
372
+ async function sendQqFile(
373
+ bot,
374
+ target,
375
+ file,
376
+ { signal, timeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS } = {},
377
+ ) {
378
+ signal?.throwIfAborted();
379
+ if (typeof bot?.sendFile !== 'function') {
380
+ const unavailable = new Error('QQ file delivery is unavailable');
381
+ unavailable.code = 'artifact-provider-unavailable';
382
+ throw unavailable;
383
+ }
384
+
385
+ try {
386
+ const timeout = AbortSignal.timeout(timeoutMs);
387
+ const waitSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
388
+ const pending = bot.sendFile(
389
+ target,
390
+ { buffer: file.bytes },
391
+ {
392
+ fileName: file.fileName,
393
+ onProgress: () => signal?.throwIfAborted(),
394
+ },
395
+ );
396
+ trackOutboundArtifactProviderPromise(file, pending);
397
+ return await waitWithSignal(pending, waitSignal);
398
+ } catch (error) {
399
+ if (signal?.aborted) throw abortReason(signal);
400
+ throw qqArtifactError(error, { dispatched: true });
401
+ }
402
+ }
403
+
404
+ function canClaimInteractionReply(message, pending) {
405
+ return pending.questions[pending.index]
406
+ && nonEmptyString(message?.senderId) === pending.actor
407
+ && (message.kind !== 'group' || message.rawEventType === 'GROUP_AT_MESSAGE_CREATE')
408
+ && !hasQqImageAttachments(message)
409
+ && !hasQqFileAttachments(message)
410
+ && nonEmptyString(safeText(message));
411
+ }
412
+
413
+ export function createQqBridgeStatus() {
414
+ return {
415
+ messagesReceived: 0,
416
+ messagesReplied: 0,
417
+ messagesRejected: 0,
418
+ artifactsSent: 0,
419
+ artifactSendErrors: 0,
420
+ lastMessageAt: null,
421
+ lastReplyAt: null,
422
+ lastRejectedAt: null,
423
+ lastError: null,
424
+ lastMessageError: null,
425
+ };
426
+ }
427
+
428
+ export class QqHarnessBridge {
429
+ #bot;
430
+ #ownerUserOpenid;
431
+ #harness;
432
+ #state;
433
+ #deferred;
434
+ #contextEnhancement;
435
+ #accessPolicy;
436
+ #status;
437
+ #logger;
438
+ #replyTimeoutMs;
439
+ #signal;
440
+ #fetchImpl;
441
+ #fileUploadTimeoutMs;
442
+ #queues = new Map();
443
+ #pendingInteractions = new Map();
444
+ #interactionKeys = new Map();
445
+ // Keep the accepted configuration through the existing queue/reply lifecycle.
446
+ #acceptedMessageIds = new Map();
447
+ #approvalTasks = new Set();
448
+ #commandTasks = new Set();
449
+ #approvals;
450
+ #batchInputs = new BatchInputManager();
451
+ #menus = new QqMenuStore();
452
+ #menuTasks = new Map();
453
+
454
+ constructor({
455
+ bot,
456
+ ownerUserOpenid,
457
+ harness,
458
+ state,
459
+ contextEnhancement,
460
+ accessPolicy,
461
+ status = createQqBridgeStatus(),
462
+ logger = console,
463
+ replyTimeoutMs = 600_000,
464
+ signal,
465
+ fetchImpl = fetch,
466
+ fileUploadTimeoutMs = DEFAULT_FILE_UPLOAD_TIMEOUT_MS,
467
+ }) {
468
+ if (!bot || typeof bot.sendText !== 'function') throw new TypeError('QQ bot client is required');
469
+ if (!ownerUserOpenid) throw new TypeError('QQ scanner identity is required');
470
+ if (!harness || !state) throw new TypeError('Harness client and state store are required');
471
+ if (typeof fetchImpl !== 'function') throw new TypeError('fetchImpl must be a function');
472
+ if (!Number.isInteger(fileUploadTimeoutMs) || fileUploadTimeoutMs < 1) {
473
+ throw new TypeError('fileUploadTimeoutMs must be a positive integer');
474
+ }
475
+ this.#bot = bot;
476
+ this.#ownerUserOpenid = ownerUserOpenid;
477
+ this.#harness = harness;
478
+ this.#state = state;
479
+ this.#contextEnhancement = contextEnhancement;
480
+ this.#accessPolicy = accessPolicy;
481
+ this.#status = status;
482
+ this.#logger = logger;
483
+ this.#replyTimeoutMs = replyTimeoutMs;
484
+ this.#signal = signal;
485
+ this.#deferred = createDeferredDeliveryCoordinator({ harness, state, signal, logger,
486
+ deliver: (entry, outcome) => this.#deliverDeferredOutcome(entry, outcome),
487
+ });
488
+ this.#fetchImpl = fetchImpl;
489
+ this.#fileUploadTimeoutMs = Math.min(fileUploadTimeoutMs, DEFAULT_FILE_UPLOAD_TIMEOUT_MS);
490
+ this.#approvals = new HarnessApprovalQueue({ label: 'qq', logger });
491
+ }
492
+
493
+ get status() {
494
+ return structuredClone(this.#status);
495
+ }
496
+
497
+ accept(message) {
498
+ if (this.#signal?.aborted) return Promise.resolve();
499
+ const messageId = nonEmptyString(message?.messageId);
500
+ const sender = nonEmptyString(message?.senderId);
501
+ if (!messageId || !sender || message?.senderIsBot === true
502
+ || !['c2c', 'group'].includes(message?.kind)
503
+ || this.#state.hasSeen(messageId)
504
+ || this.#acceptedMessageIds.has(messageId)) return Promise.resolve();
505
+ const key = conversationKey(message);
506
+ const addressed = message.kind !== 'group'
507
+ || message.rawEventType === 'GROUP_AT_MESSAGE_CREATE';
508
+ const commandText = safeText(message);
509
+ const menuTextOnly = !hasQqImageAttachments(message) && !hasQqFileAttachments(message)
510
+ && !qqReplyReference(message);
511
+ const explicitMenu = menuTextOnly && isQqMenuCommand(commandText);
512
+ const numericMenu = menuTextOnly && /^\d{1,2}$/u.test(commandText)
513
+ && this.#menus.has(key, sender)
514
+ && !this.#pendingInteractions.has(key) && !this.#approvals.hasPending(key)
515
+ && this.#batchInputs.status(key).phase === 'idle';
516
+ const menuInput = numericMenu
517
+ ? `/m pick ${this.#menus.tokenFor(key, sender)} ${commandText}` : commandText;
518
+ if (addressed) {
519
+ const access = this.#accessPolicy
520
+ ? evaluateInboundAccess(this.#accessPolicy, {
521
+ conversationType: message.kind === 'c2c' ? 'direct' : 'group',
522
+ senderIds: sender,
523
+ text: commandText,
524
+ hasImages: hasQqImageAttachments(message),
525
+ hasFiles: hasQqFileAttachments(message),
526
+ ...(explicitMenu || numericMenu ? { isCommand: true } : {}),
527
+ })
528
+ : senderAllowed(message, this.#ownerUserOpenid)
529
+ ? { allowed: true, reason: 'legacy-owner' }
530
+ : { allowed: false, reason: 'sender-not-allowed' };
531
+ if (!access.allowed) {
532
+ this.#acceptedMessageIds.set(messageId, null);
533
+ return this.#finishAccessDecision(message, messageId, access);
534
+ }
535
+ }
536
+ this.#acceptedMessageIds.set(messageId, captureContextEnhancement(
537
+ this.#contextEnhancement,
538
+ message.kind === 'c2c' ? 'direct' : 'group',
539
+ ));
540
+ if (message.kind === 'c2c'
541
+ && (this.#ownerUserOpenid === '*' || sender === this.#ownerUserOpenid)
542
+ && message.replyTarget?.scope === 'c2c'
543
+ && nonEmptyString(message.replyTarget.targetId) === sender) {
544
+ rememberConnectionTestTarget(this.#state, message.replyTarget);
545
+ }
546
+ const pending = this.#pendingInteractions.get(key);
547
+ const batchCommand = isBatchInputCommand(commandText);
548
+ const batchStatus = this.#batchInputs.status(key);
549
+ // Ordinary prompts and other commands end number selection. A pending
550
+ // question/approval or batch keeps its existing interpretation of digits.
551
+ if (addressed && !explicitMenu && !numericMenu) this.#menus.clear(key, sender);
552
+ if (batchCommand && addressed && message.kind === 'group') {
553
+ return this.#finishBatchResult(
554
+ message,
555
+ messageId,
556
+ { message: batchInputGroupUnsupportedMessage() },
557
+ );
558
+ }
559
+ if (message.kind === 'c2c'
560
+ && (batchCommand || batchStatus.phase === 'collecting')) {
561
+ if (explicitMenu) return this.#finishBatchResult(message, messageId, {
562
+ message: t('当前正在批量输入,请先发送 /send 或 /cancel,再打开菜单。'),
563
+ });
564
+ const exactBatchStart = /^\/batch$/iu.test(commandText);
565
+ const result = exactBatchStart
566
+ && batchStatus.phase === 'idle'
567
+ && (this.#queues.has(key) || pending || this.#approvals.hasPending(key))
568
+ ? { handled: true, kind: 'busy', message: batchInputBusyMessage() }
569
+ : this.#batchInputs.handle(key, commandText, {
570
+ plainText: Boolean(commandText)
571
+ && !hasQqImageAttachments(message)
572
+ && !hasQqFileAttachments(message)
573
+ && !qqReplyReference(message),
574
+ });
575
+ if (result.handled) {
576
+ if (result.kind === 'submit') {
577
+ return this.#enqueueMessage(
578
+ {
579
+ ...message,
580
+ content: result.prompt,
581
+ // The submission is exactly the collected text: the command
582
+ // message's own attachments and quoted message are not part of it.
583
+ attachments: [],
584
+ refMsgIdx: undefined,
585
+ },
586
+ messageId,
587
+ key,
588
+ { batchSubmission: result },
589
+ );
590
+ }
591
+ return this.#finishBatchResult(message, messageId, result);
592
+ }
593
+ }
594
+ const commandRunner = explicitMenu || numericMenu
595
+ ? () => this.#runMenuCommand(message, menuInput, key)
596
+ : isHistoryCommand(commandText) ? runHistoryCommand
597
+ : hasQqFileAttachments(message) ? null : isControlCommand(commandText)
598
+ ? runControlCommand
599
+ : (isModelCommand(commandText)
600
+ ? runModelCommand
601
+ : (isPresetCommand(commandText) ? runPresetCommand : null));
602
+ if (commandRunner && addressed) {
603
+ let task;
604
+ task = this.#processFastCommand(
605
+ message,
606
+ messageId,
607
+ key,
608
+ commandText,
609
+ commandRunner,
610
+ ).catch((error) => {
611
+ if (error?.code === 'turn-stopped' || this.#signal?.aborted) return;
612
+ this.#status.lastError = error?.message ?? String(error);
613
+ const failure = setLastMessageFailure(this.#status, error);
614
+ this.#logger.error?.(
615
+ `[dsh-im:qq] failed to process a command [${failure.referenceId}]:`,
616
+ messageFailureDiagnostic(error, failure),
617
+ );
618
+ return this.#bot.sendText(message.replyTarget, messageFailureText(failure))
619
+ .catch(() => undefined);
620
+ }).finally(() => {
621
+ this.#acceptedMessageIds.delete(messageId);
622
+ this.#commandTasks.delete(task);
623
+ });
624
+ this.#commandTasks.add(task);
625
+ return task;
626
+ }
627
+ const approval = this.#approvals.claimReply({
628
+ key,
629
+ actor: sender,
630
+ messageId,
631
+ text: hasQqImageAttachments(message) || hasQqFileAttachments(message) ? '' : safeText(message),
632
+ addressed: message.kind !== 'group' || message.rawEventType === 'GROUP_AT_MESSAGE_CREATE',
633
+ hasPendingQuestion: Boolean(pending),
634
+ questionCompletion: pending?.submitting || pending?.claimedReplyMessageId
635
+ ? pending.queue
636
+ : null,
637
+ isQuestionPending: () => this.#pendingInteractions.has(key),
638
+ send: (text) => this.#bot.sendText(message.replyTarget, text),
639
+ });
640
+ if (approval) {
641
+ let task;
642
+ task = approval.process(async () => {
643
+ if (this.#state.hasSeen(messageId)) return false;
644
+ await this.#state.markSeen(messageId);
645
+ this.#status.messagesReceived += 1;
646
+ this.#status.lastMessageAt = new Date().toISOString();
647
+ return true;
648
+ })
649
+ .finally(() => {
650
+ this.#acceptedMessageIds.delete(messageId);
651
+ this.#approvalTasks.delete(task);
652
+ });
653
+ this.#approvalTasks.add(task);
654
+ return task;
655
+ }
656
+ if (pending && sender !== pending.actor) {
657
+ return this.#enqueueMessage(message, messageId, key);
658
+ }
659
+ if (pending?.submitting || pending?.claimedReplyMessageId) {
660
+ return this.#enqueueMessage(message, messageId, key);
661
+ }
662
+ if (pending) {
663
+ if (canClaimInteractionReply(message, pending)) {
664
+ pending.claimedReplyMessageId = messageId;
665
+ }
666
+ const previous = pending.queue ?? Promise.resolve();
667
+ const current = previous
668
+ .catch(() => undefined)
669
+ .then(() => this.#processInteractionReply(message, messageId, key, pending))
670
+ .catch((error) => this.#handleInteractionFailure(message, messageId, error))
671
+ .finally(() => {
672
+ this.#acceptedMessageIds.delete(messageId);
673
+ if (pending.claimedReplyMessageId === messageId) pending.claimedReplyMessageId = null;
674
+ if (pending.queue === current) pending.queue = null;
675
+ });
676
+ pending.queue = current;
677
+ return current;
678
+ }
679
+ return this.#enqueueMessage(message, messageId, key);
680
+ }
681
+
682
+ #enqueueMessage(message, messageId, key, {
683
+ releaseMessageId = true,
684
+ alreadyRecorded = false,
685
+ batchSubmission = null,
686
+ } = {}) {
687
+ const addressed = message.kind !== 'group'
688
+ || message.rawEventType === 'GROUP_AT_MESSAGE_CREATE';
689
+ const preparedMessage = addressed
690
+ ? prefetchInboundFiles(
691
+ qqInboundMessage(message, { fetchImpl: this.#fetchImpl }),
692
+ { signal: this.#signal },
693
+ )
694
+ : undefined;
695
+ const previous = this.#queues.get(key) ?? Promise.resolve();
696
+ const current = previous
697
+ .catch(() => undefined)
698
+ .then(() => this.#process(message, key, {
699
+ alreadyRecorded,
700
+ preparedMessage,
701
+ batchSubmission,
702
+ }))
703
+ .finally(() => {
704
+ if (releaseMessageId) this.#acceptedMessageIds.delete(messageId);
705
+ if (this.#queues.get(key) === current) this.#queues.delete(key);
706
+ });
707
+ this.#queues.set(key, current);
708
+ return current;
709
+ }
710
+
711
+ async #deliverDeferredOutcome(entry, outcome) {
712
+ await sendMarkdownReply(this.#bot, entry.target, deferredOutcomeText(outcome), { logger: this.#logger });
713
+ return true;
714
+ }
715
+
716
+ #menuContext(key) {
717
+ const workspace = this.#harness.currentWorkspace?.();
718
+ const sessionWorkspace = typeof this.#harness.currentConversationWorkspace === 'function'
719
+ ? this.#harness.currentConversationWorkspace(key) : workspace;
720
+ return { workspace, sessionWorkspace, sessionId: this.#state.sessionFor(key) };
721
+ }
722
+
723
+ async #showMenu(message, key, name, pageView = null) {
724
+ const actor = message.senderId;
725
+ const context = this.#menuContext(key);
726
+ const entry = this.#menus.begin(key, actor, context);
727
+ const view = pageView ?? await qqMenuView(name, this.#harness, this.#state, key, {
728
+ signal: this.#signal, busy: this.#queues.has(key)
729
+ || this.#pendingInteractions.has(key) || this.#approvals.hasPending(key),
730
+ });
731
+ this.#signal?.throwIfAborted();
732
+ this.#harness.assertWorkspaceScope?.();
733
+ const current = this.#menuContext(key);
734
+ if (current.workspace !== context.workspace || current.sessionWorkspace !== context.sessionWorkspace
735
+ || current.sessionId !== context.sessionId) {
736
+ return { message: t('会话或工作区已变化,请重新发送 /m。') };
737
+ }
738
+ if (!this.#menus.publish(key, actor, entry, view)) return { messages: [] };
739
+ await sendQqMenu(this.#bot, message.replyTarget, view, entry.token, { logger: this.#logger });
740
+ this.#status.messagesReplied += 1;
741
+ this.#status.lastReplyAt = new Date().toISOString();
742
+ return { messages: [] };
743
+ }
744
+
745
+ async #runMenuCommand(message, text, key) {
746
+ const parsed = isQqMenuCommand(text) ? parseQqMenuCommand(text) : { number: Number(text) };
747
+ if (parsed.error) return { message: t('菜单命令无效,请发送 /m 重新打开。') };
748
+ if (parsed.name) return this.#showMenu(message, key, parsed.name);
749
+ const choice = this.#menus.take(key, message.senderId, parsed.number, parsed.token, this.#menuContext(key));
750
+ if (choice.error) return { message: choice.error };
751
+ const action = choice.action;
752
+ if (action.kind === 'section') return this.#showMenu(message, key, action.name);
753
+ if (action.kind === 'page') return this.#showMenu(message, key, '', qqMenuPage(action.list, action.page));
754
+ if (action.kind === 'archive') {
755
+ await this.#state.setIncludeArchivedSessions(action.include);
756
+ return this.#showMenu(message, key, 'main');
757
+ }
758
+ const command = action.text;
759
+ const pendingInteraction = this.#pendingInteractions.has(key) || this.#approvals.hasPending(key);
760
+ const isBusy = () => this.#queues.has(key) || this.#pendingInteractions.has(key)
761
+ || this.#approvals.hasPending(key) || this.#batchInputs.status(key).phase !== 'idle';
762
+ const needsIdle = /^\/(?:new|session|workspace|compact)(?:\s|$)/u.test(command);
763
+ if (isBusy() && needsIdle) {
764
+ return { message: t('当前任务仍在运行,请先停止任务或等待任务完成后再执行此操作。') };
765
+ }
766
+ const options = { signal: this.#signal, isDirect: message.kind === 'c2c', pendingInteraction,
767
+ control: { owner: this, key }, deferredDelivery: this.#deferred,
768
+ enhancement: captureContextEnhancementSource(
769
+ this.#contextEnhancement,
770
+ message.kind === 'c2c' ? 'direct' : 'group',
771
+ () => ({
772
+ channel: 'qq',
773
+ senderId: nonEmptyString(message.senderId),
774
+ senderName: message.kind === 'group' ? message.senderName : undefined,
775
+ chatId: message.kind === 'group' ? message.groupOpenid : message.senderId,
776
+ }),
777
+ ) };
778
+ // Existing runners own all Host mutations and control authorization.
779
+ const execute = async () => {
780
+ this.#signal?.throwIfAborted();
781
+ const current = this.#menuContext(key);
782
+ if (current.workspace !== choice.context.workspace
783
+ || current.sessionWorkspace !== choice.context.sessionWorkspace
784
+ || current.sessionId !== choice.context.sessionId) {
785
+ return { message: t('会话或工作区已变化,请重新发送 /m。') };
786
+ }
787
+ // A prompt may have started while this action waited for a prior menu command.
788
+ if (needsIdle && isBusy()) return { message: t('当前任务仍在运行,请先停止任务或等待任务完成后再执行此操作。') };
789
+ if (isControlCommand(command)) return runControlCommand(command, this.#harness, this.#state, key, options);
790
+ if (isModelCommand(command)) return runModelCommand(command, this.#harness, this.#state, key, options);
791
+ if (isPresetCommand(command)) return runPresetCommand(command, this.#harness, this.#state, key, options);
792
+ if (command === '/new') return withSessionBindingLock(this.#state, key, async () => {
793
+ if (isBusy()) return { message: t('当前任务仍在运行,请先停止任务或等待任务完成后再执行此操作。') };
794
+ const locked = this.#menuContext(key);
795
+ if (locked.workspace !== choice.context.workspace
796
+ || locked.sessionWorkspace !== choice.context.sessionWorkspace
797
+ || locked.sessionId !== choice.context.sessionId) {
798
+ return { message: t('会话或工作区已变化,请重新发送 /m。') };
799
+ }
800
+ await this.#state.clearSession(key);
801
+ return { message: t('已开启新会话。请发送你的问题。') };
802
+ });
803
+ if (command === '/compact') return runCompactCommand(command, this.#harness, this.#state, key, options);
804
+ return runWorkspaceCommand(command, this.#harness, key);
805
+ };
806
+ // Stop/steer must stay available while a slower menu mutation is pending.
807
+ if (isControlCommand(command)) return execute();
808
+ const previous = this.#menuTasks.get(key) ?? Promise.resolve();
809
+ const task = previous.catch(() => undefined).then(execute);
810
+ this.#menuTasks.set(key, task);
811
+ try { return await task; }
812
+ finally { if (this.#menuTasks.get(key) === task) this.#menuTasks.delete(key); }
813
+ }
814
+
815
+ async waitForIdle() {
816
+ await Promise.allSettled([
817
+ ...this.#queues.values(),
818
+ ...[...this.#pendingInteractions.values()].flatMap((pending) => (
819
+ pending.queue ? [pending.queue] : []
820
+ )),
821
+ ...this.#approvalTasks,
822
+ ...this.#commandTasks,
823
+ ]);
824
+ await this.#deferred.whenIdle();
825
+ }
826
+
827
+ async #processFastCommand(message, messageId, key, text, runner) {
828
+ this.#signal?.throwIfAborted();
829
+ if (this.#state.hasSeen(messageId)) return;
830
+ await this.#state.markSeen(messageId);
831
+ this.#status.messagesReceived += 1;
832
+ this.#status.lastMessageAt = new Date().toISOString();
833
+ const result = await runner(text, this.#harness, this.#state, key, {
834
+ signal: this.#signal,
835
+ isDirect: message.kind === 'c2c',
836
+ hasImages: hasQqImageAttachments(message),
837
+ hasFiles: hasQqFileAttachments(message),
838
+ pendingInteraction: this.#pendingInteractions.has(key)
839
+ || this.#approvals.hasPending(key),
840
+ control: { owner: this, key },
841
+ deferredDelivery: this.#deferred,
842
+ enhancement: captureContextEnhancementSource(
843
+ this.#contextEnhancement,
844
+ message.kind === 'c2c' ? 'direct' : 'group',
845
+ () => ({
846
+ channel: 'qq',
847
+ senderId: nonEmptyString(message.senderId),
848
+ senderName: message.kind === 'group' ? message.senderName : undefined,
849
+ chatId: message.kind === 'group' ? message.groupOpenid : message.senderId,
850
+ }),
851
+ ),
852
+ });
853
+ if (result?.stopped) {
854
+ await Promise.allSettled([
855
+ this.#cancelPendingInteraction(key),
856
+ this.#approvals.closeRoute(key),
857
+ ]);
858
+ }
859
+ for (const reply of result?.messages ?? [result?.message]) {
860
+ if (reply) await this.#bot.sendText(message.replyTarget, reply);
861
+ }
862
+ this.#status.lastError = null;
863
+ }
864
+
865
+ #finishBatchResult(message, messageId, result) {
866
+ let task;
867
+ task = Promise.resolve().then(async () => {
868
+ if (this.#state.hasSeen(messageId)) return;
869
+ await this.#state.markSeen(messageId);
870
+ this.#status.messagesReceived += 1;
871
+ this.#status.lastMessageAt = new Date().toISOString();
872
+ if (result.message) await this.#bot.sendText(message.replyTarget, result.message);
873
+ this.#status.lastError = null;
874
+ }).catch(async (error) => {
875
+ if (this.#signal?.aborted) return;
876
+ this.#status.lastError = error?.message ?? String(error);
877
+ const failure = setLastMessageFailure(this.#status, error);
878
+ this.#logger.error?.(
879
+ `[dsh-im:qq] failed to process a batch input message [${failure.referenceId}]:`,
880
+ messageFailureDiagnostic(error, failure),
881
+ );
882
+ await this.#bot.sendText(message.replyTarget, messageFailureText(failure))
883
+ .catch(() => undefined);
884
+ }).finally(() => {
885
+ this.#acceptedMessageIds.delete(messageId);
886
+ this.#commandTasks.delete(task);
887
+ });
888
+ this.#commandTasks.add(task);
889
+ return task;
890
+ }
891
+
892
+ #finishAccessDecision(message, messageId, access) {
893
+ let task;
894
+ task = Promise.resolve().then(async () => {
895
+ if (this.#state.hasSeen(messageId)) return;
896
+ await this.#state.markSeen(messageId);
897
+ if (access.reason === 'command-not-allowed') {
898
+ this.#status.messagesReceived += 1;
899
+ this.#status.lastMessageAt = new Date().toISOString();
900
+ await this.#bot.sendText(message.replyTarget, t(COMMAND_PERMISSION_DENIED_MESSAGE));
901
+ this.#status.messagesReplied += 1;
902
+ this.#status.lastReplyAt = new Date().toISOString();
903
+ } else {
904
+ this.#status.messagesRejected += 1;
905
+ this.#status.lastRejectedAt = new Date().toISOString();
906
+ }
907
+ this.#status.lastError = null;
908
+ }).catch((error) => {
909
+ if (this.#signal?.aborted) return;
910
+ this.#status.lastError = error?.message ?? String(error);
911
+ this.#logger.error?.('[dsh-im:qq] failed to apply inbound access policy:', error);
912
+ }).finally(() => {
913
+ this.#acceptedMessageIds.delete(messageId);
914
+ this.#commandTasks.delete(task);
915
+ });
916
+ this.#commandTasks.add(task);
917
+ return task;
918
+ }
919
+
920
+ async #deliverArtifacts(target, replyTo, artifacts = [], baseReceipt = null) {
921
+ if (artifacts.length === 0) {
922
+ return { receipt: baseReceipt, failureNoticeVisible: false, artifactSendErrors: 0 };
923
+ }
924
+ const delivery = await deliverOutboundArtifacts({
925
+ artifacts,
926
+ baseReceipt,
927
+ deliveryId: replyTo,
928
+ aggregatePresentation: baseReceipt ? 'qq-text-and-files' : 'qq-files',
929
+ alwaysMerge: true,
930
+ channelKey: 'qq',
931
+ signal: this.#signal,
932
+ sendImage: (file) => sendQqImage(this.#bot, target, file, {
933
+ signal: this.#signal,
934
+ timeoutMs: this.#fileUploadTimeoutMs,
935
+ }),
936
+ sendFile: (file) => sendQqFile(this.#bot, target, file, {
937
+ signal: this.#signal,
938
+ timeoutMs: this.#fileUploadTimeoutMs,
939
+ }),
940
+ onFailure: (artifact, error) => setLastMessageFailure(this.#status, error, {
941
+ userMessage: artifactFailureText(artifact?.fileName, error),
942
+ reason: error?.code,
943
+ }),
944
+ sendFailureNotice: (_artifact, _error, failure) => this.#bot.sendText(
945
+ target,
946
+ messageFailureText(failure),
947
+ ),
948
+ logger: this.#logger,
949
+ });
950
+ this.#status.artifactsSent = (this.#status.artifactsSent ?? 0)
951
+ + delivery.artifactsSent;
952
+ this.#status.artifactSendErrors = (this.#status.artifactSendErrors ?? 0)
953
+ + delivery.artifactSendErrors;
954
+ return {
955
+ receipt: delivery.receipt,
956
+ failureNoticeVisible: delivery.failureNoticeVisible,
957
+ artifactSendErrors: delivery.artifactSendErrors,
958
+ };
959
+ }
960
+
961
+ async #process(message, key, {
962
+ alreadyRecorded = false,
963
+ preparedMessage,
964
+ batchSubmission = null,
965
+ } = {}) {
966
+ if (this.#signal?.aborted) return;
967
+ const messageId = nonEmptyString(message?.messageId);
968
+ const sender = nonEmptyString(message?.senderId);
969
+ if (!messageId || !sender || message.senderIsBot === true) return;
970
+ if (!['c2c', 'group'].includes(message.kind)) return;
971
+ if (!alreadyRecorded) {
972
+ if (this.#state.hasSeen(messageId)) return;
973
+ this.#status.messagesReceived += 1;
974
+ this.#status.lastMessageAt = new Date().toISOString();
975
+ }
976
+ let messageRecorded = alreadyRecorded;
977
+ const markMessageSeen = async () => {
978
+ if (messageRecorded) return;
979
+ await this.#state.markSeen(messageId);
980
+ messageRecorded = true;
981
+ };
982
+ if (message.kind === 'group' && message.rawEventType !== 'GROUP_AT_MESSAGE_CREATE') return;
983
+
984
+ const target = message.replyTarget;
985
+ const promptMessage = preparedMessage
986
+ ?? qqInboundMessage(message, { fetchImpl: this.#fetchImpl });
987
+ const text = promptMessage.content;
988
+ const hasImages = hasInboundImages(promptMessage);
989
+ const hasFiles = hasInboundFiles(promptMessage);
990
+ const hasReply = hasReplyReference(promptMessage);
991
+ let stream = null;
992
+ let batchSettled = batchSubmission === null;
993
+ try {
994
+ if (!text && !hasImages && !hasFiles && !hasReply) {
995
+ await this.#bot.sendText(target, t('目前支持文字、图片和文件消息。'));
996
+ await markMessageSeen();
997
+ return;
998
+ }
999
+ const command = text.toLowerCase();
1000
+ if (!hasImages && !hasFiles && command === '/help') {
1001
+ await this.#bot.sendText(target, helpText());
1002
+ await markMessageSeen();
1003
+ return;
1004
+ }
1005
+ if (!hasImages && !hasFiles && command === '/status') {
1006
+ await this.#harness.ensureRunning({ signal: this.#signal });
1007
+ await this.#bot.sendText(target, t('QQ 机器人与 DeepSeek Harness 连接正常。'));
1008
+ await markMessageSeen();
1009
+ return;
1010
+ }
1011
+ if (!hasImages && !hasFiles && command === '/new') {
1012
+ await this.#state.clearSession(key);
1013
+ await this.#bot.sendText(target, t('已开启新会话。请发送你的问题。'));
1014
+ await markMessageSeen();
1015
+ return;
1016
+ }
1017
+ const workspaceCommand = hasImages || hasFiles
1018
+ ? null
1019
+ : await runWorkspaceCommand(text, this.#harness, key);
1020
+ if (workspaceCommand) {
1021
+ for (const reply of workspaceCommand.messages ?? [workspaceCommand.message]) {
1022
+ await this.#bot.sendText(target, reply);
1023
+ }
1024
+ await markMessageSeen();
1025
+ return;
1026
+ }
1027
+ const compactCommand = hasImages || hasFiles
1028
+ ? null
1029
+ : await runCompactCommand(
1030
+ text,
1031
+ this.#harness,
1032
+ this.#state,
1033
+ key,
1034
+ { signal: this.#signal },
1035
+ );
1036
+ if (compactCommand) {
1037
+ await this.#bot.sendText(target, compactCommand.message);
1038
+ await markMessageSeen();
1039
+ return;
1040
+ }
1041
+
1042
+ let content = hasImages || hasReply
1043
+ ? await promptContentForInboundMessage(promptMessage, { signal: this.#signal, deferImages: true })
1044
+ : undefined;
1045
+ const snapshot = this.#acceptedMessageIds.get(messageId);
1046
+ let contextEnhanced = false;
1047
+ if (snapshot) {
1048
+ const originalContent = content ?? text;
1049
+ content = enhanceContextContent(originalContent, snapshot, () => ({
1050
+ channel: 'qq',
1051
+ senderId: sender,
1052
+ senderName: message.kind === 'group' ? message.senderName : undefined,
1053
+ chatId: message.kind === 'group' ? message.groupOpenid : message.senderId,
1054
+ }));
1055
+ contextEnhanced = content !== originalContent;
1056
+ }
1057
+ // QQ stream_messages can acknowledge a final frame without rendering it in
1058
+ // some C2C clients. Standard Markdown delivery is the reliable reply path.
1059
+ const toolErrors = [];
1060
+ let answer;
1061
+ let artifacts = [];
1062
+ try {
1063
+ // Persist consumption before handing the prompt to Harness. Provider
1064
+ // redelivery after a failed error notice must never execute it twice.
1065
+ await markMessageSeen();
1066
+ ({ answer, artifacts = [] } = await askInWorkspaceSession({
1067
+ deferredDelivery: () => ({ coordinator: this.#deferred, target: { scope: target.scope, targetId: target.targetId } }),
1068
+ harness: this.#harness,
1069
+ state: this.#state,
1070
+ key,
1071
+ text,
1072
+ content,
1073
+ titleText: batchSubmission?.title,
1074
+ sourceGuidance: snapshot?.config?.guidance,
1075
+ contextEnhanced,
1076
+ createOptions: { signal: this.#signal },
1077
+ existsOptions: { signal: this.#signal },
1078
+ askOptions: {
1079
+ timeoutMs: this.#replyTimeoutMs,
1080
+ signal: this.#signal,
1081
+ control: { owner: this, key },
1082
+ progressMode: 'all',
1083
+ onUpdate: (update) => {
1084
+ if (update.error) {
1085
+ const name = (nonEmptyString(update.toolName) ?? t('工具'))
1086
+ .replace(/[\r\n]+/gu, ' ')
1087
+ .slice(0, 80);
1088
+ toolErrors.push(t(
1089
+ '工具调用「{name}」未成功,请检查工具配置或稍后重试。',
1090
+ { name },
1091
+ ));
1092
+ }
1093
+ },
1094
+ onInteraction: (interaction) => this.#handleInteraction(interaction, {
1095
+ key,
1096
+ actor: sender,
1097
+ target,
1098
+ requiresMention: message.kind === 'group',
1099
+ }),
1100
+ onInteractionResolved: (resolution) => this.#handleInteractionResolved(resolution),
1101
+ files: promptMessage.files,
1102
+ images: promptMessage.images,
1103
+ },
1104
+ }));
1105
+ if (batchSubmission) {
1106
+ this.#batchInputs.complete(key, batchSubmission.token);
1107
+ batchSettled = true;
1108
+ }
1109
+ } finally {
1110
+ await Promise.allSettled([
1111
+ this.#cancelPendingInteraction(key),
1112
+ this.#approvals.closeRoute(key),
1113
+ ]);
1114
+ }
1115
+ this.#signal?.throwIfAborted();
1116
+ const answerText = answerTextForDelivery(answer, artifacts);
1117
+ const displayAnswer = toolErrors.length > 0
1118
+ ? `${answerText}\n\n---\n\n${toolErrors.join('\n\n')}`
1119
+ : answerText;
1120
+ let textReceipt = null;
1121
+ let textSendError = null;
1122
+ try {
1123
+ let streamFinished = false;
1124
+ if (stream) {
1125
+ try {
1126
+ await stream.update(displayAnswer);
1127
+ streamFinished = true;
1128
+ textReceipt = createDeliveryReceipt({
1129
+ deliveryId: messageId,
1130
+ presentation: 'qq-text',
1131
+ providerMessageIds: providerMessageIdsFor(stream),
1132
+ });
1133
+ try {
1134
+ await stream.complete();
1135
+ } catch (error) {
1136
+ this.#logger.warn?.('[dsh-im:qq] QQ stream completion failed after visible final content:', error);
1137
+ }
1138
+ } catch (error) {
1139
+ stream.cancel?.();
1140
+ this.#logger.warn?.('[dsh-im:qq] QQ stream update failed; using markdown fallback:', error);
1141
+ }
1142
+ }
1143
+ if (!streamFinished) {
1144
+ const deliveries = await sendMarkdownReply(this.#bot, target, displayAnswer, {
1145
+ logger: this.#logger,
1146
+ });
1147
+ textReceipt = createDeliveryReceipt({
1148
+ deliveryId: messageId,
1149
+ presentation: 'qq-text',
1150
+ providerMessageIds: deliveries.flatMap((delivery) => providerMessageIdsFor(delivery)),
1151
+ });
1152
+ }
1153
+ } catch (error) {
1154
+ textSendError = channelDeliveryFailure(error);
1155
+ this.#logger.warn?.('[dsh-im:qq] final text delivery failed; continuing with result files:', error);
1156
+ }
1157
+ const delivery = await this.#deliverArtifacts(target, messageId, artifacts, textReceipt);
1158
+ const artifactDispatched = delivery.receipt?.artifacts?.some(
1159
+ ({ outcome }) => outcome === 'sent' || outcome === 'unknown',
1160
+ );
1161
+ if (textSendError && !artifactDispatched && !delivery.failureNoticeVisible) {
1162
+ throw textSendError;
1163
+ }
1164
+ if (textSendError && delivery.artifactSendErrors === 0) {
1165
+ setLastMessageFailure(this.#status, textSendError);
1166
+ }
1167
+ this.#status.messagesReplied += 1;
1168
+ this.#status.lastReplyAt = new Date().toISOString();
1169
+ this.#status.lastError = null;
1170
+ if (!textSendError && delivery.artifactSendErrors === 0) {
1171
+ clearLastMessageFailure(this.#status);
1172
+ }
1173
+ return delivery.receipt;
1174
+ } catch (error) {
1175
+ let batchFailureMessage = null;
1176
+ if (!batchSettled && batchSubmission) {
1177
+ if (error?.code === 'turn-stopped') {
1178
+ this.#batchInputs.complete(key, batchSubmission.token);
1179
+ } else {
1180
+ batchFailureMessage = this.#batchInputs.fail(key, batchSubmission.token).message ?? null;
1181
+ }
1182
+ batchSettled = true;
1183
+ }
1184
+ if (error?.code === 'turn-stopped') {
1185
+ try {
1186
+ stream?.cancel?.();
1187
+ } catch (streamError) {
1188
+ this.#logger.warn?.('[dsh-im:qq] unable to cancel a stopped QQ stream:', streamError);
1189
+ }
1190
+ try {
1191
+ await this.#bot.sendText(target, t('已停止。'));
1192
+ } catch (sendError) {
1193
+ this.#logger.warn?.('[dsh-im:qq] unable to announce a stopped QQ turn:', sendError);
1194
+ }
1195
+ await markMessageSeen();
1196
+ return;
1197
+ }
1198
+ try {
1199
+ stream?.cancel?.();
1200
+ } catch (streamError) {
1201
+ this.#logger.warn?.('[dsh-im:qq] unable to cancel a failed QQ stream:', streamError);
1202
+ }
1203
+ if (this.#signal?.aborted) return;
1204
+ this.#status.lastError = error?.message ?? String(error);
1205
+ const userMessage = inboundFileUserMessage(error)
1206
+ ?? imagePromptUserMessage(error);
1207
+ const failure = setLastMessageFailure(this.#status, error, {
1208
+ userMessage,
1209
+ reason: imagePromptDiagnostic(error)?.reason,
1210
+ });
1211
+ this.#logger.error?.(
1212
+ `[dsh-im:qq] failed to process an inbound message [${failure.referenceId}]:`,
1213
+ messageFailureDiagnostic(error, failure),
1214
+ );
1215
+ try {
1216
+ const errorMessage = messageFailureText(failure);
1217
+ await this.#bot.sendText(
1218
+ target,
1219
+ batchFailureMessage ? `${errorMessage}\n\n${batchFailureMessage}` : errorMessage,
1220
+ );
1221
+ await markMessageSeen();
1222
+ } catch (sendError) {
1223
+ this.#logger.error?.('[dsh-im:qq] failed to send the safe error reply:', sendError);
1224
+ }
1225
+ }
1226
+ }
1227
+
1228
+ async #processInteractionReply(message, messageId, key, expected) {
1229
+ this.#signal?.throwIfAborted();
1230
+ const current = this.#pendingInteractions.get(key);
1231
+ const claimed = expected.claimedReplyMessageId === messageId;
1232
+ if (!current || current !== expected || current.submitting) {
1233
+ if (claimed && (!current || current !== expected)) {
1234
+ return this.#discardResolvedInteractionReply(message, messageId);
1235
+ }
1236
+ return this.#enqueueMessage(message, messageId, key, { releaseMessageId: false });
1237
+ }
1238
+ if (this.#state.hasSeen(messageId)) return;
1239
+ await this.#state.markSeen(messageId);
1240
+ this.#status.messagesReceived += 1;
1241
+ this.#status.lastMessageAt = new Date().toISOString();
1242
+
1243
+ if (message.kind === 'group' && message.rawEventType !== 'GROUP_AT_MESSAGE_CREATE') return;
1244
+ const text = nonEmptyString(safeText(message));
1245
+ if (!text || hasQqImageAttachments(message) || hasQqFileAttachments(message)) {
1246
+ await this.#bot.sendText(message.replyTarget, t('请用文字回答当前问题。'));
1247
+ return;
1248
+ }
1249
+
1250
+ const pending = this.#pendingInteractions.get(key);
1251
+ if (!pending || pending !== expected || pending.submitting) {
1252
+ if (claimed && (!pending || pending !== expected)) {
1253
+ await this.#bot.sendText(message.replyTarget, interactionResolvedText());
1254
+ return;
1255
+ }
1256
+ return this.#enqueueMessage(message, messageId, key, {
1257
+ releaseMessageId: false,
1258
+ alreadyRecorded: true,
1259
+ });
1260
+ }
1261
+ pending.target = message.replyTarget;
1262
+ if (pending.needsPresentation) {
1263
+ try {
1264
+ await this.#presentInteraction(pending);
1265
+ } catch {
1266
+ this.#status.lastError = t('QQ 交互问题发送失败。');
1267
+ this.#logger.error?.('[dsh-im:qq] failed to retry an interaction question');
1268
+ pending.interaction.reconnect?.();
1269
+ return;
1270
+ }
1271
+ const presentedPending = this.#pendingInteractions.get(key);
1272
+ if (!presentedPending || presentedPending !== expected || presentedPending.submitting) {
1273
+ if (claimed && (!presentedPending || presentedPending !== expected)) {
1274
+ await this.#bot.sendText(message.replyTarget, interactionResolvedText())
1275
+ .catch(() => undefined);
1276
+ return;
1277
+ }
1278
+ return this.#enqueueMessage(message, messageId, key, {
1279
+ releaseMessageId: false,
1280
+ alreadyRecorded: true,
1281
+ });
1282
+ }
1283
+ }
1284
+
1285
+ const question = pending.questions[pending.index];
1286
+ if (!question) return;
1287
+ pending.answers.push(harnessAnswerForQuestion(question, text));
1288
+ pending.index += 1;
1289
+ if (pending.index < pending.questions.length) {
1290
+ if (pending.claimedReplyMessageId === messageId) {
1291
+ pending.claimedReplyMessageId = null;
1292
+ }
1293
+ pending.needsPresentation = true;
1294
+ try {
1295
+ await this.#presentInteraction(pending);
1296
+ } catch {
1297
+ this.#status.lastError = t('QQ 交互问题发送失败。');
1298
+ this.#logger.error?.('[dsh-im:qq] failed to send the next interaction question');
1299
+ pending.interaction.reconnect?.();
1300
+ }
1301
+ return;
1302
+ }
1303
+
1304
+ pending.submitting = true;
1305
+ try {
1306
+ await pending.interaction.respond({
1307
+ ok: true,
1308
+ value: {
1309
+ sessionId: pending.sessionId,
1310
+ answer: { answers: pending.answers },
1311
+ },
1312
+ });
1313
+ this.#clearPendingInteraction(key, pending.interactionId);
1314
+ this.#status.lastError = null;
1315
+ } catch (error) {
1316
+ if (this.#signal?.aborted) return;
1317
+ if (error?.code === 'interaction-not-pending') {
1318
+ this.#clearPendingInteraction(key, pending.interactionId);
1319
+ await this.#bot.sendText(pending.target, interactionResolvedText()).catch(() => undefined);
1320
+ return;
1321
+ }
1322
+ if (this.#pendingInteractions.get(key) !== pending) return;
1323
+ pending.submitting = false;
1324
+ pending.answers.pop();
1325
+ pending.index -= 1;
1326
+ this.#status.lastError = t('回答提交失败。');
1327
+ this.#logger.error?.('[dsh-im:qq] failed to answer a Harness interaction');
1328
+ await this.#bot.sendText(pending.target, t('回答提交失败,请重新发送当前问题的答案。'))
1329
+ .catch(() => undefined);
1330
+ }
1331
+ }
1332
+
1333
+ async #handleInteraction(interaction, {
1334
+ key,
1335
+ actor,
1336
+ target,
1337
+ requiresMention,
1338
+ }) {
1339
+ if (interaction?.kind === 'approval') {
1340
+ return this.#approvals.handleRequested(interaction, {
1341
+ key,
1342
+ actor,
1343
+ requiresMention,
1344
+ send: (text) => this.#bot.sendText(target, text),
1345
+ });
1346
+ }
1347
+ if (interaction?.kind !== 'question') return;
1348
+ const questions = interaction?.payload?.questions;
1349
+ const interactionId = typeof interaction?.interactionId === 'string'
1350
+ ? interaction.interactionId
1351
+ : interaction?.rpcId;
1352
+ if (typeof interaction?.rpcId !== 'string'
1353
+ || typeof interactionId !== 'string'
1354
+ || typeof interaction.sessionId !== 'string'
1355
+ || !Array.isArray(questions)
1356
+ || questions.length === 0
1357
+ || questions.some((question) => !validHarnessQuestion(question))) {
1358
+ this.#logger.warn?.('[dsh-im:qq] ignored an invalid Harness question interaction');
1359
+ return;
1360
+ }
1361
+
1362
+ if (interaction.recovered === true) {
1363
+ await interaction.respond({
1364
+ ok: false,
1365
+ error: {
1366
+ code: 'cancelled',
1367
+ message: 'QQ safely cancelled an interaction left by an earlier client.',
1368
+ details: {},
1369
+ },
1370
+ });
1371
+ await this.#bot.sendText(
1372
+ target,
1373
+ t('检测到这个 Session 中遗留的待回答问题,已安全取消并继续处理你刚才的消息。'),
1374
+ ).catch(() => undefined);
1375
+ return;
1376
+ }
1377
+
1378
+ const existing = this.#pendingInteractions.get(key);
1379
+ if (existing?.interactionId === interactionId) {
1380
+ existing.interaction = interaction;
1381
+ if (existing.needsPresentation) await this.#presentInteraction(existing);
1382
+ return;
1383
+ }
1384
+ if (this.#interactionKeys.has(interactionId)) return;
1385
+ if (existing) {
1386
+ await interaction.respond({
1387
+ ok: false,
1388
+ error: {
1389
+ code: 'cancelled',
1390
+ message: 'QQ is already handling another user interaction.',
1391
+ details: {},
1392
+ },
1393
+ });
1394
+ return;
1395
+ }
1396
+
1397
+ const pending = {
1398
+ kind: 'question',
1399
+ interactionId,
1400
+ sessionId: interaction.sessionId,
1401
+ interaction,
1402
+ actor,
1403
+ requiresMention,
1404
+ questions,
1405
+ answers: [],
1406
+ index: 0,
1407
+ target,
1408
+ queue: null,
1409
+ claimedReplyMessageId: null,
1410
+ presentationPromise: null,
1411
+ submitting: false,
1412
+ needsPresentation: true,
1413
+ };
1414
+ this.#pendingInteractions.set(key, pending);
1415
+ this.#interactionKeys.set(interactionId, key);
1416
+ await this.#presentInteraction(pending);
1417
+ }
1418
+
1419
+ async #handleInteractionResolved(resolution) {
1420
+ if (resolution?.kind === 'approval') {
1421
+ await this.#approvals.handleResolved(resolution);
1422
+ return;
1423
+ }
1424
+ const interactionId = resolution?.interactionId;
1425
+ if (resolution?.kind !== 'question' || typeof interactionId !== 'string') return;
1426
+ const key = this.#interactionKeys.get(interactionId);
1427
+ if (!key) return;
1428
+ this.#clearPendingInteraction(key, interactionId);
1429
+ }
1430
+
1431
+ #presentInteraction(pending) {
1432
+ if (!pending.needsPresentation) return Promise.resolve();
1433
+ if (pending.presentationPromise) return pending.presentationPromise;
1434
+ const question = pending.questions[pending.index];
1435
+ if (!question) return Promise.resolve();
1436
+ const presentation = this.#bot.sendText(
1437
+ pending.target,
1438
+ harnessQuestionText(
1439
+ question,
1440
+ pending.index,
1441
+ pending.questions.length,
1442
+ { requiresMention: pending.requiresMention },
1443
+ ),
1444
+ ).then(() => {
1445
+ pending.needsPresentation = false;
1446
+ }).finally(() => {
1447
+ if (pending.presentationPromise === presentation) pending.presentationPromise = null;
1448
+ });
1449
+ pending.presentationPromise = presentation;
1450
+ return presentation;
1451
+ }
1452
+
1453
+ async #discardResolvedInteractionReply(message, messageId) {
1454
+ if (this.#state.hasSeen(messageId)) return;
1455
+ await this.#state.markSeen(messageId);
1456
+ this.#status.messagesReceived += 1;
1457
+ this.#status.lastMessageAt = new Date().toISOString();
1458
+ await this.#bot.sendText(message.replyTarget, interactionResolvedText()).catch(() => undefined);
1459
+ }
1460
+
1461
+ #takePendingInteraction(key, interactionId) {
1462
+ const pending = this.#pendingInteractions.get(key);
1463
+ if (!pending
1464
+ || (interactionId !== undefined && pending.interactionId !== interactionId)) return null;
1465
+ this.#pendingInteractions.delete(key);
1466
+ this.#interactionKeys.delete(pending.interactionId);
1467
+ return pending;
1468
+ }
1469
+
1470
+ #clearPendingInteraction(key, interactionId) {
1471
+ return this.#takePendingInteraction(key, interactionId) !== null;
1472
+ }
1473
+
1474
+ async #cancelPendingInteraction(key) {
1475
+ const pending = this.#takePendingInteraction(key);
1476
+ if (!pending || pending.kind !== 'question') return;
1477
+ try {
1478
+ await pending.interaction.respond({
1479
+ ok: false,
1480
+ error: {
1481
+ code: 'cancelled',
1482
+ message: 'The QQ interaction ended before the user answered.',
1483
+ details: {},
1484
+ },
1485
+ }, { signal: AbortSignal.timeout(5_000) });
1486
+ } catch (error) {
1487
+ if (error?.code !== 'interaction-not-pending') {
1488
+ this.#logger.warn?.('[dsh-im:qq] failed to cancel a pending Harness interaction');
1489
+ }
1490
+ }
1491
+ }
1492
+
1493
+ async #handleInteractionFailure(message, messageId, error) {
1494
+ if (this.#signal?.aborted) return;
1495
+ this.#status.lastError = error?.message ?? String(error);
1496
+ const failure = setLastMessageFailure(this.#status, error);
1497
+ this.#logger.error?.(
1498
+ `[dsh-im:qq] failed to process an interaction reply [${failure.referenceId}]:`,
1499
+ messageFailureDiagnostic(error, failure),
1500
+ );
1501
+ if (!this.#state.hasSeen(messageId)) {
1502
+ await this.#state.markSeen(messageId).catch(() => undefined);
1503
+ }
1504
+ await this.#bot.sendText(message.replyTarget, messageFailureText(failure))
1505
+ .catch(() => undefined);
1506
+ }
1507
+ }