@botharness/im-provider 4.32.0-botharness.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (412) hide show
  1. package/LICENSE +21 -0
  2. package/PROVENANCE.json +25 -0
  3. package/README.en.md +445 -0
  4. package/README.md +448 -0
  5. package/THIRD_PARTY_NOTICES.md +93 -0
  6. package/assets/dingtalk-menu-template.json +6 -0
  7. package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
  8. package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
  9. package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
  10. package/assets/logo-icon.png +0 -0
  11. package/assets/logo-plugin-message-link-gradient.webp +0 -0
  12. package/assets/logo-plugin-phone.png +0 -0
  13. package/assets/logo.png +0 -0
  14. package/assets/logo_cn.png +0 -0
  15. package/assets/screenshot-menu-card.png +0 -0
  16. package/cordis.patch.yml +3 -0
  17. package/lib/client.js +20330 -0
  18. package/lib/index.js +602 -0
  19. package/locale/en.json +5 -0
  20. package/locale/zh.json +5 -0
  21. package/package.json +181 -0
  22. package/plugin-src/client/access-policy-settings.js +362 -0
  23. package/plugin-src/client/agent-preset.js +119 -0
  24. package/plugin-src/client/bot-alias.js +169 -0
  25. package/plugin-src/client/build.mjs +38 -0
  26. package/plugin-src/client/channel-card-meta.js +132 -0
  27. package/plugin-src/client/channel-logos.js +190 -0
  28. package/plugin-src/client/channels/dingtalk/api.js +267 -0
  29. package/plugin-src/client/channels/dingtalk/index.js +954 -0
  30. package/plugin-src/client/channels/dingtalk/styles.js +136 -0
  31. package/plugin-src/client/channels/discord/api.js +11 -0
  32. package/plugin-src/client/channels/discord/index.js +25 -0
  33. package/plugin-src/client/channels/discord/styles.js +19 -0
  34. package/plugin-src/client/channels/email/api.js +52 -0
  35. package/plugin-src/client/channels/email/index.js +728 -0
  36. package/plugin-src/client/channels/email/styles.js +51 -0
  37. package/plugin-src/client/channels/feishu/api.js +405 -0
  38. package/plugin-src/client/channels/feishu/group-settings.js +581 -0
  39. package/plugin-src/client/channels/feishu/index.js +1583 -0
  40. package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
  41. package/plugin-src/client/channels/feishu/styles.js +573 -0
  42. package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
  43. package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
  44. package/plugin-src/client/channels/imessage/api.js +12 -0
  45. package/plugin-src/client/channels/imessage/index.js +46 -0
  46. package/plugin-src/client/channels/imessage/styles.js +19 -0
  47. package/plugin-src/client/channels/matrix/api.js +11 -0
  48. package/plugin-src/client/channels/matrix/index.js +151 -0
  49. package/plugin-src/client/channels/matrix/styles.js +36 -0
  50. package/plugin-src/client/channels/office/api.js +46 -0
  51. package/plugin-src/client/channels/office/index.js +153 -0
  52. package/plugin-src/client/channels/office/styles.js +50 -0
  53. package/plugin-src/client/channels/qq/api.js +171 -0
  54. package/plugin-src/client/channels/qq/index.js +593 -0
  55. package/plugin-src/client/channels/qq/styles.js +19 -0
  56. package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
  57. package/plugin-src/client/channels/shared/token-api.js +124 -0
  58. package/plugin-src/client/channels/shared/token-channel.js +495 -0
  59. package/plugin-src/client/channels/slack/api.js +11 -0
  60. package/plugin-src/client/channels/slack/index.js +131 -0
  61. package/plugin-src/client/channels/slack/styles.js +34 -0
  62. package/plugin-src/client/channels/telegram/api.js +11 -0
  63. package/plugin-src/client/channels/telegram/index.js +28 -0
  64. package/plugin-src/client/channels/telegram/styles.js +31 -0
  65. package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
  66. package/plugin-src/client/channels/wecom/api.js +160 -0
  67. package/plugin-src/client/channels/wecom/index.js +625 -0
  68. package/plugin-src/client/channels/wecom/styles.js +19 -0
  69. package/plugin-src/client/channels/wecom-app/api.js +132 -0
  70. package/plugin-src/client/channels/wecom-app/index.js +634 -0
  71. package/plugin-src/client/channels/wecom-app/styles.js +25 -0
  72. package/plugin-src/client/channels/weixin/api.js +211 -0
  73. package/plugin-src/client/channels/weixin/connection-error.js +1 -0
  74. package/plugin-src/client/channels/weixin/index.js +801 -0
  75. package/plugin-src/client/channels/weixin/styles.js +115 -0
  76. package/plugin-src/client/channels/whatsapp/api.js +152 -0
  77. package/plugin-src/client/channels/whatsapp/index.js +609 -0
  78. package/plugin-src/client/channels/whatsapp/styles.js +19 -0
  79. package/plugin-src/client/connection-error.js +87 -0
  80. package/plugin-src/client/context-enhancement.js +415 -0
  81. package/plugin-src/client/credential-binding.js +118 -0
  82. package/plugin-src/client/delivery-settings.js +905 -0
  83. package/plugin-src/client/global-settings.js +433 -0
  84. package/plugin-src/client/i18n.js +1314 -0
  85. package/plugin-src/client/index.js +624 -0
  86. package/plugin-src/client/interface-language.js +89 -0
  87. package/plugin-src/client/last-message-error.js +18 -0
  88. package/plugin-src/client/lifecycle.js +86 -0
  89. package/plugin-src/client/loopback-recovery.js +75 -0
  90. package/plugin-src/client/model-setting.js +172 -0
  91. package/plugin-src/client/panel-error-boundary.js +21 -0
  92. package/plugin-src/client/plugin-page.js +51 -0
  93. package/plugin-src/client/session-channel-logos.js +243 -0
  94. package/plugin-src/client/styles.js +770 -0
  95. package/plugin-src/client/update-panel.js +14 -0
  96. package/plugin-src/client/workspace-directory-picker.js +280 -0
  97. package/plugin-src/client/workspace-editor.js +69 -0
  98. package/plugin-src/client/workspace-snapshot-fence.js +28 -0
  99. package/plugin-src/host/build.mjs +52 -0
  100. package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
  101. package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
  102. package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
  103. package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
  104. package/plugin-src/host/channels/discord/index.mjs +33 -0
  105. package/plugin-src/host/channels/discord/production.mjs +17 -0
  106. package/plugin-src/host/channels/discord/rpc.mjs +21 -0
  107. package/plugin-src/host/channels/email/availability.mjs +60 -0
  108. package/plugin-src/host/channels/email/index.mjs +36 -0
  109. package/plugin-src/host/channels/email/production.mjs +58 -0
  110. package/plugin-src/host/channels/email/rpc.mjs +163 -0
  111. package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
  112. package/plugin-src/host/channels/feishu/controller.mjs +172 -0
  113. package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
  114. package/plugin-src/host/channels/feishu/index.mjs +69 -0
  115. package/plugin-src/host/channels/feishu/production.mjs +318 -0
  116. package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
  117. package/plugin-src/host/channels/imessage/index.mjs +21 -0
  118. package/plugin-src/host/channels/imessage/production.mjs +13 -0
  119. package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
  120. package/plugin-src/host/channels/matrix/index.mjs +31 -0
  121. package/plugin-src/host/channels/matrix/production.mjs +241 -0
  122. package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
  123. package/plugin-src/host/channels/office/index.mjs +14 -0
  124. package/plugin-src/host/channels/office/production.mjs +45 -0
  125. package/plugin-src/host/channels/office/rpc.mjs +51 -0
  126. package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
  127. package/plugin-src/host/channels/qq/index.mjs +28 -0
  128. package/plugin-src/host/channels/qq/production.mjs +181 -0
  129. package/plugin-src/host/channels/qq/rpc.mjs +250 -0
  130. package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
  131. package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
  132. package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
  133. package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
  134. package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
  135. package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
  136. package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
  137. package/plugin-src/host/channels/shared/production.mjs +237 -0
  138. package/plugin-src/host/channels/shared/rpc.mjs +226 -0
  139. package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
  140. package/plugin-src/host/channels/shared/startup.mjs +76 -0
  141. package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
  142. package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
  143. package/plugin-src/host/channels/slack/index.mjs +31 -0
  144. package/plugin-src/host/channels/slack/production.mjs +176 -0
  145. package/plugin-src/host/channels/slack/rpc.mjs +221 -0
  146. package/plugin-src/host/channels/telegram/index.mjs +33 -0
  147. package/plugin-src/host/channels/telegram/production.mjs +19 -0
  148. package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
  149. package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
  150. package/plugin-src/host/channels/wecom/index.mjs +34 -0
  151. package/plugin-src/host/channels/wecom/production.mjs +187 -0
  152. package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
  153. package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
  154. package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
  155. package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
  156. package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
  157. package/plugin-src/host/channels/weixin/index.mjs +44 -0
  158. package/plugin-src/host/channels/weixin/production.mjs +257 -0
  159. package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
  160. package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
  161. package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
  162. package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
  163. package/plugin-src/host/delivery-adapter.mjs +388 -0
  164. package/plugin-src/host/delivery-http.mjs +132 -0
  165. package/plugin-src/host/delivery-rpc.mjs +173 -0
  166. package/plugin-src/host/delivery-service.mjs +552 -0
  167. package/plugin-src/host/delivery-suggestions.mjs +198 -0
  168. package/plugin-src/host/harness-command-executor.mjs +48 -0
  169. package/plugin-src/host/harness-connection.mjs +20 -0
  170. package/plugin-src/host/harness-session-coordinator.mjs +183 -0
  171. package/plugin-src/host/host-language-rpc.mjs +71 -0
  172. package/plugin-src/host/host-language.mjs +157 -0
  173. package/plugin-src/host/image-input-rpc.mjs +24 -0
  174. package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
  175. package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
  176. package/plugin-src/host/inbound-ttl-service.mjs +179 -0
  177. package/plugin-src/host/index.mjs +224 -0
  178. package/plugin-src/host/injected-context.mjs +104 -0
  179. package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
  180. package/plugin-src/host/modern-harness-api.mjs +738 -0
  181. package/plugin-src/host/rpc-authority.mjs +12 -0
  182. package/plugin-src/host/session-sync-coordinator.mjs +233 -0
  183. package/plugin-src/host/session-title-prefix.mjs +122 -0
  184. package/plugin-src/host/update-policy.mjs +31 -0
  185. package/plugin-src/host/update-rpc.mjs +16 -0
  186. package/plugin-src/host/update-runtime.mjs +339 -0
  187. package/plugin-src/host/update-service.mjs +392 -0
  188. package/plugin-src/management-rpc.mjs +87 -0
  189. package/src/channels/dingtalk/config-store.mjs +284 -0
  190. package/src/channels/dingtalk/connection-error.mjs +292 -0
  191. package/src/channels/dingtalk/device-auth.mjs +240 -0
  192. package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
  193. package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
  194. package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
  195. package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
  196. package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
  197. package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
  198. package/src/channels/dingtalk/harness-client.mjs +19 -0
  199. package/src/channels/dingtalk/state-store.mjs +325 -0
  200. package/src/channels/discord/config-store.mjs +25 -0
  201. package/src/channels/discord/discord-api.mjs +347 -0
  202. package/src/channels/discord/discord-bridge.mjs +16 -0
  203. package/src/channels/discord/discord-controller.mjs +16 -0
  204. package/src/channels/discord/discord-runtime.mjs +974 -0
  205. package/src/channels/discord/harness-client.mjs +11 -0
  206. package/src/channels/discord/state-store.mjs +3 -0
  207. package/src/channels/email/config-store.mjs +194 -0
  208. package/src/channels/email/email-api.mjs +20 -0
  209. package/src/channels/email/email-bridge.mjs +17 -0
  210. package/src/channels/email/email-controller.mjs +824 -0
  211. package/src/channels/email/email-runtime.mjs +699 -0
  212. package/src/channels/email/harness-client.mjs +7 -0
  213. package/src/channels/email/mail-format.mjs +91 -0
  214. package/src/channels/email/state-store.mjs +176 -0
  215. package/src/channels/email/transport.mjs +64 -0
  216. package/src/channels/email/transports/agent-mail.mjs +604 -0
  217. package/src/channels/email/transports/agently-cli.mjs +288 -0
  218. package/src/channels/email/transports/imap-smtp.mjs +165 -0
  219. package/src/channels/feishu/bridge.mjs +6286 -0
  220. package/src/channels/feishu/config.mjs +71 -0
  221. package/src/channels/feishu/external-consumer.mjs +77 -0
  222. package/src/channels/feishu/external-files.mjs +111 -0
  223. package/src/channels/feishu/feishu-app.mjs +54 -0
  224. package/src/channels/feishu/feishu-cards.mjs +1285 -0
  225. package/src/channels/feishu/feishu-channel.mjs +651 -0
  226. package/src/channels/feishu/feishu-runtime.mjs +950 -0
  227. package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
  228. package/src/channels/feishu/group-response-mode.mjs +15 -0
  229. package/src/channels/feishu/harness-client.mjs +19 -0
  230. package/src/channels/feishu/history-reader.mjs +77 -0
  231. package/src/channels/feishu/live-cot.mjs +260 -0
  232. package/src/channels/feishu/message-utils.mjs +613 -0
  233. package/src/channels/feishu/multi-bot-controller.mjs +1588 -0
  234. package/src/channels/feishu/nearby-history.mjs +72 -0
  235. package/src/channels/feishu/plugin-config-store.mjs +216 -0
  236. package/src/channels/feishu/plugin-controller.mjs +254 -0
  237. package/src/channels/feishu/registration-manager.mjs +349 -0
  238. package/src/channels/feishu/repair-manager.mjs +138 -0
  239. package/src/channels/feishu/reply-context.mjs +22 -0
  240. package/src/channels/feishu/slash-command-panel.mjs +155 -0
  241. package/src/channels/feishu/slash-command-registry.mjs +495 -0
  242. package/src/channels/feishu/state-store.mjs +214 -0
  243. package/src/channels/feishu/step-push-mode.mjs +25 -0
  244. package/src/channels/feishu/voice-config.mjs +34 -0
  245. package/src/channels/feishu/voice.mjs +134 -0
  246. package/src/channels/imessage/config-store.mjs +24 -0
  247. package/src/channels/imessage/controller.mjs +37 -0
  248. package/src/channels/imessage/harness-client.mjs +7 -0
  249. package/src/channels/imessage/imessage-api.mjs +194 -0
  250. package/src/channels/imessage/imessage-bridge.mjs +16 -0
  251. package/src/channels/imessage/runtime.mjs +102 -0
  252. package/src/channels/imessage/state-store.mjs +3 -0
  253. package/src/channels/matrix/matrix-api.mjs +696 -0
  254. package/src/channels/matrix/matrix-bridge.mjs +20 -0
  255. package/src/channels/matrix/matrix-config-store.mjs +368 -0
  256. package/src/channels/matrix/matrix-controller.mjs +404 -0
  257. package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
  258. package/src/channels/matrix/matrix-crypto.mjs +1014 -0
  259. package/src/channels/matrix/matrix-harness-client.mjs +11 -0
  260. package/src/channels/matrix/matrix-normalize.mjs +357 -0
  261. package/src/channels/matrix/matrix-rich-text.mjs +313 -0
  262. package/src/channels/matrix/matrix-room-history.mjs +316 -0
  263. package/src/channels/matrix/matrix-runtime.mjs +1014 -0
  264. package/src/channels/office/config-store.mjs +107 -0
  265. package/src/channels/office/office-controller.mjs +178 -0
  266. package/src/channels/office/office-job-executor.mjs +391 -0
  267. package/src/channels/office/office-runtime.mjs +175 -0
  268. package/src/channels/office/office-transport.mjs +171 -0
  269. package/src/channels/office/protocol.mjs +43 -0
  270. package/src/channels/qq/config-store.mjs +173 -0
  271. package/src/channels/qq/harness-client.mjs +11 -0
  272. package/src/channels/qq/markdown-reply.mjs +446 -0
  273. package/src/channels/qq/qq-bridge.mjs +1507 -0
  274. package/src/channels/qq/qq-controller.mjs +514 -0
  275. package/src/channels/qq/qq-menu.mjs +208 -0
  276. package/src/channels/qq/qq-runtime.mjs +303 -0
  277. package/src/channels/qq/qr-auth.mjs +24 -0
  278. package/src/channels/qq/state-error.mjs +17 -0
  279. package/src/channels/qq/state-store.mjs +143 -0
  280. package/src/channels/shared/access-policy.mjs +210 -0
  281. package/src/channels/shared/agent-preset.mjs +76 -0
  282. package/src/channels/shared/batch-input.mjs +229 -0
  283. package/src/channels/shared/bot-alias.mjs +29 -0
  284. package/src/channels/shared/bot-workspace-store.mjs +2383 -0
  285. package/src/channels/shared/command-catalog.mjs +107 -0
  286. package/src/channels/shared/command-permission.mjs +32 -0
  287. package/src/channels/shared/compact-command.mjs +109 -0
  288. package/src/channels/shared/config-read-error.mjs +24 -0
  289. package/src/channels/shared/connection-error.mjs +191 -0
  290. package/src/channels/shared/connection-test.mjs +58 -0
  291. package/src/channels/shared/context-enhancement.mjs +372 -0
  292. package/src/channels/shared/control-command.mjs +111 -0
  293. package/src/channels/shared/conversation-state-store.mjs +165 -0
  294. package/src/channels/shared/default-workspace.mjs +31 -0
  295. package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
  296. package/src/channels/shared/deferred-delivery.mjs +161 -0
  297. package/src/channels/shared/deferred-state.mjs +53 -0
  298. package/src/channels/shared/diagnostic-details.mjs +95 -0
  299. package/src/channels/shared/editable-message-stream.mjs +100 -0
  300. package/src/channels/shared/exclusive-inbound-consumers.mjs +71 -0
  301. package/src/channels/shared/file-download.mjs +64 -0
  302. package/src/channels/shared/harness-approval.mjs +508 -0
  303. package/src/channels/shared/harness-client.mjs +2143 -0
  304. package/src/channels/shared/harness-mux.mjs +123 -0
  305. package/src/channels/shared/harness-question.mjs +95 -0
  306. package/src/channels/shared/harness-session-binding.mjs +119 -0
  307. package/src/channels/shared/history-command.mjs +193 -0
  308. package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
  309. package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
  310. package/src/channels/shared/i18n-en/discord.mjs +10 -0
  311. package/src/channels/shared/i18n-en/email.mjs +25 -0
  312. package/src/channels/shared/i18n-en/feishu.mjs +404 -0
  313. package/src/channels/shared/i18n-en/image-input.mjs +18 -0
  314. package/src/channels/shared/i18n-en/matrix.mjs +85 -0
  315. package/src/channels/shared/i18n-en/office.mjs +23 -0
  316. package/src/channels/shared/i18n-en/qq.mjs +96 -0
  317. package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
  318. package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
  319. package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
  320. package/src/channels/shared/i18n-en/slack.mjs +27 -0
  321. package/src/channels/shared/i18n-en/telegram.mjs +27 -0
  322. package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
  323. package/src/channels/shared/i18n-en/wecom.mjs +62 -0
  324. package/src/channels/shared/i18n-en/weixin.mjs +88 -0
  325. package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
  326. package/src/channels/shared/i18n-en.mjs +45 -0
  327. package/src/channels/shared/i18n.mjs +78 -0
  328. package/src/channels/shared/im-source-guidance.mjs +65 -0
  329. package/src/channels/shared/image-input-policy.mjs +35 -0
  330. package/src/channels/shared/image-input-settings-store.mjs +60 -0
  331. package/src/channels/shared/image-input.mjs +124 -0
  332. package/src/channels/shared/image-prompt.mjs +360 -0
  333. package/src/channels/shared/inbound-access.mjs +43 -0
  334. package/src/channels/shared/inbound-file.mjs +323 -0
  335. package/src/channels/shared/inbound-ttl-store.mjs +110 -0
  336. package/src/channels/shared/inbound-ttl.mjs +22 -0
  337. package/src/channels/shared/injected-context.mjs +362 -0
  338. package/src/channels/shared/interface-language-store.mjs +127 -0
  339. package/src/channels/shared/interface-language.mjs +51 -0
  340. package/src/channels/shared/message-failure.mjs +257 -0
  341. package/src/channels/shared/model-command.mjs +741 -0
  342. package/src/channels/shared/model-setting.mjs +145 -0
  343. package/src/channels/shared/preset-command.mjs +308 -0
  344. package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
  345. package/src/channels/shared/semantic/artifact.mjs +750 -0
  346. package/src/channels/shared/semantic/delivery.mjs +193 -0
  347. package/src/channels/shared/semantic/reply-reference.mjs +148 -0
  348. package/src/channels/shared/session-binding-lock.mjs +40 -0
  349. package/src/channels/shared/session-channel-labels.mjs +28 -0
  350. package/src/channels/shared/session-reply-recovery.mjs +104 -0
  351. package/src/channels/shared/session-sync-registry.mjs +22 -0
  352. package/src/channels/shared/session-title.mjs +74 -0
  353. package/src/channels/shared/status-reaction.mjs +107 -0
  354. package/src/channels/shared/text-harness-bridge.mjs +1623 -0
  355. package/src/channels/shared/token-bot-controller.mjs +417 -0
  356. package/src/channels/shared/token-config-store.mjs +208 -0
  357. package/src/channels/shared/workspace-command.mjs +532 -0
  358. package/src/channels/shared/workspace-session.mjs +196 -0
  359. package/src/channels/slack/config-store.mjs +177 -0
  360. package/src/channels/slack/external-consumer.mjs +80 -0
  361. package/src/channels/slack/external-files.mjs +90 -0
  362. package/src/channels/slack/harness-client.mjs +11 -0
  363. package/src/channels/slack/history-reader.mjs +203 -0
  364. package/src/channels/slack/manifest.mjs +37 -0
  365. package/src/channels/slack/slack-api.mjs +636 -0
  366. package/src/channels/slack/slack-bridge.mjs +20 -0
  367. package/src/channels/slack/slack-controller.mjs +468 -0
  368. package/src/channels/slack/slack-runtime.mjs +879 -0
  369. package/src/channels/slack/state-store.mjs +3 -0
  370. package/src/channels/telegram/config-store.mjs +89 -0
  371. package/src/channels/telegram/harness-client.mjs +11 -0
  372. package/src/channels/telegram/state-store.mjs +3 -0
  373. package/src/channels/telegram/telegram-api.mjs +486 -0
  374. package/src/channels/telegram/telegram-bridge.mjs +81 -0
  375. package/src/channels/telegram/telegram-controller.mjs +52 -0
  376. package/src/channels/telegram/telegram-http.mjs +21 -0
  377. package/src/channels/telegram/telegram-rich-message.mjs +149 -0
  378. package/src/channels/telegram/telegram-runtime.mjs +1471 -0
  379. package/src/channels/wecom/config-store.mjs +172 -0
  380. package/src/channels/wecom/harness-client.mjs +11 -0
  381. package/src/channels/wecom/qr-auth.mjs +95 -0
  382. package/src/channels/wecom/send-error.mjs +31 -0
  383. package/src/channels/wecom/state-store.mjs +107 -0
  384. package/src/channels/wecom/wecom-bridge.mjs +1833 -0
  385. package/src/channels/wecom/wecom-cards.mjs +101 -0
  386. package/src/channels/wecom/wecom-controller.mjs +530 -0
  387. package/src/channels/wecom/wecom-runtime.mjs +269 -0
  388. package/src/channels/wecom-app/callback-server.mjs +471 -0
  389. package/src/channels/wecom-app/config-store.mjs +242 -0
  390. package/src/channels/wecom-app/harness-client.mjs +11 -0
  391. package/src/channels/wecom-app/state-store.mjs +107 -0
  392. package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
  393. package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
  394. package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
  395. package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
  396. package/src/channels/weixin/config-store.mjs +192 -0
  397. package/src/channels/weixin/connection-error.en.mjs +137 -0
  398. package/src/channels/weixin/connection-error.mjs +153 -0
  399. package/src/channels/weixin/diagnostic-details.mjs +1 -0
  400. package/src/channels/weixin/harness-client.mjs +19 -0
  401. package/src/channels/weixin/state-store.mjs +291 -0
  402. package/src/channels/weixin/weixin-api.mjs +949 -0
  403. package/src/channels/weixin/weixin-bridge.mjs +1537 -0
  404. package/src/channels/weixin/weixin-controller.mjs +669 -0
  405. package/src/channels/weixin/weixin-runtime.mjs +416 -0
  406. package/src/channels/whatsapp/config-store.mjs +210 -0
  407. package/src/channels/whatsapp/harness-client.mjs +11 -0
  408. package/src/channels/whatsapp/state-store.mjs +3 -0
  409. package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
  410. package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
  411. package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
  412. package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
