@botharness/im-provider 4.32.0-botharness.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (423) hide show
  1. package/LICENSE +21 -0
  2. package/PROVENANCE.json +25 -0
  3. package/README.en.md +445 -0
  4. package/README.md +448 -0
  5. package/THIRD_PARTY_NOTICES.md +93 -0
  6. package/assets/dingtalk-menu-template.json +6 -0
  7. package/assets/logo-dsh-im-chinese-readme-3x2.png +0 -0
  8. package/assets/logo-dsh-im-connecting-readme-3x2.png +0 -0
  9. package/assets/logo-dsh-im-connecting-square-v4.png +0 -0
  10. package/assets/logo-icon.png +0 -0
  11. package/assets/logo-plugin-message-link-gradient.webp +0 -0
  12. package/assets/logo-plugin-phone.png +0 -0
  13. package/assets/logo.png +0 -0
  14. package/assets/logo_cn.png +0 -0
  15. package/assets/screenshot-menu-card.png +0 -0
  16. package/cordis.patch.yml +3 -0
  17. package/lib/client.js +20330 -0
  18. package/lib/index.js +604 -0
  19. package/locale/en.json +5 -0
  20. package/locale/zh.json +5 -0
  21. package/package.json +181 -0
  22. package/plugin-src/client/access-policy-settings.js +362 -0
  23. package/plugin-src/client/agent-preset.js +119 -0
  24. package/plugin-src/client/bot-alias.js +169 -0
  25. package/plugin-src/client/build.mjs +38 -0
  26. package/plugin-src/client/channel-card-meta.js +132 -0
  27. package/plugin-src/client/channel-logos.js +190 -0
  28. package/plugin-src/client/channels/dingtalk/api.js +267 -0
  29. package/plugin-src/client/channels/dingtalk/index.js +954 -0
  30. package/plugin-src/client/channels/dingtalk/styles.js +136 -0
  31. package/plugin-src/client/channels/discord/api.js +11 -0
  32. package/plugin-src/client/channels/discord/index.js +25 -0
  33. package/plugin-src/client/channels/discord/styles.js +19 -0
  34. package/plugin-src/client/channels/email/api.js +52 -0
  35. package/plugin-src/client/channels/email/index.js +728 -0
  36. package/plugin-src/client/channels/email/styles.js +51 -0
  37. package/plugin-src/client/channels/feishu/api.js +405 -0
  38. package/plugin-src/client/channels/feishu/group-settings.js +581 -0
  39. package/plugin-src/client/channels/feishu/index.js +1583 -0
  40. package/plugin-src/client/channels/feishu/slash-panel-settings.js +322 -0
  41. package/plugin-src/client/channels/feishu/styles.js +573 -0
  42. package/plugin-src/client/channels/feishu/voice-editor.js +115 -0
  43. package/plugin-src/client/channels/feishu/voice-settings.js +71 -0
  44. package/plugin-src/client/channels/imessage/api.js +12 -0
  45. package/plugin-src/client/channels/imessage/index.js +46 -0
  46. package/plugin-src/client/channels/imessage/styles.js +19 -0
  47. package/plugin-src/client/channels/matrix/api.js +11 -0
  48. package/plugin-src/client/channels/matrix/index.js +151 -0
  49. package/plugin-src/client/channels/matrix/styles.js +36 -0
  50. package/plugin-src/client/channels/office/api.js +46 -0
  51. package/plugin-src/client/channels/office/index.js +153 -0
  52. package/plugin-src/client/channels/office/styles.js +50 -0
  53. package/plugin-src/client/channels/qq/api.js +171 -0
  54. package/plugin-src/client/channels/qq/index.js +593 -0
  55. package/plugin-src/client/channels/qq/styles.js +19 -0
  56. package/plugin-src/client/channels/shared/collapsible-account.js +103 -0
  57. package/plugin-src/client/channels/shared/token-api.js +124 -0
  58. package/plugin-src/client/channels/shared/token-channel.js +495 -0
  59. package/plugin-src/client/channels/slack/api.js +11 -0
  60. package/plugin-src/client/channels/slack/index.js +131 -0
  61. package/plugin-src/client/channels/slack/styles.js +34 -0
  62. package/plugin-src/client/channels/telegram/api.js +11 -0
  63. package/plugin-src/client/channels/telegram/index.js +28 -0
  64. package/plugin-src/client/channels/telegram/styles.js +31 -0
  65. package/plugin-src/client/channels/telegram/thinking-traces.js +25 -0
  66. package/plugin-src/client/channels/wecom/api.js +160 -0
  67. package/plugin-src/client/channels/wecom/index.js +625 -0
  68. package/plugin-src/client/channels/wecom/styles.js +19 -0
  69. package/plugin-src/client/channels/wecom-app/api.js +132 -0
  70. package/plugin-src/client/channels/wecom-app/index.js +634 -0
  71. package/plugin-src/client/channels/wecom-app/styles.js +25 -0
  72. package/plugin-src/client/channels/weixin/api.js +211 -0
  73. package/plugin-src/client/channels/weixin/connection-error.js +1 -0
  74. package/plugin-src/client/channels/weixin/index.js +801 -0
  75. package/plugin-src/client/channels/weixin/styles.js +115 -0
  76. package/plugin-src/client/channels/whatsapp/api.js +152 -0
  77. package/plugin-src/client/channels/whatsapp/index.js +609 -0
  78. package/plugin-src/client/channels/whatsapp/styles.js +19 -0
  79. package/plugin-src/client/connection-error.js +87 -0
  80. package/plugin-src/client/context-enhancement.js +415 -0
  81. package/plugin-src/client/credential-binding.js +118 -0
  82. package/plugin-src/client/delivery-settings.js +905 -0
  83. package/plugin-src/client/global-settings.js +433 -0
  84. package/plugin-src/client/i18n.js +1314 -0
  85. package/plugin-src/client/index.js +624 -0
  86. package/plugin-src/client/interface-language.js +89 -0
  87. package/plugin-src/client/last-message-error.js +18 -0
  88. package/plugin-src/client/lifecycle.js +86 -0
  89. package/plugin-src/client/loopback-recovery.js +75 -0
  90. package/plugin-src/client/model-setting.js +172 -0
  91. package/plugin-src/client/panel-error-boundary.js +21 -0
  92. package/plugin-src/client/plugin-page.js +51 -0
  93. package/plugin-src/client/session-channel-logos.js +243 -0
  94. package/plugin-src/client/styles.js +770 -0
  95. package/plugin-src/client/update-panel.js +14 -0
  96. package/plugin-src/client/workspace-directory-picker.js +280 -0
  97. package/plugin-src/client/workspace-editor.js +69 -0
  98. package/plugin-src/client/workspace-snapshot-fence.js +28 -0
  99. package/plugin-src/host/build.mjs +52 -0
  100. package/plugin-src/host/channels/dingtalk/connection-supervisor.mjs +130 -0
  101. package/plugin-src/host/channels/dingtalk/index.mjs +35 -0
  102. package/plugin-src/host/channels/dingtalk/production.mjs +193 -0
  103. package/plugin-src/host/channels/dingtalk/rpc.mjs +359 -0
  104. package/plugin-src/host/channels/discord/index.mjs +33 -0
  105. package/plugin-src/host/channels/discord/production.mjs +18 -0
  106. package/plugin-src/host/channels/discord/rpc.mjs +21 -0
  107. package/plugin-src/host/channels/email/availability.mjs +60 -0
  108. package/plugin-src/host/channels/email/index.mjs +36 -0
  109. package/plugin-src/host/channels/email/production.mjs +58 -0
  110. package/plugin-src/host/channels/email/rpc.mjs +163 -0
  111. package/plugin-src/host/channels/feishu/connection-supervisor.mjs +167 -0
  112. package/plugin-src/host/channels/feishu/controller.mjs +172 -0
  113. package/plugin-src/host/channels/feishu/credential-store.mjs +84 -0
  114. package/plugin-src/host/channels/feishu/index.mjs +69 -0
  115. package/plugin-src/host/channels/feishu/production.mjs +319 -0
  116. package/plugin-src/host/channels/feishu/rpc.mjs +863 -0
  117. package/plugin-src/host/channels/imessage/index.mjs +21 -0
  118. package/plugin-src/host/channels/imessage/production.mjs +13 -0
  119. package/plugin-src/host/channels/imessage/rpc.mjs +78 -0
  120. package/plugin-src/host/channels/matrix/index.mjs +31 -0
  121. package/plugin-src/host/channels/matrix/production.mjs +241 -0
  122. package/plugin-src/host/channels/matrix/rpc.mjs +228 -0
  123. package/plugin-src/host/channels/office/index.mjs +14 -0
  124. package/plugin-src/host/channels/office/production.mjs +45 -0
  125. package/plugin-src/host/channels/office/rpc.mjs +51 -0
  126. package/plugin-src/host/channels/qq/connection-supervisor.mjs +124 -0
  127. package/plugin-src/host/channels/qq/index.mjs +28 -0
  128. package/plugin-src/host/channels/qq/production.mjs +181 -0
  129. package/plugin-src/host/channels/qq/rpc.mjs +250 -0
  130. package/plugin-src/host/channels/shared/access-policy-production.mjs +137 -0
  131. package/plugin-src/host/channels/shared/access-policy-rpc.mjs +17 -0
  132. package/plugin-src/host/channels/shared/agent-preset-rpc.mjs +25 -0
  133. package/plugin-src/host/channels/shared/bot-alias-rpc.mjs +15 -0
  134. package/plugin-src/host/channels/shared/connection-supervisor.mjs +133 -0
  135. package/plugin-src/host/channels/shared/context-enhancement-rpc.mjs +17 -0
  136. package/plugin-src/host/channels/shared/model-setting-rpc.mjs +18 -0
  137. package/plugin-src/host/channels/shared/production.mjs +239 -0
  138. package/plugin-src/host/channels/shared/rpc.mjs +226 -0
  139. package/plugin-src/host/channels/shared/startup-error.mjs +55 -0
  140. package/plugin-src/host/channels/shared/startup.mjs +76 -0
  141. package/plugin-src/host/channels/shared/thinking-traces-rpc.mjs +11 -0
  142. package/plugin-src/host/channels/shared/workspace-rpc.mjs +31 -0
  143. package/plugin-src/host/channels/slack/index.mjs +31 -0
  144. package/plugin-src/host/channels/slack/production.mjs +176 -0
  145. package/plugin-src/host/channels/slack/rpc.mjs +221 -0
  146. package/plugin-src/host/channels/telegram/index.mjs +33 -0
  147. package/plugin-src/host/channels/telegram/production.mjs +19 -0
  148. package/plugin-src/host/channels/telegram/rpc.mjs +22 -0
  149. package/plugin-src/host/channels/wecom/connection-supervisor.mjs +124 -0
  150. package/plugin-src/host/channels/wecom/index.mjs +34 -0
  151. package/plugin-src/host/channels/wecom/production.mjs +187 -0
  152. package/plugin-src/host/channels/wecom/rpc.mjs +255 -0
  153. package/plugin-src/host/channels/wecom-app/index.mjs +33 -0
  154. package/plugin-src/host/channels/wecom-app/production.mjs +221 -0
  155. package/plugin-src/host/channels/wecom-app/rpc.mjs +235 -0
  156. package/plugin-src/host/channels/weixin/connection-supervisor.mjs +139 -0
  157. package/plugin-src/host/channels/weixin/index.mjs +44 -0
  158. package/plugin-src/host/channels/weixin/production.mjs +258 -0
  159. package/plugin-src/host/channels/weixin/rpc.mjs +285 -0
  160. package/plugin-src/host/channels/whatsapp/index.mjs +33 -0
  161. package/plugin-src/host/channels/whatsapp/production.mjs +198 -0
  162. package/plugin-src/host/channels/whatsapp/rpc.mjs +242 -0
  163. package/plugin-src/host/delivery-adapter.mjs +411 -0
  164. package/plugin-src/host/delivery-http.mjs +132 -0
  165. package/plugin-src/host/delivery-rpc.mjs +173 -0
  166. package/plugin-src/host/delivery-service.mjs +618 -0
  167. package/plugin-src/host/delivery-suggestions.mjs +198 -0
  168. package/plugin-src/host/harness-command-executor.mjs +48 -0
  169. package/plugin-src/host/harness-connection.mjs +20 -0
  170. package/plugin-src/host/harness-session-coordinator.mjs +183 -0
  171. package/plugin-src/host/host-language-rpc.mjs +71 -0
  172. package/plugin-src/host/host-language.mjs +157 -0
  173. package/plugin-src/host/image-input-rpc.mjs +24 -0
  174. package/plugin-src/host/inbound-ttl-rpc.mjs +86 -0
  175. package/plugin-src/host/inbound-ttl-runtime.mjs +85 -0
  176. package/plugin-src/host/inbound-ttl-service.mjs +179 -0
  177. package/plugin-src/host/index.mjs +229 -0
  178. package/plugin-src/host/injected-context.mjs +104 -0
  179. package/plugin-src/host/lark-sdk-handshake-patch.mjs +181 -0
  180. package/plugin-src/host/modern-harness-api.mjs +738 -0
  181. package/plugin-src/host/rpc-authority.mjs +12 -0
  182. package/plugin-src/host/session-sync-coordinator.mjs +233 -0
  183. package/plugin-src/host/session-title-prefix.mjs +122 -0
  184. package/plugin-src/host/update-policy.mjs +31 -0
  185. package/plugin-src/host/update-rpc.mjs +16 -0
  186. package/plugin-src/host/update-runtime.mjs +339 -0
  187. package/plugin-src/host/update-service.mjs +392 -0
  188. package/plugin-src/management-rpc.mjs +87 -0
  189. package/src/channels/dingtalk/config-store.mjs +284 -0
  190. package/src/channels/dingtalk/connection-error.mjs +292 -0
  191. package/src/channels/dingtalk/device-auth.mjs +240 -0
  192. package/src/channels/dingtalk/dingtalk-api.mjs +1140 -0
  193. package/src/channels/dingtalk/dingtalk-bridge.mjs +1889 -0
  194. package/src/channels/dingtalk/dingtalk-card-stream.mjs +242 -0
  195. package/src/channels/dingtalk/dingtalk-controller.mjs +852 -0
  196. package/src/channels/dingtalk/dingtalk-menu.mjs +95 -0
  197. package/src/channels/dingtalk/dingtalk-runtime.mjs +482 -0
  198. package/src/channels/dingtalk/harness-client.mjs +19 -0
  199. package/src/channels/dingtalk/state-store.mjs +325 -0
  200. package/src/channels/discord/config-store.mjs +28 -0
  201. package/src/channels/discord/discord-api.mjs +423 -0
  202. package/src/channels/discord/discord-bridge.mjs +16 -0
  203. package/src/channels/discord/discord-controller.mjs +29 -0
  204. package/src/channels/discord/discord-runtime.mjs +1091 -0
  205. package/src/channels/discord/external-consumer.mjs +199 -0
  206. package/src/channels/discord/external-files.mjs +97 -0
  207. package/src/channels/discord/harness-client.mjs +11 -0
  208. package/src/channels/discord/history-reader.mjs +142 -0
  209. package/src/channels/discord/nearby-history.mjs +112 -0
  210. package/src/channels/discord/state-store.mjs +3 -0
  211. package/src/channels/email/config-store.mjs +194 -0
  212. package/src/channels/email/email-api.mjs +20 -0
  213. package/src/channels/email/email-bridge.mjs +17 -0
  214. package/src/channels/email/email-controller.mjs +824 -0
  215. package/src/channels/email/email-runtime.mjs +699 -0
  216. package/src/channels/email/harness-client.mjs +7 -0
  217. package/src/channels/email/mail-format.mjs +91 -0
  218. package/src/channels/email/state-store.mjs +176 -0
  219. package/src/channels/email/transport.mjs +64 -0
  220. package/src/channels/email/transports/agent-mail.mjs +604 -0
  221. package/src/channels/email/transports/agently-cli.mjs +288 -0
  222. package/src/channels/email/transports/imap-smtp.mjs +165 -0
  223. package/src/channels/feishu/bridge.mjs +6286 -0
  224. package/src/channels/feishu/config.mjs +71 -0
  225. package/src/channels/feishu/external-cards.mjs +87 -0
  226. package/src/channels/feishu/external-consumer.mjs +89 -0
  227. package/src/channels/feishu/external-files.mjs +115 -0
  228. package/src/channels/feishu/external-images.mjs +50 -0
  229. package/src/channels/feishu/external-names.mjs +99 -0
  230. package/src/channels/feishu/feishu-app.mjs +54 -0
  231. package/src/channels/feishu/feishu-cards.mjs +1285 -0
  232. package/src/channels/feishu/feishu-channel.mjs +651 -0
  233. package/src/channels/feishu/feishu-runtime.mjs +982 -0
  234. package/src/channels/feishu/group-message-permission-manager.mjs +72 -0
  235. package/src/channels/feishu/group-response-mode.mjs +15 -0
  236. package/src/channels/feishu/harness-client.mjs +19 -0
  237. package/src/channels/feishu/history-reader.mjs +77 -0
  238. package/src/channels/feishu/live-cot.mjs +260 -0
  239. package/src/channels/feishu/message-utils.mjs +613 -0
  240. package/src/channels/feishu/multi-bot-controller.mjs +1619 -0
  241. package/src/channels/feishu/nearby-history.mjs +72 -0
  242. package/src/channels/feishu/plugin-config-store.mjs +216 -0
  243. package/src/channels/feishu/plugin-controller.mjs +254 -0
  244. package/src/channels/feishu/registration-manager.mjs +349 -0
  245. package/src/channels/feishu/repair-manager.mjs +138 -0
  246. package/src/channels/feishu/reply-context.mjs +22 -0
  247. package/src/channels/feishu/slash-command-panel.mjs +155 -0
  248. package/src/channels/feishu/slash-command-registry.mjs +495 -0
  249. package/src/channels/feishu/state-store.mjs +214 -0
  250. package/src/channels/feishu/step-push-mode.mjs +25 -0
  251. package/src/channels/feishu/voice-config.mjs +34 -0
  252. package/src/channels/feishu/voice.mjs +134 -0
  253. package/src/channels/imessage/config-store.mjs +24 -0
  254. package/src/channels/imessage/controller.mjs +37 -0
  255. package/src/channels/imessage/harness-client.mjs +7 -0
  256. package/src/channels/imessage/imessage-api.mjs +194 -0
  257. package/src/channels/imessage/imessage-bridge.mjs +16 -0
  258. package/src/channels/imessage/runtime.mjs +102 -0
  259. package/src/channels/imessage/state-store.mjs +3 -0
  260. package/src/channels/matrix/matrix-api.mjs +696 -0
  261. package/src/channels/matrix/matrix-bridge.mjs +20 -0
  262. package/src/channels/matrix/matrix-config-store.mjs +368 -0
  263. package/src/channels/matrix/matrix-controller.mjs +404 -0
  264. package/src/channels/matrix/matrix-crypto-store.mjs +279 -0
  265. package/src/channels/matrix/matrix-crypto.mjs +1014 -0
  266. package/src/channels/matrix/matrix-harness-client.mjs +11 -0
  267. package/src/channels/matrix/matrix-normalize.mjs +357 -0
  268. package/src/channels/matrix/matrix-rich-text.mjs +313 -0
  269. package/src/channels/matrix/matrix-room-history.mjs +316 -0
  270. package/src/channels/matrix/matrix-runtime.mjs +1014 -0
  271. package/src/channels/office/config-store.mjs +107 -0
  272. package/src/channels/office/office-controller.mjs +178 -0
  273. package/src/channels/office/office-job-executor.mjs +391 -0
  274. package/src/channels/office/office-runtime.mjs +175 -0
  275. package/src/channels/office/office-transport.mjs +171 -0
  276. package/src/channels/office/protocol.mjs +43 -0
  277. package/src/channels/qq/config-store.mjs +173 -0
  278. package/src/channels/qq/harness-client.mjs +11 -0
  279. package/src/channels/qq/markdown-reply.mjs +446 -0
  280. package/src/channels/qq/qq-bridge.mjs +1507 -0
  281. package/src/channels/qq/qq-controller.mjs +514 -0
  282. package/src/channels/qq/qq-menu.mjs +208 -0
  283. package/src/channels/qq/qq-runtime.mjs +303 -0
  284. package/src/channels/qq/qr-auth.mjs +24 -0
  285. package/src/channels/qq/state-error.mjs +17 -0
  286. package/src/channels/qq/state-store.mjs +143 -0
  287. package/src/channels/shared/access-policy.mjs +210 -0
  288. package/src/channels/shared/agent-preset.mjs +76 -0
  289. package/src/channels/shared/batch-input.mjs +229 -0
  290. package/src/channels/shared/bot-alias.mjs +29 -0
  291. package/src/channels/shared/bot-workspace-store.mjs +2383 -0
  292. package/src/channels/shared/command-catalog.mjs +107 -0
  293. package/src/channels/shared/command-permission.mjs +32 -0
  294. package/src/channels/shared/compact-command.mjs +109 -0
  295. package/src/channels/shared/config-read-error.mjs +24 -0
  296. package/src/channels/shared/connection-error.mjs +191 -0
  297. package/src/channels/shared/connection-test.mjs +58 -0
  298. package/src/channels/shared/context-enhancement.mjs +372 -0
  299. package/src/channels/shared/control-command.mjs +111 -0
  300. package/src/channels/shared/conversation-state-store.mjs +165 -0
  301. package/src/channels/shared/default-workspace.mjs +31 -0
  302. package/src/channels/shared/deferred-delivery-coordinator.mjs +241 -0
  303. package/src/channels/shared/deferred-delivery.mjs +161 -0
  304. package/src/channels/shared/deferred-state.mjs +53 -0
  305. package/src/channels/shared/diagnostic-details.mjs +95 -0
  306. package/src/channels/shared/editable-message-stream.mjs +100 -0
  307. package/src/channels/shared/exclusive-inbound-consumers.mjs +91 -0
  308. package/src/channels/shared/file-download.mjs +64 -0
  309. package/src/channels/shared/harness-approval.mjs +508 -0
  310. package/src/channels/shared/harness-client.mjs +2143 -0
  311. package/src/channels/shared/harness-mux.mjs +123 -0
  312. package/src/channels/shared/harness-question.mjs +95 -0
  313. package/src/channels/shared/harness-session-binding.mjs +119 -0
  314. package/src/channels/shared/history-command.mjs +193 -0
  315. package/src/channels/shared/i18n-en/diagnostics.mjs +55 -0
  316. package/src/channels/shared/i18n-en/dingtalk.mjs +81 -0
  317. package/src/channels/shared/i18n-en/discord.mjs +10 -0
  318. package/src/channels/shared/i18n-en/email.mjs +25 -0
  319. package/src/channels/shared/i18n-en/feishu.mjs +404 -0
  320. package/src/channels/shared/i18n-en/image-input.mjs +18 -0
  321. package/src/channels/shared/i18n-en/matrix.mjs +85 -0
  322. package/src/channels/shared/i18n-en/office.mjs +23 -0
  323. package/src/channels/shared/i18n-en/qq.mjs +96 -0
  324. package/src/channels/shared/i18n-en/shared-a.mjs +241 -0
  325. package/src/channels/shared/i18n-en/shared-b.mjs +263 -0
  326. package/src/channels/shared/i18n-en/shared-c.mjs +203 -0
  327. package/src/channels/shared/i18n-en/slack.mjs +27 -0
  328. package/src/channels/shared/i18n-en/telegram.mjs +27 -0
  329. package/src/channels/shared/i18n-en/wecom-app.mjs +33 -0
  330. package/src/channels/shared/i18n-en/wecom.mjs +62 -0
  331. package/src/channels/shared/i18n-en/weixin.mjs +88 -0
  332. package/src/channels/shared/i18n-en/whatsapp.mjs +17 -0
  333. package/src/channels/shared/i18n-en.mjs +45 -0
  334. package/src/channels/shared/i18n.mjs +78 -0
  335. package/src/channels/shared/im-source-guidance.mjs +65 -0
  336. package/src/channels/shared/image-input-policy.mjs +35 -0
  337. package/src/channels/shared/image-input-settings-store.mjs +60 -0
  338. package/src/channels/shared/image-input.mjs +124 -0
  339. package/src/channels/shared/image-prompt.mjs +360 -0
  340. package/src/channels/shared/inbound-access.mjs +43 -0
  341. package/src/channels/shared/inbound-file.mjs +323 -0
  342. package/src/channels/shared/inbound-ttl-store.mjs +110 -0
  343. package/src/channels/shared/inbound-ttl.mjs +22 -0
  344. package/src/channels/shared/injected-context.mjs +362 -0
  345. package/src/channels/shared/interface-language-store.mjs +127 -0
  346. package/src/channels/shared/interface-language.mjs +51 -0
  347. package/src/channels/shared/message-failure.mjs +257 -0
  348. package/src/channels/shared/model-command.mjs +741 -0
  349. package/src/channels/shared/model-setting.mjs +145 -0
  350. package/src/channels/shared/preset-command.mjs +308 -0
  351. package/src/channels/shared/semantic/artifact-delivery.mjs +177 -0
  352. package/src/channels/shared/semantic/artifact.mjs +750 -0
  353. package/src/channels/shared/semantic/delivery.mjs +193 -0
  354. package/src/channels/shared/semantic/reply-reference.mjs +148 -0
  355. package/src/channels/shared/session-binding-lock.mjs +40 -0
  356. package/src/channels/shared/session-channel-labels.mjs +28 -0
  357. package/src/channels/shared/session-reply-recovery.mjs +104 -0
  358. package/src/channels/shared/session-sync-registry.mjs +22 -0
  359. package/src/channels/shared/session-title.mjs +74 -0
  360. package/src/channels/shared/status-reaction.mjs +107 -0
  361. package/src/channels/shared/text-harness-bridge.mjs +1623 -0
  362. package/src/channels/shared/token-bot-controller.mjs +529 -0
  363. package/src/channels/shared/token-config-store.mjs +208 -0
  364. package/src/channels/shared/video-media.mjs +9 -0
  365. package/src/channels/shared/workspace-command.mjs +532 -0
  366. package/src/channels/shared/workspace-session.mjs +196 -0
  367. package/src/channels/slack/config-store.mjs +177 -0
  368. package/src/channels/slack/external-consumer.mjs +93 -0
  369. package/src/channels/slack/external-files.mjs +90 -0
  370. package/src/channels/slack/harness-client.mjs +11 -0
  371. package/src/channels/slack/history-reader.mjs +203 -0
  372. package/src/channels/slack/manifest.mjs +37 -0
  373. package/src/channels/slack/slack-api.mjs +644 -0
  374. package/src/channels/slack/slack-bridge.mjs +20 -0
  375. package/src/channels/slack/slack-controller.mjs +468 -0
  376. package/src/channels/slack/slack-runtime.mjs +895 -0
  377. package/src/channels/slack/state-store.mjs +3 -0
  378. package/src/channels/telegram/config-store.mjs +89 -0
  379. package/src/channels/telegram/harness-client.mjs +11 -0
  380. package/src/channels/telegram/state-store.mjs +3 -0
  381. package/src/channels/telegram/telegram-api.mjs +486 -0
  382. package/src/channels/telegram/telegram-bridge.mjs +81 -0
  383. package/src/channels/telegram/telegram-controller.mjs +52 -0
  384. package/src/channels/telegram/telegram-http.mjs +21 -0
  385. package/src/channels/telegram/telegram-rich-message.mjs +149 -0
  386. package/src/channels/telegram/telegram-runtime.mjs +1471 -0
  387. package/src/channels/wecom/config-store.mjs +172 -0
  388. package/src/channels/wecom/harness-client.mjs +11 -0
  389. package/src/channels/wecom/qr-auth.mjs +95 -0
  390. package/src/channels/wecom/send-error.mjs +31 -0
  391. package/src/channels/wecom/state-store.mjs +107 -0
  392. package/src/channels/wecom/wecom-bridge.mjs +1833 -0
  393. package/src/channels/wecom/wecom-cards.mjs +101 -0
  394. package/src/channels/wecom/wecom-controller.mjs +530 -0
  395. package/src/channels/wecom/wecom-runtime.mjs +269 -0
  396. package/src/channels/wecom-app/callback-server.mjs +471 -0
  397. package/src/channels/wecom-app/config-store.mjs +242 -0
  398. package/src/channels/wecom-app/harness-client.mjs +11 -0
  399. package/src/channels/wecom-app/state-store.mjs +107 -0
  400. package/src/channels/wecom-app/wecom-app-api.mjs +432 -0
  401. package/src/channels/wecom-app/wecom-app-bridge.mjs +1072 -0
  402. package/src/channels/wecom-app/wecom-app-controller.mjs +453 -0
  403. package/src/channels/wecom-app/wecom-app-runtime.mjs +222 -0
  404. package/src/channels/weixin/config-store.mjs +194 -0
  405. package/src/channels/weixin/connection-error.en.mjs +137 -0
  406. package/src/channels/weixin/connection-error.mjs +153 -0
  407. package/src/channels/weixin/diagnostic-details.mjs +1 -0
  408. package/src/channels/weixin/external-consumer.mjs +160 -0
  409. package/src/channels/weixin/external-files.mjs +84 -0
  410. package/src/channels/weixin/external-typing.mjs +120 -0
  411. package/src/channels/weixin/harness-client.mjs +19 -0
  412. package/src/channels/weixin/state-store.mjs +316 -0
  413. package/src/channels/weixin/weixin-api.mjs +1009 -0
  414. package/src/channels/weixin/weixin-bridge.mjs +1537 -0
  415. package/src/channels/weixin/weixin-controller.mjs +779 -0
  416. package/src/channels/weixin/weixin-runtime.mjs +507 -0
  417. package/src/channels/whatsapp/config-store.mjs +210 -0
  418. package/src/channels/whatsapp/harness-client.mjs +11 -0
  419. package/src/channels/whatsapp/state-store.mjs +3 -0
  420. package/src/channels/whatsapp/whatsapp-bridge.mjs +18 -0
  421. package/src/channels/whatsapp/whatsapp-controller.mjs +470 -0
  422. package/src/channels/whatsapp/whatsapp-runtime.mjs +917 -0
  423. package/src/channels/whatsapp/whatsapp-web-session.mjs +214 -0
