@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,1091 @@
1
+ import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
2
+ import { createEditableMessageStream, splitMessageText } from '../shared/editable-message-stream.mjs';
3
+ import { fetchFileStream } from '../shared/file-download.mjs';
4
+ import { fetchImageBuffer } from '../shared/image-prompt.mjs';
5
+ import { t } from '../shared/i18n.mjs';
6
+ import { captureContextEnhancement } from '../shared/context-enhancement.mjs';
7
+ import { evaluateInboundAccess } from '../shared/inbound-access.mjs';
8
+ import { externalAttachments, readExternalFile, replyExternalFile } from './external-files.mjs';
9
+ import { DiscordApi } from './discord-api.mjs';
10
+ import { createDiscordHistoryReader } from './history-reader.mjs';
11
+ import { createDiscordBridgeStatus, DiscordHarnessBridge } from './discord-bridge.mjs';
12
+ import { discordRefusal, verifiedDiscordAccount, discordMessageContentAllowed, inspectDiscordSourceChannel, normalizeDiscordExternalText,
13
+ qualifyDiscordReply, sendDiscordReply, sendDiscordCheckedText } from './external-consumer.mjs';
14
+
15
+ const DISCORD_GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15);
16
+ const THREAD_RECOVERY_TIMEOUT_MS = 5_000;
17
+ const RECONNECT_DELAYS_MS = Object.freeze([1_000, 3_000, 5_000, 10_000, 30_000]);
18
+ const GUILD_TEXT = 0;
19
+ const GUILD_ANNOUNCEMENT = 5;
20
+ const ANNOUNCEMENT_THREAD = 10;
21
+ const PUBLIC_THREAD = 11;
22
+ const PRIVATE_THREAD = 12;
23
+ const THREAD_TYPES = new Set([ANNOUNCEMENT_THREAD, PUBLIC_THREAD, PRIVATE_THREAD]);
24
+ const IMAGE_MEDIA_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
25
+ const IMAGE_FILE_TYPES = new Map([
26
+ ['.jpg', 'image/jpeg'],
27
+ ['.jpeg', 'image/jpeg'],
28
+ ['.png', 'image/png'],
29
+ ['.webp', 'image/webp'],
30
+ ['.gif', 'image/gif'],
31
+ ]);
32
+ const DISCORD_IMAGE_HOSTS = Object.freeze(['cdn.discordapp.com']);
33
+
34
+ function socketUrl(value) {
35
+ const url = new URL(value);
36
+ if (url.protocol !== 'wss:') throw new Error('Discord returned an insecure Gateway URL');
37
+ url.searchParams.set('v', '10');
38
+ url.searchParams.set('encoding', 'json');
39
+ return url.href;
40
+ }
41
+
42
+ function addSocketListener(socket, event, listener) {
43
+ if (typeof socket.addEventListener === 'function') socket.addEventListener(event, listener);
44
+ else if (typeof socket.on === 'function') socket.on(event, listener);
45
+ else throw new TypeError('Discord WebSocket does not support events');
46
+ }
47
+
48
+ function eventData(event) {
49
+ if (typeof event === 'string') return event;
50
+ if (typeof event?.data === 'string') return event.data;
51
+ if (Buffer.isBuffer(event)) return event.toString('utf8');
52
+ if (Buffer.isBuffer(event?.data)) return event.data.toString('utf8');
53
+ return null;
54
+ }
55
+
56
+ function gatewayCloseError(code) {
57
+ if (code === 4004) {
58
+ const error = new Error(t('Discord Bot Token 无效,请重新填写。'));
59
+ error.code = 'discord-401';
60
+ return error;
61
+ }
62
+ if (code === 4013 || code === 4014) {
63
+ const error = new Error(t('Discord Gateway Intents 配置不正确,请检查 Developer Portal 的 Bot 设置。'));
64
+ error.code = 'discord-intents';
65
+ return error;
66
+ }
67
+ const error = new Error(`Discord Gateway closed (${code || 'unknown'})`);
68
+ error.code = 'discord-gateway-closed';
69
+ return error;
70
+ }
71
+
72
+ function stripBotMention(text, botId) {
73
+ if (typeof text !== 'string') return '';
74
+ return text
75
+ .split(`<@${botId}>`).join('')
76
+ .split(`<@!${botId}>`).join('')
77
+ .trim();
78
+ }
79
+
80
+ function cleanThreadName(message, botId) {
81
+ const name = stripBotMention(message?.content ?? '', botId).replace(/\s+/g, ' ').trim()
82
+ || 'DeepSeek Harness';
83
+ return [...name].slice(0, 100).join('');
84
+ }
85
+
86
+ function isThreadChannel(channel) {
87
+ return THREAD_TYPES.has(Number(channel?.type));
88
+ }
89
+
90
+ function isThreadFromMessage(channel, message) {
91
+ return isThreadChannel(channel)
92
+ && String(channel?.id ?? '') === String(message?.id ?? '')
93
+ && String(channel?.parent_id ?? '') === String(message?.channel_id ?? '');
94
+ }
95
+
96
+ function rememberChannel(channel, callback) {
97
+ if (channel?.id) callback?.(channel);
98
+ return channel;
99
+ }
100
+
101
+ function withConversationRoute(normalized, channel, botId, {
102
+ fromSourceMessage = false,
103
+ fallback = null,
104
+ notice = null,
105
+ } = {}) {
106
+ const channelId = String(channel?.id ?? normalized.conversationId);
107
+ const thread = isThreadChannel(channel);
108
+ const managed = thread && String(channel?.owner_id ?? '') === String(botId);
109
+ const parentId = thread && channel?.parent_id ? String(channel.parent_id) : channelId;
110
+ return {
111
+ ...normalized,
112
+ conversationId: channelId,
113
+ addressed: normalized.addressed || managed,
114
+ requiresMention: thread ? !managed : normalized.kind === 'group',
115
+ replyTarget: {
116
+ channelId,
117
+ ...(!fromSourceMessage && normalized.replyTarget?.replyToMessageId
118
+ ? { replyToMessageId: normalized.replyTarget.replyToMessageId }
119
+ : {}),
120
+ ...(notice ? { notice } : {}),
121
+ },
122
+ connectionTestTarget: { channelId },
123
+ conversationRoute: {
124
+ peerId: parentId,
125
+ ...(thread ? { threadId: channelId, managed } : {}),
126
+ ...(fallback ? { fallback } : {}),
127
+ },
128
+ };
129
+ }
130
+
131
+ function uncertainThreadCreate(error) {
132
+ const status = Number(error?.status);
133
+ return !Number.isInteger(status) || status >= 500;
134
+ }
135
+
136
+ function threadCreateUncertain(cause) {
137
+ const error = new Error('Discord Thread creation result is uncertain', { cause });
138
+ error.code = 'discord-thread-create-uncertain';
139
+ return error;
140
+ }
141
+
142
+ async function findCreatedThread(api, message, { signal, onChannel } = {}) {
143
+ try {
144
+ const channel = rememberChannel(await api.getChannel({
145
+ channelId: String(message.id),
146
+ signal,
147
+ }), onChannel);
148
+ return isThreadFromMessage(channel, message) ? channel : null;
149
+ } catch (error) {
150
+ if (error?.status === 404) return null;
151
+ throw error;
152
+ }
153
+ }
154
+
155
+ async function sendThreadUncertainNotice(api, normalized, signal) {
156
+ try {
157
+ await api.createMessage({
158
+ channelId: normalized.replyTarget.channelId,
159
+ replyToMessageId: normalized.replyTarget.replyToMessageId,
160
+ content: t('Thread 创建结果暂时无法确认。若已创建,请在对应 Thread 中重试;若未创建,请稍后重新 @机器人。'),
161
+ signal,
162
+ });
163
+ } catch (error) {
164
+ if (signal?.aborted) throw signal.reason ?? error;
165
+ }
166
+ }
167
+
168
+ function attachmentMediaType(attachment) {
169
+ const value = typeof attachment?.content_type === 'string'
170
+ ? attachment.content_type.split(';', 1)[0].trim().toLowerCase() : '';
171
+ if (IMAGE_MEDIA_TYPES.has(value)) return value;
172
+ const filename = typeof attachment?.filename === 'string' ? attachment.filename.toLowerCase() : '';
173
+ for (const [extension, mediaType] of IMAGE_FILE_TYPES) {
174
+ if (filename.endsWith(extension)) return mediaType;
175
+ }
176
+ return null;
177
+ }
178
+
179
+ function attachmentSize(value) {
180
+ return Number.isSafeInteger(value) && value >= 0 ? value : undefined;
181
+ }
182
+
183
+ function discordImageSource(attachment, fetchImpl) {
184
+ const mediaType = attachmentMediaType(attachment);
185
+ if (!mediaType || typeof attachment?.url !== 'string') return null;
186
+ return {
187
+ name: typeof attachment.filename === 'string' ? attachment.filename : undefined,
188
+ mediaType,
189
+ size: attachmentSize(attachment.size),
190
+ load: (options) => fetchImageBuffer(attachment.url, {
191
+ ...options,
192
+ fetchImpl,
193
+ allowedHosts: DISCORD_IMAGE_HOSTS,
194
+ }),
195
+ };
196
+ }
197
+
198
+ function discordFileSource(attachment, fetchImpl) {
199
+ if (attachmentMediaType(attachment) || typeof attachment?.url !== 'string' || !attachment.url) {
200
+ return null;
201
+ }
202
+ const mediaType = typeof attachment.content_type === 'string' && attachment.content_type
203
+ ? attachment.content_type.split(';', 1)[0].trim().toLowerCase() : undefined;
204
+ return {
205
+ name: typeof attachment.filename === 'string' && attachment.filename
206
+ ? attachment.filename : String(attachment.id ?? 'discord-file'),
207
+ ...(mediaType ? { mediaType } : {}),
208
+ size: attachmentSize(attachment.size),
209
+ load: ({ signal } = {}) => fetchFileStream(attachment.url, {
210
+ fetchImpl,
211
+ signal,
212
+ allowedHosts: DISCORD_IMAGE_HOSTS,
213
+ }),
214
+ };
215
+ }
216
+
217
+ function discordReplyAttachment(attachment) {
218
+ if (!attachment || typeof attachment !== 'object') return null;
219
+ const mediaType = typeof attachment.content_type === 'string'
220
+ ? attachment.content_type.split(';', 1)[0].trim().toLowerCase() : '';
221
+ const kind = mediaType.startsWith('image/') ? 'image'
222
+ : mediaType.startsWith('audio/') ? 'audio'
223
+ : mediaType.startsWith('video/') ? 'video' : 'file';
224
+ const name = typeof attachment.filename === 'string' && attachment.filename
225
+ ? attachment.filename : undefined;
226
+ return { kind, ...(name ? { name } : {}) };
227
+ }
228
+
229
+ function discordReplySnapshot(message, fallbackMessageId) {
230
+ if (!message || typeof message !== 'object') return null;
231
+ const messageId = typeof message.id === 'string' && message.id
232
+ ? message.id : fallbackMessageId;
233
+ const authorId = typeof message.author?.id === 'string' && message.author.id
234
+ ? message.author.id : undefined;
235
+ const authorName = [message.member?.nick, message.author?.global_name, message.author?.username]
236
+ .find((value) => typeof value === 'string' && value.trim());
237
+ const attachments = Array.isArray(message.attachments)
238
+ ? message.attachments.map(discordReplyAttachment).filter(Boolean)
239
+ : [];
240
+ if (Array.isArray(message.sticker_items)) {
241
+ attachments.push(...message.sticker_items.map((sticker) => ({
242
+ kind: 'image',
243
+ ...(typeof sticker?.name === 'string' && sticker.name ? { name: sticker.name } : {}),
244
+ })));
245
+ }
246
+ return {
247
+ ...(messageId ? { messageId: String(messageId) } : {}),
248
+ ...(authorId ? { authorId } : {}),
249
+ ...(authorName ? { authorName } : {}),
250
+ content: typeof message.content === 'string' ? message.content : '',
251
+ attachments,
252
+ };
253
+ }
254
+
255
+ function discordReplyReference(message, loadReply) {
256
+ const channelId = String(message?.channel_id ?? '');
257
+ const referenceId = typeof message?.message_reference?.message_id === 'string'
258
+ && message.message_reference.message_id
259
+ ? message.message_reference.message_id : undefined;
260
+ const referenceChannelId = message?.message_reference?.channel_id;
261
+ if (referenceChannelId !== undefined && String(referenceChannelId) !== channelId) {
262
+ return {
263
+ ...(referenceId ? { messageId: referenceId } : {}),
264
+ unavailableReason: 'not-found',
265
+ };
266
+ }
267
+ if (Object.hasOwn(message ?? {}, 'referenced_message')) {
268
+ if (message.referenced_message === null) {
269
+ return {
270
+ ...(referenceId ? { messageId: referenceId } : {}),
271
+ unavailableReason: 'deleted',
272
+ };
273
+ }
274
+ if (message.referenced_message && typeof message.referenced_message === 'object') {
275
+ const snapshotId = typeof message.referenced_message.id === 'string'
276
+ && message.referenced_message.id ? message.referenced_message.id : undefined;
277
+ if (String(message.referenced_message.channel_id ?? '') !== channelId
278
+ || !snapshotId || (referenceId && snapshotId !== referenceId)) {
279
+ return {
280
+ ...(referenceId ? { messageId: referenceId } : {}),
281
+ unavailableReason: 'not-found',
282
+ };
283
+ }
284
+ return discordReplySnapshot(message.referenced_message, referenceId) ?? undefined;
285
+ }
286
+ }
287
+ if (!referenceId) return undefined;
288
+ if (typeof loadReply !== 'function') {
289
+ return { messageId: referenceId, unavailableReason: 'not-delivered' };
290
+ }
291
+ return {
292
+ messageId: referenceId,
293
+ load: async ({ signal } = {}) => {
294
+ const referenced = await loadReply({ channelId, messageId: referenceId, signal });
295
+ if (!referenced || String(referenced.id ?? '') !== referenceId
296
+ || String(referenced.channel_id ?? '') !== channelId) return null;
297
+ return discordReplySnapshot(referenced, referenceId);
298
+ },
299
+ };
300
+ }
301
+
302
+ export function normalizeDiscordMessage(message, botId, {
303
+ fetchImpl = fetch,
304
+ loadReply,
305
+ } = {}) {
306
+ if (!message?.id || !message?.channel_id || !message?.author?.id
307
+ || Number(message.type) === 21) return null;
308
+ const direct = !message.guild_id;
309
+ const addressed = direct
310
+ || message.mentions?.some((mention) => String(mention?.id) === String(botId));
311
+ const replyTo = discordReplyReference(message, loadReply);
312
+ return {
313
+ messageId: String(message.id),
314
+ senderId: String(message.author.id),
315
+ contextSource: () => ({
316
+ senderName: [message.member?.nick, message.author.global_name, message.author.username]
317
+ .find((value) => typeof value === 'string' && value.trim()),
318
+ }),
319
+ senderIsBot: message.author.bot === true,
320
+ kind: direct ? 'direct' : 'group',
321
+ conversationId: String(message.channel_id),
322
+ content: stripBotMention(message.content ?? '', botId),
323
+ plainText: (!Array.isArray(message.attachments) || message.attachments.length === 0)
324
+ && (!Array.isArray(message.sticker_items) || message.sticker_items.length === 0)
325
+ && !message.poll,
326
+ images: Array.isArray(message.attachments)
327
+ ? message.attachments.map((attachment) => discordImageSource(attachment, fetchImpl)).filter(Boolean)
328
+ : [],
329
+ files: Array.isArray(message.attachments)
330
+ ? message.attachments.map((attachment) => discordFileSource(attachment, fetchImpl)).filter(Boolean)
331
+ : [],
332
+ ...(replyTo ? { replyTo } : {}),
333
+ addressed,
334
+ replyTarget: {
335
+ channelId: String(message.channel_id),
336
+ replyToMessageId: String(message.id),
337
+ },
338
+ reactionTarget: {
339
+ channelId: String(message.channel_id),
340
+ messageId: String(message.id),
341
+ },
342
+ connectionTestTarget: { channelId: String(message.channel_id) },
343
+ };
344
+ }
345
+
346
+ export async function resolveDiscordMessageRoute(message, botId, {
347
+ api,
348
+ channel,
349
+ fetchImpl = fetch,
350
+ signal,
351
+ onChannel,
352
+ } = {}) {
353
+ const normalized = normalizeDiscordMessage(message, botId, {
354
+ fetchImpl,
355
+ loadReply: typeof api?.getMessage === 'function'
356
+ ? (options) => api.getMessage(options)
357
+ : undefined,
358
+ });
359
+ if (!normalized || normalized.senderIsBot) return normalized;
360
+ signal?.throwIfAborted();
361
+ if (normalized.kind === 'direct') {
362
+ return withConversationRoute(normalized, { id: normalized.conversationId, type: 1 }, botId);
363
+ }
364
+ if (!api || typeof api.getChannel !== 'function') {
365
+ throw new TypeError('Discord route resolution requires the Discord API');
366
+ }
367
+
368
+ const sourceChannel = rememberChannel(channel ?? await api.getChannel({
369
+ channelId: normalized.conversationId,
370
+ signal,
371
+ }), onChannel);
372
+ if (isThreadChannel(sourceChannel)) {
373
+ return withConversationRoute(normalized, sourceChannel, botId);
374
+ }
375
+ if (!normalized.addressed) return withConversationRoute(normalized, sourceChannel, botId);
376
+
377
+ const sourceType = Number(sourceChannel?.type);
378
+ if (sourceType !== GUILD_TEXT && sourceType !== GUILD_ANNOUNCEMENT) {
379
+ return withConversationRoute(normalized, sourceChannel, botId, {
380
+ fallback: 'unsupported-channel',
381
+ notice: '当前频道不支持自动创建 Thread,已直接在当前频道回复。',
382
+ });
383
+ }
384
+
385
+ signal?.throwIfAborted();
386
+ let created;
387
+ try {
388
+ created = rememberChannel(await api.startThreadFromMessage({
389
+ channelId: normalized.conversationId,
390
+ messageId: normalized.messageId,
391
+ name: cleanThreadName(message, botId),
392
+ signal,
393
+ }), onChannel);
394
+ if (!isThreadFromMessage(created, message)) {
395
+ throw new Error('Discord returned an invalid thread for the source message');
396
+ }
397
+ } catch (error) {
398
+ let recovered;
399
+ try {
400
+ recovered = await findCreatedThread(api, message, {
401
+ signal: AbortSignal.timeout(THREAD_RECOVERY_TIMEOUT_MS),
402
+ onChannel,
403
+ });
404
+ } catch (recoveryError) {
405
+ if (signal?.aborted) throw signal.reason ?? error;
406
+ await sendThreadUncertainNotice(api, normalized, signal);
407
+ throw threadCreateUncertain(recoveryError);
408
+ }
409
+ if (recovered) {
410
+ return withConversationRoute(normalized, recovered, botId, { fromSourceMessage: true });
411
+ }
412
+ if (signal?.aborted) throw signal.reason ?? error;
413
+ if (uncertainThreadCreate(error)) {
414
+ await sendThreadUncertainNotice(api, normalized, signal);
415
+ throw threadCreateUncertain(error);
416
+ }
417
+ return withConversationRoute(normalized, sourceChannel, botId, {
418
+ fallback: 'thread-create-failed',
419
+ notice: '无法创建 Thread,已直接在当前频道回复。',
420
+ });
421
+ }
422
+ return withConversationRoute(normalized, created, botId, { fromSourceMessage: true });
423
+ }
424
+
425
+ export class DiscordBotClient {
426
+ #api;
427
+ #signal;
428
+ #deliveredNotices = new WeakSet();
429
+
430
+ constructor({ api, signal }) {
431
+ this.#api = api;
432
+ this.#signal = signal;
433
+ }
434
+
435
+ async sendText(target, text) {
436
+ const notice = !this.#deliveredNotices.has(target) && target?.notice
437
+ ? String(target.notice) : null;
438
+ const chunks = splitMessageText(notice ? `${notice}\n\n${text}` : text, 1_900);
439
+ const providerMessageIds = [];
440
+ for (const [index, chunk] of chunks.entries()) {
441
+ const result = await this.#api.createMessage({
442
+ channelId: target.channelId,
443
+ content: chunk,
444
+ replyToMessageId: index === 0 ? target.replyToMessageId : undefined,
445
+ signal: this.#signal,
446
+ });
447
+ if (notice && index === 0) this.#deliveredNotices.add(target);
448
+ if (typeof result?.id === 'string' && result.id) providerMessageIds.push(result.id);
449
+ }
450
+ return { providerMessageIds };
451
+ }
452
+
453
+ sendTyping(target) {
454
+ return this.#api.sendTyping({ channelId: target.channelId, signal: this.#signal });
455
+ }
456
+
457
+ sendFile(target, file) {
458
+ return this.#api.createFileMessage({
459
+ channelId: target.channelId,
460
+ file,
461
+ replyToMessageId: target.replyToMessageId,
462
+ signal: this.#signal,
463
+ });
464
+ }
465
+
466
+ addReaction(target, emoji, { signal } = {}) {
467
+ return this.#api.addOwnReaction({
468
+ channelId: target.channelId,
469
+ messageId: target.messageId,
470
+ emoji,
471
+ signal: this.#operationSignal(signal),
472
+ });
473
+ }
474
+
475
+ removeReaction(target, reactionKey, { signal } = {}) {
476
+ return this.#api.removeOwnReaction({
477
+ channelId: target.channelId,
478
+ messageId: target.messageId,
479
+ emoji: reactionKey,
480
+ signal: this.#operationSignal(signal),
481
+ });
482
+ }
483
+
484
+ async openStream(target) {
485
+ const notice = !this.#deliveredNotices.has(target) && target?.notice
486
+ ? String(target.notice) : null;
487
+ const decorate = (content) => notice ? `${notice}\n\n${content}` : content;
488
+ const stream = createEditableMessageStream({
489
+ limit: notice ? 1_800 : 1_900,
490
+ create: async (content) => {
491
+ const message = await this.#api.createMessage({
492
+ channelId: target.channelId,
493
+ content: decorate(content),
494
+ replyToMessageId: target.replyToMessageId,
495
+ signal: this.#signal,
496
+ });
497
+ if (notice) this.#deliveredNotices.add(target);
498
+ return message.id;
499
+ },
500
+ edit: (messageId, content) => this.#api.editMessage({
501
+ channelId: target.channelId,
502
+ messageId,
503
+ content: decorate(content),
504
+ signal: this.#signal,
505
+ }),
506
+ sendRemainder: (content) => this.#api.createMessage({
507
+ channelId: target.channelId,
508
+ content,
509
+ signal: this.#signal,
510
+ }),
511
+ messageIdForResult: (message) => message?.id,
512
+ });
513
+ return stream.start();
514
+ }
515
+
516
+ #operationSignal(signal) {
517
+ return signal ?? this.#signal;
518
+ }
519
+ }
520
+
521
+ export function createDiscordRuntimeStatus() {
522
+ return {
523
+ startedAt: null,
524
+ ready: false,
525
+ connectionState: 'idle',
526
+ harnessReachable: false,
527
+ lastCheckedAt: null,
528
+ lastConnectedAt: null,
529
+ lastError: null,
530
+ ...createDiscordBridgeStatus(),
531
+ };
532
+ }
533
+
534
+ export class DiscordRuntime {
535
+ #config;
536
+ #token;
537
+ #harness;
538
+ #state;
539
+ #contextEnhancement;
540
+ #accessPolicy;
541
+ #logger;
542
+ #diagnostics;
543
+ #replyTimeoutMs;
544
+ #connectTimeoutMs;
545
+ #createApi;
546
+ #createWebSocket;
547
+ #random;
548
+ #status = createDiscordRuntimeStatus();
549
+ #api = null;
550
+ #bridge = null;
551
+ #abortController = null;
552
+ #socket = null;
553
+ #gatewayUrl = null;
554
+ #resumeUrl = null;
555
+ #sessionId = null;
556
+ #sequence = null;
557
+ #heartbeatTimer = null;
558
+ #heartbeatAcked = true;
559
+ #reconnectTimer = null;
560
+ #reconnectAttempt = 0;
561
+ #generation = 0;
562
+ #stopped = true;
563
+ #starting = null;
564
+ #channels = new Map();
565
+ #routing = new Map();
566
+ #account = null;
567
+ #externalConsumer;
568
+ #externalSourceFiles;
569
+ #externalOrdinaryText;
570
+ #ordinaryAuthorized = false;
571
+ #readHistory = createDiscordHistoryReader();
572
+
573
+ constructor({
574
+ config,
575
+ token,
576
+ harness,
577
+ state,
578
+ contextEnhancement,
579
+ accessPolicy,
580
+ logger = console,
581
+ replyTimeoutMs = 600_000,
582
+ connectTimeoutMs = 20_000,
583
+ createApi = (options) => new DiscordApi(options),
584
+ createWebSocket = (url) => new WebSocket(url),
585
+ random = Math.random,
586
+ externalConsumer,
587
+ externalSourceFiles = () => false,
588
+ externalOrdinaryText = () => false,
589
+ }) {
590
+ if (!config || !token || !harness || !state) {
591
+ throw new TypeError('DiscordRuntime requires config, token, Harness, and state');
592
+ }
593
+ if (typeof createWebSocket !== 'function') throw new TypeError('DiscordRuntime requires WebSocket');
594
+ this.#config = config;
595
+ this.#externalConsumer = externalConsumer;
596
+ this.#externalSourceFiles = externalSourceFiles;
597
+ this.#externalOrdinaryText = externalOrdinaryText;
598
+ this.#token = token;
599
+ this.#harness = harness;
600
+ this.#state = state;
601
+ this.#contextEnhancement = contextEnhancement;
602
+ this.#accessPolicy = accessPolicy;
603
+ this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'discord', logger });
604
+ this.#replyTimeoutMs = replyTimeoutMs;
605
+ this.#connectTimeoutMs = connectTimeoutMs;
606
+ this.#createApi = createApi;
607
+ this.#createWebSocket = createWebSocket;
608
+ this.#random = random;
609
+ }
610
+
611
+ get status() {
612
+ return structuredClone(this.#status);
613
+ }
614
+
615
+ async sendConnectionTest(text) {
616
+ if (!this.#status.ready || !this.#bridge) {
617
+ const error = new Error('Discord bot is not connected');
618
+ error.code = 'test-target-unavailable';
619
+ throw error;
620
+ }
621
+ return this.#bridge.sendConnectionTest(text);
622
+ }
623
+
624
+ async sendProactiveText(target, text, options = {}) {
625
+ if (this.#config.consumerMode === 'external-consumer') {
626
+ const checked = this.#checkedLifetime(options.signal);
627
+ if (options.expectedFingerprint !== checked.account.fingerprint) throw discordRefusal('account-changed');
628
+ if (target?.kind !== 'channel') throw discordRefusal('invalid-target');
629
+ const channel = await inspectDiscordSourceChannel(checked.api, target.route?.channelId, checked.account, checked.signal, { forReply: true });
630
+ checked.assertCurrent();
631
+ return sendDiscordCheckedText(checked.api, checked.account, channel, text, { ...options, signal: checked.signal });
632
+ }
633
+ if (!this.#status.ready || !this.#bridge) {
634
+ const error = new Error('Discord bot is not connected');
635
+ error.code = 'bot-not-connected';
636
+ throw error;
637
+ }
638
+ const channelId = typeof target?.route?.channelId === 'string'
639
+ ? target.route.channelId.trim() : '';
640
+ if (target?.kind !== 'channel' || !channelId) {
641
+ const error = new TypeError('Invalid Discord proactive delivery target');
642
+ error.code = 'invalid-target';
643
+ throw error;
644
+ }
645
+ return this.#bridge.sendProactiveText({ channelId }, text, options);
646
+ }
647
+
648
+ #checkedLifetime(signal) {
649
+ if (!this.#status.ready || !this.#account || !this.#api || !this.#abortController
650
+ || this.#config.consumerMode !== 'external-consumer') throw discordRefusal('capability-unavailable');
651
+ const generation = this.#generation;
652
+ const combined = signal ? AbortSignal.any([signal, this.#abortController.signal]) : this.#abortController.signal;
653
+ return { api: this.#api, account: this.#account, signal: combined, assertCurrent: () => {
654
+ combined.throwIfAborted();
655
+ if (generation !== this.#generation || this.#stopped || !this.#status.ready) throw discordRefusal('capability-unavailable');
656
+ } };
657
+ }
658
+
659
+ async qualifyReplyChecked(route, { signal } = {}) {
660
+ const checked = this.#checkedLifetime(signal);
661
+ const result = await qualifyDiscordReply(checked.api, checked.account, route, checked.signal);
662
+ checked.assertCurrent();
663
+ return result.route;
664
+ }
665
+
666
+ async historyChecked(route, query, { signal } = {}) {
667
+ const checked = this.#checkedLifetime(signal);
668
+ return this.#readHistory(checked.api, { botId: this.#config.botId, account: checked.account },
669
+ route, query, checked.signal, checked.assertCurrent);
670
+ }
671
+
672
+ async externalFileChecked(route, file, options = {}) {
673
+ const checked = this.#checkedLifetime(options.signal);
674
+ if (this.#externalSourceFiles() !== true) throw discordRefusal('capability-unavailable');
675
+ const operation = options.reply ? replyExternalFile : readExternalFile;
676
+ return operation(checked.api, checked.account, route, file, { ...options,
677
+ signal: checked.signal, assertCurrent: checked.assertCurrent });
678
+ }
679
+
680
+ async replyChecked(route, text, options = {}) {
681
+ const checked = this.#checkedLifetime(options.signal);
682
+ return sendDiscordReply(checked.api, checked.account, route, text, { ...options,
683
+ signal: checked.signal, assertCurrent: checked.assertCurrent });
684
+ }
685
+
686
+ async start() {
687
+ if (this.#status.ready && this.#socket) return this.status;
688
+ if (this.#starting) return this.#starting;
689
+ this.#starting = this.#start().finally(() => {
690
+ this.#starting = null;
691
+ });
692
+ return this.#starting;
693
+ }
694
+
695
+ async #start() {
696
+ await this.stop();
697
+ this.#ordinaryAuthorized = false;
698
+ this.#stopped = false;
699
+ this.#sessionId = null;
700
+ this.#resumeUrl = null;
701
+ this.#sequence = null;
702
+ this.#reconnectAttempt = 0;
703
+ this.#channels.clear();
704
+ this.#routing.clear();
705
+ this.#status.startedAt = new Date().toISOString();
706
+ this.#status.connectionState = 'connecting';
707
+ this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
708
+ await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
709
+ this.#status.harnessReachable = true;
710
+ const controller = new AbortController();
711
+ this.#abortController = controller;
712
+ const api = this.#createApi({ token: this.#token });
713
+ this.#api = api;
714
+ try {
715
+ const [bot, gateway] = await Promise.all([
716
+ api.getCurrentUser({ signal: controller.signal }),
717
+ api.getGatewayBot({ signal: controller.signal }),
718
+ ]);
719
+ if (String(bot?.id ?? '') !== this.#config.platformId || bot?.bot !== true) {
720
+ throw new Error('Discord token identity does not match the saved bot');
721
+ }
722
+ if (this.#config.consumerMode === 'external-consumer') {
723
+ const application = await api.getCurrentApplication({ signal: controller.signal });
724
+ this.#account = verifiedDiscordAccount(bot, application);
725
+ this.#ordinaryAuthorized = this.#externalOrdinaryText() === true && discordMessageContentAllowed(application);
726
+ }
727
+ this.#gatewayUrl = gateway?.url;
728
+ const client = new DiscordBotClient({ api, signal: controller.signal });
729
+ this.#bridge = this.#config.consumerMode === 'external-consumer' ? null : new DiscordHarnessBridge({
730
+ bot: client,
731
+ harness: this.#harness,
732
+ state: this.#state,
733
+ contextEnhancement: this.#contextEnhancement,
734
+ accessPolicy: this.#accessPolicy,
735
+ status: this.#status,
736
+ logger: this.#logger,
737
+ replyTimeoutMs: this.#replyTimeoutMs,
738
+ signal: controller.signal,
739
+ });
740
+ let timer;
741
+ try {
742
+ await Promise.race([
743
+ this.#openSocket(false),
744
+ new Promise((_, reject) => {
745
+ timer = setTimeout(() => reject(Object.assign(new Error('Discord Gateway did not become ready in time'), { code: 'ETIMEDOUT', timeoutMs: this.#connectTimeoutMs })), this.#connectTimeoutMs);
746
+ }),
747
+ ]);
748
+ } finally {
749
+ clearTimeout(timer);
750
+ }
751
+ return this.status;
752
+ } catch (error) {
753
+ this.#status.ready = false;
754
+ this.#status.connectionState = 'failed';
755
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.restore', reuse: true, botId: this.#config?.botId, automatic: true }).publicError;
756
+ this.#status.lastError = this.#status.error.message;
757
+ await this.stop();
758
+ throw error;
759
+ }
760
+ }
761
+
762
+ #openSocket(resume) {
763
+ if (this.#stopped) return Promise.reject(new Error('Discord runtime is stopped'));
764
+ const generation = ++this.#generation;
765
+ const url = socketUrl(resume && this.#resumeUrl ? this.#resumeUrl : this.#gatewayUrl);
766
+ const socket = this.#createWebSocket(url);
767
+ this.#socket = socket;
768
+ let settled = false;
769
+ return new Promise((resolve, reject) => {
770
+ const markReady = () => {
771
+ if (settled || generation !== this.#generation) return;
772
+ settled = true;
773
+ this.#reconnectAttempt = 0;
774
+ const now = Date.now();
775
+ this.#status.ready = true;
776
+ this.#status.connectionState = 'connected';
777
+ this.#status.lastCheckedAt = now;
778
+ this.#status.lastConnectedAt = now;
779
+ this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
780
+ resolve();
781
+ };
782
+ addSocketListener(socket, 'message', (event) => {
783
+ if (generation !== this.#generation || this.#stopped) return;
784
+ const raw = eventData(event);
785
+ if (!raw) return;
786
+ let packet;
787
+ try {
788
+ packet = JSON.parse(raw);
789
+ } catch {
790
+ this.#logger.warn?.('[dsh-im:discord] ignored malformed Gateway JSON');
791
+ return;
792
+ }
793
+ if (Number.isSafeInteger(packet.s)) this.#sequence = packet.s;
794
+ if (packet.op === 10) {
795
+ this.#startHeartbeat(packet.d?.heartbeat_interval, socket, generation);
796
+ if (resume && this.#sessionId) {
797
+ this.#sendGateway(socket, {
798
+ op: 6,
799
+ d: { token: this.#token, session_id: this.#sessionId, seq: this.#sequence },
800
+ });
801
+ } else {
802
+ this.#sendGateway(socket, {
803
+ op: 2,
804
+ d: {
805
+ token: this.#token,
806
+ intents: this.#config.consumerMode === 'external-consumer'
807
+ ? (1 << 0) | (1 << 9) | (this.#ordinaryAuthorized && this.#externalOrdinaryText() === true ? (1 << 15) : 0)
808
+ : DISCORD_GATEWAY_INTENTS,
809
+ properties: {
810
+ os: process.platform,
811
+ browser: 'dsh-im',
812
+ device: 'dsh-im',
813
+ },
814
+ },
815
+ });
816
+ }
817
+ return;
818
+ }
819
+ if (packet.op === 11) {
820
+ this.#heartbeatAcked = true;
821
+ this.#status.lastCheckedAt = Date.now();
822
+ return;
823
+ }
824
+ if (packet.op === 1) {
825
+ this.#heartbeat(socket);
826
+ return;
827
+ }
828
+ if (packet.op === 7) {
829
+ socket.close(4000, 'Reconnect requested');
830
+ return;
831
+ }
832
+ if (packet.op === 9) {
833
+ if (packet.d !== true) {
834
+ this.#sessionId = null;
835
+ this.#resumeUrl = null;
836
+ this.#sequence = null;
837
+ }
838
+ socket.close(4000, 'Invalid session');
839
+ return;
840
+ }
841
+ if (packet.op !== 0) return;
842
+ if (packet.t === 'READY') {
843
+ if (this.#account && (packet.d?.application?.id !== this.#account.appId
844
+ || packet.d?.user?.id !== this.#account.userId || packet.d?.user?.bot !== true)) {
845
+ this.#status.ready = false;
846
+ this.#status.connectionState = 'failed';
847
+ settled = true;
848
+ reject(discordRefusal('account-changed'));
849
+ socket.close(4000, 'Account identity changed');
850
+ return;
851
+ }
852
+ this.#sessionId = packet.d?.session_id ?? null;
853
+ this.#resumeUrl = packet.d?.resume_gateway_url ?? null;
854
+ markReady();
855
+ } else if (packet.t === 'RESUMED') {
856
+ markReady();
857
+ } else if (packet.t === 'GUILD_CREATE') {
858
+ for (const channel of [...(packet.d?.channels ?? []), ...(packet.d?.threads ?? [])]) {
859
+ this.#rememberChannel(channel);
860
+ }
861
+ } else if (packet.t === 'CHANNEL_CREATE' || packet.t === 'CHANNEL_UPDATE'
862
+ || packet.t === 'THREAD_CREATE' || packet.t === 'THREAD_UPDATE') {
863
+ this.#rememberChannel(packet.d);
864
+ } else if (packet.t === 'CHANNEL_DELETE' || packet.t === 'THREAD_DELETE') {
865
+ if (packet.d?.id) this.#channels.delete(String(packet.d.id));
866
+ } else if (packet.t === 'THREAD_LIST_SYNC') {
867
+ for (const channel of packet.d?.threads ?? []) this.#rememberChannel(channel);
868
+ } else if (packet.t === 'MESSAGE_CREATE') {
869
+ if (this.#config.consumerMode === 'external-consumer') {
870
+ void this.#acceptExternalMessage(packet.d, packet.s, generation).catch(error => {
871
+ if (generation === this.#generation && !this.#stopped)
872
+ this.#logger.warn?.(`[dsh-im:discord] external phase=intake-failed code=${error?.code ?? 'source-unavailable'}`);
873
+ });
874
+ return;
875
+ }
876
+ const bridge = this.#bridge;
877
+ if (packet.d && bridge) {
878
+ void this.#acceptMessage(packet.d, bridge).catch((error) => {
879
+ if (generation !== this.#generation || this.#stopped) return;
880
+ this.#logger.error?.(
881
+ `[dsh-im:discord] bot ${this.#config.botId} message handling failed:`,
882
+ extractConnectionEvidence(error).details,
883
+ );
884
+ });
885
+ }
886
+ }
887
+ });
888
+ addSocketListener(socket, 'close', (event = {}) => {
889
+ if (generation !== this.#generation) return;
890
+ this.#clearHeartbeat();
891
+ if (this.#socket === socket) this.#socket = null;
892
+ if (this.#stopped) {
893
+ if (!settled) reject(new DOMException('Stopped', 'AbortError'));
894
+ return;
895
+ }
896
+ const error = gatewayCloseError(Number(event.code) || 0);
897
+ this.#status.ready = false;
898
+ this.#status.connectionState = 'connecting';
899
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
900
+ this.#status.lastError = this.#status.error.message;
901
+ if (!settled) {
902
+ settled = true;
903
+ reject(error);
904
+ }
905
+ if (error.code === 'discord-401' || error.code === 'discord-intents') {
906
+ this.#status.connectionState = 'failed';
907
+ return;
908
+ }
909
+ this.#scheduleReconnect();
910
+ });
911
+ addSocketListener(socket, 'error', (event) => {
912
+ const error = event?.error ?? new Error('WebSocket error');
913
+ if (generation !== this.#generation || this.#stopped) return;
914
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
915
+ this.#status.lastError = this.#status.error.message;
916
+ });
917
+ });
918
+ }
919
+
920
+ #rememberChannel(channel) {
921
+ if (!channel?.id) return;
922
+ this.#channels.set(String(channel.id), channel);
923
+ }
924
+
925
+ async #acceptExternalMessage(message, sequence, generation) {
926
+ if (!this.#account || !this.#status.ready || generation !== this.#generation
927
+ || !message?.guild_id || message.author?.bot === true || message.webhook_id
928
+ || !Array.isArray(message.mentions)) return;
929
+ const mentioned = message.mentions.some(user => user.id === this.#account.userId);
930
+ if (!mentioned && (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
931
+ || typeof message.content !== 'string' || !message.content.trim())) return;
932
+ const checked = this.#checkedLifetime();
933
+ if (!mentioned) {
934
+ const application = await checked.api.getCurrentApplication({ signal: checked.signal });
935
+ if (verifiedDiscordAccount({ id: checked.account.userId, bot: true }, application).fingerprint !== checked.account.fingerprint)
936
+ throw discordRefusal('account-changed');
937
+ checked.assertCurrent();
938
+ if (!discordMessageContentAllowed(application) || this.#externalOrdinaryText() !== true) return;
939
+ }
940
+ const channel = await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
941
+ let event = normalizeDiscordExternalText(message, { botId: this.#config.botId, account: checked.account,
942
+ channel, eventId: `gateway:${this.#sessionId}:${sequence}`, ordinaryText: !mentioned });
943
+ checked.assertCurrent();
944
+ if (!event) return;
945
+ if (!mentioned && this.#externalOrdinaryText() !== true) return;
946
+ if (mentioned && this.#externalSourceFiles() === true) event = externalAttachments(event, message);
947
+ if (typeof this.#externalConsumer !== 'function') throw discordRefusal('consumer-unavailable');
948
+ const result = await this.#externalConsumer(event, checked.signal);
949
+ checked.assertCurrent();
950
+ if (result?.accepted !== true) throw discordRefusal('ingress-not-accepted');
951
+ this.#status.messagesReceived++;
952
+ }
953
+
954
+ async #acceptMessage(message, bridge) {
955
+ const messageId = String(message?.id ?? '');
956
+ if (!messageId || this.#state.hasSeen(messageId)) return;
957
+ const preflight = normalizeDiscordMessage(message, this.#config.platformId);
958
+ let accessDecision;
959
+ if (preflight?.kind === 'group' && preflight.addressed === true
960
+ && preflight.senderIsBot !== true) {
961
+ accessDecision = evaluateInboundAccess(this.#accessPolicy, {
962
+ conversationType: 'group',
963
+ senderIds: [preflight.senderId],
964
+ text: preflight.content,
965
+ hasImages: preflight.images.length > 0,
966
+ hasFiles: preflight.files.length > 0,
967
+ });
968
+ if (!accessDecision.allowed) {
969
+ // Let the shared bridge apply its normal silent/command-denial behavior,
970
+ // but do so against the source channel before creating a Thread.
971
+ await bridge.accept(preflight, { accessDecision });
972
+ return;
973
+ }
974
+ }
975
+ let route = this.#routing.get(messageId);
976
+ if (!route) {
977
+ const contextSnapshot = captureContextEnhancement(
978
+ this.#contextEnhancement,
979
+ message.guild_id ? 'group' : 'direct',
980
+ );
981
+ const pendingRoute = resolveDiscordMessageRoute(message, this.#config.platformId, {
982
+ api: this.#api,
983
+ channel: this.#channels.get(String(message.channel_id)),
984
+ signal: this.#abortController?.signal,
985
+ onChannel: (resolved) => this.#rememberChannel(resolved),
986
+ });
987
+ route = { pendingRoute, contextSnapshot };
988
+ this.#routing.set(messageId, route);
989
+ void pendingRoute.finally(() => {
990
+ if (this.#routing.get(messageId) === route) this.#routing.delete(messageId);
991
+ }).catch(() => undefined);
992
+ }
993
+ try {
994
+ const normalized = await route.pendingRoute;
995
+ if (normalized) {
996
+ await bridge.accept(normalized, {
997
+ contextSnapshot: route.contextSnapshot,
998
+ ...(accessDecision ? { accessDecision } : {}),
999
+ });
1000
+ }
1001
+ } catch (error) {
1002
+ if (error?.code === 'discord-thread-create-uncertain') {
1003
+ await this.#state.markSeen(messageId);
1004
+ }
1005
+ throw error;
1006
+ }
1007
+ }
1008
+
1009
+ #sendGateway(socket, payload) {
1010
+ if (socket.readyState !== 1) return;
1011
+ socket.send(JSON.stringify(payload));
1012
+ }
1013
+
1014
+ #startHeartbeat(interval, socket, generation) {
1015
+ this.#clearHeartbeat();
1016
+ if (!Number.isFinite(interval) || interval < 1_000) {
1017
+ socket.close(4000, 'Invalid heartbeat interval');
1018
+ return;
1019
+ }
1020
+ this.#heartbeatAcked = true;
1021
+ const schedule = (delay) => {
1022
+ this.#heartbeatTimer = setTimeout(() => {
1023
+ if (this.#stopped || generation !== this.#generation || this.#socket !== socket) return;
1024
+ if (!this.#heartbeatAcked) {
1025
+ socket.close(4000, 'Heartbeat was not acknowledged');
1026
+ return;
1027
+ }
1028
+ this.#heartbeat(socket);
1029
+ schedule(interval);
1030
+ }, delay);
1031
+ this.#heartbeatTimer?.unref?.();
1032
+ };
1033
+ schedule(Math.floor(interval * this.#random()));
1034
+ }
1035
+
1036
+ #heartbeat(socket) {
1037
+ this.#heartbeatAcked = false;
1038
+ this.#sendGateway(socket, { op: 1, d: this.#sequence });
1039
+ }
1040
+
1041
+ #clearHeartbeat() {
1042
+ if (this.#heartbeatTimer !== null) clearTimeout(this.#heartbeatTimer);
1043
+ this.#heartbeatTimer = null;
1044
+ this.#heartbeatAcked = true;
1045
+ }
1046
+
1047
+ #scheduleReconnect() {
1048
+ if (this.#stopped || this.#reconnectTimer !== null) return;
1049
+ const delay = RECONNECT_DELAYS_MS[Math.min(this.#reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)];
1050
+ this.#reconnectAttempt += 1;
1051
+ this.#reconnectTimer = setTimeout(() => {
1052
+ this.#reconnectTimer = null;
1053
+ void this.#openSocket(Boolean(this.#sessionId)).catch((error) => {
1054
+ if (this.#stopped) return;
1055
+ this.#logger.warn?.('[dsh-im:discord] Gateway reconnect failed:', extractConnectionEvidence(error).details);
1056
+ this.#scheduleReconnect();
1057
+ });
1058
+ }, delay);
1059
+ this.#reconnectTimer?.unref?.();
1060
+ }
1061
+
1062
+ async stop() {
1063
+ this.#readHistory = createDiscordHistoryReader();
1064
+ this.#stopped = true;
1065
+ this.#generation += 1;
1066
+ this.#abortController?.abort();
1067
+ this.#abortController = null;
1068
+ if (this.#reconnectTimer !== null) clearTimeout(this.#reconnectTimer);
1069
+ this.#reconnectTimer = null;
1070
+ this.#clearHeartbeat();
1071
+ const socket = this.#socket;
1072
+ const bridge = this.#bridge;
1073
+ this.#socket = null;
1074
+ this.#bridge = null;
1075
+ this.#api = null;
1076
+ this.#account = null;
1077
+ this.#routing.clear();
1078
+ try {
1079
+ if (socket && socket.readyState < 2) socket.close(1000, 'Plugin stopped');
1080
+ } catch (error) {
1081
+ this.#logger.warn?.(`[dsh-im:discord] bot ${this.#config.botId} failed to close Gateway:`, extractConnectionEvidence(error).details);
1082
+ }
1083
+ await Promise.race([
1084
+ bridge?.waitForIdle() ?? Promise.resolve(),
1085
+ new Promise((resolve) => setTimeout(resolve, 2_000)),
1086
+ ]);
1087
+ this.#status.ready = false;
1088
+ this.#status.connectionState = 'idle';
1089
+ return this.status;
1090
+ }
1091
+ }