@@ -0,0 +1,879 @@
1
+ import { extractConnectionEvidence, createConnectionDiagnostics, atConnectionStage } from '../shared/connection-error.mjs';
2
+ import { splitMessageText } from '../shared/editable-message-stream.mjs';
3
+ import { t } from '../shared/i18n.mjs';
4
+ import { createSlackHistoryReader } from './history-reader.mjs';
5
+ import { externalAttachments, readExternalFile, replyExternalFile } from './external-files.mjs';
6
+ import { SlackApi } from './slack-api.mjs';
7
+ import { createSlackBridgeStatus, SlackHarnessBridge } from './slack-bridge.mjs';
8
+ import { normalizeSlackExternalText, verifiedSlackAccount, slackRefusal, slackTimestamp } from './external-consumer.mjs';
9
+
10
+ const RECONNECT_DELAYS_MS = Object.freeze([1_000, 3_000, 5_000, 10_000, 30_000]);
11
+ const SLACK_MESSAGE_LIMIT = 38_000;
12
+ const SLACK_STREAM_CHUNK_LIMIT = 11_000;
13
+ const IMAGE_MEDIA_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
14
+
15
+ function addSocketListener(socket, event, listener) {
16
+ if (typeof socket.addEventListener === 'function') socket.addEventListener(event, listener);
17
+ else if (typeof socket.on === 'function') socket.on(event, listener);
18
+ else throw new TypeError('Slack WebSocket does not support events');
19
+ }
20
+
21
+ function eventData(event) {
22
+ const value = event?.data ?? event;
23
+ if (typeof value === 'string') return value;
24
+ if (Buffer.isBuffer(value)) return value.toString('utf8');
25
+ if (value instanceof ArrayBuffer) return Buffer.from(value).toString('utf8');
26
+ if (ArrayBuffer.isView(value)) {
27
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength).toString('utf8');
28
+ }
29
+ return null;
30
+ }
31
+
32
+ function socketUrl(value) {
33
+ const url = new URL(value);
34
+ if (url.protocol !== 'wss:') throw new Error('Slack returned an insecure Socket Mode URL');
35
+ return url.href;
36
+ }
37
+
38
+ function decodeSlackText(value) {
39
+ return typeof value === 'string' ? value
40
+ .replaceAll('&', '&')
41
+ .replaceAll('&lt;', '<')
42
+ .replaceAll('&gt;', '>') : '';
43
+ }
44
+
45
+ function stripBotMention(value, botUserId) {
46
+ return decodeSlackText(value)
47
+ .split(`<@${botUserId}>`).join('')
48
+ .split(`<@${String(botUserId).toLowerCase()}>`).join('')
49
+ .split(`<@${String(botUserId).toUpperCase()}>`).join('')
50
+ .trim();
51
+ }
52
+
53
+ function slackFileUrl(file) {
54
+ return typeof file?.url_private_download === 'string' && file.url_private_download
55
+ ? file.url_private_download : file?.url_private;
56
+ }
57
+
58
+ function slackReplyAttachment(file) {
59
+ if (!file || typeof file !== 'object') return null;
60
+ const mediaType = typeof file.mimetype === 'string' ? file.mimetype.toLowerCase() : '';
61
+ const kind = mediaType.startsWith('image/') ? 'image'
62
+ : mediaType.startsWith('audio/') ? 'audio'
63
+ : mediaType.startsWith('video/') ? 'video' : 'file';
64
+ const name = typeof file.name === 'string' && file.name
65
+ ? file.name : typeof file.title === 'string' && file.title ? file.title : undefined;
66
+ return { kind, ...(name ? { name } : {}) };
67
+ }
68
+
69
+ function slackReplySnapshot(message, messageTs) {
70
+ if (!message || String(message.ts ?? '') !== messageTs) return null;
71
+ const authorId = typeof message.user === 'string' && message.user
72
+ ? message.user : typeof message.bot_id === 'string' && message.bot_id
73
+ ? message.bot_id : undefined;
74
+ const authorName = typeof message.username === 'string' && message.username
75
+ ? message.username : undefined;
76
+ return {
77
+ messageId: messageTs,
78
+ ...(authorId ? { authorId } : {}),
79
+ ...(authorName ? { authorName } : {}),
80
+ content: decodeSlackText(message.text ?? ''),
81
+ attachments: Array.isArray(message.files)
82
+ ? message.files.map(slackReplyAttachment).filter(Boolean)
83
+ : [],
84
+ };
85
+ }
86
+
87
+ function slackThreadReplyReference(event, loadReply) {
88
+ const messageTs = typeof event?.thread_ts === 'string' ? event.thread_ts : '';
89
+ if (!messageTs || messageTs === String(event?.ts ?? '')) return undefined;
90
+ return {
91
+ messageId: messageTs,
92
+ load: async ({ signal } = {}) => {
93
+ try {
94
+ const message = await loadReply({
95
+ channelId: String(event.channel),
96
+ messageTs,
97
+ signal,
98
+ });
99
+ return slackReplySnapshot(message, messageTs);
100
+ } catch (error) {
101
+ if (error?.code === 'slack-missing-scope') {
102
+ return { messageId: messageTs, unavailableReason: 'permission-denied' };
103
+ }
104
+ throw error;
105
+ }
106
+ },
107
+ };
108
+ }
109
+
110
+ function slackImageSource(file, loadFile) {
111
+ const mediaType = typeof file?.mimetype === 'string' ? file.mimetype.toLowerCase() : '';
112
+ const url = slackFileUrl(file);
113
+ if (!IMAGE_MEDIA_TYPES.has(mediaType) || typeof url !== 'string' || !url) return null;
114
+ return {
115
+ name: typeof file.name === 'string' ? file.name : undefined,
116
+ mediaType,
117
+ size: Number.isSafeInteger(file.size) && file.size >= 0 ? file.size : undefined,
118
+ load: (options) => loadFile(url, options),
119
+ };
120
+ }
121
+
122
+ function slackFileSource(file, loadFile, loadFileInfo) {
123
+ const mediaType = typeof file?.mimetype === 'string' && file.mimetype
124
+ ? file.mimetype.toLowerCase() : undefined;
125
+ const url = slackFileUrl(file);
126
+ if (IMAGE_MEDIA_TYPES.has(mediaType)) return null;
127
+ const requiresInfo = file?.file_access === 'check_file_info'
128
+ && typeof file?.id === 'string' && file.id;
129
+ if ((typeof url !== 'string' || !url) && !requiresInfo) return null;
130
+ return {
131
+ name: typeof file?.name === 'string' && file.name
132
+ ? file.name : typeof file?.title === 'string' && file.title
133
+ ? file.title : requiresInfo ? file.id : 'slack-file',
134
+ ...(mediaType ? { mediaType } : {}),
135
+ size: Number.isSafeInteger(file?.size) && file.size >= 0 ? file.size : undefined,
136
+ load: async ({ signal } = {}) => {
137
+ if (!requiresInfo) return loadFile(url, { signal });
138
+ const resolved = await loadFileInfo(file.id, { signal });
139
+ const resolvedUrl = slackFileUrl(resolved);
140
+ if (typeof resolvedUrl !== 'string' || !resolvedUrl) {
141
+ throw new Error('Slack files.info returned no downloadable URL');
142
+ }
143
+ const loaded = await loadFile(resolvedUrl, { signal });
144
+ const name = typeof resolved?.name === 'string' && resolved.name
145
+ ? resolved.name : typeof resolved?.title === 'string' && resolved.title
146
+ ? resolved.title : file.id;
147
+ const resolvedMediaType = typeof resolved?.mimetype === 'string' && resolved.mimetype
148
+ ? resolved.mimetype.toLowerCase() : undefined;
149
+ if (Buffer.isBuffer(loaded) || loaded instanceof Uint8Array) {
150
+ return { data: loaded, name, ...(resolvedMediaType ? { mediaType: resolvedMediaType } : {}) };
151
+ }
152
+ return {
153
+ ...loaded,
154
+ name,
155
+ ...(resolvedMediaType ? { mediaType: resolvedMediaType } : {}),
156
+ };
157
+ },
158
+ };
159
+ }
160
+
161
+ export function normalizeSlackEvent(payload, botUserId, {
162
+ loadFile = async () => { throw new Error('Slack file downloader is unavailable'); },
163
+ loadFileStream = loadFile,
164
+ loadFileInfo = async () => { throw new Error('Slack file metadata loader is unavailable'); },
165
+ loadReply = async () => { throw new Error('Slack reply loader is unavailable'); },
166
+ } = {}) {
167
+ const event = payload?.event;
168
+ if (!event || !payload?.event_id || !event.channel || !event.user || !event.ts) return null;
169
+ const direct = event.type === 'message' && event.channel_type === 'im';
170
+ const mentioned = event.type === 'app_mention';
171
+ if (!direct && !mentioned) return null;
172
+ if ((event.subtype && event.subtype !== 'file_share') || event.bot_id || event.app_id) return null;
173
+ const threadTs = String(event.thread_ts ?? event.ts);
174
+ const replyTo = slackThreadReplyReference(event, loadReply);
175
+ return {
176
+ messageId: String(payload.event_id),
177
+ senderId: String(event.user),
178
+ senderIsBot: String(event.user) === String(botUserId),
179
+ kind: direct ? 'direct' : 'group',
180
+ conversationId: direct ? String(event.channel) : `${event.channel}:${threadTs}`,
181
+ contextSource: () => ({
182
+ chatId: String(event.channel),
183
+ threadId: event.thread_ts ? String(event.thread_ts) : undefined,
184
+ }),
185
+ content: stripBotMention(event.text ?? '', botUserId),
186
+ plainText: !Array.isArray(event.files) || event.files.length === 0,
187
+ images: Array.isArray(event.files)
188
+ ? event.files.map((file) => slackImageSource(file, loadFile)).filter(Boolean)
189
+ : [],
190
+ files: Array.isArray(event.files)
191
+ ? event.files.map((file) => slackFileSource(file, loadFileStream, loadFileInfo)).filter(Boolean)
192
+ : [],
193
+ ...(replyTo ? { replyTo } : {}),
194
+ addressed: direct || mentioned,
195
+ reactionTarget: {
196
+ channelId: String(event.channel),
197
+ messageTs: String(event.ts),
198
+ },
199
+ replyTarget: {
200
+ channelId: String(event.channel),
201
+ threadTs,
202
+ recipientUserId: String(event.user),
203
+ recipientTeamId: String(event.user_team ?? payload.team_id ?? ''),
204
+ },
205
+ connectionTestTarget: { channelId: String(event.channel) },
206
+ };
207
+ }
208
+
209
+ export function isSlackToolProgress(text) {
210
+ if (typeof text !== 'string') return false;
211
+ const marker = '__DSH_IM_TOOL_NAME__';
212
+ const template = t('正在使用{name}…', { name: marker });
213
+ const markerIndex = template.indexOf(marker);
214
+ if (markerIndex < 0) return false;
215
+ const prefix = template.slice(0, markerIndex);
216
+ const suffix = template.slice(markerIndex + marker.length);
217
+ const source = text.trim();
218
+ return source.startsWith(prefix)
219
+ && source.endsWith(suffix)
220
+ && source.length > prefix.length + suffix.length;
221
+ }
222
+
223
+ async function appendInChunks(api, target, ts, text, signal) {
224
+ if (!text) return;
225
+ for (let offset = 0; offset < text.length; offset += SLACK_STREAM_CHUNK_LIMIT) {
226
+ await api.appendStream({
227
+ channelId: target.channelId,
228
+ ts,
229
+ markdownText: text.slice(offset, offset + SLACK_STREAM_CHUNK_LIMIT),
230
+ signal,
231
+ });
232
+ }
233
+ }
234
+
235
+ async function createSlackMessageStream({ api, target, signal, logger }) {
236
+ const started = await api.startStream({
237
+ channelId: target.channelId,
238
+ threadTs: target.threadTs,
239
+ recipientTeamId: target.recipientTeamId || undefined,
240
+ recipientUserId: target.recipientUserId || undefined,
241
+ signal,
242
+ });
243
+ const ts = typeof started?.ts === 'string' ? started.ts : null;
244
+ if (!ts) throw new Error('Slack did not return a streaming message timestamp');
245
+
246
+ let appended = '';
247
+ let pending = '';
248
+ let timer = null;
249
+ let inFlight = null;
250
+ let broken = false;
251
+ let closed = false;
252
+ const providerMessageIds = [ts];
253
+
254
+ const appendLatest = async (text) => {
255
+ const next = splitMessageText(text, SLACK_MESSAGE_LIMIT)[0] ?? '';
256
+ if (!next || !next.startsWith(appended)) return;
257
+ const delta = next.slice(appended.length);
258
+ if (!delta) return;
259
+ await appendInChunks(api, target, ts, delta, signal);
260
+ appended = next;
261
+ };
262
+
263
+ const schedule = () => {
264
+ if (closed || broken || timer !== null || inFlight || !pending) return;
265
+ timer = setTimeout(() => {
266
+ timer = null;
267
+ const text = pending;
268
+ pending = '';
269
+ inFlight = appendLatest(text)
270
+ .catch((error) => {
271
+ broken = true;
272
+ logger.warn?.('[dsh-im:slack] streaming append failed:', error);
273
+ })
274
+ .finally(() => {
275
+ inFlight = null;
276
+ schedule();
277
+ });
278
+ }, 350);
279
+ timer?.unref?.();
280
+ };
281
+
282
+ return {
283
+ messageId: ts,
284
+ get providerMessageIds() {
285
+ return [...providerMessageIds];
286
+ },
287
+ update(text) {
288
+ if (closed || broken || typeof text !== 'string' || !text.trim()
289
+ || isSlackToolProgress(text)) return;
290
+ pending = text;
291
+ schedule();
292
+ },
293
+ async finish(text) {
294
+ if (closed) throw new Error('Slack message stream is already closed');
295
+ closed = true;
296
+ if (timer !== null) clearTimeout(timer);
297
+ timer = null;
298
+ pending = '';
299
+ await inFlight?.catch(() => undefined);
300
+
301
+ const chunks = splitMessageText(text, SLACK_MESSAGE_LIMIT);
302
+ const first = chunks[0] ?? t('处理完成。');
303
+ if (!broken && first.startsWith(appended)) {
304
+ await appendInChunks(api, target, ts, first.slice(appended.length), signal);
305
+ await api.stopStream({ channelId: target.channelId, ts, signal });
306
+ } else {
307
+ await api.stopStream({ channelId: target.channelId, ts, signal }).catch(() => undefined);
308
+ await api.updateMessage({ channelId: target.channelId, ts, text: first, signal });
309
+ }
310
+ for (const chunk of chunks.slice(1)) {
311
+ const result = await api.postMessage({
312
+ channelId: target.channelId,
313
+ threadTs: target.threadTs,
314
+ text: chunk,
315
+ signal,
316
+ });
317
+ if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
318
+ }
319
+ },
320
+ cancel() {
321
+ closed = true;
322
+ pending = '';
323
+ if (timer !== null) clearTimeout(timer);
324
+ timer = null;
325
+ void api.stopStream({ channelId: target.channelId, ts, signal }).catch(() => undefined);
326
+ },
327
+ };
328
+ }
329
+
330
+ export class SlackBotClient {
331
+ #api;
332
+ #signal;
333
+ #logger;
334
+
335
+ constructor({ api, signal, logger }) {
336
+ this.#api = api;
337
+ this.#signal = signal;
338
+ this.#logger = logger;
339
+ }
340
+
341
+ async sendText(target, text) {
342
+ const chunks = splitMessageText(text, SLACK_MESSAGE_LIMIT);
343
+ const providerMessageIds = [];
344
+ for (const chunk of chunks) {
345
+ const result = await this.#api.postMessage({
346
+ channelId: target.channelId,
347
+ threadTs: target.threadTs,
348
+ text: chunk,
349
+ signal: this.#signal,
350
+ });
351
+ if (typeof result?.ts === 'string' && result.ts) providerMessageIds.push(result.ts);
352
+ }
353
+ return { providerMessageIds };
354
+ }
355
+
356
+ async addReaction(target, emoji, { signal } = {}) {
357
+ const reactionKey = String(emoji ?? '').trim();
358
+ await this.#api.addReaction({
359
+ channelId: target.channelId,
360
+ messageTs: target.messageTs,
361
+ emojiName: reactionKey,
362
+ signal: signal ?? this.#signal,
363
+ });
364
+ return reactionKey;
365
+ }
366
+
367
+ removeReaction(target, reactionKey, { signal } = {}) {
368
+ return this.#api.removeReaction({
369
+ channelId: target.channelId,
370
+ messageTs: target.messageTs,
371
+ emojiName: reactionKey,
372
+ signal: signal ?? this.#signal,
373
+ });
374
+ }
375
+
376
+ openStream(target) {
377
+ return createSlackMessageStream({
378
+ api: this.#api,
379
+ target,
380
+ signal: this.#signal,
381
+ logger: this.#logger,
382
+ });
383
+ }
384
+
385
+ sendFile(target, file) {
386
+ return this.#api.uploadFile({
387
+ channelId: target.channelId,
388
+ threadTs: target.threadTs,
389
+ file,
390
+ signal: this.#signal,
391
+ });
392
+ }
393
+ }
394
+
395
+ export function createSlackRuntimeStatus() {
396
+ return {
397
+ startedAt: null,
398
+ ready: false,
399
+ connectionState: 'idle',
400
+ harnessReachable: false,
401
+ lastCheckedAt: null,
402
+ lastConnectedAt: null,
403
+ lastError: null,
404
+ ...createSlackBridgeStatus(),
405
+ };
406
+ }
407
+
408
+ export class SlackRuntime {
409
+ #config;
410
+ #botToken;
411
+ #appToken;
412
+ #harness;
413
+ #state;
414
+ #contextEnhancement;
415
+ #accessPolicy;
416
+ #logger;
417
+ #diagnostics;
418
+ #replyTimeoutMs;
419
+ #connectTimeoutMs;
420
+ #createApi;
421
+ #createWebSocket;
422
+ #status = createSlackRuntimeStatus();
423
+ #api = null;
424
+ #bridge = null;
425
+ #abortController = null;
426
+ #socket = null;
427
+ #appId = null;
428
+ #reconnectTimer = null;
429
+ #reconnectAttempt = 0;
430
+ #generation = 0;
431
+ #stopped = true;
432
+ #starting = null;
433
+ #externalConsumer;
434
+ #externalSourceFiles;
435
+ #externalOrdinaryText;
436
+ #account;
437
+
438
+ constructor({
439
+ config,
440
+ botToken,
441
+ appToken,
442
+ harness,
443
+ state,
444
+ contextEnhancement,
445
+ accessPolicy,
446
+ externalConsumer,
447
+ externalSourceFiles = () => false,
448
+ externalOrdinaryText = () => false,
449
+ logger = console,
450
+ replyTimeoutMs = 600_000,
451
+ connectTimeoutMs = 20_000,
452
+ createApi = (options) => new SlackApi(options),
453
+ createWebSocket = (url) => new WebSocket(url),
454
+ }) {
455
+ if (!config || !botToken || !appToken || !harness || !state) {
456
+ throw new TypeError('SlackRuntime requires config, both tokens, Harness, and state');
457
+ }
458
+ if (typeof createWebSocket !== 'function') throw new TypeError('SlackRuntime requires WebSocket');
459
+ this.#config = config;
460
+ this.#botToken = botToken;
461
+ this.#appToken = appToken;
462
+ this.#harness = harness;
463
+ this.#state = state;
464
+ this.#contextEnhancement = contextEnhancement;
465
+ this.#accessPolicy = accessPolicy;
466
+ this.#externalConsumer = externalConsumer;
467
+ this.#externalSourceFiles = externalSourceFiles;
468
+ this.#externalOrdinaryText = externalOrdinaryText;
469
+ this.#logger = logger; this.#diagnostics = createConnectionDiagnostics({ channel: 'slack', logger });
470
+ this.#replyTimeoutMs = replyTimeoutMs;
471
+ this.#connectTimeoutMs = connectTimeoutMs;
472
+ this.#createApi = createApi;
473
+ this.#createWebSocket = createWebSocket;
474
+ }
475
+
476
+ get status() {
477
+ return structuredClone(this.#status);
478
+ }
479
+
480
+ async sendConnectionTest(text) {
481
+ if (!this.#status.ready || !this.#bridge) {
482
+ const error = new Error('Slack bot is not connected');
483
+ error.code = 'test-target-unavailable';
484
+ throw error;
485
+ }
486
+ return this.#bridge.sendConnectionTest(text);
487
+ }
488
+
489
+ async sendProactiveText(target, text, options = {}) {
490
+ if (this.#config.consumerMode === 'external-consumer') {
491
+ const generation = this.#generation;
492
+ if (!this.#status.ready || !this.#account) throw slackRefusal('bot-not-connected');
493
+ if (options.expectedFingerprint !== this.#account.fingerprint) throw slackRefusal('account-changed');
494
+ const channelId = target?.route?.channelId;
495
+ if (target?.kind !== 'conversation' || typeof channelId !== 'string' || target.route.threadTs !== undefined)
496
+ throw slackRefusal('invalid-target');
497
+ if (options.receipt !== undefined && typeof options.receipt !== 'boolean') throw slackRefusal('bad-request');
498
+ if (options.format !== undefined && options.format !== 'plain') throw slackRefusal('capability-unavailable');
499
+ await this.#verifyChannel(channelId, options.signal);
500
+ options.signal?.throwIfAborted();
501
+ if (generation !== this.#generation || this.#stopped || !this.#status.ready)
502
+ throw slackRefusal('capability-unavailable');
503
+ const sent = await this.#postChecked({ channelId, text, signal: options.signal });
504
+ return { sent: true, ...(options.receipt
505
+ ? { receipt: { version: 1, messageId: sent.ts, conversationId: sent.channel } } : {}) };
506
+ }
507
+ if (!this.#status.ready || !this.#bridge) {
508
+ const error = new Error('Slack bot is not connected');
509
+ error.code = 'bot-not-connected';
510
+ throw error;
511
+ }
512
+ const channelId = typeof target?.route?.channelId === 'string'
513
+ ? target.route.channelId.trim() : '';
514
+ const threadTs = typeof target?.route?.threadTs === 'string'
515
+ ? target.route.threadTs.trim() : '';
516
+ if (!channelId
517
+ || (target?.kind !== 'conversation' && target?.kind !== 'thread')
518
+ || (target.kind === 'thread' && !threadTs)
519
+ || (target.kind === 'conversation' && threadTs)) {
520
+ const error = new TypeError('Invalid Slack proactive delivery target');
521
+ error.code = 'invalid-target';
522
+ throw error;
523
+ }
524
+ return this.#bridge.sendProactiveText({
525
+ channelId,
526
+ ...(threadTs ? { threadTs } : {}),
527
+ }, text, options);
528
+ }
529
+
530
+ async #verifyChannel(channelId, signal) {
531
+ signal?.throwIfAborted();
532
+ const channel = await this.#api.conversationInfo({ channelId, signal });
533
+ if (channel?.id !== channelId || channel.is_member !== true || channel.is_archived === true
534
+ || channel.is_private === true || channel.is_im === true || channel.is_mpim === true)
535
+ throw slackRefusal('reply-permission-denied');
536
+ return channel;
537
+ }
538
+
539
+ async #replySource(route, signal) {
540
+ if (!this.#status.ready || !this.#account || this.#config.consumerMode !== 'external-consumer')
541
+ throw slackRefusal('capability-unavailable');
542
+ if (!route || !slackTimestamp(route.messageId) || !slackTimestamp(route.threadId)
543
+ || route.rootId !== route.threadId || route.parentId !== undefined
544
+ || typeof route.actorId !== 'string' || !/^[UW][A-Z0-9]{4,30}$/.test(route.actorId))
545
+ throw slackRefusal('stale-route');
546
+ await this.#verifyChannel(route.conversationId, signal);
547
+ const source = route.messageId === route.threadId
548
+ ? await this.#api.getMessage({ channelId: route.conversationId, messageTs: route.messageId, signal })
549
+ : await this.#api.threadMessage({ channelId: route.conversationId, threadTs: route.threadId, messageTs: route.messageId, signal });
550
+ if (!source || source.deleted === true) throw slackRefusal('source-not-found');
551
+ if (source.ts !== route.messageId || (source.thread_ts ?? source.ts) !== route.threadId
552
+ || source.user !== route.actorId || source.bot_id || source.app_id)
553
+ throw slackRefusal('stale-route');
554
+ signal?.throwIfAborted();
555
+ return source;
556
+ }
557
+
558
+ async qualifyReplyChecked(route, { signal } = {}) {
559
+ const source = await this.#replySource(route, signal);
560
+ return { messageId: route.messageId, conversationId: route.conversationId,
561
+ actorId: source.user, threadId: route.threadId, rootId: route.rootId };
562
+ }
563
+
564
+ async externalFileChecked(route, file, { signal, reply = false } = {}) {
565
+ const generation = this.#generation;
566
+ const api = this.#api;
567
+ const lifetime = this.#abortController?.signal;
568
+ if (!api || !lifetime) throw slackRefusal('capability-unavailable');
569
+ const combined = signal ? AbortSignal.any([signal, lifetime]) : lifetime;
570
+ const assertCurrent = () => {
571
+ combined.throwIfAborted();
572
+ if (generation !== this.#generation || this.#stopped || !this.#status.ready)
573
+ throw slackRefusal('capability-unavailable');
574
+ };
575
+ const source = () => this.#replySource(route, combined);
576
+ return reply
577
+ ? replyExternalFile(api, route, file, { signal: combined, assertCurrent, source })
578
+ : readExternalFile(api, route, file, { signal: combined, assertCurrent, source });
579
+ }
580
+
581
+ #readHistory = createSlackHistoryReader();
582
+
583
+ async historyChecked(route, query, { signal } = {}) {
584
+ const generation = this.#generation;
585
+ const assertCurrent = () => {
586
+ if (generation !== this.#generation || this.#stopped || !this.#status.ready)
587
+ throw slackRefusal('capability-unavailable');
588
+ };
589
+ // Same membership/author/native thread qualification as a checked reply, every page.
590
+ try { await this.qualifyReplyChecked(route, { signal }); }
591
+ catch (error) {
592
+ if (error?.code === 'reply-permission-denied' || ['missing_scope', 'not_in_channel',
593
+ 'channel_not_found', 'is_archived', 'no_permission'].includes(error?.providerCode))
594
+ throw slackRefusal('history-permission-denied');
595
+ if (error?.providerCode === 'thread_not_found') throw slackRefusal('thread-unavailable');
596
+ throw error;
597
+ }
598
+ assertCurrent();
599
+ return this.#readHistory(this.#api, { botId: this.#config.botId, account: this.#account },
600
+ route, query, signal, assertCurrent);
601
+ }
602
+
603
+ async #postChecked(input) {
604
+ try {
605
+ const sent = await this.#api.postMessage({ ...input, retry: false });
606
+ if (!slackTimestamp(sent?.ts) || sent.channel !== input.channelId)
607
+ throw slackRefusal('reply-result-unknown');
608
+ return sent;
609
+ } catch (error) {
610
+ if (['missing_scope', 'not_in_channel', 'channel_not_found', 'is_archived', 'no_permission'].includes(error?.providerCode))
611
+ throw slackRefusal('reply-permission-denied');
612
+ throw slackRefusal('reply-result-unknown');
613
+ }
614
+ }
615
+
616
+ async replyChecked(route, text, { signal, receipt = false, beforeSend } = {}) {
617
+ const generation = this.#generation;
618
+ await this.qualifyReplyChecked(route, { signal });
619
+ if (beforeSend && beforeSend() !== true) throw slackRefusal('stale-route');
620
+ signal?.throwIfAborted();
621
+ if (generation !== this.#generation || this.#stopped || !this.#status.ready)
622
+ throw slackRefusal('capability-unavailable');
623
+ const sent = await this.#postChecked({ channelId: route.conversationId, threadTs: route.threadId, text, signal });
624
+ return { sent: true, ...(receipt ? { receipt: { version: 1, messageId: sent.ts, conversationId: sent.channel } } : {}) };
625
+ }
626
+
627
+ async start() {
628
+ if (this.#status.ready && this.#socket) return this.status;
629
+ if (this.#starting) return this.#starting;
630
+ this.#starting = this.#start().finally(() => {
631
+ this.#starting = null;
632
+ });
633
+ return this.#starting;
634
+ }
635
+
636
+ async #start() {
637
+ await this.stop();
638
+ this.#stopped = false;
639
+ this.#reconnectAttempt = 0;
640
+ this.#status.startedAt = new Date().toISOString();
641
+ this.#status.connectionState = 'connecting';
642
+ this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
643
+ await atConnectionStage('harness.check', () => this.#harness.ensureRunning());
644
+ this.#status.harnessReachable = true;
645
+ const controller = new AbortController();
646
+ this.#abortController = controller;
647
+ const api = this.#createApi({ botToken: this.#botToken, appToken: this.#appToken });
648
+ this.#api = api;
649
+ try {
650
+ const identity = await api.authTest({ signal: controller.signal });
651
+ if (`${identity?.team_id}:${identity?.user_id}` !== this.#config.platformId) {
652
+ throw new Error('Slack Bot Token identity does not match the saved bot');
653
+ }
654
+ if (this.#config.consumerMode === 'external-consumer') {
655
+ this.#account = verifiedSlackAccount(identity, await api.botInfo({ botId: identity.bot_id, signal: controller.signal }));
656
+ }
657
+ if (this.#config.consumerMode !== 'external-consumer') {
658
+ const client = new SlackBotClient({ api, signal: controller.signal, logger: this.#logger });
659
+ this.#bridge = new SlackHarnessBridge({
660
+ bot: client,
661
+ harness: this.#harness,
662
+ state: this.#state,
663
+ contextEnhancement: this.#contextEnhancement,
664
+ accessPolicy: this.#accessPolicy,
665
+ status: this.#status,
666
+ logger: this.#logger,
667
+ replyTimeoutMs: this.#replyTimeoutMs,
668
+ signal: controller.signal,
669
+ });
670
+ }
671
+ let timer;
672
+ try {
673
+ await Promise.race([
674
+ this.#connect(),
675
+ new Promise((_, reject) => {
676
+ timer = setTimeout(
677
+ () => reject(Object.assign(new Error('Slack Socket Mode did not become ready in time'), { code: 'ETIMEDOUT', timeoutMs: this.#connectTimeoutMs })),
678
+ this.#connectTimeoutMs,
679
+ );
680
+ timer?.unref?.();
681
+ }),
682
+ ]);
683
+ } finally {
684
+ clearTimeout(timer);
685
+ }
686
+ return this.status;
687
+ } catch (error) {
688
+ this.#status.ready = false;
689
+ this.#status.connectionState = 'failed';
690
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.restore', reuse: true, botId: this.#config?.botId, automatic: true }).publicError;
691
+ this.#status.lastError = this.#status.error.message;
692
+ await this.stop();
693
+ throw error;
694
+ }
695
+ }
696
+
697
+ async #connect() {
698
+ if (this.#stopped) throw new Error('Slack runtime is stopped');
699
+ const connection = await this.#api.openConnection({ signal: this.#abortController?.signal });
700
+ return this.#openSocket(connection?.url);
701
+ }
702
+
703
+ #openSocket(value) {
704
+ if (this.#stopped) return Promise.reject(new Error('Slack runtime is stopped'));
705
+ const generation = ++this.#generation;
706
+ const socket = this.#createWebSocket(socketUrl(value));
707
+ this.#socket = socket;
708
+ let settled = false;
709
+ return new Promise((resolve, reject) => {
710
+ const markReady = (packet) => {
711
+ if (settled || generation !== this.#generation) return;
712
+ settled = true;
713
+ this.#appId = packet?.connection_info?.app_id ?? null;
714
+ if (this.#account && this.#appId !== this.#account.appId) {
715
+ reject(slackRefusal('account-changed'));
716
+ socket.close(4000, 'Account mismatch');
717
+ return;
718
+ }
719
+ this.#reconnectAttempt = 0;
720
+ const now = Date.now();
721
+ this.#status.ready = true;
722
+ this.#status.connectionState = 'connected';
723
+ this.#status.lastCheckedAt = now;
724
+ this.#status.lastConnectedAt = now;
725
+ this.#status.lastError = null; this.#status.error = null; this.#diagnostics.clear();
726
+ resolve();
727
+ };
728
+
729
+ addSocketListener(socket, 'message', (event) => {
730
+ if (generation !== this.#generation || this.#stopped) return;
731
+ const raw = eventData(event);
732
+ if (!raw) return;
733
+ let packet;
734
+ try {
735
+ packet = JSON.parse(raw);
736
+ } catch {
737
+ this.#logger.warn?.('[dsh-im:slack] ignored malformed Socket Mode JSON');
738
+ return;
739
+ }
740
+ if (packet.type === 'hello') {
741
+ markReady(packet);
742
+ return;
743
+ }
744
+ const acknowledge = () => {
745
+ if (generation !== this.#generation || this.#stopped || socket.readyState !== 1) return;
746
+ if (!packet.envelope_id) return;
747
+ socket.send(JSON.stringify({ envelope_id: packet.envelope_id }));
748
+ this.#status.lastCheckedAt = Date.now();
749
+ };
750
+ if (packet.type === 'disconnect') {
751
+ socket.close(4000, 'Slack requested reconnect');
752
+ return;
753
+ }
754
+ if (this.#config.consumerMode === 'external-consumer') {
755
+ if (packet.type !== 'events_api' || packet.payload?.type !== 'event_callback') { acknowledge(); return; }
756
+ void this.#acceptExternal(packet.payload, generation).then(acknowledge).catch(error => {
757
+ if (generation !== this.#generation || this.#stopped) return;
758
+ this.#diagnostics.report(error, { operation: 'inbound.accept', botId: this.#config.botId,
759
+ publicError: { code: error?.code ?? 'ingress-not-accepted', message: 'External consumer did not accept the Slack event.' } });
760
+ });
761
+ return;
762
+ }
763
+ acknowledge();
764
+ if (packet.type !== 'events_api' || packet.payload?.type !== 'event_callback') return;
765
+ if (this.#appId && packet.payload.api_app_id
766
+ && packet.payload.api_app_id !== this.#appId) return;
767
+ const message = normalizeSlackEvent(packet.payload, this.#config.platformId.split(':')[1], {
768
+ loadFile: (url, options) => this.#api.downloadFile({ url, ...options }),
769
+ loadFileStream: (url, options) => this.#api.downloadFileStream({ url, ...options }),
770
+ loadFileInfo: (fileId, options) => this.#api.fileInfo({ fileId, ...options }),
771
+ loadReply: (options) => this.#api.getMessage(options),
772
+ });
773
+ const bridge = this.#bridge;
774
+ if (message && bridge) {
775
+ void bridge.accept(message).catch((error) => {
776
+ if (generation !== this.#generation || this.#stopped) return;
777
+ this.#logger.error?.(
778
+ `[dsh-im:slack] bot ${this.#config.botId} message handling failed:`,
779
+ extractConnectionEvidence(error).details,
780
+ );
781
+ });
782
+ }
783
+ });
784
+
785
+ addSocketListener(socket, 'close', (event = {}) => {
786
+ if (generation !== this.#generation) return;
787
+ if (this.#socket === socket) this.#socket = null;
788
+ if (this.#stopped) {
789
+ if (!settled) reject(new DOMException('Stopped', 'AbortError'));
790
+ return;
791
+ }
792
+ const code = Number(event.code) || 0;
793
+ const error = new Error(`Slack Socket Mode closed (${code || 'unknown'})`);
794
+ this.#status.ready = false;
795
+ this.#status.connectionState = 'connecting';
796
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
797
+ this.#status.lastError = this.#status.error.message;
798
+ if (!settled) {
799
+ settled = true;
800
+ reject(error);
801
+ }
802
+ this.#scheduleReconnect();
803
+ });
804
+
805
+ addSocketListener(socket, 'error', (event) => {
806
+ const error = event?.error ?? new Error('WebSocket error');
807
+ if (generation !== this.#generation || this.#stopped) return;
808
+ this.#status.error = this.#diagnostics.report(error, { operation: 'connection.monitor', botId: this.#config?.botId, automatic: true }).publicError;
809
+ this.#status.lastError = this.#status.error.message;
810
+ });
811
+ });
812
+ }
813
+
814
+ #scheduleReconnect() {
815
+ if (this.#stopped || this.#reconnectTimer !== null) return;
816
+ const delay = RECONNECT_DELAYS_MS[Math.min(this.#reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)];
817
+ this.#reconnectAttempt += 1;
818
+ this.#reconnectTimer = setTimeout(() => {
819
+ this.#reconnectTimer = null;
820
+ void this.#connect().catch((error) => {
821
+ if (this.#stopped) return;
822
+ this.#logger.warn?.('[dsh-im:slack] Socket Mode reconnect failed:', extractConnectionEvidence(error).details);
823
+ this.#scheduleReconnect();
824
+ });
825
+ }, delay);
826
+ this.#reconnectTimer?.unref?.();
827
+ }
828
+
829
+ async #acceptExternal(payload, generation) {
830
+ if (!this.#account || typeof this.#externalConsumer !== 'function') throw slackRefusal('consumer-unavailable');
831
+ const evidence = normalizeSlackExternalText(payload, { botId: this.#config.botId, account: this.#account, sourceFiles: this.#externalSourceFiles(), ordinaryText: this.#externalOrdinaryText() });
832
+ if (!evidence) return;
833
+ const signal = this.#abortController.signal;
834
+ await this.#verifyChannel(evidence.conversation.id, signal);
835
+ let name;
836
+ try {
837
+ const user = await this.#api.userInfo({ userId: evidence.actor.id, signal });
838
+ if (user?.id === evidence.actor.id) name = user.profile?.display_name || user.real_name || user.name;
839
+ } catch { signal.throwIfAborted(); }
840
+ const withFiles = this.#externalSourceFiles()
841
+ ? await externalAttachments(evidence, () => this.#replySource(evidence.reply, signal)) : evidence;
842
+ const enriched = { ...withFiles,
843
+ actor: { ...evidence.actor, ...(typeof name === 'string' && name ? { name: name.slice(0, 512) } : {}) } };
844
+ if (generation !== this.#generation || this.#stopped) throw slackRefusal('cancelled');
845
+ const result = await this.#externalConsumer(enriched, signal);
846
+ signal.throwIfAborted();
847
+ if (result?.accepted !== true) throw slackRefusal('ingress-not-accepted');
848
+ this.#status.messagesReceived += 1;
849
+ }
850
+
851
+ async stop() {
852
+ this.#readHistory = createSlackHistoryReader();
853
+ this.#stopped = true;
854
+ this.#generation += 1;
855
+ this.#abortController?.abort();
856
+ this.#abortController = null;
857
+ if (this.#reconnectTimer !== null) clearTimeout(this.#reconnectTimer);
858
+ this.#reconnectTimer = null;
859
+ const socket = this.#socket;
860
+ const bridge = this.#bridge;
861
+ this.#socket = null;
862
+ this.#bridge = null;
863
+ this.#api = null;
864
+ this.#appId = null;
865
+ this.#account = null;
866
+ try {
867
+ if (socket && socket.readyState < 2) socket.close(1000, 'Plugin stopped');
868
+ } catch (error) {
869
+ this.#logger.warn?.(`[dsh-im:slack] bot ${this.#config.botId} failed to close Socket Mode:`, extractConnectionEvidence(error).details);
870
+ }
871
+ await Promise.race([
872
+ bridge?.waitForIdle() ?? Promise.resolve(),
873
+ new Promise((resolve) => setTimeout(resolve, 2_000)),
874
+ ]);
875
+ this.#status.ready = false;
876
+ this.#status.connectionState = 'idle';
877
+ return this.status;
878
+ }
879
+ }