@@ -0,0 +1,779 @@
1
+ import { ExclusiveInboundConsumers } from '../shared/exclusive-inbound-consumers.mjs';
2
+ import { pairedWeixinAccount, normalizeWeixinExternalText, weixinRefusal } from './external-consumer.mjs';
3
+ import { privateWeixinFile } from './external-files.mjs';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { createWeixinDiagnostics, knownWeixinErrorCode, weixinStageError } from './connection-error.mjs';
6
+
7
+ import {
8
+ normalizeWeixinApiBaseUrl,
9
+ WEIXIN_QR_BASE_URL,
10
+ WeixinApiError,
11
+ } from './weixin-api.mjs';
12
+ import { deriveWeixinBotIdentity, maskWeixinAccountId } from './config-store.mjs';
13
+ import {
14
+ connectionTestMessage,
15
+ connectionTestTargetUnavailable,
16
+ } from '../shared/connection-test.mjs';
17
+ import { publicMessageFailure } from '../shared/message-failure.mjs';
18
+ import { t } from '../shared/i18n.mjs';
19
+
20
+ const ACTIVE_ATTEMPT_STATES = new Set([
21
+ 'starting',
22
+ 'pending',
23
+ 'scanned',
24
+ 'needs_verification',
25
+ 'connecting',
26
+ ]);
27
+ const TERMINAL_ATTEMPT_STATES = new Set(['connected', 'expired', 'failed', 'cancelled']);
28
+ const QR_TTL_MS = 5 * 60_000;
29
+ function cleanString(value) {
30
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
31
+ }
32
+
33
+ function abortError() {
34
+ return new DOMException('Provisioning was cancelled', 'AbortError');
35
+ }
36
+
37
+ function apiBaseFromServer(value, fallback) {
38
+ const raw = cleanString(value);
39
+ if (!raw) return normalizeWeixinApiBaseUrl(fallback);
40
+ return normalizeWeixinApiBaseUrl(raw.includes('://') ? raw : `https://${raw}`);
41
+ }
42
+
43
+ function publicAttempt(record) {
44
+ if (!record) return null;
45
+ return {
46
+ attemptId: record.id,
47
+ status: record.state,
48
+ ...(record.verificationUrl ? { verificationUrl: record.verificationUrl } : {}),
49
+ ...(record.expiresAt ? { expiresAt: record.expiresAt } : {}),
50
+ pollIntervalMs: 1_000,
51
+ ...(record.state === 'needs_verification' ? { verificationRequired: true } : {}),
52
+ ...(record.botId ? { botId: record.botId } : {}),
53
+ ...(record.alreadyConnected ? { alreadyConnected: true } : {}),
54
+ ...(record.error ? { error: structuredClone(record.error) } : {}),
55
+ };
56
+ }
57
+
58
+ function safeAccountError(code, message) {
59
+ return Object.freeze({ code, message });
60
+ }
61
+
62
+ function preserveActivationError(error, fallbackCode) {
63
+ return knownWeixinErrorCode(error?.code) ? error : weixinStageError(fallbackCode, error);
64
+ }
65
+
66
+ export class WeixinController {
67
+ #inboundConsumers = new ExclusiveInboundConsumers();
68
+ #api;
69
+ #credentials;
70
+ #configStore;
71
+ #createRuntime;
72
+ #deleteState;
73
+ #diagnostics;
74
+ #runtimes = new Map();
75
+ #errors = new Map();
76
+ #attempts = new Map();
77
+ #activeAttemptId = null;
78
+ #transitions = new Map();
79
+ #revision = 0;
80
+ #closed = false;
81
+
82
+ constructor({
83
+ api,
84
+ credentials,
85
+ configStore,
86
+ createRuntime,
87
+ deleteState = async () => {},
88
+ logger = console,
89
+ diagnostics,
90
+ }) {
91
+ if (!api || typeof api.beginLogin !== 'function' || typeof api.pollLogin !== 'function') {
92
+ throw new TypeError('WeixinController requires a Weixin API client');
93
+ }
94
+ if (!credentials
95
+ || typeof credentials.resolve !== 'function'
96
+ || typeof credentials.set !== 'function'
97
+ || typeof credentials.unset !== 'function') {
98
+ throw new TypeError('WeixinController requires the DSH credential provider');
99
+ }
100
+ if (!configStore
101
+ || typeof configStore.list !== 'function'
102
+ || typeof configStore.save !== 'function'
103
+ || typeof configStore.remove !== 'function') {
104
+ throw new TypeError('WeixinController requires a config store');
105
+ }
106
+ if (typeof createRuntime !== 'function') throw new TypeError('createRuntime is required');
107
+ this.#api = api;
108
+ this.#credentials = credentials;
109
+ this.#configStore = configStore;
110
+ this.#createRuntime = createRuntime;
111
+ this.#deleteState = deleteState;
112
+ this.#diagnostics = diagnostics ?? createWeixinDiagnostics({ logger });
113
+ }
114
+
115
+ async initialize() {
116
+ if (this.#closed) return this.status();
117
+ for (const config of this.#configStore.list()) {
118
+ const current = this.#runtimes.get(config.botId);
119
+ if (current?.status?.ready === true) continue;
120
+ await this.#withBotTransition(config.botId, async () => {
121
+ const latest = this.#configStore.get(config.botId);
122
+ if (!latest || this.#closed) return;
123
+ try {
124
+ const token = await this.#resolveToken(latest.tokenRef);
125
+ if (!token) throw weixinStageError('missing-token');
126
+ await this.#startRuntime(latest, token, { operation: 'connection.restore', automatic: true });
127
+ this.#errors.delete(latest.botId);
128
+ this.#diagnostics.clear(latest.botId);
129
+ } catch (error) {
130
+ this.#errors.set(latest.botId, this.#diagnostics.report(error, {
131
+ operation: 'connection.restore', stage: 'connection.start', botId: latest.botId, automatic: true,
132
+ }).publicError);
133
+ } finally {
134
+ this.#touch();
135
+ }
136
+ });
137
+ }
138
+ return this.status();
139
+ }
140
+
141
+ reportRestoreFailure(error) {
142
+ for (const config of this.#configStore.list()) {
143
+ if (this.#runtimes.get(config.botId)?.status?.ready) continue;
144
+ this.#errors.set(config.botId, this.#diagnostics.report(error, {
145
+ operation: 'connection.restore', stage: 'harness.check', code: 'harness-check-unknown-failed',
146
+ botId: config.botId, automatic: true,
147
+ }).publicError);
148
+ }
149
+ this.#touch();
150
+ }
151
+
152
+ async #deliveryAccount(config, signal) {
153
+ signal?.throwIfAborted();
154
+ if (this.#closed) throw weixinRefusal('provider-unavailable');
155
+ return pairedWeixinAccount(config, await this.#resolveToken(config.tokenRef));
156
+ }
157
+
158
+ async describeDeliveryAccount(botId) {
159
+ return this.#withBotTransition(botId, async () => {
160
+ const config = this.#configStore.get(botId);
161
+ if (!config) throw weixinRefusal('unknown-bot');
162
+ const account = await this.#deliveryAccount(config);
163
+ return { version: 1, botId, channel: 'weixin', account,
164
+ connected: this.#runtimes.get(botId)?.status?.ready === true,
165
+ capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'proactive-fence-checked', 'exclusive-text-consumer', 'reply-text-checked',
166
+ 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'typing-lifecycle-checked',
167
+ 'source-file-checked', 'reply-file-checked', 'reply-file-fence-checked',
168
+ 'source-image-checked', 'reply-image-fence-checked', 'source-voice-transcript-checked', 'source-voice-audio-checked', 'source-video-checked', 'reply-video-fence-checked', 'source-quote-checked'] };
169
+ });
170
+ }
171
+
172
+ async consumeInbound(botId, { expectedFingerprint, onEvent, signal, sourceFiles = false, sourceImages = false, sourceVoiceTranscripts = false, sourceVoiceAudio = false, sourceVideos = false, sourceQuotes = false } = {}) {
173
+ return this.#withBotTransition(botId, async () => {
174
+ const config = this.#configStore.get(botId);
175
+ if (!config) throw weixinRefusal('unknown-bot');
176
+ const account = await this.#deliveryAccount(config, signal);
177
+ if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
178
+ const dispose = this.#inboundConsumers.register(botId, { fingerprint: expectedFingerprint, onEvent, signal, sourceFiles, sourceImages, sourceVoiceTranscripts, sourceVoiceAudio, sourceVideos, sourceQuotes });
179
+ try {
180
+ const saved = await this.#configStore.save({ ...config, consumerMode: 'external-consumer' });
181
+ await this.#startRuntime(saved, await this.#resolveToken(saved.tokenRef));
182
+ signal?.throwIfAborted();
183
+ return dispose;
184
+ } catch (error) { dispose(); throw error; }
185
+ });
186
+ }
187
+
188
+ async #checkedRuntime(botId, expectedFingerprint, signal) {
189
+ const config = this.#configStore.get(botId);
190
+ if (!config) throw weixinRefusal('unknown-bot');
191
+ const account = await this.#deliveryAccount(config, signal);
192
+ if (account.fingerprint !== expectedFingerprint) throw weixinRefusal('account-changed');
193
+ const runtime = this.#runtimes.get(botId);
194
+ if (config.consumerMode !== 'external-consumer' || !runtime?.status?.ready) throw weixinRefusal('capability-unavailable');
195
+ const lease = this.#inboundConsumers.signalFor(botId, expectedFingerprint);
196
+ return { runtime, account, signal: signal ? AbortSignal.any([signal, lease]) : lease };
197
+ }
198
+
199
+ async qualifyReplyChecked(botId, route, options = {}) {
200
+ return this.#withBotTransition(botId, async () => {
201
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
202
+ return checked.runtime.qualifyReplyChecked(route, checked);
203
+ });
204
+ }
205
+
206
+ async replyChecked(botId, route, text, options = {}) {
207
+ return this.#withBotTransition(botId, async () => {
208
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
209
+ return checked.runtime.replyChecked(route, text, { ...options, ...checked });
210
+ });
211
+ }
212
+
213
+ async beginTypingChecked(botId, route, options = {}) {
214
+ return this.#withBotTransition(botId, async () => {
215
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
216
+ return checked.runtime.beginTypingChecked(route, { ...options, ...checked });
217
+ });
218
+ }
219
+
220
+ async externalFileChecked(botId, route, file, options = {}) {
221
+ return this.#withBotTransition(botId, async () => {
222
+ const checked = await this.#checkedRuntime(botId, options.expectedFingerprint, options.signal);
223
+ return checked.runtime.externalFileChecked(route, file, { ...options, ...checked });
224
+ });
225
+ }
226
+
227
+ async startProvisioning() {
228
+ if (this.#closed) throw new Error('dsh-weixin controller is closed');
229
+ if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
230
+
231
+ const record = {
232
+ id: randomUUID(),
233
+ state: 'starting',
234
+ createdAt: Date.now(),
235
+ expiresAt: Date.now() + QR_TTL_MS,
236
+ controller: new AbortController(),
237
+ pendingVerifyCode: null,
238
+ verifyResolve: null,
239
+ currentBaseUrl: WEIXIN_QR_BASE_URL,
240
+ error: null,
241
+ botId: null,
242
+ task: null,
243
+ };
244
+ this.#attempts.set(record.id, record);
245
+ this.#activeAttemptId = record.id;
246
+ this.#touch();
247
+
248
+ try {
249
+ const localTokens = (await Promise.all(
250
+ this.#configStore.list().slice(-10).map(async (config) => {
251
+ try { return await this.#resolveToken(config.tokenRef); }
252
+ catch (error) {
253
+ this.#diagnostics.report(error, { operation: 'provision.begin', botId: config.botId, warning: true });
254
+ return undefined;
255
+ }
256
+ }),
257
+ )).filter(Boolean);
258
+ const login = await this.#api.beginLogin({
259
+ localTokens,
260
+ signal: record.controller.signal,
261
+ });
262
+ this.#assertAttemptActive(record);
263
+ record.qrcode = login.qrcode;
264
+ record.verificationUrl = login.qrcodeUrl;
265
+ record.state = 'pending';
266
+ record.expiresAt = Date.now() + QR_TTL_MS;
267
+ this.#touch();
268
+ record.task = this.#runProvisioning(record);
269
+ return publicAttempt(record);
270
+ } catch (error) {
271
+ if (record.controller.signal.aborted) {
272
+ record.state = 'cancelled';
273
+ record.error = safeAccountError('cancelled', t('扫码绑定已取消。'));
274
+ } else {
275
+ record.state = 'failed';
276
+ error = this.#diagnostics.report(error, { operation: 'provision.begin', stage: 'qr.begin', code: 'qr-start-failed' });
277
+ record.error = error.publicError;
278
+ }
279
+ if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
280
+ this.#touch();
281
+ throw error;
282
+ }
283
+ }
284
+
285
+ registrationStatus(attemptId) {
286
+ return publicAttempt(this.#attempts.get(attemptId));
287
+ }
288
+
289
+ async submitVerification(attemptId, verifyCode) {
290
+ const record = this.#attempts.get(attemptId);
291
+ if (!record || record.state !== 'needs_verification') {
292
+ throw weixinStageError(record ? 'provision-state-invalid' : 'provision-attempt-not-found', undefined, 'qr.verify');
293
+ }
294
+ const code = cleanString(verifyCode);
295
+ if (!code || !/^\d{4,8}$/.test(code)) {
296
+ throw new TypeError('Verification code must contain 4 to 8 digits');
297
+ }
298
+ record.pendingVerifyCode = code;
299
+ record.state = 'scanned';
300
+ record.verifyResolve?.();
301
+ record.verifyResolve = null;
302
+ this.#touch();
303
+ return publicAttempt(record);
304
+ }
305
+
306
+ async cancelProvisioning(attemptId) {
307
+ const record = this.#attempts.get(attemptId);
308
+ if (!record) return null;
309
+ if (!TERMINAL_ATTEMPT_STATES.has(record.state)) {
310
+ record.controller.abort();
311
+ record.verifyResolve?.();
312
+ record.verifyResolve = null;
313
+ await record.task?.catch(() => undefined);
314
+ if (!TERMINAL_ATTEMPT_STATES.has(record.state)) record.state = 'cancelled';
315
+ record.error ??= safeAccountError('cancelled', t('扫码绑定已取消。'));
316
+ }
317
+ if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
318
+ this.#touch();
319
+ return publicAttempt(record);
320
+ }
321
+
322
+ async reconnectBot(botId) {
323
+ const config = this.#configStore.get(botId);
324
+ if (!config) throw new Error('Unknown Weixin account');
325
+ await this.#withBotTransition(botId, async () => {
326
+ try {
327
+ const token = await this.#resolveToken(config.tokenRef);
328
+ if (!token) throw weixinStageError('missing-token');
329
+ await this.#startRuntime(config, token, { operation: 'bot.reconnect' });
330
+ this.#errors.delete(botId);
331
+ this.#diagnostics.clear(botId);
332
+ } catch (error) {
333
+ const failure = this.#diagnostics.report(error, { operation: 'bot.reconnect', stage: 'connection.start', botId });
334
+ this.#errors.set(botId, failure.publicError);
335
+ throw failure;
336
+ } finally {
337
+ this.#touch();
338
+ }
339
+ });
340
+ return this.status();
341
+ }
342
+
343
+ async sendConnectionTest(botId) {
344
+ const config = this.#configStore.get(botId);
345
+ if (!config) throw new Error('Unknown Weixin account');
346
+ return this.#withBotTransition(botId, async () => {
347
+ const runtime = this.#runtimes.get(botId);
348
+ if (!runtime?.status?.ready || typeof runtime.sendConnectionTest !== 'function') {
349
+ throw connectionTestTargetUnavailable(t('微信机器人'));
350
+ }
351
+ return runtime.sendConnectionTest(connectionTestMessage(
352
+ t('微信机器人({name})', { name: maskWeixinAccountId(config.accountId) }),
353
+ ));
354
+ });
355
+ }
356
+
357
+ async sendProactiveText(botId, target, text, options = {}) {
358
+ return this.#withBotTransition(botId, async () => {
359
+ const config = this.#configStore.get(botId);
360
+ if (!config) throw weixinRefusal('unknown-bot');
361
+ const runtime = this.#runtimes.get(botId);
362
+ if (!runtime?.status?.ready || typeof runtime.sendProactiveText !== 'function') {
363
+ const error = new Error(t('微信连接当前离线'));
364
+ error.code = 'bot-not-connected';
365
+ throw error;
366
+ }
367
+ let account;
368
+ if (options.expectedFingerprint !== undefined) {
369
+ account = await this.#deliveryAccount(config, options.signal);
370
+ if (account.fingerprint !== options.expectedFingerprint) throw weixinRefusal('account-changed');
371
+ if (target?.kind !== 'user' || target.route?.toUserId !== account.ownerUserId) throw weixinRefusal('invalid-target');
372
+ }
373
+ return runtime.sendProactiveText(target, text, { ...options, ...(account === undefined ? {} : { account }) });
374
+ });
375
+ }
376
+
377
+ async deleteBot(botId) {
378
+ this.#inboundConsumers.remove(botId);
379
+ const config = this.#configStore.get(botId);
380
+ if (!config) throw weixinStageError('workspace-bot-not-found', undefined, 'account.remove');
381
+ const warnings = [];
382
+ const context = { operation: 'bot.delete', botId };
383
+ await this.#withBotTransition(botId, async () => {
384
+ const previousToken = await this.#credentials.resolve(config.tokenRef).catch(error => {
385
+ warnings.push(this.#diagnostics.report(weixinStageError('credential-read-failed', error), { ...context, warning: true }).publicError);
386
+ });
387
+ warnings.push(...await this.#stopRuntime(botId));
388
+ let stage = 'credential-remove-failed';
389
+ try {
390
+ await this.#writeCredential(config.tokenRef, undefined);
391
+ stage = 'account-config-remove-failed';
392
+ await this.#configStore.remove(botId);
393
+ } catch (error) {
394
+ // A config removal observer may throw after the account was durably removed.
395
+ if (stage === 'account-config-remove-failed' && !this.#configStore.get(botId)) {
396
+ warnings.push(this.#diagnostics.report(weixinStageError('workspace-cleanup-failed', error), { ...context, warning: true }).publicError);
397
+ } else {
398
+ const failure = this.#diagnostics.report(weixinStageError(stage, error), context);
399
+ let rollback = previousToken?.value ? 'succeeded' : 'unknown';
400
+ if (previousToken?.value) {
401
+ for (const restore of [
402
+ () => this.#credentials.set(config.tokenRef, previousToken.value),
403
+ () => this.#startRuntime(config, previousToken.value, context),
404
+ ]) {
405
+ try { await restore(); }
406
+ catch (restoreError) {
407
+ rollback = 'failed';
408
+ this.#diagnostics.report(weixinStageError('rollback-failed', restoreError), { ...context, warning: true, parentReferenceId: failure.publicError.details.referenceId });
409
+ }
410
+ }
411
+ }
412
+ if (rollback === 'succeeded' && !this.#runtimes.get(botId)?.status?.ready) rollback = 'unknown';
413
+ this.#diagnostics.outcome(failure, rollback);
414
+ throw failure;
415
+ }
416
+ }
417
+ try {
418
+ await this.#deleteState({ botId, config });
419
+ } catch (error) {
420
+ warnings.push(this.#diagnostics.report(weixinStageError('account-state-cleanup-failed', error), { ...context, warning: true }).publicError);
421
+ }
422
+ this.#errors.delete(botId);
423
+ this.#diagnostics.clear(botId);
424
+ this.#touch();
425
+ });
426
+ return { ...this.status(), ...(warnings.length ? { warnings } : {}) };
427
+ }
428
+
429
+ status() {
430
+ const accounts = this.#configStore.list().map((config) => {
431
+ const runtimeStatus = this.#runtimes.get(config.botId)?.status ?? null;
432
+ const connected = runtimeStatus?.ready === true
433
+ && runtimeStatus.weixinConnectionState === 'connected'
434
+ && runtimeStatus.harnessReachable === true;
435
+ const state = connected
436
+ ? 'connected'
437
+ : runtimeStatus?.weixinConnectionState === 'connecting'
438
+ ? 'connecting'
439
+ : this.#errors.has(config.botId) || runtimeStatus?.weixinConnectionState === 'failed'
440
+ ? 'error'
441
+ : 'offline';
442
+ const error = connected ? null : this.#errors.get(config.botId) ?? runtimeStatus?.connectionError ?? (state === 'error'
443
+ ? safeAccountError('connection-failed', t('微信连接未就绪,插件会自动重试。'))
444
+ : null);
445
+ return {
446
+ botId: config.botId,
447
+ state,
448
+ connected,
449
+ configured: true,
450
+ bot: {
451
+ name: t('微信机器人'),
452
+ accountIdMasked: maskWeixinAccountId(config.accountId),
453
+ },
454
+ health: {
455
+ status: connected ? 'healthy' : state === 'error' ? 'error' : 'offline',
456
+ summary: connected
457
+ ? t('微信消息长轮询运行正常')
458
+ : state === 'error'
459
+ ? t('微信连接未就绪,插件会自动重试')
460
+ : t('微信连接当前离线'),
461
+ lastCheckedAt: runtimeStatus?.lastCheckedAt ?? null,
462
+ },
463
+ stats: {
464
+ messagesReceived: runtimeStatus?.messagesReceived ?? 0,
465
+ messagesReplied: runtimeStatus?.messagesReplied ?? 0,
466
+ },
467
+ lastMessageError: publicMessageFailure(runtimeStatus?.lastMessageError),
468
+ error: error ? structuredClone(error) : null,
469
+ };
470
+ });
471
+ const connectedCount = accounts.filter((account) => account.connected).length;
472
+ const active = this.#activeAttemptId ? this.#attempts.get(this.#activeAttemptId) : null;
473
+ return {
474
+ schemaVersion: 1,
475
+ revision: this.#revision,
476
+ state: active && ACTIVE_ATTEMPT_STATES.has(active.state)
477
+ ? 'provisioning'
478
+ : accounts.length === 0
479
+ ? 'disconnected'
480
+ : connectedCount === accounts.length
481
+ ? 'connected'
482
+ : connectedCount > 0
483
+ ? 'degraded'
484
+ : 'offline',
485
+ bots: accounts,
486
+ totals: { configured: accounts.length, connected: connectedCount },
487
+ ...(active && ACTIVE_ATTEMPT_STATES.has(active.state)
488
+ ? { provisioning: publicAttempt(active) }
489
+ : {}),
490
+ };
491
+ }
492
+
493
+ async close() {
494
+ this.#inboundConsumers.close();
495
+ if (this.#closed) return;
496
+ this.#closed = true;
497
+ if (this.#activeAttemptId) await this.cancelProvisioning(this.#activeAttemptId);
498
+ await Promise.allSettled([...this.#runtimes.keys()].map((botId) => this.#stopRuntime(botId)));
499
+ this.#diagnostics.clear();
500
+ }
501
+
502
+ async #runProvisioning(record) {
503
+ try {
504
+ while (!record.controller.signal.aborted && Date.now() < record.expiresAt) {
505
+ if (record.state === 'needs_verification' && !record.pendingVerifyCode) {
506
+ await new Promise((resolve) => {
507
+ record.verifyResolve = resolve;
508
+ if (record.controller.signal.aborted) resolve();
509
+ });
510
+ record.verifyResolve = null;
511
+ this.#assertAttemptActive(record);
512
+ }
513
+
514
+ const response = await this.#api.pollLogin({
515
+ qrcode: record.qrcode,
516
+ baseUrl: record.currentBaseUrl,
517
+ verifyCode: record.pendingVerifyCode,
518
+ signal: record.controller.signal,
519
+ });
520
+ this.#assertAttemptActive(record);
521
+ if (response.status === 'wait') {
522
+ record.state = 'pending';
523
+ } else if (response.status === 'scaned') {
524
+ record.pendingVerifyCode = null;
525
+ record.state = 'scanned';
526
+ } else if (response.status === 'need_verifycode') {
527
+ record.pendingVerifyCode = null;
528
+ record.state = 'needs_verification';
529
+ } else if (response.status === 'verify_code_blocked') {
530
+ record.state = 'failed';
531
+ record.error = safeAccountError('verification-blocked', t('配对码多次错误,请重新生成二维码。'));
532
+ break;
533
+ } else if (response.status === 'expired') {
534
+ record.state = 'expired';
535
+ record.error = safeAccountError('expired', t('二维码已过期,请重新生成。'));
536
+ break;
537
+ } else if (response.status === 'scaned_but_redirect') {
538
+ record.currentBaseUrl = apiBaseFromServer(response.redirect_host, record.currentBaseUrl);
539
+ record.state = 'scanned';
540
+ } else if (response.status === 'binded_redirect') {
541
+ const existing = this.#configStore.list().find(
542
+ (config) => this.#runtimes.get(config.botId)?.status?.ready === true,
543
+ ) ?? this.#configStore.list()[0];
544
+ if (!existing) {
545
+ record.state = 'failed';
546
+ record.error = safeAccountError('already-bound', t('该微信账号已绑定,但本机没有可恢复的凭据。'));
547
+ } else {
548
+ record.state = 'connected';
549
+ record.botId = existing.botId;
550
+ record.alreadyConnected = true;
551
+ }
552
+ break;
553
+ } else if (response.status === 'confirmed') {
554
+ const token = cleanString(response.bot_token);
555
+ const accountId = cleanString(response.ilink_bot_id);
556
+ const ownerUserId = cleanString(response.ilink_user_id);
557
+ if (!token || !accountId || !ownerUserId) {
558
+ throw new WeixinApiError('incomplete-login', t('微信授权成功,但返回的账号凭据不完整。'));
559
+ }
560
+ record.state = 'connecting';
561
+ this.#touch();
562
+ const baseUrl = apiBaseFromServer(response.baseurl, record.currentBaseUrl);
563
+ record.botId = await this.#activateAccount(record, {
564
+ token,
565
+ accountId,
566
+ ownerUserId,
567
+ baseUrl,
568
+ });
569
+ record.state = 'connected';
570
+ record.error = null;
571
+ break;
572
+ }
573
+ this.#touch();
574
+ }
575
+ if (!record.controller.signal.aborted && Date.now() >= record.expiresAt
576
+ && !TERMINAL_ATTEMPT_STATES.has(record.state)) {
577
+ record.state = 'expired';
578
+ record.error = safeAccountError('expired', t('二维码已过期,请重新生成。'));
579
+ }
580
+ } catch (error) {
581
+ if (record.controller.signal.aborted || error?.name === 'AbortError') {
582
+ record.state = 'cancelled';
583
+ record.error = safeAccountError('cancelled', t('扫码绑定已取消。'));
584
+ } else {
585
+ const failedStage = record.state === 'connecting' ? 'activation' : 'qr.poll';
586
+ record.state = 'failed';
587
+ record.error = this.#diagnostics.report(error, {
588
+ operation: 'provision.poll', stage: failedStage,
589
+ code: 'activation-unknown-failed', rollback: error?.rollback,
590
+ }).publicError;
591
+ }
592
+ } finally {
593
+ record.pendingVerifyCode = null;
594
+ record.verifyResolve?.();
595
+ record.verifyResolve = null;
596
+ if (this.#activeAttemptId === record.id) this.#activeAttemptId = null;
597
+ this.#touch();
598
+ this.#pruneAttempts();
599
+ }
600
+ }
601
+
602
+ async #activateAccount(record, { token, accountId, ownerUserId, baseUrl }) {
603
+ const identity = deriveWeixinBotIdentity(accountId);
604
+ const previousConfig = this.#configStore.getByAccountId(accountId);
605
+ const config = {
606
+ botId: identity.botId,
607
+ accountId,
608
+ tokenRef: identity.tokenRef,
609
+ ownerUserId,
610
+ baseUrl,
611
+ createdAt: previousConfig?.createdAt ?? new Date().toISOString(),
612
+ connectedAt: new Date().toISOString(),
613
+ ...(previousConfig?.consumerMode ? { consumerMode: previousConfig.consumerMode } : {}),
614
+ };
615
+ let previousToken;
616
+ try {
617
+ previousToken = await this.#credentials.resolve(identity.tokenRef);
618
+ } catch (error) {
619
+ throw weixinStageError('credential-read-failed', error);
620
+ }
621
+
622
+ return this.#withBotTransition(identity.botId, async () => {
623
+ try {
624
+ try {
625
+ await this.#writeCredential(identity.tokenRef, token);
626
+ } catch (error) {
627
+ throw weixinStageError('credential-save-failed', error);
628
+ }
629
+ this.#assertAttemptActive(record);
630
+ try {
631
+ await this.#configStore.save(config);
632
+ } catch (error) {
633
+ throw weixinStageError('account-config-save-failed', error);
634
+ }
635
+ this.#assertAttemptActive(record);
636
+ await this.#startRuntime(config, token, { operation: 'provision.poll' });
637
+ this.#assertAttemptActive(record);
638
+ this.#errors.delete(identity.botId);
639
+ this.#touch();
640
+ return identity.botId;
641
+ } catch (error) {
642
+ const cancelled = record.controller.signal.aborted || error?.name === 'AbortError';
643
+ const failure = cancelled ? error : this.#diagnostics.report(error, {
644
+ operation: 'provision.poll', stage: 'activation', code: 'activation-unknown-failed', botId: identity.botId,
645
+ });
646
+ let rollback = 'succeeded';
647
+ const recover = async (action) => {
648
+ try { return await action(); }
649
+ catch (restoreError) {
650
+ rollback = 'failed';
651
+ this.#diagnostics.report(weixinStageError('rollback-failed', restoreError), {
652
+ operation: cancelled ? 'provision.cancel' : 'provision.poll', botId: identity.botId, warning: true,
653
+ parentReferenceId: failure.publicError?.details.referenceId,
654
+ });
655
+ }
656
+ };
657
+ await this.#stopRuntime(identity.botId);
658
+ if (previousConfig) await recover(() => this.#configStore.save(previousConfig));
659
+ else if (this.#configStore.get(identity.botId)) {
660
+ const removed = await recover(() => this.#configStore.remove(identity.botId));
661
+ if (removed) await recover(() => this.#deleteState({ botId: identity.botId, config }));
662
+ }
663
+ await recover(() => previousToken?.value
664
+ ? this.#credentials.set(identity.tokenRef, previousToken.value)
665
+ : this.#credentials.unset(identity.tokenRef));
666
+ if (previousConfig && previousToken?.value) {
667
+ await recover(() => this.#startRuntime(previousConfig, previousToken.value, { operation: 'provision.poll' }));
668
+ if (rollback === 'succeeded' && !this.#runtimes.get(identity.botId)?.status?.ready) rollback = 'unknown';
669
+ }
670
+ this.#diagnostics.outcome(failure, rollback);
671
+ throw failure;
672
+ }
673
+ });
674
+ }
675
+
676
+ async #startRuntime(config, token, context = {}) {
677
+ await this.#stopRuntime(config.botId);
678
+ let runtime;
679
+ try {
680
+ const account = config.consumerMode === 'external-consumer' ? pairedWeixinAccount(config, token) : undefined;
681
+ runtime = await this.#createRuntime({ botId: config.botId, config, token,
682
+ externalConsumer: async (message, state, signal) => {
683
+ const current = await this.#deliveryAccount(this.#configStore.get(config.botId), signal);
684
+ if (current.fingerprint !== account.fingerprint) throw weixinRefusal('account-changed');
685
+ this.#inboundConsumers.signalFor(config.botId, account.fingerprint).throwIfAborted();
686
+ const event = normalizeWeixinExternalText(message, { botId: config.botId, account,
687
+ sourceFiles: this.#inboundConsumers.acceptsFiles(config.botId),
688
+ sourceImages: this.#inboundConsumers.acceptsImages(config.botId),
689
+ sourceVoiceTranscripts: this.#inboundConsumers.acceptsVoiceTranscripts(config.botId),
690
+ sourceVoiceAudio: this.#inboundConsumers.acceptsVoiceAudio(config.botId),
691
+ sourceQuotes: this.#inboundConsumers.acceptsQuotes(config.botId),
692
+ sourceVideos: this.#inboundConsumers.acceptsVideos(config.botId) });
693
+ if (!event) return { accepted: true, ignored: true };
694
+ await state.rememberContextToken?.({ userId: event.actor.id, contextToken: message.context_token,
695
+ seq: message.seq, messageTimeMs: message.create_time_ms, fingerprint: account.fingerprint,
696
+ expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000 });
697
+ await state.rememberExternalReplySource({ messageId: event.messageId, actorId: event.actor.id,
698
+ fingerprint: account.fingerprint, contextToken: message.context_token,
699
+ expiresAt: Date.now() + 30 * 24 * 60 * 60 * 1000,
700
+ ...(event.attachments?.length ? { file: privateWeixinFile(message, event) } : {}) });
701
+ return this.#inboundConsumers.accept(config.botId, event, signal);
702
+ } });
703
+ } catch (error) {
704
+ throw preserveActivationError(error, 'runtime-prepare-failed');
705
+ }
706
+ if (!runtime || typeof runtime.start !== 'function' || typeof runtime.stop !== 'function') {
707
+ throw weixinStageError(
708
+ 'runtime-prepare-failed',
709
+ new TypeError('createRuntime returned an invalid Weixin runtime'),
710
+ );
711
+ }
712
+ try {
713
+ await runtime.start({ ...context, botId: config.botId });
714
+ this.#runtimes.set(config.botId, runtime);
715
+ } catch (error) {
716
+ await runtime.stop().catch(() => undefined);
717
+ throw preserveActivationError(error, 'connection-start-failed');
718
+ }
719
+ }
720
+
721
+ async #stopRuntime(botId) {
722
+ const runtime = this.#runtimes.get(botId);
723
+ this.#runtimes.delete(botId);
724
+ try {
725
+ const stopped = await runtime?.stop();
726
+ return stopped?.warnings ?? [];
727
+ } catch (error) {
728
+ return [this.#diagnostics.report(error, {
729
+ operation: 'connection.close', stage: 'connection.stop', code: 'connection-stop-failed', botId, warning: true,
730
+ }).publicError];
731
+ }
732
+ }
733
+
734
+ async #resolveToken(ref) {
735
+ try { return cleanString((await this.#credentials.resolve(ref))?.value); }
736
+ catch (error) { throw weixinStageError('credential-read-failed', error); }
737
+ }
738
+
739
+ async #writeCredential(ref, value) {
740
+ try {
741
+ if (value === undefined) await this.#credentials.unset(ref);
742
+ else await this.#credentials.set(ref, value);
743
+ } catch (cause) {
744
+ let description;
745
+ try { description = await this.#credentials.describe?.(ref); } catch { /* Preserve the original write failure. */ }
746
+ if (description?.writable === false) {
747
+ cause = Object.assign(new Error('Credential source is read-only', { cause }), { code: 'read-only' });
748
+ }
749
+ throw weixinStageError(value === undefined ? 'credential-remove-failed' : 'credential-save-failed', cause);
750
+ }
751
+ }
752
+
753
+ #assertAttemptActive(record) {
754
+ if (record.controller.signal.aborted || this.#activeAttemptId !== record.id) throw abortError();
755
+ }
756
+
757
+ #withBotTransition(botId, operation) {
758
+ const previous = this.#transitions.get(botId) ?? Promise.resolve();
759
+ const current = previous.catch(() => undefined).then(operation);
760
+ const settled = current.finally(() => {
761
+ if (this.#transitions.get(botId) === settled) this.#transitions.delete(botId);
762
+ });
763
+ this.#transitions.set(botId, settled);
764
+ return settled;
765
+ }
766
+
767
+ #pruneAttempts() {
768
+ for (const [id, record] of this.#attempts) {
769
+ if (id !== this.#activeAttemptId && TERMINAL_ATTEMPT_STATES.has(record.state)
770
+ && this.#attempts.size > 16) {
771
+ this.#attempts.delete(id);
772
+ }
773
+ }
774
+ }
775
+
776
+ #touch() {
777
+ this.#revision += 1;
778
+ }
779
+ }