@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,416 @@
1
+ import { createWeixinDiagnostics } from './connection-error.mjs';
2
+ import { DEFAULT_WEIXIN_MAX_MESSAGE_CHARS, WeixinApiError, rejectedProviderResponse } from './weixin-api.mjs';
3
+ import {
4
+ createWeixinBridgeStatus, WeixinHarnessBridge, weixinSendError, weixinSendFailureOptions,
5
+ } from './weixin-bridge.mjs';
6
+ import { providerMessageIdsFor } from '../shared/semantic/delivery.mjs';
7
+ import {
8
+ channelDeliveryFailure, clearLastMessageFailure, setLastMessageFailure,
9
+ } from '../shared/message-failure.mjs';
10
+ import {
11
+ connectionTestTarget,
12
+ connectionTestTargetUnavailable,
13
+ } from '../shared/connection-test.mjs';
14
+ import { t } from '../shared/i18n.mjs';
15
+
16
+ const DEFAULT_START_RETRY_DELAYS_MS = Object.freeze([250, 1_000, 3_000]);
17
+ const HARNESS_HEALTH_ERROR_CODES = new Set([
18
+ 'harness-connect-failed',
19
+ 'harness-timeout',
20
+ 'harness-auth-required',
21
+ 'harness-proxy-auth-required',
22
+ 'harness-loopback-forbidden',
23
+ 'harness-host-untrusted',
24
+ 'harness-request-forbidden',
25
+ 'harness-api-not-found',
26
+ 'harness-http-failed',
27
+ 'harness-response-invalid',
28
+ 'harness-rpc-rejected',
29
+ ]);
30
+
31
+ function startRetryDelays(value) {
32
+ if (value === undefined) return [...DEFAULT_START_RETRY_DELAYS_MS];
33
+ if (!Array.isArray(value)) throw new TypeError('startRetryDelaysMs must be an array');
34
+ return value.map((wait) => {
35
+ if (!Number.isFinite(wait) || wait < 0) {
36
+ throw new TypeError('startRetryDelaysMs must contain non-negative delays');
37
+ }
38
+ return wait;
39
+ });
40
+ }
41
+
42
+ function retryableStartError(error) {
43
+ if (!(error instanceof WeixinApiError)) return false;
44
+ if (error.code === 'network-error' || error.code === 'timeout') return true;
45
+ return error.code === 'http-error'
46
+ && (error.status === 408 || error.status === 425 || error.status === 429 || error.status >= 500);
47
+ }
48
+
49
+ function runtimeStartError(code, cause) {
50
+ const error = new Error(`Weixin runtime failed during ${code}`, { cause });
51
+ error.name = 'WeixinRuntimeStartError';
52
+ error.code = code;
53
+ return error;
54
+ }
55
+
56
+ function harnessHealthError(cause) {
57
+ const code = HARNESS_HEALTH_ERROR_CODES.has(cause?.code)
58
+ ? cause.code
59
+ : 'harness-check-unknown-failed';
60
+ return runtimeStartError(code, cause);
61
+ }
62
+
63
+ function delay(ms, signal) {
64
+ return new Promise((resolve, reject) => {
65
+ if (signal?.aborted) {
66
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
67
+ return;
68
+ }
69
+ const finish = () => {
70
+ signal?.removeEventListener('abort', onAbort);
71
+ resolve();
72
+ };
73
+ const timer = setTimeout(finish, ms);
74
+ const onAbort = () => {
75
+ clearTimeout(timer);
76
+ signal?.removeEventListener('abort', onAbort);
77
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
78
+ };
79
+ signal?.addEventListener('abort', onAbort, { once: true });
80
+ });
81
+ }
82
+
83
+ export function orderWeixinMessages(messages) {
84
+ if (!Array.isArray(messages) || messages.length < 2) return Array.isArray(messages) ? messages : [];
85
+ const orderField = ['seq', 'create_time_ms'].find((field) => messages.every((message) => (
86
+ (typeof message?.[field] === 'number' && Number.isFinite(message[field]))
87
+ || (typeof message?.[field] === 'string'
88
+ && message[field].trim()
89
+ && Number.isFinite(Number(message[field])))
90
+ )));
91
+ if (!orderField) return messages;
92
+ return messages
93
+ .map((message, index) => ({ message, index, order: Number(message[orderField]) }))
94
+ .sort((left, right) => (
95
+ left.order - right.order || left.index - right.index
96
+ ))
97
+ .map(({ message }) => message);
98
+ }
99
+
100
+ export function createWeixinRuntimeStatus() {
101
+ return {
102
+ startedAt: null,
103
+ ready: false,
104
+ weixinConnectionState: 'idle',
105
+ harnessReachable: false,
106
+ lastCheckedAt: null,
107
+ lastError: null,
108
+ connectionError: null,
109
+ ...createWeixinBridgeStatus(),
110
+ };
111
+ }
112
+
113
+ export class WeixinRuntime {
114
+ #api;
115
+ #config;
116
+ #token;
117
+ #harness;
118
+ #state;
119
+ #contextEnhancement;
120
+ #accessPolicy;
121
+ #logger;
122
+ #diagnostics;
123
+ #startContext = {};
124
+ #replyTimeoutMs;
125
+ #maxMessageChars;
126
+ #startRetryDelaysMs;
127
+ #status = createWeixinRuntimeStatus();
128
+ #bridge = null;
129
+ #abortController = null;
130
+ #monitor = null;
131
+ #starting = null;
132
+
133
+ constructor({
134
+ api,
135
+ config,
136
+ token,
137
+ harness,
138
+ state,
139
+ contextEnhancement,
140
+ accessPolicy,
141
+ logger = console,
142
+ diagnostics,
143
+ replyTimeoutMs = 600_000,
144
+ maxMessageChars = DEFAULT_WEIXIN_MAX_MESSAGE_CHARS,
145
+ startRetryDelaysMs,
146
+ }) {
147
+ if (!api || !config || !token || !harness || !state) {
148
+ throw new TypeError('WeixinRuntime requires API, account, token, Harness, and state');
149
+ }
150
+ this.#api = api;
151
+ this.#config = config;
152
+ this.#token = token;
153
+ this.#harness = harness;
154
+ this.#state = state;
155
+ this.#contextEnhancement = contextEnhancement;
156
+ this.#accessPolicy = accessPolicy;
157
+ this.#logger = logger;
158
+ this.#diagnostics = diagnostics ?? createWeixinDiagnostics({ logger });
159
+ this.#replyTimeoutMs = replyTimeoutMs;
160
+ this.#maxMessageChars = maxMessageChars;
161
+ this.#startRetryDelaysMs = startRetryDelays(startRetryDelaysMs);
162
+ }
163
+
164
+ get status() {
165
+ return structuredClone(this.#status);
166
+ }
167
+
168
+ async start(context = {}) {
169
+ if (this.#status.ready && this.#monitor) return this.status;
170
+ if (this.#starting) return this.#starting;
171
+ this.#startContext = context;
172
+ this.#starting = this.#start().finally(() => {
173
+ this.#starting = null;
174
+ });
175
+ return this.#starting;
176
+ }
177
+
178
+ async #start() {
179
+ await this.stop();
180
+ this.#status.startedAt = new Date().toISOString();
181
+ this.#status.weixinConnectionState = 'connecting';
182
+ this.#status.lastError = null;
183
+ this.#status.connectionError = null;
184
+ try {
185
+ try {
186
+ await this.#harness.ensureRunning();
187
+ } catch (error) {
188
+ throw harnessHealthError(error);
189
+ }
190
+ this.#status.harnessReachable = true;
191
+ await this.#state.bindContextTokens?.(this.#token);
192
+ await this.#notifyStart();
193
+ this.#abortController = new AbortController();
194
+ const signal = this.#abortController.signal;
195
+ this.#bridge = new WeixinHarnessBridge({
196
+ api: this.#api,
197
+ baseUrl: this.#config.baseUrl,
198
+ token: this.#token,
199
+ ownerUserId: this.#config.ownerUserId,
200
+ harness: this.#harness,
201
+ state: this.#state,
202
+ contextEnhancement: this.#contextEnhancement,
203
+ accessPolicy: this.#accessPolicy,
204
+ status: this.#status,
205
+ logger: this.#logger,
206
+ replyTimeoutMs: this.#replyTimeoutMs,
207
+ maxMessageChars: this.#maxMessageChars,
208
+ signal,
209
+ });
210
+ this.#status.ready = true;
211
+ this.#status.weixinConnectionState = 'connected';
212
+ this.#status.lastCheckedAt = Date.now();
213
+ this.#monitor = this.#runMonitor(signal).catch((error) => {
214
+ if (signal.aborted) return;
215
+ this.#status.ready = false;
216
+ this.#status.weixinConnectionState = 'failed';
217
+ const failure = this.#diagnostics.report(error, {
218
+ operation: 'connection.monitor', stage: 'connection.poll', botId: this.#config.botId, automatic: true,
219
+ });
220
+ this.#status.connectionError = failure.publicError;
221
+ this.#status.lastError = failure.publicError.message;
222
+ });
223
+ return this.status;
224
+ } catch (error) {
225
+ this.#abortController?.abort();
226
+ this.#abortController = null;
227
+ this.#bridge = null;
228
+ this.#status.ready = false;
229
+ this.#status.weixinConnectionState = 'failed';
230
+ throw error;
231
+ }
232
+ }
233
+
234
+ async #notifyStart() {
235
+ for (let attempt = 0; ; attempt += 1) {
236
+ try {
237
+ return await this.#api.notifyStart({
238
+ baseUrl: this.#config.baseUrl,
239
+ token: this.#token,
240
+ });
241
+ } catch (error) {
242
+ const wait = this.#startRetryDelaysMs[attempt];
243
+ if (wait === undefined || !retryableStartError(error)) throw error;
244
+ this.#diagnostics.report(error, {
245
+ ...this.#startContext, stage: 'connection.start', botId: this.#config.botId, automatic: true, warning: true,
246
+ });
247
+ await delay(wait);
248
+ }
249
+ }
250
+ }
251
+
252
+ async #runMonitor(signal) {
253
+ let consecutiveFailures = 0;
254
+ while (!signal.aborted) {
255
+ try {
256
+ const response = await this.#api.getUpdates({
257
+ baseUrl: this.#config.baseUrl,
258
+ token: this.#token,
259
+ getUpdatesBuf: this.#state.getUpdatesBuf(),
260
+ signal,
261
+ });
262
+ if (signal.aborted) return;
263
+ const providerCode = rejectedProviderResponse(response, ['errcode', 'ret']);
264
+ if (providerCode) {
265
+ throw new WeixinApiError(
266
+ providerCode === '-14' ? 'stale-token' : 'updates-rejected',
267
+ providerCode === '-14' ? t('微信登录凭据已失效,请移除账号后重新扫码。') : t('微信消息同步请求被拒绝。'),
268
+ { providerCode },
269
+ );
270
+ }
271
+ consecutiveFailures = 0;
272
+ this.#status.ready = true;
273
+ this.#status.weixinConnectionState = 'connected';
274
+ this.#status.lastCheckedAt = Date.now();
275
+ this.#status.lastError = null;
276
+ this.#status.connectionError = null;
277
+
278
+ for (const message of orderWeixinMessages(response?.msgs)) {
279
+ void this.#bridge.accept(message).catch((error) => {
280
+ if (signal.aborted) return;
281
+ this.#logger.error?.(
282
+ `[dsh-weixin] account ${this.#config.botId} message handling failed:`,
283
+ error,
284
+ );
285
+ });
286
+ }
287
+ if (typeof response?.get_updates_buf === 'string' && response.get_updates_buf) {
288
+ await this.#state.setGetUpdatesBuf(response.get_updates_buf);
289
+ }
290
+ } catch (error) {
291
+ if (signal.aborted) return;
292
+ consecutiveFailures += 1;
293
+ const failure = this.#diagnostics.report(error, {
294
+ operation: 'connection.monitor', stage: 'connection.poll', botId: this.#config.botId, automatic: true, warning: true,
295
+ });
296
+ this.#status.lastError = failure.publicError.message;
297
+ if (error instanceof WeixinApiError && error.code === 'stale-token') throw failure;
298
+ if (consecutiveFailures >= 3) throw failure;
299
+ await delay(Math.min(2_000 * (2 ** (consecutiveFailures - 1)), 10_000), signal);
300
+ }
301
+ }
302
+ }
303
+
304
+ async stop() {
305
+ const warnings = [];
306
+ const monitor = this.#monitor;
307
+ const bridge = this.#bridge;
308
+ const wasStarted = Boolean(this.#abortController || monitor || this.#status.ready);
309
+ this.#abortController?.abort();
310
+ this.#abortController = null;
311
+ this.#monitor = null;
312
+ await bridge?.close?.();
313
+ await monitor?.catch(() => undefined);
314
+ await bridge?.waitForIdle();
315
+ this.#bridge = null;
316
+ if (wasStarted) {
317
+ try {
318
+ await this.#api.notifyStop({
319
+ baseUrl: this.#config.baseUrl,
320
+ token: this.#token,
321
+ signal: AbortSignal.timeout(10_000),
322
+ });
323
+ } catch (error) {
324
+ warnings.push(this.#diagnostics.report(error, {
325
+ operation: 'connection.close', stage: 'connection.stop', code: 'connection-stop-failed', botId: this.#config.botId, warning: true,
326
+ }).publicError);
327
+ }
328
+ }
329
+ this.#status.ready = false;
330
+ this.#status.weixinConnectionState = 'idle';
331
+ return { ...this.status, ...(warnings.length ? { warnings } : {}) };
332
+ }
333
+
334
+ async sendConnectionTest(text) {
335
+ const remembered = connectionTestTarget(this.#state);
336
+ const toUserId = typeof remembered?.toUserId === 'string' && remembered.toUserId.trim()
337
+ ? remembered.toUserId.trim()
338
+ : typeof this.#config.ownerUserId === 'string' && this.#config.ownerUserId.trim()
339
+ ? this.#config.ownerUserId.trim()
340
+ : null;
341
+ if (!toUserId) throw connectionTestTargetUnavailable(t('微信机器人'));
342
+ if (!this.#status.ready || !this.#abortController) {
343
+ throw new Error('Weixin runtime is not connected');
344
+ }
345
+ await this.#sendTrackedText({
346
+ toUserId,
347
+ text,
348
+ signal: this.#abortController.signal,
349
+ });
350
+ return { sent: true };
351
+ }
352
+
353
+ async #sendTrackedText({ toUserId, text, signal }) {
354
+ const sentAt = Date.now();
355
+ const contextToken = this.#state.contextTokenFor?.(toUserId);
356
+ let result;
357
+ try {
358
+ result = await this.#api.sendText({
359
+ baseUrl: this.#config.baseUrl,
360
+ token: this.#token,
361
+ toUserId,
362
+ text,
363
+ contextToken,
364
+ signal,
365
+ });
366
+ } catch (cause) {
367
+ if (signal?.aborted) throw cause;
368
+ const error = weixinSendError(cause, {
369
+ baseUrl: this.#config.baseUrl, text, chunk: text, chunkIndex: 0, chunkCount: 1,
370
+ maxMessageChars: this.#maxMessageChars, contextToken,
371
+ });
372
+ const failure = setLastMessageFailure(this.#status,
373
+ channelDeliveryFailure(error, { uncertain: cause?.code !== 'send-rejected' }),
374
+ weixinSendFailureOptions(error, { proactive: true }));
375
+ this.#logger.warn?.(`[dsh-weixin] outbound delivery failed [${failure.referenceId}]: ${failure.message}`);
376
+ throw error;
377
+ }
378
+ if (this.#status.lastMessageError?.reason === 'WEIXIN_SEND_FAILED') {
379
+ clearLastMessageFailure(this.#status);
380
+ }
381
+ try {
382
+ await this.#state.rememberOutboundMessage?.({
383
+ toUserId,
384
+ text,
385
+ sentAt,
386
+ completedAt: Date.now(),
387
+ providerMessageIds: providerMessageIdsFor(result),
388
+ });
389
+ } catch (error) {
390
+ this.#logger.warn?.('[dsh-weixin] failed to remember an outbound message:', error);
391
+ }
392
+ return result;
393
+ }
394
+
395
+ async sendProactiveText(target, text, { signal } = {}) {
396
+ const toUserId = typeof target?.route?.toUserId === 'string'
397
+ ? target.route.toUserId.trim() : '';
398
+ if (target?.kind !== 'user' || !toUserId) {
399
+ const error = new TypeError('Invalid Weixin proactive delivery target');
400
+ error.code = 'invalid-target';
401
+ throw error;
402
+ }
403
+ if (!this.#status.ready || !this.#abortController) {
404
+ const error = new Error('Weixin runtime is not connected');
405
+ error.code = 'bot-not-connected';
406
+ throw error;
407
+ }
408
+ signal?.throwIfAborted();
409
+ await this.#sendTrackedText({
410
+ toUserId,
411
+ text,
412
+ signal: signal ?? this.#abortController.signal,
413
+ });
414
+ return { sent: true };
415
+ }
416
+ }
@@ -0,0 +1,210 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+
5
+ import { t } from '../shared/i18n.mjs';
6
+
7
+ const EMPTY_DOCUMENT = Object.freeze({ version: 2, bots: Object.freeze([]) });
8
+ const BOT_ID_PATTERN = /^whatsapp_[a-f0-9]{24}$/;
9
+ const AUTH_DIRECTORY_PATTERN = /^[a-f0-9-]{36}$/;
10
+ const WHATSAPP_PHONE_NUMBER = /^[1-9]\d{4,14}$/;
11
+
12
+ export const WHATSAPP_ACCESS_MODES = Object.freeze({
13
+ selfOnly: 'self-only',
14
+ privateAllowlist: 'private-allowlist',
15
+ open: 'open',
16
+ });
17
+
18
+ function cleanString(value) {
19
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
20
+ }
21
+
22
+ export function normalizeWhatsappAccountJid(value) {
23
+ const jid = cleanString(value)?.toLowerCase();
24
+ return /^\d{5,32}@(s\.whatsapp\.net|lid)$/.test(jid ?? '') ? jid : null;
25
+ }
26
+
27
+ export function deriveWhatsappBotId(accountJid) {
28
+ const normalized = normalizeWhatsappAccountJid(accountJid);
29
+ if (!normalized) throw new TypeError('A valid WhatsApp account JID is required');
30
+ return `whatsapp_${createHash('sha256').update(normalized).digest('hex').slice(0, 24)}`;
31
+ }
32
+
33
+ export function maskWhatsappAccount(accountJid) {
34
+ const digits = normalizeWhatsappAccountJid(accountJid)?.split('@')[0] ?? '';
35
+ if (!digits) return t('WhatsApp账号');
36
+ if (digits.length <= 7) return `${digits.slice(0, 2)}•••${digits.slice(-2)}`;
37
+ return `${digits.slice(0, 4)}••••${digits.slice(-4)}`;
38
+ }
39
+
40
+ export function normalizeWhatsappAllowedNumbers(value) {
41
+ if (value === undefined) return Object.freeze([]);
42
+ if (!Array.isArray(value)) {
43
+ throw new TypeError('allowedNumbers must be an array of WhatsApp phone numbers');
44
+ }
45
+ const normalized = value.map((entry) => {
46
+ const number = typeof entry === 'string' ? entry.trim().replace(/^\+/, '') : '';
47
+ if (!WHATSAPP_PHONE_NUMBER.test(number)) {
48
+ throw new TypeError('allowedNumbers contains an invalid WhatsApp phone number');
49
+ }
50
+ return number;
51
+ });
52
+ return Object.freeze([...new Set(normalized)]);
53
+ }
54
+
55
+ export function normalizeWhatsappAccessPolicy(value = {}) {
56
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
57
+ throw new TypeError('WhatsApp access policy must be an object');
58
+ }
59
+ const accessMode = value.accessMode ?? WHATSAPP_ACCESS_MODES.selfOnly;
60
+ if (!Object.values(WHATSAPP_ACCESS_MODES).includes(accessMode)) {
61
+ throw new TypeError('WhatsApp accessMode is invalid');
62
+ }
63
+ return Object.freeze({
64
+ accessMode,
65
+ allowedNumbers: normalizeWhatsappAllowedNumbers(value.allowedNumbers),
66
+ });
67
+ }
68
+
69
+ export class WhatsappConfigStore {
70
+ #path;
71
+ #value = EMPTY_DOCUMENT;
72
+ #writeQueue = Promise.resolve();
73
+
74
+ constructor(path) {
75
+ this.#path = path;
76
+ }
77
+
78
+ async load() {
79
+ try {
80
+ const normalized = this.#normalizeDocument(JSON.parse(await readFile(this.#path, 'utf8')));
81
+ if (!normalized) throw new Error('dsh-im WhatsApp config contains invalid account data');
82
+ this.#value = normalized;
83
+ } catch (error) {
84
+ if (error?.code !== 'ENOENT') throw error;
85
+ this.#value = EMPTY_DOCUMENT;
86
+ }
87
+ return this;
88
+ }
89
+
90
+ list() {
91
+ return structuredClone(this.#value.bots);
92
+ }
93
+
94
+ get(botId) {
95
+ const bot = this.#value.bots.find((candidate) => candidate.botId === botId);
96
+ return bot ? structuredClone(bot) : null;
97
+ }
98
+
99
+ getByAccountJid(accountJid) {
100
+ const normalized = normalizeWhatsappAccountJid(accountJid);
101
+ const bot = this.#value.bots.find((candidate) => candidate.accountJid === normalized);
102
+ return bot ? structuredClone(bot) : null;
103
+ }
104
+
105
+ async save(value) {
106
+ const normalized = this.#normalizeBot(value);
107
+ if (!normalized) throw new Error('Refusing to persist incomplete WhatsApp account data');
108
+ return this.#mutate((bots) => {
109
+ const duplicate = bots.find((bot) => bot.accountJid === normalized.accountJid
110
+ && bot.botId !== normalized.botId);
111
+ const authCollision = bots.find((bot) => bot.authDirectory === normalized.authDirectory
112
+ && bot.botId !== normalized.botId);
113
+ if (duplicate || authCollision) throw new Error('Duplicate WhatsApp account identity');
114
+ const index = bots.findIndex((bot) => bot.botId === normalized.botId);
115
+ if (index === -1) bots.push(normalized);
116
+ else bots[index] = normalized;
117
+ return structuredClone(normalized);
118
+ });
119
+ }
120
+
121
+ async remove(botId) {
122
+ if (!BOT_ID_PATTERN.test(botId)) throw new TypeError('Invalid WhatsApp bot id');
123
+ return this.#mutate((bots) => {
124
+ const index = bots.findIndex((bot) => bot.botId === botId);
125
+ if (index === -1) return null;
126
+ const [removed] = bots.splice(index, 1);
127
+ return structuredClone(removed);
128
+ });
129
+ }
130
+
131
+ async clear() {
132
+ const operation = this.#writeQueue.then(async () => {
133
+ try {
134
+ await unlink(this.#path);
135
+ } catch (error) {
136
+ if (error?.code !== 'ENOENT') throw error;
137
+ }
138
+ this.#value = EMPTY_DOCUMENT;
139
+ });
140
+ this.#writeQueue = operation.then(() => undefined, () => undefined);
141
+ await operation;
142
+ }
143
+
144
+ #normalizeBot(value) {
145
+ if (!value || typeof value !== 'object') return null;
146
+ const accountJid = normalizeWhatsappAccountJid(value.accountJid);
147
+ const botId = cleanString(value.botId);
148
+ const authDirectory = cleanString(value.authDirectory);
149
+ const name = cleanString(value.name);
150
+ if (!accountJid || !botId || !authDirectory || !name
151
+ || !BOT_ID_PATTERN.test(botId) || !AUTH_DIRECTORY_PATTERN.test(authDirectory)
152
+ || deriveWhatsappBotId(accountJid) !== botId) return null;
153
+ let accessPolicy;
154
+ try {
155
+ accessPolicy = normalizeWhatsappAccessPolicy(value);
156
+ } catch {
157
+ return null;
158
+ }
159
+ return Object.freeze({
160
+ botId,
161
+ accountJid,
162
+ authDirectory,
163
+ name,
164
+ createdAt: cleanString(value.createdAt) ?? new Date().toISOString(),
165
+ connectedAt: cleanString(value.connectedAt),
166
+ ...accessPolicy,
167
+ });
168
+ }
169
+
170
+ #normalizeDocument(value) {
171
+ if (!value || value.version !== 2 || !Array.isArray(value.bots)) return null;
172
+ const bots = value.bots.map((bot) => this.#normalizeBot(bot));
173
+ if (bots.some((bot) => bot === null)) return null;
174
+ const botIds = new Set();
175
+ const accountJids = new Set();
176
+ const authDirectories = new Set();
177
+ for (const bot of bots) {
178
+ if (botIds.has(bot.botId) || accountJids.has(bot.accountJid)
179
+ || authDirectories.has(bot.authDirectory)) return null;
180
+ botIds.add(bot.botId);
181
+ accountJids.add(bot.accountJid);
182
+ authDirectories.add(bot.authDirectory);
183
+ }
184
+ return Object.freeze({ version: 2, bots: Object.freeze(bots) });
185
+ }
186
+
187
+ async #mutate(mutator) {
188
+ let result;
189
+ const operation = this.#writeQueue.then(async () => {
190
+ const bots = [...this.#value.bots];
191
+ result = mutator(bots);
192
+ const document = Object.freeze({ version: 2, bots: Object.freeze(bots) });
193
+ await this.#write(document);
194
+ this.#value = document;
195
+ });
196
+ this.#writeQueue = operation.then(() => undefined, () => undefined);
197
+ await operation;
198
+ return result;
199
+ }
200
+
201
+ async #write(document) {
202
+ await mkdir(dirname(this.#path), { recursive: true, mode: 0o700 });
203
+ const temporary = `${this.#path}.tmp`;
204
+ await writeFile(temporary, `${JSON.stringify(document, null, 2)}\n`, {
205
+ encoding: 'utf8',
206
+ mode: 0o600,
207
+ });
208
+ await rename(temporary, this.#path);
209
+ }
210
+ }
@@ -0,0 +1,11 @@
1
+ import { HarnessClient } from '../shared/harness-client.mjs';
2
+
3
+ export class WhatsappHarnessClient extends HarnessClient {
4
+ constructor(options) {
5
+ super({
6
+ ...options,
7
+ rpcIdPrefix: 'whatsapp',
8
+ logPrefix: 'dsh-whatsapp',
9
+ });
10
+ }
11
+ }
@@ -0,0 +1,3 @@
1
+ import { ConversationStateStore } from '../shared/conversation-state-store.mjs';
2
+
3
+ export class WhatsappStateStore extends ConversationStateStore {}
@@ -0,0 +1,18 @@
1
+ import { t } from '../shared/i18n.mjs';
2
+ import { createTextBridgeStatus, TextHarnessBridge } from '../shared/text-harness-bridge.mjs';
3
+
4
+ export const WHATSAPP_DESCRIPTOR = Object.freeze({
5
+ key: 'whatsapp',
6
+ label: 'WhatsApp',
7
+ // Translated lazily: t() must run after setImHostLanguage, not at import time.
8
+ get connectionLabel() { return t(' Web 关联设备'); },
9
+ reactions: Object.freeze({ processing: '👀', success: '✅', error: '❌' }),
10
+ });
11
+
12
+ export class WhatsappHarnessBridge extends TextHarnessBridge {
13
+ constructor(options) {
14
+ super({ ...options, descriptor: WHATSAPP_DESCRIPTOR });
15
+ }
16
+ }
17
+
18
+ export { createTextBridgeStatus as createWhatsappBridgeStatus };